PluginProbe
Elementor Website Builder – more than just a page builder / 4.2.0-beta1
Elementor Website Builder – more than just a page builder v4.2.0-beta1
4.3.4 4.3.3 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 All 457 releases
elementor / assets / js / common.js

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

30,425 lines 1.1 MB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (() => { // webpackBootstrap
2 /******/ var __webpack_modules__ = ({
3
4 /***/ "../assets/dev/js/editor/utils/editor-one-events.js":
5 /*!**********************************************************!*\
6 !*** ../assets/dev/js/editor/utils/editor-one-events.js ***!
7 \**********************************************************/
8 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
9
10 "use strict";
11
12
13 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
14 Object.defineProperty(exports, "__esModule", ({
15 value: true
16 }));
17 exports["default"] = exports.createDebouncedWidgetPanelSearch = exports.createDebouncedFinderSearch = exports.EditorOneEventManager = void 0;
18 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
19 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
20 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
21 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
22 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
23 var EditorOneEventManager = exports.EditorOneEventManager = /*#__PURE__*/function () {
24 function EditorOneEventManager() {
25 (0, _classCallCheck2.default)(this, EditorOneEventManager);
26 }
27 return (0, _createClass2.default)(EditorOneEventManager, null, [{
28 key: "getEventsManager",
29 value: function getEventsManager() {
30 var _elementorCommon;
31 return (_elementorCommon = elementorCommon) === null || _elementorCommon === void 0 ? void 0 : _elementorCommon.eventsManager;
32 }
33 }, {
34 key: "getConfig",
35 value: function getConfig() {
36 var _this$getEventsManage;
37 return (_this$getEventsManage = this.getEventsManager()) === null || _this$getEventsManage === void 0 ? void 0 : _this$getEventsManage.config;
38 }
39 }, {
40 key: "canSendEvents",
41 value: function canSendEvents() {
42 var _elementorCommon2;
43 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;
44 }
45 }, {
46 key: "isEventsManagerAvailable",
47 value: function isEventsManagerAvailable() {
48 var eventsManager = this.getEventsManager();
49 return eventsManager && 'function' === typeof eventsManager.dispatchEvent;
50 }
51 }, {
52 key: "dispatchEvent",
53 value: function dispatchEvent(eventName, payload) {
54 if (!this.isEventsManagerAvailable() || !this.canSendEvents()) {
55 return false;
56 }
57 try {
58 return this.getEventsManager().dispatchEvent(eventName, payload);
59 } catch (error) {
60 return false;
61 }
62 }
63 }, {
64 key: "toLowerSnake",
65 value: function toLowerSnake(value) {
66 if (!value || 'string' !== typeof value) {
67 return value;
68 }
69 return value.replace(/\s+/g, '_').toLowerCase();
70 }
71 }, {
72 key: "decodeHtmlEntities",
73 value: function decodeHtmlEntities(text) {
74 if (!text || 'string' !== typeof text) {
75 return text;
76 }
77 var doc = new DOMParser().parseFromString(text, 'text/html');
78 return doc.body.textContent || text;
79 }
80 }, {
81 key: "isInEditorContext",
82 value: function isInEditorContext() {
83 var _window$elementor;
84 return 'undefined' !== typeof window.elementor && !!((_window$elementor = window.elementor) !== null && _window$elementor !== void 0 && _window$elementor.documents);
85 }
86 }, {
87 key: "getFinderContext",
88 value: function getFinderContext() {
89 var _config$appTypes, _config$appTypes2, _config$locations, _config$locations2;
90 var config = this.getConfig();
91 var isEditor = this.isInEditorContext();
92 return {
93 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,
94 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)
95 };
96 }
97 }, {
98 key: "createBasePayload",
99 value: function createBasePayload() {
100 var _config$appTypes$edit, _config$appTypes3, _config$appTypes$edit2, _config$appTypes4;
101 var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
102 var config = this.getConfig();
103 return _objectSpread({
104 app_type: (_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',
105 window_name: (_config$appTypes$edit2 = config === null || config === void 0 || (_config$appTypes4 = config.appTypes) === null || _config$appTypes4 === void 0 ? void 0 : _config$appTypes4.editor) !== null && _config$appTypes$edit2 !== void 0 ? _config$appTypes$edit2 : 'editor'
106 }, overrides);
107 }
108 }, {
109 key: "sendTopBarPublishDropdown",
110 value: function sendTopBarPublishDropdown(targetName) {
111 var _config$names, _config$triggers, _config$targetTypes, _config$interactionRe, _config$locations3, _config$secondaryLoca, _config$targetTypes2;
112 var config = this.getConfig();
113 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({
114 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers = config.triggers) === null || _config$triggers === void 0 ? void 0 : _config$triggers.click),
115 target_type: config === null || config === void 0 || (_config$targetTypes = config.targetTypes) === null || _config$targetTypes === void 0 ? void 0 : _config$targetTypes.dropdownItem,
116 target_name: targetName,
117 interaction_result: config === null || config === void 0 || (_config$interactionRe = config.interactionResults) === null || _config$interactionRe === void 0 ? void 0 : _config$interactionRe.actionSelected,
118 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations3 = config.locations) === null || _config$locations3 === void 0 ? void 0 : _config$locations3.topBar),
119 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca = config.secondaryLocations) === null || _config$secondaryLoca === void 0 ? void 0 : _config$secondaryLoca.publishDropdown),
120 location_l2: config === null || config === void 0 || (_config$targetTypes2 = config.targetTypes) === null || _config$targetTypes2 === void 0 ? void 0 : _config$targetTypes2.dropdownItem,
121 interaction_description: 'User selected an action from the publish dropdown'
122 }));
123 }
124 }, {
125 key: "sendTopBarPageList",
126 value: function sendTopBarPageList(targetName) {
127 var _config$names2, _config$triggers2, _config$targetTypes3, _config$interactionRe2, _config$interactionRe3, _config$locations4, _config$secondaryLoca2, _config$targetTypes4;
128 var isCreate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
129 var config = this.getConfig();
130 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({
131 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers2 = config.triggers) === null || _config$triggers2 === void 0 ? void 0 : _config$triggers2.click),
132 target_type: config === null || config === void 0 || (_config$targetTypes3 = config.targetTypes) === null || _config$targetTypes3 === void 0 ? void 0 : _config$targetTypes3.dropdownItem,
133 target_name: targetName,
134 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,
135 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations4 = config.locations) === null || _config$locations4 === void 0 ? void 0 : _config$locations4.topBar),
136 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca2 = config.secondaryLocations) === null || _config$secondaryLoca2 === void 0 ? void 0 : _config$secondaryLoca2.pageListDropdown),
137 location_l2: config === null || config === void 0 || (_config$targetTypes4 = config.targetTypes) === null || _config$targetTypes4 === void 0 ? void 0 : _config$targetTypes4.dropdownItem,
138 interaction_description: 'User selected an action from the page list dropdown'
139 }));
140 }
141 }, {
142 key: "sendSiteSettingsSession",
143 value: function sendSiteSettingsSession(_ref) {
144 var _config$names3, _config$triggers3, _config$interactionRe4, _config$locations5, _config$secondaryLoca3;
145 var targetType = _ref.targetType,
146 _ref$visitedItems = _ref.visitedItems,
147 visitedItems = _ref$visitedItems === void 0 ? [] : _ref$visitedItems,
148 _ref$savedItems = _ref.savedItems,
149 savedItems = _ref$savedItems === void 0 ? [] : _ref$savedItems,
150 state = _ref.state;
151 var config = this.getConfig();
152 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({
153 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers3 = config.triggers) === null || _config$triggers3 === void 0 ? void 0 : _config$triggers3.click),
154 target_type: targetType,
155 target_name: 'site_settings',
156 interaction_result: config === null || config === void 0 || (_config$interactionRe4 = config.interactionResults) === null || _config$interactionRe4 === void 0 ? void 0 : _config$interactionRe4.sessionEnd,
157 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations5 = config.locations) === null || _config$locations5 === void 0 ? void 0 : _config$locations5.leftPanel),
158 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca3 = config.secondaryLocations) === null || _config$secondaryLoca3 === void 0 ? void 0 : _config$secondaryLoca3.siteSettings),
159 interaction_description: 'Records areas visited as part of the site setting session',
160 metadata: {
161 visited_items: visitedItems,
162 saved_items: savedItems
163 },
164 state: state
165 }));
166 }
167 }, {
168 key: "sendELibraryNav",
169 value: function sendELibraryNav(tabName) {
170 var _config$names4, _config$triggers4, _config$targetTypes5, _config$interactionRe5, _config$locations6, _config$secondaryLoca4;
171 var config = this.getConfig();
172 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({
173 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers4 = config.triggers) === null || _config$triggers4 === void 0 ? void 0 : _config$triggers4.tabSelect),
174 target_type: config === null || config === void 0 || (_config$targetTypes5 = config.targetTypes) === null || _config$targetTypes5 === void 0 ? void 0 : _config$targetTypes5.tab,
175 target_name: this.toLowerSnake(tabName),
176 interaction_result: config === null || config === void 0 || (_config$interactionRe5 = config.interactionResults) === null || _config$interactionRe5 === void 0 ? void 0 : _config$interactionRe5.tabChanged,
177 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations6 = config.locations) === null || _config$locations6 === void 0 ? void 0 : _config$locations6.elementorLibrary),
178 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca4 = config.secondaryLocations) === null || _config$secondaryLoca4 === void 0 ? void 0 : _config$secondaryLoca4.libraryTabs),
179 interaction_description: 'User navigates within elementor library'
180 }));
181 }
182 }, {
183 key: "sendELibraryInsert",
184 value: function sendELibraryInsert(_ref2) {
185 var _config$triggers5, _config$targetTypes6, _config$interactionRe6, _config$locations7, _config$secondaryLoca5, _config$names5;
186 var assetId = _ref2.assetId,
187 assetName = _ref2.assetName,
188 libraryType = _ref2.libraryType,
189 _ref2$proRequired = _ref2.proRequired,
190 proRequired = _ref2$proRequired === void 0 ? false : _ref2$proRequired;
191 var config = this.getConfig();
192 var payload = this.createBasePayload({
193 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers5 = config.triggers) === null || _config$triggers5 === void 0 ? void 0 : _config$triggers5.insert),
194 target_type: config === null || config === void 0 || (_config$targetTypes6 = config.targetTypes) === null || _config$targetTypes6 === void 0 ? void 0 : _config$targetTypes6.button,
195 target_name: String(assetId),
196 interaction_result: config === null || config === void 0 || (_config$interactionRe6 = config.interactionResults) === null || _config$interactionRe6 === void 0 ? void 0 : _config$interactionRe6.assetInserted,
197 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations7 = config.locations) === null || _config$locations7 === void 0 ? void 0 : _config$locations7.elementorLibrary),
198 location_l1: this.toLowerSnake(libraryType),
199 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca5 = config.secondaryLocations) === null || _config$secondaryLoca5 === void 0 ? void 0 : _config$secondaryLoca5.assetCard),
200 interaction_description: 'User inserts block/pages from elementor library',
201 metadata: {
202 template_id: String(assetId),
203 template_name: this.decodeHtmlEntities(assetName) || ''
204 }
205 });
206 if (proRequired) {
207 payload.state = 'pro_plan_required';
208 }
209 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);
210 }
211 }, {
212 key: "sendELibraryFavorite",
213 value: function sendELibraryFavorite(_ref3) {
214 var _config$triggers6, _config$targetTypes7, _config$interactionRe7, _config$locations8, _config$secondaryLoca6, _config$names6;
215 var assetId = _ref3.assetId,
216 assetName = _ref3.assetName,
217 libraryType = _ref3.libraryType,
218 isFavorite = _ref3.isFavorite,
219 _ref3$proRequired = _ref3.proRequired,
220 proRequired = _ref3$proRequired === void 0 ? false : _ref3$proRequired;
221 var config = this.getConfig();
222 var payload = this.createBasePayload({
223 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers6 = config.triggers) === null || _config$triggers6 === void 0 ? void 0 : _config$triggers6.click),
224 target_type: config === null || config === void 0 || (_config$targetTypes7 = config.targetTypes) === null || _config$targetTypes7 === void 0 ? void 0 : _config$targetTypes7.toggle,
225 target_name: String(assetId),
226 interaction_result: config === null || config === void 0 || (_config$interactionRe7 = config.interactionResults) === null || _config$interactionRe7 === void 0 ? void 0 : _config$interactionRe7.assetFavorite,
227 target_value: Boolean(isFavorite),
228 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations8 = config.locations) === null || _config$locations8 === void 0 ? void 0 : _config$locations8.elementorLibrary),
229 location_l1: this.toLowerSnake(libraryType),
230 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca6 = config.secondaryLocations) === null || _config$secondaryLoca6 === void 0 ? void 0 : _config$secondaryLoca6.assetCard),
231 interaction_description: 'User favorite block/pages from elementor library',
232 metadata: {
233 template_id: String(assetId),
234 template_name: this.decodeHtmlEntities(assetName) || ''
235 }
236 });
237 if (proRequired) {
238 payload.state = 'pro_plan_required';
239 }
240 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);
241 }
242 }, {
243 key: "sendELibraryGenerateAi",
244 value: function sendELibraryGenerateAi(_ref4) {
245 var _config$names7, _config$triggers7, _config$targetTypes8, _config$interactionRe8, _config$locations9, _config$secondaryLoca7;
246 var assetId = _ref4.assetId,
247 assetName = _ref4.assetName,
248 libraryType = _ref4.libraryType;
249 var config = this.getConfig();
250 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({
251 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers7 = config.triggers) === null || _config$triggers7 === void 0 ? void 0 : _config$triggers7.click),
252 target_type: config === null || config === void 0 || (_config$targetTypes8 = config.targetTypes) === null || _config$targetTypes8 === void 0 ? void 0 : _config$targetTypes8.button,
253 target_name: String(assetId),
254 interaction_result: config === null || config === void 0 || (_config$interactionRe8 = config.interactionResults) === null || _config$interactionRe8 === void 0 ? void 0 : _config$interactionRe8.aiGenerate,
255 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations9 = config.locations) === null || _config$locations9 === void 0 ? void 0 : _config$locations9.elementorLibrary),
256 location_l1: this.toLowerSnake(libraryType),
257 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca7 = config.secondaryLocations) === null || _config$secondaryLoca7 === void 0 ? void 0 : _config$secondaryLoca7.assetCard),
258 interaction_description: 'User generated block/page based on a library asset',
259 metadata: {
260 template_id: String(assetId),
261 template_name: this.decodeHtmlEntities(assetName) || ''
262 }
263 }));
264 }
265 }, {
266 key: "sendFinderSearchInput",
267 value: function sendFinderSearchInput(_ref5) {
268 var _config$triggers8, _config$targetTypes9, _config$interactionRe9, _config$interactionRe0, _config$secondaryLoca8, _config$names8;
269 var resultsCount = _ref5.resultsCount,
270 _ref5$searchTerm = _ref5.searchTerm,
271 searchTerm = _ref5$searchTerm === void 0 ? null : _ref5$searchTerm;
272 var config = this.getConfig();
273 var hasResults = resultsCount > 0;
274 var finderContext = this.getFinderContext();
275 var payload = this.createBasePayload({
276 window_name: finderContext.windowName,
277 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers8 = config.triggers) === null || _config$triggers8 === void 0 ? void 0 : _config$triggers8.typing),
278 target_type: config === null || config === void 0 || (_config$targetTypes9 = config.targetTypes) === null || _config$targetTypes9 === void 0 ? void 0 : _config$targetTypes9.searchInput,
279 target_name: 'finder',
280 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,
281 target_location: finderContext.targetLocation,
282 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca8 = config.secondaryLocations) === null || _config$secondaryLoca8 === void 0 ? void 0 : _config$secondaryLoca8.finder),
283 interaction_description: 'Finder search input, follows debounce behavior',
284 metadata: {
285 results_count: resultsCount
286 }
287 });
288 if (!hasResults && searchTerm) {
289 payload.metadata.search_term = searchTerm;
290 }
291 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);
292 }
293 }, {
294 key: "sendFinderResultSelect",
295 value: function sendFinderResultSelect(choice) {
296 var _config$names9, _config$triggers9, _config$targetTypes0, _config$interactionRe1, _config$secondaryLoca9, _config$secondaryLoca0;
297 var config = this.getConfig();
298 var finderContext = this.getFinderContext();
299 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({
300 window_name: finderContext.windowName,
301 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers9 = config.triggers) === null || _config$triggers9 === void 0 ? void 0 : _config$triggers9.click),
302 target_type: config === null || config === void 0 || (_config$targetTypes0 = config.targetTypes) === null || _config$targetTypes0 === void 0 ? void 0 : _config$targetTypes0.searchResult,
303 target_name: choice,
304 interaction_result: config === null || config === void 0 || (_config$interactionRe1 = config.interactionResults) === null || _config$interactionRe1 === void 0 ? void 0 : _config$interactionRe1.selected,
305 target_location: finderContext.targetLocation,
306 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca9 = config.secondaryLocations) === null || _config$secondaryLoca9 === void 0 ? void 0 : _config$secondaryLoca9.finder),
307 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca0 = config.secondaryLocations) === null || _config$secondaryLoca0 === void 0 ? void 0 : _config$secondaryLoca0.finderResults),
308 interaction_description: 'Finder search results was selected'
309 }));
310 }
311 }, {
312 key: "sendCanvasEmptyBoxAction",
313 value: function sendCanvasEmptyBoxAction(_ref6) {
314 var _config$triggers0, _config$targetTypes1, _config$interactionRe10, _config$locations0, _config$secondaryLoca1, _config$names0;
315 var targetName = _ref6.targetName,
316 _ref6$metadata = _ref6.metadata,
317 metadata = _ref6$metadata === void 0 ? {} : _ref6$metadata,
318 _ref6$containerCreate = _ref6.containerCreated,
319 containerCreated = _ref6$containerCreate === void 0 ? null : _ref6$containerCreate;
320 var config = this.getConfig();
321 var payload = this.createBasePayload({
322 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers0 = config.triggers) === null || _config$triggers0 === void 0 ? void 0 : _config$triggers0.click),
323 target_type: config === null || config === void 0 || (_config$targetTypes1 = config.targetTypes) === null || _config$targetTypes1 === void 0 ? void 0 : _config$targetTypes1.buttons,
324 target_name: targetName,
325 interaction_result: config === null || config === void 0 || (_config$interactionRe10 = config.interactionResults) === null || _config$interactionRe10 === void 0 ? void 0 : _config$interactionRe10.selected,
326 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations0 = config.locations) === null || _config$locations0 === void 0 ? void 0 : _config$locations0.canvas),
327 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca1 = config.secondaryLocations) === null || _config$secondaryLoca1 === void 0 ? void 0 : _config$secondaryLoca1.emptyBox),
328 interaction_description: 'Empty box on canvas actions'
329 });
330 if (Object.keys(metadata).length > 0) {
331 payload.metadata = metadata;
332 }
333 if (containerCreated !== null) {
334 payload.state = containerCreated;
335 }
336 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);
337 }
338 }, {
339 key: "sendWidgetPanelSearch",
340 value: function sendWidgetPanelSearch(_ref7) {
341 var _config$triggers1, _config$targetTypes10, _config$interactionRe11, _config$interactionRe12, _config$locations1, _config$locations10, _config$secondaryLoca10, _config$names1;
342 var resultsCount = _ref7.resultsCount,
343 _ref7$userInput = _ref7.userInput,
344 userInput = _ref7$userInput === void 0 ? null : _ref7$userInput;
345 var config = this.getConfig();
346 var hasResults = resultsCount > 0;
347 var payload = this.createBasePayload({
348 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers1 = config.triggers) === null || _config$triggers1 === void 0 ? void 0 : _config$triggers1.typing),
349 target_type: config === null || config === void 0 || (_config$targetTypes10 = config.targetTypes) === null || _config$targetTypes10 === void 0 ? void 0 : _config$targetTypes10.searchWidget,
350 target_name: 'search_widget',
351 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,
352 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations1 = config.locations) === null || _config$locations1 === void 0 ? void 0 : _config$locations1.leftPanel),
353 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$locations10 = config.locations) === null || _config$locations10 === void 0 ? void 0 : _config$locations10.widgetPanel),
354 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca10 = config.secondaryLocations) === null || _config$secondaryLoca10 === void 0 ? void 0 : _config$secondaryLoca10.searchBar),
355 interaction_description: 'Widget search input, follows debounce behavior'
356 });
357 if (!hasResults && userInput) {
358 payload.metadata = {
359 user_input: userInput
360 };
361 }
362 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);
363 }
364 }, {
365 key: "createWpDashPayload",
366 value: function createWpDashPayload() {
367 var _config$appTypes$wpDa, _config$appTypes5, _config$locations11;
368 var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
369 var config = this.getConfig();
370 return this.createBasePayload(_objectSpread({
371 window_name: (_config$appTypes$wpDa = config === null || config === void 0 || (_config$appTypes5 = config.appTypes) === null || _config$appTypes5 === void 0 ? void 0 : _config$appTypes5.wpDash) !== null && _config$appTypes$wpDa !== void 0 ? _config$appTypes$wpDa : 'wpdash',
372 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations11 = config.locations) === null || _config$locations11 === void 0 ? void 0 : _config$locations11.wpDashAdmin),
373 location_l2: ''
374 }, overrides));
375 }
376 }, {
377 key: "sendWpDashElementorMenuClick",
378 value: function sendWpDashElementorMenuClick() {
379 var _config$names10, _config$triggers10, _config$targetTypes11, _config$interactionRe13, _config$secondaryLoca11;
380 var config = this.getConfig();
381 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({
382 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers10 = config.triggers) === null || _config$triggers10 === void 0 ? void 0 : _config$triggers10.click),
383 target_type: config === null || config === void 0 || (_config$targetTypes11 = config.targetTypes) === null || _config$targetTypes11 === void 0 ? void 0 : _config$targetTypes11.wpDashAdminMenuItem,
384 target_name: 'elementor_menu_item',
385 interaction_result: config === null || config === void 0 || (_config$interactionRe13 = config.interactionResults) === null || _config$interactionRe13 === void 0 ? void 0 : _config$interactionRe13.elementorSideMenuOpened,
386 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca11 = config.secondaryLocations) === null || _config$secondaryLoca11 === void 0 ? void 0 : _config$secondaryLoca11.wpDashElementorCoreMenu),
387 interaction_description: 'core_user_clicked_elementor_menu_item'
388 }));
389 }
390 }, {
391 key: "sendWpDashEditorSubMenuHover",
392 value: function sendWpDashEditorSubMenuHover() {
393 var _config$names11, _config$triggers11, _config$targetTypes12, _config$interactionRe14, _config$secondaryLoca12;
394 var config = this.getConfig();
395 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({
396 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers11 = config.triggers) === null || _config$triggers11 === void 0 ? void 0 : _config$triggers11.hover),
397 target_type: config === null || config === void 0 || (_config$targetTypes12 = config.targetTypes) === null || _config$targetTypes12 === void 0 ? void 0 : _config$targetTypes12.wpDashEditorMenu,
398 target_name: 'wpdash_editor_sub_menu',
399 interaction_result: config === null || config === void 0 || (_config$interactionRe14 = config.interactionResults) === null || _config$interactionRe14 === void 0 ? void 0 : _config$interactionRe14.editorSubMenuOpened,
400 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca12 = config.secondaryLocations) === null || _config$secondaryLoca12 === void 0 ? void 0 : _config$secondaryLoca12.wpDashElementorCoreSubMenu),
401 interaction_description: 'core_user_hovered_sub_menu'
402 }));
403 }
404 }, {
405 key: "sendWpDashThemeBuilderClick",
406 value: function sendWpDashThemeBuilderClick() {
407 var _config$names12, _config$triggers12, _config$targetTypes13, _config$interactionRe15, _config$secondaryLoca13;
408 var config = this.getConfig();
409 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({
410 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers12 = config.triggers) === null || _config$triggers12 === void 0 ? void 0 : _config$triggers12.click),
411 target_type: config === null || config === void 0 || (_config$targetTypes13 = config.targetTypes) === null || _config$targetTypes13 === void 0 ? void 0 : _config$targetTypes13.wpDashSubMenuItem,
412 target_name: 'theme_builder_menu_item',
413 interaction_result: config === null || config === void 0 || (_config$interactionRe15 = config.interactionResults) === null || _config$interactionRe15 === void 0 ? void 0 : _config$interactionRe15.themeBuilderPromotionWindow,
414 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca13 = config.secondaryLocations) === null || _config$secondaryLoca13 === void 0 ? void 0 : _config$secondaryLoca13.wpDashThemeBuilder),
415 interaction_description: 'core_user_clicked_theme_builder_menu_item'
416 }));
417 }
418 }]);
419 }();
420 var createDebouncedFinderSearch = exports.createDebouncedFinderSearch = function createDebouncedFinderSearch() {
421 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300;
422 return _.debounce(function (resultsCount, searchTerm) {
423 EditorOneEventManager.sendFinderSearchInput({
424 resultsCount: resultsCount,
425 searchTerm: searchTerm
426 });
427 }, delay);
428 };
429 var createDebouncedWidgetPanelSearch = exports.createDebouncedWidgetPanelSearch = function createDebouncedWidgetPanelSearch() {
430 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2000;
431 return _.debounce(function (resultsCount, userInput) {
432 EditorOneEventManager.sendWidgetPanelSearch({
433 resultsCount: resultsCount,
434 userInput: userInput
435 });
436 }, delay);
437 };
438 var _default = exports["default"] = EditorOneEventManager;
439
440 /***/ }),
441
442 /***/ "../assets/dev/js/editor/utils/files-upload-handler.js":
443 /*!*************************************************************!*\
444 !*** ../assets/dev/js/editor/utils/files-upload-handler.js ***!
445 \*************************************************************/
446 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
447
448 "use strict";
449 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
450
451
452 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
453 Object.defineProperty(exports, "__esModule", ({
454 value: true
455 }));
456 exports["default"] = void 0;
457 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
458 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
459 var FilesUploadHandler = exports["default"] = /*#__PURE__*/function () {
460 function FilesUploadHandler() {
461 (0, _classCallCheck2.default)(this, FilesUploadHandler);
462 }
463 return (0, _createClass2.default)(FilesUploadHandler, null, [{
464 key: "isUploadEnabled",
465 value: function isUploadEnabled(mediaType) {
466 var unfilteredFilesTypes = ['svg', 'application/json'];
467 if (!unfilteredFilesTypes.includes(mediaType)) {
468 return true;
469 }
470 return elementorCommon.config.filesUpload.unfilteredFiles;
471 }
472 }, {
473 key: "setUploadTypeCaller",
474 value: function setUploadTypeCaller(frame) {
475 frame.uploader.uploader.param('uploadTypeCaller', 'elementor-wp-media-upload');
476 }
477 }, {
478 key: "getUnfilteredFilesNonAdminDialog",
479 value: function getUnfilteredFilesNonAdminDialog() {
480 return elementorCommon.dialogsManager.createWidget('alert', {
481 id: 'e-unfiltered-files-disabled-dialog',
482 headerMessage: __('Sorry, you can\'t upload that file yet', 'elementor'),
483 message: __('This is because JSON files may pose a security risk.', 'elementor') + '<br><br>' + __('To upload them anyway, ask the site administrator to enable unfiltered file uploads.', 'elementor'),
484 strings: {
485 confirm: __('Got it', 'elementor')
486 }
487 });
488 }
489 }, {
490 key: "getUnfilteredFilesNotEnabledDialog",
491 value: function getUnfilteredFilesNotEnabledDialog(callback) {
492 var elementorInstance = window.elementorAdmin || window.elementor;
493 if (!elementorInstance.config.user.is_administrator) {
494 return this.getUnfilteredFilesNonAdminDialog();
495 }
496 var onConfirm = function onConfirm() {
497 elementorCommon.ajax.addRequest('enable_unfiltered_files_upload', {}, true);
498 elementorCommon.config.filesUpload.unfilteredFiles = true;
499 callback();
500 };
501 return elementorInstance.helpers.getSimpleDialog('e-enable-unfiltered-files-dialog', __('Enable Unfiltered File Uploads', 'elementor'), __('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'), __('Enable', 'elementor'), onConfirm);
502 }
503 }, {
504 key: "getUnfilteredFilesNotEnabledImportTemplateDialog",
505 value: function getUnfilteredFilesNotEnabledImportTemplateDialog(callback) {
506 if (!(window.elementorAdmin || window.elementor).config.user.is_administrator) {
507 return this.getUnfilteredFilesNonAdminDialog();
508 }
509 return elementorCommon.dialogsManager.createWidget('confirm', {
510 id: 'e-enable-unfiltered-files-dialog-import-template',
511 headerMessage: __('Enable Unfiltered File Uploads', 'elementor'),
512 message: __('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 />' + __('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'),
513 position: {
514 my: 'center center',
515 at: 'center center'
516 },
517 strings: {
518 confirm: __('Enable and Import', 'elementor'),
519 cancel: __('Import Without Enabling', 'elementor')
520 },
521 onConfirm: function onConfirm() {
522 elementorCommon.ajax.addRequest('enable_unfiltered_files_upload', {
523 success: function success() {
524 // This utility is used in both the admin and the Editor.
525 elementorCommon.config.filesUpload.unfilteredFiles = true;
526 callback();
527 }
528 }, true);
529 },
530 onCancel: function onCancel() {
531 return callback();
532 }
533 });
534 }
535 }]);
536 }();
537
538 /***/ }),
539
540 /***/ "../assets/dev/js/editor/utils/is-instanceof.js":
541 /*!******************************************************!*\
542 !*** ../assets/dev/js/editor/utils/is-instanceof.js ***!
543 \******************************************************/
544 /***/ ((__unused_webpack_module, exports) => {
545
546 "use strict";
547
548
549 Object.defineProperty(exports, "__esModule", ({
550 value: true
551 }));
552 exports["default"] = void 0;
553 function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
554 function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); 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; } }
555 function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
556 /**
557 * Some FileAPI objects such as FileList, DataTransferItem and DataTransferItemList has inconsistency with the retrieved
558 * object (from events, etc.) and the actual JavaScript object so a regular instanceof doesn't work. This function can
559 * check whether it's instanceof by using the objects constructor and prototype names.
560 *
561 * @param object
562 * @param constructors
563 * @return {boolean}
564 */
565 var _default = exports["default"] = function _default(object, constructors) {
566 constructors = Array.isArray(constructors) ? constructors : [constructors];
567 var _iterator = _createForOfIteratorHelper(constructors),
568 _step;
569 try {
570 for (_iterator.s(); !(_step = _iterator.n()).done;) {
571 var constructor = _step.value;
572 if (object.constructor.name === constructor.prototype[Symbol.toStringTag]) {
573 return true;
574 }
575 }
576 } catch (err) {
577 _iterator.e(err);
578 } finally {
579 _iterator.f();
580 }
581 return false;
582 };
583
584 /***/ }),
585
586 /***/ "../assets/dev/js/modules/imports/args-object.js":
587 /*!*******************************************************!*\
588 !*** ../assets/dev/js/modules/imports/args-object.js ***!
589 \*******************************************************/
590 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
591
592 "use strict";
593
594
595 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
596 Object.defineProperty(exports, "__esModule", ({
597 value: true
598 }));
599 exports["default"] = void 0;
600 var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js"));
601 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
602 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
603 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
604 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
605 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
606 var _instanceType = _interopRequireDefault(__webpack_require__(/*! ./instance-type */ "../assets/dev/js/modules/imports/instance-type.js"));
607 var _isInstanceof = _interopRequireDefault(__webpack_require__(/*! ../../editor/utils/is-instanceof */ "../assets/dev/js/editor/utils/is-instanceof.js"));
608 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
609 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
610 var ArgsObject = exports["default"] = /*#__PURE__*/function (_InstanceType) {
611 /**
612 * Function constructor().
613 *
614 * Create ArgsObject.
615 *
616 * @param {{}} args
617 */
618 function ArgsObject(args) {
619 var _this;
620 (0, _classCallCheck2.default)(this, ArgsObject);
621 _this = _callSuper(this, ArgsObject);
622 _this.args = args;
623 return _this;
624 }
625
626 /**
627 * Function requireArgument().
628 *
629 * Validate property in args.
630 *
631 * @param {string} property
632 * @param {{}} args
633 *
634 * @throws {Error}
635 */
636 (0, _inherits2.default)(ArgsObject, _InstanceType);
637 return (0, _createClass2.default)(ArgsObject, [{
638 key: "requireArgument",
639 value: function requireArgument(property) {
640 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.args;
641 if (!Object.prototype.hasOwnProperty.call(args, property)) {
642 throw Error("".concat(property, " is required."));
643 }
644 }
645
646 /**
647 * Function requireArgumentType().
648 *
649 * Validate property in args using `type === typeof(args.whatever)`.
650 *
651 * @param {string} property
652 * @param {string} type
653 * @param {{}} args
654 *
655 * @throws {Error}
656 */
657 }, {
658 key: "requireArgumentType",
659 value: function requireArgumentType(property, type) {
660 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
661 this.requireArgument(property, args);
662 if ((0, _typeof2.default)(args[property]) !== type) {
663 throw Error("".concat(property, " invalid type: ").concat(type, "."));
664 }
665 }
666
667 /**
668 * Function requireArgumentInstance().
669 *
670 * Validate property in args using `args.whatever instanceof instance`.
671 *
672 * @param {string} property
673 * @param {*} instance
674 * @param {{}} args
675 *
676 * @throws {Error}
677 */
678 }, {
679 key: "requireArgumentInstance",
680 value: function requireArgumentInstance(property, instance) {
681 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
682 this.requireArgument(property, args);
683 if (!(args[property] instanceof instance) && !(0, _isInstanceof.default)(args[property], instance)) {
684 throw Error("".concat(property, " invalid instance."));
685 }
686 }
687
688 /**
689 * Function requireArgumentConstructor().
690 *
691 * Validate property in args using `type === args.whatever.constructor`.
692 *
693 * @param {string} property
694 * @param {*} type
695 * @param {{}} args
696 *
697 * @throws {Error}
698 */
699 }, {
700 key: "requireArgumentConstructor",
701 value: function requireArgumentConstructor(property, type) {
702 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
703 this.requireArgument(property, args);
704
705 // Note: Converting the constructor to string in order to avoid equation issues
706 // due to different memory addresses between iframes (window.Object !== window.top.Object).
707 if (args[property].constructor.toString() !== type.prototype.constructor.toString()) {
708 throw Error("".concat(property, " invalid constructor type."));
709 }
710 }
711 }], [{
712 key: "getInstanceType",
713 value: function getInstanceType() {
714 return 'ArgsObject';
715 }
716 }]);
717 }(_instanceType.default);
718
719 /***/ }),
720
721 /***/ "../assets/dev/js/modules/imports/instance-type.js":
722 /*!*********************************************************!*\
723 !*** ../assets/dev/js/modules/imports/instance-type.js ***!
724 \*********************************************************/
725 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
726
727 "use strict";
728
729
730 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
731 Object.defineProperty(exports, "__esModule", ({
732 value: true
733 }));
734 exports["default"] = void 0;
735 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
736 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
737 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
738 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
739 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
740 var InstanceType = exports["default"] = /*#__PURE__*/function () {
741 function InstanceType() {
742 var _this = this;
743 (0, _classCallCheck2.default)(this, InstanceType);
744 // Since anonymous classes sometimes do not get validated by babel, do it manually.
745 var target = this instanceof InstanceType ? this.constructor : void 0;
746 var prototypes = [];
747 while (target.__proto__ && target.__proto__.name) {
748 prototypes.push(target.__proto__);
749 target = target.__proto__;
750 }
751 prototypes.reverse().forEach(function (proto) {
752 return _this instanceof proto;
753 });
754 }
755 return (0, _createClass2.default)(InstanceType, null, [{
756 key: Symbol.hasInstance,
757 value: function value(target) {
758 /**
759 * This is function extending being called each time JS uses instanceOf, since babel use it each time it create new class
760 * its give's opportunity to mange capabilities of instanceOf operator.
761 * saving current class each time will give option later to handle instanceOf manually.
762 */
763 var result = _superPropGet(InstanceType, Symbol.hasInstance, this, 2)([target]);
764
765 // Act normal when validate a class, which does not have instance type.
766 if (target && !target.constructor.getInstanceType) {
767 return result;
768 }
769 if (target) {
770 if (!target.instanceTypes) {
771 target.instanceTypes = [];
772 }
773 if (!result) {
774 if (this.getInstanceType() === target.constructor.getInstanceType()) {
775 result = true;
776 }
777 }
778 if (result) {
779 var name = this.getInstanceType === InstanceType.getInstanceType ? 'BaseInstanceType' : this.getInstanceType();
780 if (-1 === target.instanceTypes.indexOf(name)) {
781 target.instanceTypes.push(name);
782 }
783 }
784 }
785 if (!result && target) {
786 // Check if the given 'target', is instance of known types.
787 result = target.instanceTypes && Array.isArray(target.instanceTypes) && -1 !== target.instanceTypes.indexOf(this.getInstanceType());
788 }
789 return result;
790 }
791 }, {
792 key: "getInstanceType",
793 value: function getInstanceType() {
794 elementorModules.ForceMethodImplementation();
795 }
796 }]);
797 }();
798
799 /***/ }),
800
801 /***/ "../assets/dev/js/modules/imports/module.js":
802 /*!**************************************************!*\
803 !*** ../assets/dev/js/modules/imports/module.js ***!
804 \**************************************************/
805 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
806
807 "use strict";
808
809
810 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
811 var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js"));
812 var Module = function Module() {
813 var $ = jQuery,
814 instanceParams = arguments,
815 self = this,
816 events = {};
817 var settings;
818 var ensureClosureMethods = function ensureClosureMethods() {
819 $.each(self, function (methodName) {
820 var oldMethod = self[methodName];
821 if ('function' !== typeof oldMethod) {
822 return;
823 }
824 self[methodName] = function () {
825 return oldMethod.apply(self, arguments);
826 };
827 });
828 };
829 var initSettings = function initSettings() {
830 settings = self.getDefaultSettings();
831 var instanceSettings = instanceParams[0];
832 if (instanceSettings) {
833 $.extend(true, settings, instanceSettings);
834 }
835 };
836 var init = function init() {
837 self.__construct.apply(self, instanceParams);
838 ensureClosureMethods();
839 initSettings();
840 self.trigger('init');
841 };
842 this.getItems = function (items, itemKey) {
843 if (itemKey) {
844 var keyStack = itemKey.split('.'),
845 currentKey = keyStack.splice(0, 1);
846 if (!keyStack.length) {
847 return items[currentKey];
848 }
849 if (!items[currentKey]) {
850 return;
851 }
852 return this.getItems(items[currentKey], keyStack.join('.'));
853 }
854 return items;
855 };
856 this.getSettings = function (setting) {
857 return this.getItems(settings, setting);
858 };
859 this.setSettings = function (settingKey, value, settingsContainer) {
860 if (!settingsContainer) {
861 settingsContainer = settings;
862 }
863 if ('object' === (0, _typeof2.default)(settingKey)) {
864 $.extend(settingsContainer, settingKey);
865 return self;
866 }
867 var keyStack = settingKey.split('.'),
868 currentKey = keyStack.splice(0, 1);
869 if (!keyStack.length) {
870 settingsContainer[currentKey] = value;
871 return self;
872 }
873 if (!settingsContainer[currentKey]) {
874 settingsContainer[currentKey] = {};
875 }
876 return self.setSettings(keyStack.join('.'), value, settingsContainer[currentKey]);
877 };
878 this.getErrorMessage = function (type, functionName) {
879 var message;
880 switch (type) {
881 case 'forceMethodImplementation':
882 message = "The method '".concat(functionName, "' must to be implemented in the inheritor child.");
883 break;
884 default:
885 message = 'An error occurs';
886 }
887 return message;
888 };
889
890 // TODO: This function should be deleted ?.
891 this.forceMethodImplementation = function (functionName) {
892 throw new Error(this.getErrorMessage('forceMethodImplementation', functionName));
893 };
894 this.on = function (eventName, callback) {
895 if ('object' === (0, _typeof2.default)(eventName)) {
896 $.each(eventName, function (singleEventName) {
897 self.on(singleEventName, this);
898 });
899 return self;
900 }
901 var eventNames = eventName.split(' ');
902 eventNames.forEach(function (singleEventName) {
903 if (!events[singleEventName]) {
904 events[singleEventName] = [];
905 }
906 events[singleEventName].push(callback);
907 });
908 return self;
909 };
910 this.off = function (eventName, callback) {
911 if (!events[eventName]) {
912 return self;
913 }
914 if (!callback) {
915 delete events[eventName];
916 return self;
917 }
918 var callbackIndex = events[eventName].indexOf(callback);
919 if (-1 !== callbackIndex) {
920 delete events[eventName][callbackIndex];
921
922 // Reset array index (for next off on same event).
923 events[eventName] = events[eventName].filter(function (val) {
924 return val;
925 });
926 }
927 return self;
928 };
929 this.trigger = function (eventName) {
930 var methodName = 'on' + eventName[0].toUpperCase() + eventName.slice(1),
931 params = Array.prototype.slice.call(arguments, 1);
932 if (self[methodName]) {
933 self[methodName].apply(self, params);
934 }
935 var callbacks = events[eventName];
936 if (!callbacks) {
937 return self;
938 }
939 $.each(callbacks, function (index, callback) {
940 callback.apply(self, params);
941 });
942 return self;
943 };
944 init();
945 };
946 Module.prototype.__construct = function () {};
947 Module.prototype.getDefaultSettings = function () {
948 return {};
949 };
950 Module.prototype.getConstructorID = function () {
951 return this.constructor.name;
952 };
953 Module.extend = function (properties) {
954 var $ = jQuery,
955 parent = this;
956 var child = function child() {
957 return parent.apply(this, arguments);
958 };
959 $.extend(child, parent);
960 child.prototype = Object.create($.extend({}, parent.prototype, properties));
961 child.prototype.constructor = child;
962 child.__super__ = parent.prototype;
963 return child;
964 };
965 module.exports = Module;
966
967 /***/ }),
968
969 /***/ "../assets/dev/js/utils/notifications.js":
970 /*!***********************************************!*\
971 !*** ../assets/dev/js/utils/notifications.js ***!
972 \***********************************************/
973 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
974
975 "use strict";
976
977
978 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
979 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
980 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
981 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
982 module.exports = elementorModules.Module.extend({
983 initToast: function initToast() {
984 var toast = elementorCommon.dialogsManager.createWidget('buttons', {
985 id: 'elementor-toast',
986 position: {
987 my: 'center bottom',
988 at: 'center bottom-10',
989 of: '#elementor-panel-inner',
990 autoRefresh: true
991 },
992 hide: {
993 onClick: true,
994 auto: true,
995 autoDelay: 10000
996 },
997 effects: {
998 show: function show() {
999 var $widget = toast.getElements('widget');
1000 $widget.show();
1001 toast.refreshPosition();
1002 var top = parseInt($widget.css('top'), 10);
1003 $widget.hide().css('top', top + 100);
1004 $widget.animate({
1005 opacity: 'show',
1006 height: 'show',
1007 paddingBottom: 'show',
1008 paddingTop: 'show',
1009 top: top
1010 }, {
1011 easing: 'linear',
1012 duration: 300
1013 });
1014 },
1015 hide: function hide() {
1016 var $widget = toast.getElements('widget'),
1017 top = parseInt($widget.css('top'), 10);
1018 $widget.animate({
1019 opacity: 'hide',
1020 height: 'hide',
1021 paddingBottom: 'hide',
1022 paddingTop: 'hide',
1023 top: top + 100
1024 }, {
1025 easing: 'linear',
1026 duration: 300
1027 });
1028 }
1029 },
1030 button: {
1031 tag: 'button'
1032 }
1033 });
1034
1035 // Add role="status" and aria-live for screen reader announcement
1036 toast.getElements('widget').attr({
1037 role: 'status',
1038 'aria-live': 'polite',
1039 'aria-atomic': 'true'
1040 });
1041 this.getToast = function () {
1042 return toast;
1043 };
1044 },
1045 showToast: function showToast(options) {
1046 var toast = this.getToast();
1047 toast.setMessage(options.message);
1048 toast.getElements('buttonsWrapper').empty();
1049 toast.focusedButton = null;
1050 toast.buttons = [];
1051 var isPositionValid = this.isPositionValid(options === null || options === void 0 ? void 0 : options.position);
1052 if (!isPositionValid) {
1053 this.positionToWindow();
1054 }
1055 if (options !== null && options !== void 0 && options.position && isPositionValid) {
1056 toast.setSettings('position', options.position);
1057 }
1058 if (options.buttons) {
1059 options.buttons.forEach(function (button) {
1060 toast.addButton(button);
1061 });
1062 }
1063 if (options.classes) {
1064 toast.getElements('widget').addClass(options.classes);
1065 }
1066 if (options.sticky) {
1067 toast.setSettings({
1068 hide: {
1069 auto: false,
1070 onClick: false
1071 }
1072 });
1073 }
1074 return toast.show();
1075 },
1076 isPositionValid: function isPositionValid(position) {
1077 var _position$of;
1078 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;
1079 if (!positionToCheck) {
1080 return false;
1081 }
1082 return !!document.querySelector(positionToCheck);
1083 },
1084 positionToWindow: function positionToWindow() {
1085 var toast = this.getToast();
1086 var position = _objectSpread(_objectSpread({}, toast.getSettings('position')), {}, {
1087 my: 'right top',
1088 at: 'right-10 top+42',
1089 // 42px is the default admin bar height + 10px
1090 of: ''
1091 });
1092 toast.setSettings('position', position);
1093 toast.getElements('widget').addClass('dialog-position-window');
1094 },
1095 onInit: function onInit() {
1096 this.initToast();
1097 }
1098 });
1099
1100 /***/ }),
1101
1102 /***/ "../assets/dev/js/utils/tiers.js":
1103 /*!***************************************!*\
1104 !*** ../assets/dev/js/utils/tiers.js ***!
1105 \***************************************/
1106 /***/ ((__unused_webpack_module, exports) => {
1107
1108 "use strict";
1109
1110
1111 Object.defineProperty(exports, "__esModule", ({
1112 value: true
1113 }));
1114 exports.isTierAtLeast = exports.TIERS_PRIORITY = exports.TIERS = void 0;
1115 var TIERS_PRIORITY = exports.TIERS_PRIORITY = Object.freeze(['free', 'essential', 'essential-oct2023', 'advanced', 'expert', 'agency']);
1116
1117 /**
1118 * @type {Readonly<{
1119 * free: string;
1120 * essential: string;
1121 * 'essential-oct2023': string;
1122 * advanced: string;
1123 * expert: string;
1124 * agency: string;
1125 * }>}
1126 */
1127 var TIERS = exports.TIERS = Object.freeze(TIERS_PRIORITY.reduce(function (acc, tier) {
1128 acc[tier] = tier;
1129 return acc;
1130 }, {}));
1131 var isTierAtLeast = exports.isTierAtLeast = function isTierAtLeast(currentTier, expectedTier) {
1132 var currentTierIndex = TIERS_PRIORITY.indexOf(currentTier);
1133 var expectedTierIndex = TIERS_PRIORITY.indexOf(expectedTier);
1134 if (-1 === currentTierIndex || -1 === expectedTierIndex) {
1135 return false;
1136 }
1137 return currentTierIndex >= expectedTierIndex;
1138 };
1139
1140 /***/ }),
1141
1142 /***/ "../assets/dev/js/utils/time.js":
1143 /*!**************************************!*\
1144 !*** ../assets/dev/js/utils/time.js ***!
1145 \**************************************/
1146 /***/ ((__unused_webpack_module, exports) => {
1147
1148 "use strict";
1149
1150
1151 Object.defineProperty(exports, "__esModule", ({
1152 value: true
1153 }));
1154 exports["default"] = getUserTimestamp;
1155 /**
1156 * Returns the timestamp in ISO8601 format with the UTC timezone offset.
1157 *
1158 * @since 3.6.0
1159 *
1160 * @param {Date} date
1161 * @return {Date} timestamp
1162 */
1163 function getUserTimestamp() {
1164 var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
1165 var timezoneOffset = date.getTimezoneOffset();
1166
1167 // Local time for the user
1168 var UTCTimestamp = new Date(date.getTime() - timezoneOffset * 60000).toISOString();
1169
1170 // Remove the Z suffix from the string.
1171 UTCTimestamp = UTCTimestamp.slice(0, -1);
1172
1173 // Create the offset string in the format `+HH:00` (or minus (-) prefix for negative offset instead of plus)
1174 var decimalTimezoneOffset = timezoneOffset / 60,
1175 // Negative offsets include a '-' sign in the getTimezoneOffset value, positive values need a '+' prefix (ISO8601).
1176 sign = 0 <= decimalTimezoneOffset ? '+' : '-',
1177 hours = Math.abs(Math.floor(decimalTimezoneOffset)),
1178 minutes = Math.abs(decimalTimezoneOffset % 1) * 60,
1179 addZeroToHour = 10 > hours ? '0' : '',
1180 addZeroToMinutes = 10 > minutes ? '0' : '';
1181 var formattedTimezoneOffset = sign + addZeroToHour + hours + ':' + addZeroToMinutes + minutes;
1182 return UTCTimestamp + formattedTimezoneOffset;
1183 }
1184
1185 /***/ }),
1186
1187 /***/ "../core/common/assets/js/components/wordpress/commands-data/index.js":
1188 /*!****************************************************************************!*\
1189 !*** ../core/common/assets/js/components/wordpress/commands-data/index.js ***!
1190 \****************************************************************************/
1191 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1192
1193 "use strict";
1194
1195
1196 Object.defineProperty(exports, "__esModule", ({
1197 value: true
1198 }));
1199 Object.defineProperty(exports, "Media", ({
1200 enumerable: true,
1201 get: function get() {
1202 return _media.Media;
1203 }
1204 }));
1205 var _media = __webpack_require__(/*! ./media */ "../core/common/assets/js/components/wordpress/commands-data/media.js");
1206
1207 /***/ }),
1208
1209 /***/ "../core/common/assets/js/components/wordpress/commands-data/media.js":
1210 /*!****************************************************************************!*\
1211 !*** ../core/common/assets/js/components/wordpress/commands-data/media.js ***!
1212 \****************************************************************************/
1213 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1214
1215 "use strict";
1216 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
1217
1218
1219 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1220 Object.defineProperty(exports, "__esModule", ({
1221 value: true
1222 }));
1223 exports.Media = void 0;
1224 var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "../node_modules/@babel/runtime/regenerator/index.js"));
1225 var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
1226 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1227 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1228 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1229 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1230 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
1231 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1232 var _commandData = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-data */ "../modules/web-cli/assets/js/modules/command-data.js"));
1233 var _filesUploadHandler = _interopRequireDefault(__webpack_require__(/*! elementor-editor/utils/files-upload-handler */ "../assets/dev/js/editor/utils/files-upload-handler.js"));
1234 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1235 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1236 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
1237 var Media = exports.Media = /*#__PURE__*/function (_CommandData) {
1238 function Media() {
1239 (0, _classCallCheck2.default)(this, Media);
1240 return _callSuper(this, Media, arguments);
1241 }
1242 (0, _inherits2.default)(Media, _CommandData);
1243 return (0, _createClass2.default)(Media, [{
1244 key: "validateArgs",
1245 value: function validateArgs() {
1246 this.requireArgumentInstance('file', File);
1247 }
1248 }, {
1249 key: "getRequestData",
1250 value: function getRequestData() {
1251 var requestData = _superPropGet(Media, "getRequestData", this, 3)([]);
1252 requestData.namespace = 'wp';
1253 requestData.version = '2';
1254 return requestData;
1255 }
1256 }, {
1257 key: "applyBeforeCreate",
1258 value: function applyBeforeCreate(args) {
1259 var _args$options;
1260 args.headers = {
1261 'Content-Disposition': "attachment; filename=".concat(this.file.name),
1262 'Content-Type': this.file.type
1263 };
1264 args.query = {
1265 uploadTypeCaller: 'elementor-wp-media-upload'
1266 };
1267 args.data = this.file;
1268 if ((_args$options = args.options) !== null && _args$options !== void 0 && _args$options.progress) {
1269 this.toast = elementor.notifications.showToast({
1270 // eslint-disable-next-line @wordpress/i18n-ellipsis
1271 message: __('Uploading...'),
1272 sticky: true
1273 });
1274 }
1275 return args;
1276 }
1277 }, {
1278 key: "applyAfterCreate",
1279 value: function applyAfterCreate(data, args) {
1280 var _args$options2;
1281 if ((_args$options2 = args.options) !== null && _args$options2 !== void 0 && _args$options2.progress) {
1282 this.toast.hide();
1283 }
1284 return data;
1285 }
1286 }, {
1287 key: "run",
1288 value: function () {
1289 var _run = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
1290 return _regenerator.default.wrap(function (_context) {
1291 while (1) switch (_context.prev = _context.next) {
1292 case 0:
1293 this.file = this.args.file;
1294 if (!(this.file.size > parseInt(window._wpPluploadSettings.defaults.filters.max_file_size, 10))) {
1295 _context.next = 1;
1296 break;
1297 }
1298 throw new Error(__('The file exceeds the maximum upload size for this site.', 'elementor'));
1299 case 1:
1300 if (!(!window._wpPluploadSettings.defaults.filters.mime_types[0].extensions.split(',').includes(this.file.name.split('.').pop()) && !elementor.config.filesUpload.unfilteredFiles)) {
1301 _context.next = 2;
1302 break;
1303 }
1304 _filesUploadHandler.default.getUnfilteredFilesNotEnabledDialog(function () {}).show();
1305 return _context.abrupt("return");
1306 case 2:
1307 _context.next = 3;
1308 return _superPropGet(Media, "run", this, 3)([]);
1309 case 3:
1310 return _context.abrupt("return", _context.sent);
1311 case 4:
1312 case "end":
1313 return _context.stop();
1314 }
1315 }, _callee, this);
1316 }));
1317 function run() {
1318 return _run.apply(this, arguments);
1319 }
1320 return run;
1321 }()
1322 }], [{
1323 key: "getEndpointFormat",
1324 value: function getEndpointFormat() {
1325 // 'wp/media' to 'media' since `requestData.namespace` is 'wp'.
1326 return 'media';
1327 }
1328 }]);
1329 }(_commandData.default);
1330
1331 /***/ }),
1332
1333 /***/ "../core/common/assets/js/components/wordpress/component.js":
1334 /*!******************************************************************!*\
1335 !*** ../core/common/assets/js/components/wordpress/component.js ***!
1336 \******************************************************************/
1337 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1338
1339 "use strict";
1340
1341
1342 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1343 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
1344 Object.defineProperty(exports, "__esModule", ({
1345 value: true
1346 }));
1347 exports["default"] = void 0;
1348 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1349 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1350 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1351 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1352 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1353 var _componentBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
1354 var dataCommands = _interopRequireWildcard(__webpack_require__(/*! ./commands-data/ */ "../core/common/assets/js/components/wordpress/commands-data/index.js"));
1355 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
1356 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1357 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1358 var Component = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
1359 function Component() {
1360 (0, _classCallCheck2.default)(this, Component);
1361 return _callSuper(this, Component, arguments);
1362 }
1363 (0, _inherits2.default)(Component, _ComponentBase);
1364 return (0, _createClass2.default)(Component, [{
1365 key: "getNamespace",
1366 value: function getNamespace() {
1367 return 'wp';
1368 }
1369 }, {
1370 key: "defaultData",
1371 value: function defaultData() {
1372 return this.importCommands(dataCommands);
1373 }
1374 }]);
1375 }(_componentBase.default);
1376
1377 /***/ }),
1378
1379 /***/ "../core/common/assets/js/utils/debug.js":
1380 /*!***********************************************!*\
1381 !*** ../core/common/assets/js/utils/debug.js ***!
1382 \***********************************************/
1383 /***/ ((module) => {
1384
1385 "use strict";
1386
1387
1388 // Moved from assets/dev/js/editor/utils
1389 var Debug = function Debug() {
1390 var self = this,
1391 errorStack = [],
1392 settings = {},
1393 elements = {};
1394 var initSettings = function initSettings() {
1395 settings = {
1396 debounceDelay: 500,
1397 urlsToWatch: ['elementor/assets']
1398 };
1399 };
1400 var initElements = function initElements() {
1401 elements.$window = jQuery(window);
1402 };
1403 var onError = function onError(event) {
1404 var _event$originalEvent;
1405 var error = (_event$originalEvent = event.originalEvent) === null || _event$originalEvent === void 0 ? void 0 : _event$originalEvent.error;
1406 if (!error) {
1407 return;
1408 }
1409 var isInWatchList = false,
1410 urlsToWatch = settings.urlsToWatch;
1411 jQuery.each(urlsToWatch, function () {
1412 if (-1 !== error.stack.indexOf(this)) {
1413 isInWatchList = true;
1414 return false;
1415 }
1416 });
1417 if (!isInWatchList) {
1418 return;
1419 }
1420 self.addError({
1421 type: error.name,
1422 message: error.message,
1423 url: event.originalEvent.filename,
1424 line: event.originalEvent.lineno,
1425 column: event.originalEvent.colno
1426 });
1427 };
1428 var bindEvents = function bindEvents() {
1429 elements.$window.on('error', onError);
1430 };
1431 var init = function init() {
1432 initSettings();
1433 initElements();
1434 bindEvents();
1435 self.sendErrors = _.debounce(self.sendErrors, settings.debounceDelay);
1436 };
1437 this.addURLToWatch = function (url) {
1438 settings.urlsToWatch.push(url);
1439 };
1440 this.addCustomError = function (error, category, tag) {
1441 var errorInfo = {
1442 type: error.name,
1443 message: error.message,
1444 url: error.fileName || error.sourceURL,
1445 line: error.lineNumber || error.line,
1446 column: error.columnNumber || error.column,
1447 customFields: {
1448 category: category || 'general',
1449 tag: tag
1450 }
1451 };
1452 if (!errorInfo.url) {
1453 var stackInfo = error.stack.match(/\n {4}at (.*?(?=:(\d+):(\d+)))/);
1454 if (stackInfo) {
1455 errorInfo.url = stackInfo[1];
1456 errorInfo.line = stackInfo[2];
1457 errorInfo.column = stackInfo[3];
1458 }
1459 }
1460 this.addError(errorInfo);
1461 };
1462 this.addError = function (errorParams) {
1463 var defaultParams = {
1464 type: 'Error',
1465 timestamp: Math.floor(new Date().getTime() / 1000),
1466 message: null,
1467 url: null,
1468 line: null,
1469 column: null,
1470 customFields: {}
1471 };
1472 errorStack.push(jQuery.extend(true, defaultParams, errorParams));
1473 self.sendErrors();
1474 };
1475 this.sendErrors = function () {
1476 // Avoid recursions on errors in ajax
1477 elements.$window.off('error', onError);
1478 jQuery.ajax({
1479 url: elementorCommon.config.ajax.url,
1480 method: 'POST',
1481 data: {
1482 action: 'elementor_js_log',
1483 _nonce: elementorCommon.ajax.getSettings('nonce'),
1484 data: errorStack
1485 },
1486 success: function success() {
1487 errorStack = [];
1488
1489 // Restore error handler
1490 elements.$window.on('error', onError);
1491 }
1492 });
1493 };
1494 init();
1495 };
1496 module.exports = Debug;
1497
1498 /***/ }),
1499
1500 /***/ "../core/common/assets/js/utils/helpers.js":
1501 /*!*************************************************!*\
1502 !*** ../core/common/assets/js/utils/helpers.js ***!
1503 \*************************************************/
1504 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1505
1506 "use strict";
1507
1508
1509 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1510 Object.defineProperty(exports, "__esModule", ({
1511 value: true
1512 }));
1513 exports["default"] = void 0;
1514 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1515 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1516 var Helpers = exports["default"] = /*#__PURE__*/function () {
1517 function Helpers() {
1518 (0, _classCallCheck2.default)(this, Helpers);
1519 }
1520 return (0, _createClass2.default)(Helpers, [{
1521 key: "consoleWarn",
1522 value:
1523 /**
1524 * @param {*} args
1525 * @deprecated since 3.7.0, use `elementorDevTools.consoleWarn()` instead.
1526 */
1527 function consoleWarn() {
1528 var _elementorDevTools;
1529 (_elementorDevTools = elementorDevTools).consoleWarn.apply(_elementorDevTools, arguments);
1530
1531 // This is is self is deprecated.
1532 elementorDevTools.deprecation.deprecated('elementorCommon.helpers.consoleWarn()', '3.7.0', 'elementorDevTools.consoleWarn()');
1533 }
1534
1535 /**
1536 * @param {string} message
1537 * @deprecated since 3.7.0, use `console.error()` instead.
1538 */
1539 }, {
1540 key: "consoleError",
1541 value: function consoleError(message) {
1542 // eslint-disable-next-line no-console
1543 console.error(message);
1544
1545 // This is is self is deprecated.
1546 elementorDevTools.deprecation.deprecated('elementorCommon.helpers.consoleError()', '3.7.0', 'console.error()');
1547 }
1548 }, {
1549 key: "cloneObject",
1550 value: function cloneObject(object) {
1551 return JSON.parse(JSON.stringify(object));
1552 }
1553 }, {
1554 key: "upperCaseWords",
1555 value: function upperCaseWords(string) {
1556 return (string + '').replace(/^(.)|\s+(.)/g, function ($1) {
1557 return $1.toUpperCase();
1558 });
1559 }
1560 }, {
1561 key: "getUniqueId",
1562 value: function getUniqueId() {
1563 return Math.random().toString(16).substr(2, 7);
1564 }
1565 }]);
1566 }();
1567
1568 /***/ }),
1569
1570 /***/ "../core/common/assets/js/utils/storage.js":
1571 /*!*************************************************!*\
1572 !*** ../core/common/assets/js/utils/storage.js ***!
1573 \*************************************************/
1574 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1575
1576 "use strict";
1577
1578
1579 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1580 Object.defineProperty(exports, "__esModule", ({
1581 value: true
1582 }));
1583 exports["default"] = void 0;
1584 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1585 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1586 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1587 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1588 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1589 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1590 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1591 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
1592 function _default() {
1593 (0, _classCallCheck2.default)(this, _default);
1594 return _callSuper(this, _default, arguments);
1595 }
1596 (0, _inherits2.default)(_default, _elementorModules$Mod);
1597 return (0, _createClass2.default)(_default, [{
1598 key: "get",
1599 value: function get(key, options) {
1600 options = options || {};
1601 var storage;
1602 try {
1603 storage = options.session ? sessionStorage : localStorage;
1604 } catch (e) {
1605 return key ? undefined : {};
1606 }
1607 var elementorStorage = storage.getItem('elementor');
1608 if (elementorStorage) {
1609 elementorStorage = JSON.parse(elementorStorage);
1610 } else {
1611 elementorStorage = {};
1612 }
1613 if (!elementorStorage.__expiration) {
1614 elementorStorage.__expiration = {};
1615 }
1616 var expiration = elementorStorage.__expiration;
1617 var expirationToCheck = [];
1618 if (key) {
1619 if (expiration[key]) {
1620 expirationToCheck = [key];
1621 }
1622 } else {
1623 expirationToCheck = Object.keys(expiration);
1624 }
1625 var entryExpired = false;
1626 expirationToCheck.forEach(function (expirationKey) {
1627 if (new Date(expiration[expirationKey]) < new Date()) {
1628 delete elementorStorage[expirationKey];
1629 delete expiration[expirationKey];
1630 entryExpired = true;
1631 }
1632 });
1633 if (entryExpired) {
1634 this.save(elementorStorage, options.session);
1635 }
1636 if (key) {
1637 return elementorStorage[key];
1638 }
1639 return elementorStorage;
1640 }
1641 }, {
1642 key: "set",
1643 value: function set(key, value, options) {
1644 options = options || {};
1645 var elementorStorage = this.get(null, options);
1646 elementorStorage[key] = value;
1647 if (options.lifetimeInSeconds) {
1648 var date = new Date();
1649 date.setTime(date.getTime() + options.lifetimeInSeconds * 1000);
1650 elementorStorage.__expiration[key] = date.getTime();
1651 }
1652 this.save(elementorStorage, options.session);
1653 }
1654 }, {
1655 key: "save",
1656 value: function save(object, session) {
1657 var storage;
1658 try {
1659 storage = session ? sessionStorage : localStorage;
1660 } catch (e) {
1661 return;
1662 }
1663 storage.setItem('elementor', JSON.stringify(object));
1664 }
1665 }]);
1666 }(elementorModules.Module);
1667
1668 /***/ }),
1669
1670 /***/ "../core/common/modules/ajax/assets/js/ajax.js":
1671 /*!*****************************************************!*\
1672 !*** ../core/common/modules/ajax/assets/js/ajax.js ***!
1673 \*****************************************************/
1674 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1675
1676 "use strict";
1677
1678
1679 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1680 Object.defineProperty(exports, "__esModule", ({
1681 value: true
1682 }));
1683 exports["default"] = void 0;
1684 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
1685 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1686 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1687 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1688 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1689 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1690 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1691 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1692 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
1693 function _default() {
1694 var _this;
1695 (0, _classCallCheck2.default)(this, _default);
1696 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1697 args[_key] = arguments[_key];
1698 }
1699 _this = _callSuper(this, _default, [].concat(args));
1700 _this.requests = {};
1701 _this.cache = {};
1702 _this.initRequestConstants();
1703 _this.debounceSendBatch = _.debounce(_this.sendBatch.bind(_this), 500);
1704 return _this;
1705 }
1706 (0, _inherits2.default)(_default, _elementorModules$Mod);
1707 return (0, _createClass2.default)(_default, [{
1708 key: "getDefaultSettings",
1709 value: function getDefaultSettings() {
1710 return {
1711 ajaxParams: {
1712 type: 'POST',
1713 url: elementorCommon.config.ajax.url,
1714 data: {},
1715 dataType: 'json'
1716 },
1717 actionPrefix: 'elementor_'
1718 };
1719 }
1720 }, {
1721 key: "initRequestConstants",
1722 value: function initRequestConstants() {
1723 this.requestConstants = {
1724 _nonce: this.getSettings('nonce')
1725 };
1726 }
1727 }, {
1728 key: "addRequestConstant",
1729 value: function addRequestConstant(key, value) {
1730 this.requestConstants[key] = value;
1731 }
1732 }, {
1733 key: "getCacheKey",
1734 value: function getCacheKey(request) {
1735 return JSON.stringify({
1736 unique_id: request.unique_id,
1737 data: request.data
1738 });
1739 }
1740 }, {
1741 key: "loadObjects",
1742 value: function loadObjects(options) {
1743 var _this2 = this;
1744 var dataCollection = {};
1745 var deferredArray = [];
1746 if (options.before) {
1747 options.before();
1748 }
1749 options.ids.forEach(function (objectId) {
1750 deferredArray.push(_this2.load({
1751 action: options.action,
1752 unique_id: options.data.unique_id + objectId,
1753 data: jQuery.extend({
1754 id: objectId
1755 }, options.data)
1756 }).done(function (data) {
1757 return dataCollection = jQuery.extend(dataCollection, data);
1758 }));
1759 });
1760 jQuery.when.apply(jQuery, deferredArray).done(function () {
1761 return options.success(dataCollection);
1762 });
1763 }
1764 }, {
1765 key: "load",
1766 value: function load(request, immediately) {
1767 var _this3 = this;
1768 if (!request.unique_id) {
1769 request.unique_id = request.action;
1770 }
1771 if (request.before) {
1772 request.before();
1773 }
1774 var deferred;
1775 var cacheKey = this.getCacheKey(request);
1776 if (_.has(this.cache, cacheKey)) {
1777 deferred = jQuery.Deferred().done(request.success).resolve(this.cache[cacheKey]);
1778 } else {
1779 var _request$error;
1780 deferred = this.addRequest(request.action, {
1781 data: request.data,
1782 unique_id: request.unique_id,
1783 success: function success(data) {
1784 return _this3.cache[cacheKey] = data;
1785 },
1786 error: (_request$error = request.error) !== null && _request$error !== void 0 ? _request$error : function () {}
1787 }, immediately).done(request.success);
1788 }
1789 return deferred;
1790 }
1791 }, {
1792 key: "cancelRequest",
1793 value: function cancelRequest(requestId) {
1794 var request = this.requests[requestId];
1795 if (!request) {
1796 return null;
1797 }
1798 if (request.options.deferred.jqXhr) {
1799 return request.options.deferred.jqXhr.abort('Request canceled');
1800 }
1801 if (request.options.deferred) {
1802 return request.options.deferred.reject('Request canceled');
1803 }
1804 }
1805 }, {
1806 key: "addRequest",
1807 value: function addRequest(action, options, immediately) {
1808 options = options || {};
1809 if (!options.unique_id) {
1810 options.unique_id = action;
1811 }
1812 options.deferred = jQuery.Deferred().done(options.success).fail(options.error).always(options.complete);
1813 var request = {
1814 action: action,
1815 options: options
1816 };
1817 if (immediately) {
1818 var requests = {};
1819 requests[options.unique_id] = request;
1820 options.deferred.jqXhr = this.sendBatch(requests);
1821 } else {
1822 this.requests[options.unique_id] = request;
1823 this.debounceSendBatch();
1824 }
1825 return options.deferred;
1826 }
1827 }, {
1828 key: "sendBatch",
1829 value: function sendBatch(requests) {
1830 var actions = {};
1831 if (!requests) {
1832 requests = this.requests;
1833
1834 // Empty for next batch.
1835 this.requests = {};
1836 }
1837 Object.entries(requests).forEach(function (_ref) {
1838 var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
1839 id = _ref2[0],
1840 request = _ref2[1];
1841 return actions[id] = {
1842 action: request.action,
1843 data: request.options.data
1844 };
1845 });
1846 return this.send('ajax', {
1847 data: {
1848 actions: JSON.stringify(actions)
1849 },
1850 success: function success(data) {
1851 Object.entries(data.responses).forEach(function (_ref3) {
1852 var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
1853 id = _ref4[0],
1854 response = _ref4[1];
1855 var options = requests[id].options;
1856 if (options) {
1857 if (response.success) {
1858 options.deferred.resolve(response.data);
1859 } else if (!response.success) {
1860 options.deferred.reject(response.data);
1861 }
1862 }
1863 });
1864 },
1865 error: function error(data) {
1866 return Object.values(requests).forEach(function (args) {
1867 if (args.options) {
1868 args.options.deferred.reject(data);
1869 }
1870 });
1871 }
1872 });
1873 }
1874 }, {
1875 key: "prepareSend",
1876 value: function prepareSend(action, options) {
1877 var _this4 = this;
1878 var settings = this.getSettings(),
1879 ajaxParams = elementorCommon.helpers.cloneObject(settings.ajaxParams);
1880 options = options || {};
1881 action = settings.actionPrefix + action;
1882 jQuery.extend(ajaxParams, options);
1883 var requestConstants = elementorCommon.helpers.cloneObject(this.requestConstants);
1884 requestConstants.action = action;
1885 var isFormData = ajaxParams.data instanceof FormData;
1886 Object.entries(requestConstants).forEach(function (_ref5) {
1887 var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
1888 key = _ref6[0],
1889 value = _ref6[1];
1890 if (isFormData) {
1891 ajaxParams.data.append(key, value);
1892 } else {
1893 ajaxParams.data[key] = value;
1894 }
1895 });
1896 var successCallback = ajaxParams.success,
1897 errorCallback = ajaxParams.error;
1898 if (successCallback || errorCallback) {
1899 ajaxParams.success = function (response) {
1900 if (response.success && successCallback) {
1901 successCallback(response.data);
1902 }
1903 if (!response.success && errorCallback) {
1904 errorCallback(response.data);
1905 }
1906 };
1907 if (errorCallback) {
1908 ajaxParams.error = function (data) {
1909 return errorCallback(data);
1910 };
1911 } else {
1912 ajaxParams.error = function (xmlHttpRequest) {
1913 if (xmlHttpRequest.readyState || 'abort' !== xmlHttpRequest.statusText) {
1914 _this4.trigger('request:unhandledError', xmlHttpRequest);
1915 }
1916 };
1917 }
1918 }
1919 return ajaxParams;
1920 }
1921 }, {
1922 key: "send",
1923 value: function send(action, options) {
1924 return jQuery.ajax(this.prepareSend(action, options));
1925 }
1926 }, {
1927 key: "addRequestCache",
1928 value: function addRequestCache(request, data) {
1929 var cacheKey = this.getCacheKey(request);
1930 this.cache[cacheKey] = data;
1931 }
1932 }, {
1933 key: "invalidateCache",
1934 value: function invalidateCache(request) {
1935 var cacheKey = this.getCacheKey(request);
1936 delete this.cache[cacheKey];
1937 }
1938 }]);
1939 }(elementorModules.Module);
1940
1941 /***/ }),
1942
1943 /***/ "../core/common/modules/connect/assets/js/connect.js":
1944 /*!***********************************************************!*\
1945 !*** ../core/common/modules/connect/assets/js/connect.js ***!
1946 \***********************************************************/
1947 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1948
1949 "use strict";
1950 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
1951
1952
1953 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1954 Object.defineProperty(exports, "__esModule", ({
1955 value: true
1956 }));
1957 exports["default"] = void 0;
1958 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1959 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1960 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1961 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1962 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
1963 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1964 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
1965 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1966 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
1967 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Vie) {
1968 function _default() {
1969 (0, _classCallCheck2.default)(this, _default);
1970 return _callSuper(this, _default, arguments);
1971 }
1972 (0, _inherits2.default)(_default, _elementorModules$Vie);
1973 return (0, _createClass2.default)(_default, [{
1974 key: "addPopupPlugin",
1975 value: function addPopupPlugin() {
1976 var counter = 0;
1977 jQuery.fn.elementorConnect = function (options) {
1978 var _this = this;
1979 // Open the Connect Dialog in a popup window.
1980 if (options !== null && options !== void 0 && options.popup) {
1981 jQuery(this).on('click', function (event) {
1982 var _options$popup, _options$popup2;
1983 event.preventDefault();
1984 var width = ((_options$popup = options.popup) === null || _options$popup === void 0 ? void 0 : _options$popup.width) || 600,
1985 height = ((_options$popup2 = options.popup) === null || _options$popup2 === void 0 ? void 0 : _options$popup2.height) || 700;
1986 window.open(jQuery(_this).attr('href') + '&mode=popup', 'elementorConnect', "toolbar=no, menubar=no, width=".concat(width, ", height=").concat(height, ", top=200, left=0"));
1987 });
1988 delete options.popup;
1989 }
1990 var settings = jQuery.extend({
1991 // These are the defaults.
1992 success: function success() {
1993 return location.reload();
1994 },
1995 error: function error() {
1996 elementor.notifications.showToast({
1997 message: __('Unable to connect', 'elementor')
1998 });
1999 },
2000 parseUrl: function parseUrl(url) {
2001 return url;
2002 } // Allow to change the url, e.g: replace placeholders like '%%template_type%%' with actual value.
2003 }, options);
2004 this.each(function () {
2005 counter++;
2006 var $this = jQuery(this),
2007 callbackId = 'cb' + counter;
2008 $this.attr({
2009 target: '_blank',
2010 rel: 'opener',
2011 href: settings.parseUrl($this.attr('href') + '&mode=popup&callback_id=' + callbackId)
2012 });
2013 elementorCommon.elements.$window.on('elementor/connect/success/' + callbackId, settings.success).on('elementor/connect/error/' + callbackId, settings.error);
2014 });
2015 return this;
2016 };
2017 }
2018 }, {
2019 key: "getDefaultSettings",
2020 value: function getDefaultSettings() {
2021 return {
2022 selectors: {
2023 connectButton: '#elementor-template-library-connect__button'
2024 }
2025 };
2026 }
2027 }, {
2028 key: "getDefaultElements",
2029 value: function getDefaultElements() {
2030 return {
2031 $connectButton: jQuery(this.getSettings('selectors.connectButton'))
2032 };
2033 }
2034 }, {
2035 key: "applyPopup",
2036 value: function applyPopup() {
2037 this.elements.$connectButton.elementorConnect();
2038 }
2039 }, {
2040 key: "onInit",
2041 value: function onInit() {
2042 _superPropGet(_default, "onInit", this, 3)([]);
2043 this.addPopupPlugin();
2044 this.applyPopup();
2045 }
2046 }]);
2047 }(elementorModules.ViewModule);
2048
2049 /***/ }),
2050
2051 /***/ "../core/common/modules/event-tracker/assets/js/data/commands-data/index.js":
2052 /*!**********************************************************************************!*\
2053 !*** ../core/common/modules/event-tracker/assets/js/data/commands-data/index.js ***!
2054 \**********************************************************************************/
2055 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2056
2057 "use strict";
2058
2059
2060 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2061 Object.defineProperty(exports, "__esModule", ({
2062 value: true
2063 }));
2064 exports.Index = void 0;
2065 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2066 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2067 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2068 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2069 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2070 var _commandData = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-data */ "../modules/web-cli/assets/js/modules/command-data.js"));
2071 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2072 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2073 var Index = exports.Index = /*#__PURE__*/function (_CommandData) {
2074 function Index() {
2075 (0, _classCallCheck2.default)(this, Index);
2076 return _callSuper(this, Index, arguments);
2077 }
2078 (0, _inherits2.default)(Index, _CommandData);
2079 return (0, _createClass2.default)(Index, null, [{
2080 key: "getEndpointFormat",
2081 value: function getEndpointFormat() {
2082 return 'send-event';
2083 }
2084 }]);
2085 }(_commandData.default);
2086
2087 /***/ }),
2088
2089 /***/ "../core/common/modules/event-tracker/assets/js/data/component.js":
2090 /*!************************************************************************!*\
2091 !*** ../core/common/modules/event-tracker/assets/js/data/component.js ***!
2092 \************************************************************************/
2093 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2094
2095 "use strict";
2096
2097
2098 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2099 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2100 Object.defineProperty(exports, "__esModule", ({
2101 value: true
2102 }));
2103 exports["default"] = void 0;
2104 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2105 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2106 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2107 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2108 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2109 var _componentBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
2110 var commandsData = _interopRequireWildcard(__webpack_require__(/*! ./commands-data/ */ "../core/common/modules/event-tracker/assets/js/data/commands-data/index.js"));
2111 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
2112 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2113 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2114 var Component = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
2115 function Component() {
2116 (0, _classCallCheck2.default)(this, Component);
2117 return _callSuper(this, Component, arguments);
2118 }
2119 (0, _inherits2.default)(Component, _ComponentBase);
2120 return (0, _createClass2.default)(Component, [{
2121 key: "getNamespace",
2122 value: function getNamespace() {
2123 return 'event-tracker';
2124 }
2125 }, {
2126 key: "defaultData",
2127 value: function defaultData() {
2128 return this.importCommands(commandsData);
2129 }
2130 }]);
2131 }(_componentBase.default);
2132
2133 /***/ }),
2134
2135 /***/ "../core/common/modules/event-tracker/assets/js/events.js":
2136 /*!****************************************************************!*\
2137 !*** ../core/common/modules/event-tracker/assets/js/events.js ***!
2138 \****************************************************************/
2139 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2140
2141 "use strict";
2142
2143
2144 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2145 Object.defineProperty(exports, "__esModule", ({
2146 value: true
2147 }));
2148 exports["default"] = void 0;
2149 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2150 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2151 var _time = _interopRequireDefault(__webpack_require__(/*! elementor-utils/time */ "../assets/dev/js/utils/time.js"));
2152 var Events = exports["default"] = /*#__PURE__*/function () {
2153 function Events() {
2154 (0, _classCallCheck2.default)(this, Events);
2155 }
2156 return (0, _createClass2.default)(Events, [{
2157 key: "dispatchEvent",
2158 value: function dispatchEvent(eventData) {
2159 if (!eventData) {
2160 return;
2161 }
2162 eventData.ts = (0, _time.default)();
2163
2164 // No need to wait for response, no need to block browser in any way.
2165 $e.data.create('event-tracker/index', {
2166 event_data: eventData
2167 });
2168 }
2169 }]);
2170 }();
2171
2172 /***/ }),
2173
2174 /***/ "../core/common/modules/events-manager/assets/js/events-config.js":
2175 /*!************************************************************************!*\
2176 !*** ../core/common/modules/events-manager/assets/js/events-config.js ***!
2177 \************************************************************************/
2178 /***/ ((__unused_webpack_module, exports) => {
2179
2180 "use strict";
2181
2182
2183 Object.defineProperty(exports, "__esModule", ({
2184 value: true
2185 }));
2186 exports["default"] = void 0;
2187 var eventsConfig = {
2188 appTypes: {
2189 editor: 'editor',
2190 wpAdmin: 'wpadmin',
2191 wpDash: 'wpdash'
2192 },
2193 targetTypes: {
2194 dropdownItem: 'dropdown_item',
2195 button: 'button',
2196 tab: 'tab',
2197 toggle: 'toggle',
2198 searchInput: 'search_input',
2199 searchResult: 'search_result',
2200 buttons: 'buttons',
2201 searchWidget: 'search_widget',
2202 wpDashAdminMenuItem: 'wpdash_admin_menu_item',
2203 wpDashEditorMenu: 'wpdash_editor_menu',
2204 wpDashSubMenuItem: 'wpdash_sub_menu_item'
2205 },
2206 interactionResults: {
2207 actionSelected: 'action_selected',
2208 navigate: 'navigate',
2209 create: 'create',
2210 sessionEnd: 'session_end',
2211 tabChanged: 'tab_changed',
2212 assetInserted: 'asset_inserted',
2213 assetFavorite: 'asset_favorite',
2214 aiGenerate: 'ai_generate',
2215 resultsUpdated: 'results_updated',
2216 noResults: 'no_results',
2217 selected: 'selected',
2218 promotionViewed: 'promotion_viewed',
2219 upgradeNow: 'upgrade_now',
2220 elementorSideMenuOpened: 'elementor_side_menu_opened',
2221 editorSubMenuOpened: 'wpdash_editor_sub_menu_opened',
2222 themeBuilderPromotionWindow: 'theme_builder_promotion_window'
2223 },
2224 targetNames: {
2225 publishDropdown: {
2226 saveDraft: 'save_draft',
2227 saveAsTemplate: 'save_as_template',
2228 viewPage: 'view_page',
2229 copyAndShare: 'copy_and_share'
2230 },
2231 pageList: {
2232 addNewPage: 'add_new_page'
2233 }
2234 },
2235 triggers: {
2236 click: 'Click',
2237 rightClick: 'Right Click',
2238 doubleClick: 'Double Click',
2239 accordionClick: 'Accordion Click',
2240 toggleClick: 'Toggle Click',
2241 dropdownClick: 'Click Dropdown',
2242 editorLoaded: 'Editor Loaded',
2243 visible: 'Visible',
2244 pageLoaded: 'Page Loaded',
2245 typing: 'Typing',
2246 tabSelect: 'Tab Select',
2247 insert: 'Insert',
2248 hover: 'Hover'
2249 },
2250 locations: {
2251 widgetPanel: 'Widget Panel',
2252 topBar: 'Top Bar',
2253 sidebar: 'Sidebar',
2254 elementorEditor: 'Elementor Editor',
2255 templatesLibrary: {
2256 library: 'Templates Library'
2257 },
2258 app: {
2259 import: 'Import Kit',
2260 export: 'Export Kit',
2261 kitLibrary: 'Kit Library',
2262 cloudKitLibrary: 'Cloud Kit Library'
2263 },
2264 variables: 'Variables Panel',
2265 variablesManager: 'Variables Manager',
2266 admin: 'WP admin',
2267 wpDashAdmin: 'wpdash_admin',
2268 structurePanel: 'Structure Panel',
2269 canvas: 'Canvas',
2270 leftPanel: 'Left Panel',
2271 elementorLibrary: 'Elementor Library',
2272 components: {
2273 instanceEditingPanel: 'Instance Editing Panel'
2274 }
2275 },
2276 secondaryLocations: {
2277 layout: 'Layout Section',
2278 basic: 'Basic Section',
2279 'pro-elements': 'Pro Section',
2280 general: 'General Section',
2281 'theme-elements': 'Site Section',
2282 'theme-elements-single': 'Single Section',
2283 'woocommerce-elements': 'WooCommerce Section',
2284 wordpress: 'WordPress Section',
2285 categories: 'Widgets Tab',
2286 global: 'Globals Tab',
2287 'whats-new': 'What\'s New',
2288 'document-settings': 'Document Settings icon',
2289 'preview-page': 'Preview Page',
2290 'publish-button': 'Publish Button',
2291 'widget-panel': 'Widget Panel Icon',
2292 finder: 'Finder',
2293 help: 'Help',
2294 elementorLogoDropdown: 'top_bar_elementor_logo_dropdown',
2295 elementorLogo: 'Elementor Logo',
2296 eLogoMenu: 'E-logo Menu',
2297 notes: 'Notes',
2298 siteSettings: 'Site Settings',
2299 structure: 'Structure',
2300 documentNameDropdown: 'Document Name dropdown',
2301 responsiveControls: 'Responsive controls',
2302 launchpad: 'launchpad',
2303 checklistHeader: 'Checklist Header',
2304 checklistSteps: 'Checklist Steps',
2305 userPreferences: 'User Preferences',
2306 contextMenu: 'Context Menu',
2307 templateLibrary: {
2308 saveModal: 'Save to Modal',
2309 moveModal: 'Move to Modal',
2310 bulkMoveModal: 'Bulk Move to Modal',
2311 copyModal: 'Copy to Modal',
2312 bulkCopyModal: 'Bulk Copy to Modal',
2313 saveModalSelectFolder: 'Save to Modal - select folder',
2314 saveModalSelectConnect: 'Save to Modal - connect',
2315 saveModalSelectUpgrade: 'Save to Modal - upgrade',
2316 importModal: 'Import Modal',
2317 newFolderModal: 'New Folder Modal',
2318 deleteDialog: 'Delete Dialog',
2319 deleteFolderDialog: 'Delete Folder Dialog',
2320 renameDialog: 'Rename Dialog',
2321 createFolderDialog: 'Create Folder Dialog',
2322 applySettingsDialog: 'Apply Settings Dialog',
2323 cloudTab: 'Cloud Tab',
2324 siteTab: 'Site Tab',
2325 cloudTabFolder: 'Cloud Tab - Folder',
2326 cloudTabConnect: 'Cloud Tab - Connect',
2327 cloudTabUpgrade: 'Cloud Tab - Upgrade',
2328 morePopup: 'Context Menu',
2329 quotaBar: 'Quota Bar'
2330 },
2331 kitLibrary: {
2332 cloudKitLibrary: 'kits_cloud_library',
2333 cloudKitLibraryConnect: 'kits_cloud_library_connect',
2334 cloudKitLibraryUpgrade: 'kits_cloud_library_upgrade',
2335 kitExportCustomization: 'kit_export_customization',
2336 kitExport: 'kit_export',
2337 kitExportCustomizationEdit: 'kit_export_customization_edit',
2338 kitExportSummary: 'kit_export_summary',
2339 kitImportUploadBox: 'kit_import_upload_box',
2340 kitImportCustomization: 'kit_import_customization',
2341 kitImportSummary: 'kit_import_summary'
2342 },
2343 variablesPopover: 'Variables Popover',
2344 admin: {
2345 pluginToolsTab: 'plugin_tools_tab',
2346 pluginWebsiteTemplatesTab: 'plugin_website_templates_tab'
2347 },
2348 componentsTab: 'Components Tab',
2349 canvasElement: 'Canvas Element',
2350 publishDropdown: 'Publish Dropdown',
2351 pageListDropdown: 'Page List Dropdown',
2352 emptyBox: 'Empty Box',
2353 searchBar: 'Search Bar',
2354 finderResults: 'Finder Results',
2355 libraryTabs: 'Library Tabs',
2356 assetCard: 'Asset Card',
2357 wpDashElementorCoreMenu: 'elementor_editor_core_menu',
2358 wpDashElementorCoreSubMenu: 'elementor_editor_core_sub_menu',
2359 wpDashThemeBuilder: 'wpdash_core_sub_menu_theme_builder'
2360 },
2361 elements: {
2362 accordionSection: 'Accordion section',
2363 buttonIcon: 'Button Icon',
2364 mainCta: 'Main CTA',
2365 button: 'Button',
2366 link: 'Link',
2367 dropdown: 'Dropdown',
2368 toggle: 'Toggle',
2369 launchpadChecklist: 'Checklist popup'
2370 },
2371 names: {
2372 v1: {
2373 layout: 'v1_widgets_tab_layout_section',
2374 basic: 'v1_widgets_tab_basic_section',
2375 'pro-elements': 'v1_widgets_tab_pro_section',
2376 general: 'v1_widgets_tab_general_section',
2377 'theme-elements': 'v1_widgets_tab_site_section',
2378 'theme-elements-single': 'v1_widgets_tab_single_section',
2379 'woocommerce-elements': 'v1_widgets_tab_woocommerce_section',
2380 wordpress: 'v1_widgets_tab_wordpress_section',
2381 categories: 'v1_widgets_tab',
2382 global: 'v1_globals_tab'
2383 },
2384 topBar: {
2385 whatsNew: 'top_bar_whats_new',
2386 documentSettings: 'top_bar_document_settings_icon',
2387 previewPage: 'top_bar_preview_page',
2388 publishButton: 'top_bar_publish_button',
2389 widgetPanel: 'top_bar_widget_panel_icon',
2390 finder: 'top_bar_finder',
2391 help: 'top_bar_help',
2392 history: 'top_bar_elementor_logo_dropdown_history',
2393 userPreferences: 'top_bar_elementor_logo_dropdown_user_preferences',
2394 keyboardShortcuts: 'top_bar_elementor_logo_dropdown_keyboard_shortcuts',
2395 exitToWordpress: 'top_bar_elementor_logo_dropdown_exit_to_wordpress',
2396 themeBuilder: 'top_bar_elementor_logo_dropdown_theme_builder',
2397 notes: 'top_bar_notes',
2398 siteSettings: 'top_bar_site_setting',
2399 structure: 'top_bar_structure',
2400 documentNameDropdown: 'top_bar_document_name_dropdown',
2401 responsiveControls: 'top_bar_responsive_controls',
2402 launchpadOn: 'top_bar_checklist_icon_show',
2403 launchpadOff: 'top_bar_checklist_icon_hide',
2404 elementorLogoDropdown: 'open_e_menu',
2405 connectAccount: 'connect_account',
2406 accountConnected: 'account_connected'
2407 },
2408 // ChecklistSteps event names are generated dynamically, based on stepId and action type taken: title, action, done, undone, upgrade
2409 elementorEditor: {
2410 editorLoaded: 'editor_loaded',
2411 checklist: {
2412 checklistHeaderClose: 'checklist_header_close_icon',
2413 checklistFirstPopup: 'checklist popup triggered'
2414 },
2415 userPreferences: {
2416 checklistShow: 'checklist_userpreferences_toggle_show',
2417 checklistHide: 'checklist_userpreferences_toggle_hide'
2418 }
2419 },
2420 variables: {
2421 open: 'open_variables_popover',
2422 add: 'add_new_variable',
2423 connect: 'connect_variable',
2424 save: 'save_new_variable',
2425 openManager: 'open_variables_manager',
2426 saveChanges: 'save_variables_changes',
2427 delete: 'delete_variable',
2428 variableSyncToV3: 'variable_sync_to_v3'
2429 },
2430 design_system: {
2431 importOpened: 'design_system_import_opened',
2432 fileSelected: 'design_system_file_selected',
2433 validationFailed: 'design_system_validation_failed',
2434 conflictChoice: 'design_system_conflict_choice',
2435 confirmed: 'design_system_import_confirmed',
2436 imported: 'design_system_imported',
2437 importFailed: 'design_system_import_failed',
2438 export: 'design_system_export',
2439 opened: 'design_system_opened'
2440 },
2441 components: {
2442 createClicked: 'component_create_clicked',
2443 createCancelled: 'component_creation_cancelled',
2444 created: 'component_created',
2445 instanceAdded: 'component_instance_added',
2446 edited: 'component_edited',
2447 propertiesPanelOpened: 'component_properties_panel_opened',
2448 propertiesGroupCreated: 'component_properties_group_created',
2449 propertyExposed: 'component_property_exposed',
2450 propertyRemoved: 'component_property_removed',
2451 detached: 'component_detached'
2452 },
2453 global_classes: {
2454 classApplied: 'class_applied',
2455 classRemoved: 'class_removed',
2456 classManagerFilterCleared: 'class_manager_filter_cleared',
2457 classDeleted: 'class_deleted',
2458 classPublishConflict: 'class_publish_conflict',
2459 classRenamed: 'class_renamed',
2460 classCreated: 'class_created',
2461 classManagerSearched: 'class_manager_searched',
2462 classManagerFiltersOpened: 'class_manager_filters_opened',
2463 classManagerOpened: 'class_manager_opened',
2464 classManagerReorder: 'class_manager_reorder',
2465 classManagerFilterUsed: 'class_manager_filter_used',
2466 classUsageLocate: 'class_usage_locate',
2467 classUsageHovered: 'class_usage_hovered',
2468 classStyled: 'class_styled',
2469 classStateClicked: 'class_state_clicked',
2470 classUsageClicked: 'class_usage_clicked',
2471 classDuplicate: 'class_duplicate',
2472 classSyncToV3PopupShown: 'class_sync_to_v3_popup_shown',
2473 classSyncToV3: 'class_sync_to_v3',
2474 classSyncToV3PopupClick: 'class_sync_to_v3_popup_click'
2475 },
2476 editorOne: {
2477 topBarPublishDropdown: 'top_bar_publish_dropdown',
2478 topBarPageList: 'top_bar_page_list',
2479 siteSettingsSession: 'site_settings_session',
2480 eLibraryNav: 'e_library_nav',
2481 eLibraryInsert: 'e_library_insert',
2482 eLibraryFavorite: 'e_library_favorite',
2483 eLibraryGenerateAi: 'e_library_generate_ai',
2484 finderSearchInput: 'finder_search_input',
2485 finderResultSelect: 'finder_result_select',
2486 canvasEmptyBoxAction: 'canvas_empty_box_action',
2487 widgetPanelSearch: 'widget_panel_search',
2488 wpDashElementorMenuClick: 'wpdash_elementor_menu_click',
2489 wpDashEditorSubMenuHover: 'wpdash_editor_sub_menu_hover',
2490 wpDashThemeBuilderClick: 'wpdash_theme_builder_click'
2491 },
2492 interactions: {
2493 created: 'interactions_created'
2494 },
2495 promotions: {
2496 viewPromotion: 'view_promotion',
2497 upgradePromotionClick: 'upgrade_promotion_click'
2498 }
2499 }
2500 };
2501 var _default = exports["default"] = eventsConfig;
2502
2503 /***/ }),
2504
2505 /***/ "../core/common/modules/events-manager/assets/js/module.js":
2506 /*!*****************************************************************!*\
2507 !*** ../core/common/modules/events-manager/assets/js/module.js ***!
2508 \*****************************************************************/
2509 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2510
2511 "use strict";
2512
2513
2514 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2515 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2516 Object.defineProperty(exports, "__esModule", ({
2517 value: true
2518 }));
2519 exports["default"] = void 0;
2520 var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "../node_modules/@babel/runtime/regenerator/index.js"));
2521 var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
2522 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2523 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2524 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2525 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2526 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2527 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
2528 var _eventsConfig = _interopRequireDefault(__webpack_require__(/*! ./events-config */ "../core/common/modules/events-manager/assets/js/events-config.js"));
2529 var _mixpanelBrowser = _interopRequireWildcard(__webpack_require__(/*! mixpanel-browser */ "../node_modules/mixpanel-browser/dist/mixpanel.module.js"));
2530 var _tiers = __webpack_require__(/*! elementor-utils/tiers */ "../assets/dev/js/utils/tiers.js");
2531 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t2 in e) "default" !== _t2 && {}.hasOwnProperty.call(e, _t2) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t2)) && (i.get || i.set) ? o(f, _t2, i) : f[_t2] = e[_t2]); return f; })(e, t); }
2532 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2533 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2534 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2535 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2536 /** @type {Mixpanel | null} */
2537 var mixpanelInstance = null;
2538 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
2539 function _default() {
2540 var _this;
2541 (0, _classCallCheck2.default)(this, _default);
2542 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2543 args[_key] = arguments[_key];
2544 }
2545 _this = _callSuper(this, _default, [].concat(args));
2546 (0, _defineProperty2.default)(_this, "trackingEnabled", false);
2547 (0, _defineProperty2.default)(_this, "availableExperiments", []);
2548 return _this;
2549 }
2550 (0, _inherits2.default)(_default, _elementorModules$Mod);
2551 return (0, _createClass2.default)(_default, [{
2552 key: "onInit",
2553 value: function onInit() {
2554 var _this2 = this;
2555 this.config = _eventsConfig.default;
2556 if (!this.canSendEvents()) {
2557 return;
2558 }
2559 this.initializeMixpanel(function () {
2560 return _this2.enableTracking();
2561 });
2562 }
2563 }, {
2564 key: "initializeMixpanel",
2565 value: function initializeMixpanel(onLoaded) {
2566 if (mixpanelInstance && mixpanelInstance.isInitialized) {
2567 onLoaded(mixpanelInstance);
2568 } else {
2569 var _elementorCommon$conf, _elementorCommon$conf2, _elementorCommon$conf3, _elementorCommon$conf4, _elementorCommon$conf5;
2570 mixpanelInstance = _mixpanelBrowser.default.init((_elementorCommon$conf = elementorCommon.config.editor_events) === null || _elementorCommon$conf === void 0 ? void 0 : _elementorCommon$conf.token, {
2571 persistence: 'localStorage',
2572 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,
2573 autocapture: false,
2574 flags: true,
2575 api_host: 'https://api-eu.mixpanel.com',
2576 loaded: onLoaded,
2577 record_sessions_percent: (_elementorCommon$conf4 = (_elementorCommon$conf5 = elementorCommon.config.editor_events) === null || _elementorCommon$conf5 === void 0 ? void 0 : _elementorCommon$conf5.session_recording_percent) !== null && _elementorCommon$conf4 !== void 0 ? _elementorCommon$conf4 : 0,
2578 record_idle_timeout_ms: 60 * 1000,
2579 // 60 Seconds
2580 record_min_ms: 5 * 1000,
2581 // 5 Seconds
2582 record_mask_text_selector: '',
2583 remote_settings_mode: 'strict'
2584 }, 'elementor-editor');
2585 }
2586 elementorCommon.config.editor_events.mixpanelInstance = mixpanelInstance;
2587 }
2588 }, {
2589 key: "enableTracking",
2590 value: function enableTracking() {
2591 var _elementorCommon$conf6;
2592 if (!this.isMixpanelReady()) {
2593 return;
2594 }
2595 var userId = (_elementorCommon$conf6 = elementorCommon.config.editor_events) === null || _elementorCommon$conf6 === void 0 ? void 0 : _elementorCommon$conf6.user_id;
2596 mixpanelInstance.register({
2597 appType: 'Editor'
2598 });
2599 if (userId) {
2600 var _elementorCommon$conf7;
2601 mixpanelInstance.identify(userId);
2602 mixpanelInstance.people.set_once({
2603 $user_id: userId,
2604 $last_login: new Date().toISOString(),
2605 $plan_type: ((_elementorCommon$conf7 = elementorCommon.config.library_connect) === null || _elementorCommon$conf7 === void 0 ? void 0 : _elementorCommon$conf7.plan_type) || _tiers.TIERS.free
2606 });
2607 }
2608 this.trackingEnabled = true;
2609 this.availableExperiments = Object.keys(elementorCommon.config.experimentalFeatures || {});
2610 }
2611 }, {
2612 key: "dispatchEvent",
2613 value: function dispatchEvent(name, data) {
2614 var _elementorCommon$conf8, _elementorCommon$conf9, _elementorCommon$conf0, _elementorCommon$conf1, _elementorCommon$conf10, _elementorCommon$conf11, _elementorCommon$conf12, _elementorCommon$conf13, _elementorCommon$conf14;
2615 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2616 if (!this.canSendEvents()) {
2617 return;
2618 }
2619 if (!this.trackingEnabled) {
2620 this.enableTracking();
2621 }
2622 var eventData = _objectSpread({
2623 user_id: ((_elementorCommon$conf8 = elementorCommon.config.editor_events) === null || _elementorCommon$conf8 === void 0 ? void 0 : _elementorCommon$conf8.user_id) || null,
2624 user_roles: ((_elementorCommon$conf9 = elementorCommon.config.library_connect) === null || _elementorCommon$conf9 === void 0 ? void 0 : _elementorCommon$conf9.user_roles) || [],
2625 subscription_id: ((_elementorCommon$conf0 = elementorCommon.config.editor_events) === null || _elementorCommon$conf0 === void 0 ? void 0 : _elementorCommon$conf0.subscription_id) || null,
2626 user_tier: ((_elementorCommon$conf1 = elementorCommon.config.library_connect) === null || _elementorCommon$conf1 === void 0 ? void 0 : _elementorCommon$conf1.current_access_tier) || null,
2627 url: (_elementorCommon$conf10 = elementorCommon.config.editor_events) === null || _elementorCommon$conf10 === void 0 ? void 0 : _elementorCommon$conf10.site_url,
2628 wp_version: (_elementorCommon$conf11 = elementorCommon.config.editor_events) === null || _elementorCommon$conf11 === void 0 ? void 0 : _elementorCommon$conf11.wp_version,
2629 client_id: (_elementorCommon$conf12 = elementorCommon.config.editor_events) === null || _elementorCommon$conf12 === void 0 ? void 0 : _elementorCommon$conf12.site_key,
2630 app_version: (_elementorCommon$conf13 = elementorCommon.config.editor_events) === null || _elementorCommon$conf13 === void 0 ? void 0 : _elementorCommon$conf13.elementor_version,
2631 site_language: (_elementorCommon$conf14 = elementorCommon.config.editor_events) === null || _elementorCommon$conf14 === void 0 ? void 0 : _elementorCommon$conf14.site_language,
2632 experiments: this.availableExperiments
2633 }, data);
2634 mixpanelInstance.track(name, eventData, options);
2635 }
2636 }, {
2637 key: "featureFlagIsActive",
2638 value: function () {
2639 var _featureFlagIsActive = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(flagName) {
2640 var _mixpanelInstance;
2641 var isEnabled;
2642 return _regenerator.default.wrap(function (_context) {
2643 while (1) switch (_context.prev = _context.next) {
2644 case 0:
2645 if (!('function' !== typeof ((_mixpanelInstance = mixpanelInstance) === null || _mixpanelInstance === void 0 || (_mixpanelInstance = _mixpanelInstance.flags) === null || _mixpanelInstance === void 0 ? void 0 : _mixpanelInstance.is_enabled))) {
2646 _context.next = 1;
2647 break;
2648 }
2649 return _context.abrupt("return", false);
2650 case 1:
2651 _context.next = 2;
2652 return mixpanelInstance.flags.is_enabled(flagName, false);
2653 case 2:
2654 isEnabled = _context.sent;
2655 return _context.abrupt("return", true === isEnabled);
2656 case 3:
2657 case "end":
2658 return _context.stop();
2659 }
2660 }, _callee);
2661 }));
2662 function featureFlagIsActive(_x) {
2663 return _featureFlagIsActive.apply(this, arguments);
2664 }
2665 return featureFlagIsActive;
2666 }()
2667 }, {
2668 key: "getExperimentVariant",
2669 value: function () {
2670 var _getExperimentVariant = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2(experimentName) {
2671 var defaultValue,
2672 _elementorCommon$conf15,
2673 _elementorCommon$conf16,
2674 isAbTestingEnabled,
2675 variant,
2676 _args2 = arguments,
2677 _t;
2678 return _regenerator.default.wrap(function (_context2) {
2679 while (1) switch (_context2.prev = _context2.next) {
2680 case 0:
2681 defaultValue = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 'control';
2682 _context2.prev = 1;
2683 if (this.canSendEvents()) {
2684 _context2.next = 2;
2685 break;
2686 }
2687 return _context2.abrupt("return", defaultValue);
2688 case 2:
2689 isAbTestingEnabled = (_elementorCommon$conf15 = (_elementorCommon$conf16 = elementorCommon.config.editor_events) === null || _elementorCommon$conf16 === void 0 ? void 0 : _elementorCommon$conf16.flags_enabled) !== null && _elementorCommon$conf15 !== void 0 ? _elementorCommon$conf15 : false;
2690 if (isAbTestingEnabled) {
2691 _context2.next = 3;
2692 break;
2693 }
2694 return _context2.abrupt("return", defaultValue);
2695 case 3:
2696 if (mixpanelInstance) {
2697 _context2.next = 4;
2698 break;
2699 }
2700 return _context2.abrupt("return", defaultValue);
2701 case 4:
2702 if (!this.trackingEnabled) {
2703 this.enableTracking();
2704 }
2705 if (mixpanelInstance.flags) {
2706 _context2.next = 5;
2707 break;
2708 }
2709 return _context2.abrupt("return", defaultValue);
2710 case 5:
2711 if (!('function' !== typeof mixpanelInstance.flags.get_variant_value)) {
2712 _context2.next = 6;
2713 break;
2714 }
2715 return _context2.abrupt("return", defaultValue);
2716 case 6:
2717 _context2.next = 7;
2718 return mixpanelInstance.flags.get_variant_value(experimentName, defaultValue);
2719 case 7:
2720 variant = _context2.sent;
2721 if (!(undefined === variant || null === variant)) {
2722 _context2.next = 8;
2723 break;
2724 }
2725 return _context2.abrupt("return", defaultValue);
2726 case 8:
2727 return _context2.abrupt("return", variant);
2728 case 9:
2729 _context2.prev = 9;
2730 _t = _context2["catch"](1);
2731 return _context2.abrupt("return", defaultValue);
2732 case 10:
2733 case "end":
2734 return _context2.stop();
2735 }
2736 }, _callee2, this, [[1, 9]]);
2737 }));
2738 function getExperimentVariant(_x2) {
2739 return _getExperimentVariant.apply(this, arguments);
2740 }
2741 return getExperimentVariant;
2742 }()
2743 }, {
2744 key: "startExperiment",
2745 value: function startExperiment(experimentName, experimentVariant) {
2746 if (!this.trackingEnabled) {
2747 return;
2748 }
2749 mixpanelInstance.track('$experiment_started', {
2750 'Experiment name': experimentName,
2751 'Variant name': experimentVariant
2752 });
2753 }
2754 }, {
2755 key: "isMixpanelReady",
2756 value: function isMixpanelReady() {
2757 if ('undefined' === typeof mixpanelInstance || !mixpanelInstance) {
2758 return false;
2759 }
2760 try {
2761 var distinctId = mixpanelInstance.get_distinct_id();
2762 return distinctId !== undefined && distinctId !== null;
2763 } catch (error) {
2764 return false;
2765 }
2766 }
2767 }, {
2768 key: "canSendEvents",
2769 value: function canSendEvents() {
2770 var _elementorCommon;
2771 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);
2772 }
2773 }, {
2774 key: "getMixpanelInstance",
2775 value: function getMixpanelInstance() {
2776 return this.isMixpanelReady() ? mixpanelInstance : undefined;
2777 }
2778 }]);
2779 }(elementorModules.Module);
2780
2781 /***/ }),
2782
2783 /***/ "../core/common/modules/finder/assets/js/commands/index.js":
2784 /*!*****************************************************************!*\
2785 !*** ../core/common/modules/finder/assets/js/commands/index.js ***!
2786 \*****************************************************************/
2787 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2788
2789 "use strict";
2790
2791
2792 Object.defineProperty(exports, "__esModule", ({
2793 value: true
2794 }));
2795 Object.defineProperty(exports, "NavigateDown", ({
2796 enumerable: true,
2797 get: function get() {
2798 return _navigateDown.NavigateDown;
2799 }
2800 }));
2801 Object.defineProperty(exports, "NavigateSelect", ({
2802 enumerable: true,
2803 get: function get() {
2804 return _navigateSelect.NavigateSelect;
2805 }
2806 }));
2807 Object.defineProperty(exports, "NavigateUp", ({
2808 enumerable: true,
2809 get: function get() {
2810 return _navigateUp.NavigateUp;
2811 }
2812 }));
2813 var _navigateDown = __webpack_require__(/*! ./navigate-down */ "../core/common/modules/finder/assets/js/commands/navigate-down.js");
2814 var _navigateSelect = __webpack_require__(/*! ./navigate-select */ "../core/common/modules/finder/assets/js/commands/navigate-select.js");
2815 var _navigateUp = __webpack_require__(/*! ./navigate-up */ "../core/common/modules/finder/assets/js/commands/navigate-up.js");
2816
2817 /***/ }),
2818
2819 /***/ "../core/common/modules/finder/assets/js/commands/navigate-down.js":
2820 /*!*************************************************************************!*\
2821 !*** ../core/common/modules/finder/assets/js/commands/navigate-down.js ***!
2822 \*************************************************************************/
2823 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2824
2825 "use strict";
2826
2827
2828 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2829 Object.defineProperty(exports, "__esModule", ({
2830 value: true
2831 }));
2832 exports["default"] = exports.NavigateDown = void 0;
2833 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2834 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2835 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2836 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2837 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2838 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2839 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2840 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2841 var NavigateDown = exports.NavigateDown = /*#__PURE__*/function (_CommandBase) {
2842 function NavigateDown() {
2843 (0, _classCallCheck2.default)(this, NavigateDown);
2844 return _callSuper(this, NavigateDown, arguments);
2845 }
2846 (0, _inherits2.default)(NavigateDown, _CommandBase);
2847 return (0, _createClass2.default)(NavigateDown, [{
2848 key: "apply",
2849 value: function apply() {
2850 this.component.getItemsView().activateNextItem();
2851 }
2852 }]);
2853 }(_commandBase.default);
2854 var _default = exports["default"] = NavigateDown;
2855
2856 /***/ }),
2857
2858 /***/ "../core/common/modules/finder/assets/js/commands/navigate-select.js":
2859 /*!***************************************************************************!*\
2860 !*** ../core/common/modules/finder/assets/js/commands/navigate-select.js ***!
2861 \***************************************************************************/
2862 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2863
2864 "use strict";
2865
2866
2867 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2868 Object.defineProperty(exports, "__esModule", ({
2869 value: true
2870 }));
2871 exports["default"] = exports.NavigateSelect = void 0;
2872 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2873 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2874 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2875 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2876 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2877 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2878 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2879 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2880 var NavigateSelect = exports.NavigateSelect = /*#__PURE__*/function (_CommandBase) {
2881 function NavigateSelect() {
2882 (0, _classCallCheck2.default)(this, NavigateSelect);
2883 return _callSuper(this, NavigateSelect, arguments);
2884 }
2885 (0, _inherits2.default)(NavigateSelect, _CommandBase);
2886 return (0, _createClass2.default)(NavigateSelect, [{
2887 key: "apply",
2888 value: function apply(args) {
2889 this.component.getItemsView().goToActiveItem(args);
2890 }
2891 }]);
2892 }(_commandBase.default);
2893 var _default = exports["default"] = NavigateSelect;
2894
2895 /***/ }),
2896
2897 /***/ "../core/common/modules/finder/assets/js/commands/navigate-up.js":
2898 /*!***********************************************************************!*\
2899 !*** ../core/common/modules/finder/assets/js/commands/navigate-up.js ***!
2900 \***********************************************************************/
2901 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2902
2903 "use strict";
2904
2905
2906 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2907 Object.defineProperty(exports, "__esModule", ({
2908 value: true
2909 }));
2910 exports["default"] = exports.NavigateUp = void 0;
2911 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2912 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2913 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2914 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2915 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2916 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2917 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2918 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2919 var NavigateUp = exports.NavigateUp = /*#__PURE__*/function (_CommandBase) {
2920 function NavigateUp() {
2921 (0, _classCallCheck2.default)(this, NavigateUp);
2922 return _callSuper(this, NavigateUp, arguments);
2923 }
2924 (0, _inherits2.default)(NavigateUp, _CommandBase);
2925 return (0, _createClass2.default)(NavigateUp, [{
2926 key: "apply",
2927 value: function apply() {
2928 this.component.getItemsView().activateNextItem(true);
2929 }
2930 }]);
2931 }(_commandBase.default);
2932 var _default = exports["default"] = NavigateUp;
2933
2934 /***/ }),
2935
2936 /***/ "../core/common/modules/finder/assets/js/component.js":
2937 /*!************************************************************!*\
2938 !*** ../core/common/modules/finder/assets/js/component.js ***!
2939 \************************************************************/
2940 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2941
2942 "use strict";
2943
2944
2945 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2946 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2947 Object.defineProperty(exports, "__esModule", ({
2948 value: true
2949 }));
2950 exports["default"] = void 0;
2951 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
2952 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2953 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2954 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2955 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2956 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
2957 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2958 var _componentModalBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-modal-base */ "../modules/web-cli/assets/js/modules/component-modal-base.js"));
2959 var _layout = _interopRequireDefault(__webpack_require__(/*! ./modal/views/layout */ "../core/common/modules/finder/assets/js/modal/views/layout.js"));
2960 var commands = _interopRequireWildcard(__webpack_require__(/*! ./commands/ */ "../core/common/modules/finder/assets/js/commands/index.js"));
2961 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
2962 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
2963 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2964 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
2965 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2966 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
2967 var Component = exports["default"] = /*#__PURE__*/function (_ComponentModalBase) {
2968 function Component() {
2969 (0, _classCallCheck2.default)(this, Component);
2970 return _callSuper(this, Component, arguments);
2971 }
2972 (0, _inherits2.default)(Component, _ComponentModalBase);
2973 return (0, _createClass2.default)(Component, [{
2974 key: "getNamespace",
2975 value: function getNamespace() {
2976 return 'finder';
2977 }
2978 }, {
2979 key: "defaultShortcuts",
2980 value: function defaultShortcuts() {
2981 var _this = this;
2982 return {
2983 '': {
2984 keys: 'ctrl+e'
2985 },
2986 'navigate-down': {
2987 keys: 'down',
2988 scopes: [this.getNamespace()],
2989 dependency: function dependency() {
2990 return _this.getItemsView();
2991 }
2992 },
2993 'navigate-up': {
2994 keys: 'up',
2995 scopes: [this.getNamespace()],
2996 dependency: function dependency() {
2997 return _this.getItemsView();
2998 }
2999 },
3000 'navigate-select': {
3001 keys: 'enter',
3002 scopes: [this.getNamespace()],
3003 dependency: function dependency() {
3004 return _this.getItemsView().$activeItem;
3005 }
3006 }
3007 };
3008 }
3009 }, {
3010 key: "defaultCommands",
3011 value: function defaultCommands() {
3012 var modalCommands = _superPropGet(Component, "defaultCommands", this, 3)([]);
3013 return _objectSpread(_objectSpread({
3014 'navigate/down': function navigate_down() {
3015 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/down' )", '3.0.0', "$e.run( 'finder/navigate-down' )");
3016 $e.run('finder/navigate-down');
3017 },
3018 'navigate/up': function navigate_up() {
3019 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/up' )", '3.0.0', "$e.run( 'finder/navigate-up' )");
3020 $e.run('finder/navigate-up');
3021 },
3022 'navigate/select': function navigate_select(event) {
3023 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/select', event )", '3.0.0', "$e.run( 'finder/navigate-select', event )");
3024
3025 // TODO: Fix $e.shortcuts use args. ( args.event ).
3026 $e.run('finder/navigate-select', event);
3027 }
3028 }, modalCommands), this.importCommands(commands));
3029 }
3030 }, {
3031 key: "getModalLayout",
3032 value: function getModalLayout() {
3033 return _layout.default;
3034 }
3035 }, {
3036 key: "getItemsView",
3037 value: function getItemsView() {
3038 return this.layout.modalContent.currentView.content.currentView;
3039 }
3040 }]);
3041 }(_componentModalBase.default);
3042
3043 /***/ }),
3044
3045 /***/ "../core/common/modules/finder/assets/js/finder.js":
3046 /*!*********************************************************!*\
3047 !*** ../core/common/modules/finder/assets/js/finder.js ***!
3048 \*********************************************************/
3049 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3050
3051 "use strict";
3052
3053
3054 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3055 Object.defineProperty(exports, "__esModule", ({
3056 value: true
3057 }));
3058 exports["default"] = void 0;
3059 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3060 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3061 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3062 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3063 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3064 var _component = _interopRequireDefault(__webpack_require__(/*! ./component */ "../core/common/modules/finder/assets/js/component.js"));
3065 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3066 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3067 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
3068 function _default() {
3069 (0, _classCallCheck2.default)(this, _default);
3070 return _callSuper(this, _default, arguments);
3071 }
3072 (0, _inherits2.default)(_default, _elementorModules$Mod);
3073 return (0, _createClass2.default)(_default, [{
3074 key: "onInit",
3075 value: function onInit() {
3076 // TODO: Temp fix, do not load finder in theme-builder.
3077 // Better to pass into '$e' constructor the app owner. ( admin, editor, preview, iframe ).
3078 if (window.top !== window) {
3079 return;
3080 }
3081 this.channel = Backbone.Radio.channel('ELEMENTOR:finder');
3082 $e.components.register(new _component.default({
3083 manager: this
3084 }));
3085 }
3086 }]);
3087 }(elementorModules.Module);
3088
3089 /***/ }),
3090
3091 /***/ "../core/common/modules/finder/assets/js/modal/model/item.js":
3092 /*!*******************************************************************!*\
3093 !*** ../core/common/modules/finder/assets/js/modal/model/item.js ***!
3094 \*******************************************************************/
3095 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3096
3097 "use strict";
3098
3099
3100 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3101 Object.defineProperty(exports, "__esModule", ({
3102 value: true
3103 }));
3104 exports["default"] = void 0;
3105 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3106 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3107 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3108 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3109 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3110 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3111 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3112 var _default = exports["default"] = /*#__PURE__*/function (_Backbone$Model) {
3113 function _default() {
3114 (0, _classCallCheck2.default)(this, _default);
3115 return _callSuper(this, _default, arguments);
3116 }
3117 (0, _inherits2.default)(_default, _Backbone$Model);
3118 return (0, _createClass2.default)(_default, [{
3119 key: "defaults",
3120 value: function defaults() {
3121 return {
3122 description: '',
3123 icon: 'settings',
3124 url: '',
3125 keywords: [],
3126 actions: [],
3127 lock: null
3128 };
3129 }
3130 }]);
3131 }(Backbone.Model);
3132
3133 /***/ }),
3134
3135 /***/ "../core/common/modules/finder/assets/js/modal/views/categories.js":
3136 /*!*************************************************************************!*\
3137 !*** ../core/common/modules/finder/assets/js/modal/views/categories.js ***!
3138 \*************************************************************************/
3139 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3140
3141 "use strict";
3142
3143
3144 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3145 Object.defineProperty(exports, "__esModule", ({
3146 value: true
3147 }));
3148 exports["default"] = void 0;
3149 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3150 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3151 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3152 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3153 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3154 var _category = _interopRequireDefault(__webpack_require__(/*! ./category */ "../core/common/modules/finder/assets/js/modal/views/category.js"));
3155 var _dynamicCategory = _interopRequireDefault(__webpack_require__(/*! ./dynamic-category */ "../core/common/modules/finder/assets/js/modal/views/dynamic-category.js"));
3156 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3157 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3158 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$Composite) {
3159 function _default() {
3160 (0, _classCallCheck2.default)(this, _default);
3161 return _callSuper(this, _default, arguments);
3162 }
3163 (0, _inherits2.default)(_default, _Marionette$Composite);
3164 return (0, _createClass2.default)(_default, [{
3165 key: "id",
3166 value: function id() {
3167 return 'elementor-finder__results-container';
3168 }
3169 }, {
3170 key: "ui",
3171 value: function ui() {
3172 this.selectors = {
3173 noResults: '#elementor-finder__no-results',
3174 categoryItem: '.elementor-finder__results__item'
3175 };
3176 return this.selectors;
3177 }
3178 }, {
3179 key: "events",
3180 value: function events() {
3181 return {
3182 'mouseenter @ui.categoryItem': 'onCategoryItemMouseEnter'
3183 };
3184 }
3185 }, {
3186 key: "getTemplate",
3187 value: function getTemplate() {
3188 return '#tmpl-elementor-finder-results-container';
3189 }
3190 }, {
3191 key: "getChildView",
3192 value: function getChildView(childModel) {
3193 return childModel.get('dynamic') ? _dynamicCategory.default : _category.default;
3194 }
3195 }, {
3196 key: "initialize",
3197 value: function initialize() {
3198 this.$activeItem = null;
3199 this.childViewContainer = '#elementor-finder__results';
3200 this.collection = new Backbone.Collection(Object.values(elementorCommon.finder.getSettings('data')));
3201 }
3202 }, {
3203 key: "activateItem",
3204 value: function activateItem($item) {
3205 if (this.$activeItem) {
3206 this.$activeItem.removeClass('elementor-active');
3207 }
3208 $item.addClass('elementor-active');
3209 this.$activeItem = $item;
3210 }
3211 }, {
3212 key: "activateNextItem",
3213 value: function activateNextItem(reverse) {
3214 var $allItems = jQuery(this.selectors.categoryItem);
3215 var nextItemIndex = 0;
3216 if (this.$activeItem) {
3217 nextItemIndex = $allItems.index(this.$activeItem) + (reverse ? -1 : 1);
3218 if (nextItemIndex >= $allItems.length) {
3219 nextItemIndex = 0;
3220 } else if (nextItemIndex < 0) {
3221 nextItemIndex = $allItems.length - 1;
3222 }
3223 }
3224 var $nextItem = $allItems.eq(nextItemIndex);
3225 this.activateItem($nextItem);
3226 $nextItem[0].scrollIntoView({
3227 block: 'nearest'
3228 });
3229 }
3230 }, {
3231 key: "goToActiveItem",
3232 value: function goToActiveItem(event) {
3233 var $a = this.$activeItem.children('a'),
3234 isControlClicked = $e.shortcuts.isControlEvent(event);
3235 if (isControlClicked) {
3236 $a.attr('target', '_blank');
3237 }
3238 $a[0].click();
3239 if (isControlClicked) {
3240 $a.removeAttr('target');
3241 }
3242 }
3243 }, {
3244 key: "onCategoryItemMouseEnter",
3245 value: function onCategoryItemMouseEnter(event) {
3246 this.activateItem(jQuery(event.currentTarget));
3247 }
3248 }, {
3249 key: "onChildviewToggleVisibility",
3250 value: function onChildviewToggleVisibility() {
3251 var allCategoriesAreEmpty = this.children.every(function (child) {
3252 return !child.isVisible;
3253 });
3254 this.ui.noResults.toggle(allCategoriesAreEmpty);
3255 }
3256 }]);
3257 }(Marionette.CompositeView);
3258
3259 /***/ }),
3260
3261 /***/ "../core/common/modules/finder/assets/js/modal/views/category.js":
3262 /*!***********************************************************************!*\
3263 !*** ../core/common/modules/finder/assets/js/modal/views/category.js ***!
3264 \***********************************************************************/
3265 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3266
3267 "use strict";
3268
3269
3270 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3271 Object.defineProperty(exports, "__esModule", ({
3272 value: true
3273 }));
3274 exports["default"] = void 0;
3275 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3276 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3277 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3278 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3279 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3280 var _item = _interopRequireDefault(__webpack_require__(/*! ./item */ "../core/common/modules/finder/assets/js/modal/views/item.js"));
3281 var _item2 = _interopRequireDefault(__webpack_require__(/*! ../model/item */ "../core/common/modules/finder/assets/js/modal/model/item.js"));
3282 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3283 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3284 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$Composite) {
3285 function _default() {
3286 (0, _classCallCheck2.default)(this, _default);
3287 return _callSuper(this, _default, arguments);
3288 }
3289 (0, _inherits2.default)(_default, _Marionette$Composite);
3290 return (0, _createClass2.default)(_default, [{
3291 key: "className",
3292 value: function className() {
3293 return 'elementor-finder__results__category';
3294 }
3295 }, {
3296 key: "getTemplate",
3297 value: function getTemplate() {
3298 return '#tmpl-elementor-finder__results__category';
3299 }
3300 }, {
3301 key: "getChildView",
3302 value: function getChildView() {
3303 return _item.default;
3304 }
3305 }, {
3306 key: "initialize",
3307 value: function initialize() {
3308 this.childViewContainer = '.elementor-finder__results__category__items';
3309 this.isVisible = true;
3310 var items = this.model.get('items');
3311 if (items) {
3312 items = Object.values(items);
3313 }
3314 this.collection = new Backbone.Collection(items, {
3315 model: _item2.default
3316 });
3317 }
3318 }, {
3319 key: "filter",
3320 value: function filter(childModel) {
3321 var textFilter = this.getTextFilter();
3322 if (childModel.get('title').toLowerCase().indexOf(textFilter) >= 0) {
3323 return true;
3324 }
3325 return childModel.get('keywords').some(function (keyword) {
3326 return keyword.indexOf(textFilter) >= 0;
3327 });
3328 }
3329 }, {
3330 key: "getTextFilter",
3331 value: function getTextFilter() {
3332 return elementorCommon.finder.channel.request('filter:text').trim().toLowerCase();
3333 }
3334 }, {
3335 key: "toggleElement",
3336 value: function toggleElement() {
3337 var isCurrentlyVisible = !!this.children.length;
3338 if (isCurrentlyVisible !== this.isVisible) {
3339 this.isVisible = isCurrentlyVisible;
3340 this.$el.toggle(isCurrentlyVisible);
3341 this.triggerMethod('toggle:visibility');
3342 }
3343 }
3344 }, {
3345 key: "onRender",
3346 value: function onRender() {
3347 this.listenTo(elementorCommon.finder.channel, 'filter:change', this.onFilterChange.bind(this));
3348 }
3349 }, {
3350 key: "onFilterChange",
3351 value: function onFilterChange() {
3352 this._renderChildren();
3353 }
3354 }, {
3355 key: "onRenderCollection",
3356 value: function onRenderCollection() {
3357 this.toggleElement();
3358 }
3359 }]);
3360 }(Marionette.CompositeView);
3361
3362 /***/ }),
3363
3364 /***/ "../core/common/modules/finder/assets/js/modal/views/content.js":
3365 /*!**********************************************************************!*\
3366 !*** ../core/common/modules/finder/assets/js/modal/views/content.js ***!
3367 \**********************************************************************/
3368 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3369
3370 "use strict";
3371
3372
3373 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3374 Object.defineProperty(exports, "__esModule", ({
3375 value: true
3376 }));
3377 exports["default"] = void 0;
3378 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3379 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3380 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3381 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3382 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3383 var _categories = _interopRequireDefault(__webpack_require__(/*! ./categories */ "../core/common/modules/finder/assets/js/modal/views/categories.js"));
3384 var _editorOneEvents = __webpack_require__(/*! elementor-editor-utils/editor-one-events */ "../assets/dev/js/editor/utils/editor-one-events.js");
3385 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3386 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3387 var FINDER_SEARCH_DEBOUNCE_MS = 300;
3388 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$LayoutVie) {
3389 function _default() {
3390 (0, _classCallCheck2.default)(this, _default);
3391 return _callSuper(this, _default, arguments);
3392 }
3393 (0, _inherits2.default)(_default, _Marionette$LayoutVie);
3394 return (0, _createClass2.default)(_default, [{
3395 key: "id",
3396 value: function id() {
3397 return 'elementor-finder';
3398 }
3399 }, {
3400 key: "getTemplate",
3401 value: function getTemplate() {
3402 return '#tmpl-elementor-finder';
3403 }
3404 }, {
3405 key: "ui",
3406 value: function ui() {
3407 return {
3408 searchInput: '#elementor-finder__search__input'
3409 };
3410 }
3411 }, {
3412 key: "events",
3413 value: function events() {
3414 return {
3415 'input @ui.searchInput': 'onSearchInputInput'
3416 };
3417 }
3418 }, {
3419 key: "regions",
3420 value: function regions() {
3421 return {
3422 content: '#elementor-finder__content'
3423 };
3424 }
3425 }, {
3426 key: "initialize",
3427 value: function initialize() {
3428 this.debouncedTrackSearch = (0, _editorOneEvents.createDebouncedFinderSearch)(FINDER_SEARCH_DEBOUNCE_MS);
3429 }
3430 }, {
3431 key: "showCategoriesView",
3432 value: function showCategoriesView() {
3433 this.content.show(new _categories.default());
3434 }
3435 }, {
3436 key: "getResultsCount",
3437 value: function getResultsCount() {
3438 if (!this.content.currentView) {
3439 return 0;
3440 }
3441 var $visibleItems = this.content.currentView.$el.find('.elementor-finder__results__item:visible');
3442 return $visibleItems.length;
3443 }
3444 }, {
3445 key: "onSearchInputInput",
3446 value: function onSearchInputInput() {
3447 var _this = this;
3448 var value = this.ui.searchInput.val();
3449 if (value) {
3450 elementorCommon.finder.channel.reply('filter:text', value).trigger('filter:change');
3451 if (!(this.content.currentView instanceof _categories.default)) {
3452 this.showCategoriesView();
3453 }
3454 setTimeout(function () {
3455 var resultsCount = _this.getResultsCount();
3456 _this.debouncedTrackSearch(resultsCount, value);
3457 }, 50);
3458 }
3459 this.content.currentView.$el.toggle(!!value);
3460 }
3461 }, {
3462 key: "onDestroy",
3463 value: function onDestroy() {
3464 var _this$debouncedTrackS;
3465 if ((_this$debouncedTrackS = this.debouncedTrackSearch) !== null && _this$debouncedTrackS !== void 0 && _this$debouncedTrackS.cancel) {
3466 this.debouncedTrackSearch.cancel();
3467 }
3468 }
3469 }]);
3470 }(Marionette.LayoutView);
3471
3472 /***/ }),
3473
3474 /***/ "../core/common/modules/finder/assets/js/modal/views/dynamic-category.js":
3475 /*!*******************************************************************************!*\
3476 !*** ../core/common/modules/finder/assets/js/modal/views/dynamic-category.js ***!
3477 \*******************************************************************************/
3478 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3479
3480 "use strict";
3481
3482
3483 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3484 Object.defineProperty(exports, "__esModule", ({
3485 value: true
3486 }));
3487 exports["default"] = void 0;
3488 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3489 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3490 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3491 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3492 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
3493 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3494 var _category = _interopRequireDefault(__webpack_require__(/*! ./category */ "../core/common/modules/finder/assets/js/modal/views/category.js"));
3495 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3496 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3497 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
3498 var _default = exports["default"] = /*#__PURE__*/function (_Category) {
3499 function _default() {
3500 (0, _classCallCheck2.default)(this, _default);
3501 return _callSuper(this, _default, arguments);
3502 }
3503 (0, _inherits2.default)(_default, _Category);
3504 return (0, _createClass2.default)(_default, [{
3505 key: "className",
3506 value: function className() {
3507 return _superPropGet(_default, "className", this, 3)([]) + ' elementor-finder__results__category--dynamic';
3508 }
3509 }, {
3510 key: "ui",
3511 value: function ui() {
3512 return {
3513 title: '.elementor-finder__results__category__title'
3514 };
3515 }
3516 }, {
3517 key: "fetchData",
3518 value: function fetchData() {
3519 var _this = this;
3520 this.ui.loadingIcon.show();
3521 elementorCommon.ajax.addRequest('finder_get_category_items', {
3522 data: {
3523 category: this.model.get('name'),
3524 filter: this.getTextFilter()
3525 },
3526 success: function success(data) {
3527 if (_this.isDestroyed) {
3528 return;
3529 }
3530 _this.collection.set(data);
3531 _this.toggleElement();
3532 _this.ui.loadingIcon.hide();
3533 }
3534 });
3535 }
3536 }, {
3537 key: "filter",
3538 value: function filter() {
3539 return true;
3540 }
3541 }, {
3542 key: "onFilterChange",
3543 value: function onFilterChange() {
3544 this.fetchData();
3545 }
3546 }, {
3547 key: "onRender",
3548 value: function onRender() {
3549 _superPropGet(_default, "onRender", this, 3)([]);
3550 this.ui.loadingIcon = jQuery('<i>', {
3551 class: 'eicon-loading eicon-animation-spin'
3552 });
3553 this.ui.title.after(this.ui.loadingIcon);
3554 this.fetchData();
3555 }
3556 }]);
3557 }(_category.default);
3558
3559 /***/ }),
3560
3561 /***/ "../core/common/modules/finder/assets/js/modal/views/item.js":
3562 /*!*******************************************************************!*\
3563 !*** ../core/common/modules/finder/assets/js/modal/views/item.js ***!
3564 \*******************************************************************/
3565 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3566
3567 "use strict";
3568 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
3569
3570
3571 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3572 Object.defineProperty(exports, "__esModule", ({
3573 value: true
3574 }));
3575 exports["default"] = void 0;
3576 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3577 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3578 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3579 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3580 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3581 var _editorOneEvents = __webpack_require__(/*! elementor-editor-utils/editor-one-events */ "../assets/dev/js/editor/utils/editor-one-events.js");
3582 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3583 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3584 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$ItemView) {
3585 function _default() {
3586 (0, _classCallCheck2.default)(this, _default);
3587 return _callSuper(this, _default, arguments);
3588 }
3589 (0, _inherits2.default)(_default, _Marionette$ItemView);
3590 return (0, _createClass2.default)(_default, [{
3591 key: "className",
3592 value: function className() {
3593 return 'elementor-finder__results__item';
3594 }
3595 }, {
3596 key: "getTemplate",
3597 value: function getTemplate() {
3598 return '#tmpl-elementor-finder__results__item';
3599 }
3600 }, {
3601 key: "events",
3602 value: function events() {
3603 this.$el[0].addEventListener('click', this.onClick.bind(this), true);
3604 }
3605 }, {
3606 key: "trackResultSelect",
3607 value: function trackResultSelect() {
3608 var title = this.model.get('title');
3609 _editorOneEvents.EditorOneEventManager.sendFinderResultSelect(title);
3610 }
3611 }, {
3612 key: "onClick",
3613 value: function onClick(e) {
3614 var _this = this;
3615 var lockOptions = this.model.get('lock');
3616 if (!(lockOptions !== null && lockOptions !== void 0 && lockOptions.is_locked)) {
3617 this.trackResultSelect();
3618 return;
3619 }
3620 e.preventDefault();
3621 e.stopImmediatePropagation();
3622 elementorCommon.dialogsManager.createWidget('confirm', {
3623 id: 'elementor-finder__lock-dialog',
3624 headerMessage: lockOptions.content.heading,
3625 message: lockOptions.content.description,
3626 position: {
3627 my: 'center center',
3628 at: 'center center'
3629 },
3630 strings: {
3631 confirm: lockOptions.button.text,
3632 cancel: __('Cancel', 'elementor')
3633 },
3634 onConfirm: function onConfirm() {
3635 _this.trackResultSelect();
3636 var link = _this.replaceLockLinkPlaceholders(lockOptions.button.url);
3637 window.open(link, '_blank');
3638 }
3639 }).show();
3640 }
3641 }, {
3642 key: "replaceLockLinkPlaceholders",
3643 value: function replaceLockLinkPlaceholders(link) {
3644 return link.replace(/%%utm_source%%/g, 'finder').replace(/%%utm_medium%%/g, 'wp-dash');
3645 }
3646 }]);
3647 }(Marionette.ItemView);
3648
3649 /***/ }),
3650
3651 /***/ "../core/common/modules/finder/assets/js/modal/views/layout.js":
3652 /*!*********************************************************************!*\
3653 !*** ../core/common/modules/finder/assets/js/modal/views/layout.js ***!
3654 \*********************************************************************/
3655 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3656
3657 "use strict";
3658 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
3659
3660
3661 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3662 Object.defineProperty(exports, "__esModule", ({
3663 value: true
3664 }));
3665 exports["default"] = void 0;
3666 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3667 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3668 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3669 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3670 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
3671 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3672 var _content = _interopRequireDefault(__webpack_require__(/*! ./content */ "../core/common/modules/finder/assets/js/modal/views/content.js"));
3673 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3674 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3675 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
3676 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$com) {
3677 function _default() {
3678 (0, _classCallCheck2.default)(this, _default);
3679 return _callSuper(this, _default, arguments);
3680 }
3681 (0, _inherits2.default)(_default, _elementorModules$com);
3682 return (0, _createClass2.default)(_default, [{
3683 key: "getModalOptions",
3684 value: function getModalOptions() {
3685 return {
3686 id: 'elementor-finder__modal',
3687 draggable: true,
3688 effects: {
3689 show: 'show',
3690 hide: 'hide'
3691 },
3692 position: {
3693 enable: false
3694 }
3695 };
3696 }
3697 }, {
3698 key: "getLogoOptions",
3699 value: function getLogoOptions() {
3700 return {
3701 title: __('Finder', 'elementor')
3702 };
3703 }
3704 }, {
3705 key: "initialize",
3706 value: function initialize() {
3707 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3708 args[_key] = arguments[_key];
3709 }
3710 _superPropGet(_default, "initialize", this, 3)(args);
3711 this.showLogo();
3712 this.showContentView();
3713 }
3714 }, {
3715 key: "showContentView",
3716 value: function showContentView() {
3717 this.modalContent.show(new _content.default());
3718 }
3719 }, {
3720 key: "showModal",
3721 value: function showModal() {
3722 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
3723 args[_key2] = arguments[_key2];
3724 }
3725 _superPropGet(_default, "showModal", this, 3)(args);
3726 this.modalContent.currentView.ui.searchInput.focus();
3727 }
3728 }]);
3729 }(elementorModules.common.views.modal.Layout);
3730
3731 /***/ }),
3732
3733 /***/ "../modules/web-cli/assets/js/core/data/errors/base-error.js":
3734 /*!*******************************************************************!*\
3735 !*** ../modules/web-cli/assets/js/core/data/errors/base-error.js ***!
3736 \*******************************************************************/
3737 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3738
3739 "use strict";
3740
3741
3742 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3743 Object.defineProperty(exports, "__esModule", ({
3744 value: true
3745 }));
3746 exports["default"] = void 0;
3747 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3748 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3749 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3750 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3751 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3752 var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js"));
3753 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
3754 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
3755 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../../../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
3756 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
3757 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
3758 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3759 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3760 var BaseError = exports["default"] = /*#__PURE__*/function (_Error) {
3761 /**
3762 * Error constructor.
3763 *
3764 * @param {string} message
3765 * @param {string} code
3766 * @param {*} data
3767 */
3768 function BaseError() {
3769 var _this;
3770 var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
3771 var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
3772 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
3773 (0, _classCallCheck2.default)(this, BaseError);
3774 _this = _callSuper(this, BaseError, [message]);
3775 /**
3776 * The server error code.
3777 *
3778 * @type {string}
3779 */
3780 (0, _defineProperty2.default)(_this, "code", '');
3781 /**
3782 * Additional data about the current error.
3783 *
3784 * @type {*[]}
3785 */
3786 (0, _defineProperty2.default)(_this, "data", []);
3787 _this.code = code;
3788 _this.data = data;
3789 return _this;
3790 }
3791
3792 /**
3793 * Notify a message when the error occurs.
3794 */
3795 (0, _inherits2.default)(BaseError, _Error);
3796 return (0, _createClass2.default)(BaseError, [{
3797 key: "notify",
3798 value: function notify() {
3799 _console.default.error(_objectSpread({
3800 message: this.message
3801 }, this));
3802 }
3803 }], [{
3804 key: "create",
3805 value:
3806 /**
3807 * Static helper function to create the error.
3808 *
3809 * @param {string} message
3810 * @param {string} code
3811 * @param {*} data
3812 * @return {BaseError} error
3813 */
3814 function create(message) {
3815 var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
3816 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
3817 return new this(message, code, data);
3818 }
3819
3820 /**
3821 * Returns the status code of the error.
3822 */
3823 }, {
3824 key: "getHTTPErrorCode",
3825 value: function getHTTPErrorCode() {
3826 (0, _forceMethodImplementation.default)();
3827 }
3828 }]);
3829 }(/*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
3830
3831 /***/ }),
3832
3833 /***/ "../modules/web-cli/assets/js/core/data/errors/default-error.js":
3834 /*!**********************************************************************!*\
3835 !*** ../modules/web-cli/assets/js/core/data/errors/default-error.js ***!
3836 \**********************************************************************/
3837 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3838
3839 "use strict";
3840
3841
3842 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3843 Object.defineProperty(exports, "__esModule", ({
3844 value: true
3845 }));
3846 exports["default"] = exports.DefaultError = void 0;
3847 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3848 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3849 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3850 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3851 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3852 var _baseError = _interopRequireDefault(__webpack_require__(/*! ./base-error */ "../modules/web-cli/assets/js/core/data/errors/base-error.js"));
3853 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3854 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3855 var DefaultError = exports.DefaultError = /*#__PURE__*/function (_BaseError) {
3856 function DefaultError() {
3857 (0, _classCallCheck2.default)(this, DefaultError);
3858 return _callSuper(this, DefaultError, arguments);
3859 }
3860 (0, _inherits2.default)(DefaultError, _BaseError);
3861 return (0, _createClass2.default)(DefaultError, null, [{
3862 key: "getHTTPErrorCode",
3863 value: function getHTTPErrorCode() {
3864 return 501;
3865 }
3866 }]);
3867 }(_baseError.default);
3868 var _default = exports["default"] = DefaultError;
3869
3870 /***/ }),
3871
3872 /***/ "../modules/web-cli/assets/js/core/data/errors/error-404.js":
3873 /*!******************************************************************!*\
3874 !*** ../modules/web-cli/assets/js/core/data/errors/error-404.js ***!
3875 \******************************************************************/
3876 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3877
3878 "use strict";
3879
3880
3881 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3882 Object.defineProperty(exports, "__esModule", ({
3883 value: true
3884 }));
3885 exports["default"] = exports.Error404 = void 0;
3886 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3887 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3888 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3889 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3890 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3891 var _baseError = _interopRequireDefault(__webpack_require__(/*! ./base-error */ "../modules/web-cli/assets/js/core/data/errors/base-error.js"));
3892 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
3893 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3894 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3895 var Error404 = exports.Error404 = /*#__PURE__*/function (_BaseError) {
3896 function Error404() {
3897 (0, _classCallCheck2.default)(this, Error404);
3898 return _callSuper(this, Error404, arguments);
3899 }
3900 (0, _inherits2.default)(Error404, _BaseError);
3901 return (0, _createClass2.default)(Error404, [{
3902 key: "notify",
3903 value: function notify() {
3904 _console.default.warn(this.message);
3905 }
3906 }], [{
3907 key: "getHTTPErrorCode",
3908 value: function getHTTPErrorCode() {
3909 return 404;
3910 }
3911 }]);
3912 }(_baseError.default);
3913 var _default = exports["default"] = Error404;
3914
3915 /***/ }),
3916
3917 /***/ "../modules/web-cli/assets/js/core/data/errors/index.js":
3918 /*!**************************************************************!*\
3919 !*** ../modules/web-cli/assets/js/core/data/errors/index.js ***!
3920 \**************************************************************/
3921 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3922
3923 "use strict";
3924
3925
3926 Object.defineProperty(exports, "__esModule", ({
3927 value: true
3928 }));
3929 Object.defineProperty(exports, "DefaultError", ({
3930 enumerable: true,
3931 get: function get() {
3932 return _defaultError.DefaultError;
3933 }
3934 }));
3935 Object.defineProperty(exports, "Error404", ({
3936 enumerable: true,
3937 get: function get() {
3938 return _error.Error404;
3939 }
3940 }));
3941 var _defaultError = __webpack_require__(/*! ./default-error */ "../modules/web-cli/assets/js/core/data/errors/default-error.js");
3942 var _error = __webpack_require__(/*! ./error-404 */ "../modules/web-cli/assets/js/core/data/errors/error-404.js");
3943
3944 /***/ }),
3945
3946 /***/ "../modules/web-cli/assets/js/modules/command-base.js":
3947 /*!************************************************************!*\
3948 !*** ../modules/web-cli/assets/js/modules/command-base.js ***!
3949 \************************************************************/
3950 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3951
3952 "use strict";
3953
3954
3955 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3956 Object.defineProperty(exports, "__esModule", ({
3957 value: true
3958 }));
3959 exports["default"] = void 0;
3960 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3961 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3962 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3963 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3964 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3965 var _commandInfra = _interopRequireDefault(__webpack_require__(/*! ./command-infra */ "../modules/web-cli/assets/js/modules/command-infra.js"));
3966 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
3967 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
3968 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3969 /**
3970 * @name $e.modules.CommandBase
3971 */
3972 var CommandBase = exports["default"] = /*#__PURE__*/function (_CommandInfra) {
3973 function CommandBase() {
3974 (0, _classCallCheck2.default)(this, CommandBase);
3975 return _callSuper(this, CommandBase, arguments);
3976 }
3977 (0, _inherits2.default)(CommandBase, _CommandInfra);
3978 return (0, _createClass2.default)(CommandBase, [{
3979 key: "onBeforeRun",
3980 value: function onBeforeRun() {
3981 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3982 $e.hooks.runUIBefore(this.command, args);
3983 }
3984 }, {
3985 key: "onAfterRun",
3986 value: function onAfterRun() {
3987 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3988 var result = arguments.length > 1 ? arguments[1] : undefined;
3989 $e.hooks.runUIAfter(this.command, args, result);
3990 }
3991 }, {
3992 key: "onBeforeApply",
3993 value: function onBeforeApply() {
3994 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3995 $e.hooks.runDataDependency(this.command, args);
3996 }
3997 }, {
3998 key: "onAfterApply",
3999 value: function onAfterApply() {
4000 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4001 var result = arguments.length > 1 ? arguments[1] : undefined;
4002 return $e.hooks.runDataAfter(this.command, args, result);
4003 }
4004 }, {
4005 key: "onCatchApply",
4006 value: function onCatchApply(e) {
4007 this.runCatchHooks(e);
4008 }
4009
4010 /**
4011 * Run all the catch hooks.
4012 *
4013 * @param {Error} e
4014 */
4015 }, {
4016 key: "runCatchHooks",
4017 value: function runCatchHooks(e) {
4018 $e.hooks.runDataCatch(this.command, this.args, e);
4019 $e.hooks.runUICatch(this.command, this.args, e);
4020 }
4021
4022 /**
4023 * TODO - Remove - Backwards compatibility.
4024 *
4025 * Function requireContainer().
4026 *
4027 * Validate `arg.container` & `arg.containers`.
4028 *
4029 * @param {{}} args
4030 * @deprecated since 3.7.0, extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase` instead.
4031 *
4032 * @throws {Error}
4033 */
4034 }, {
4035 key: "requireContainer",
4036 value: function requireContainer() {
4037 var _this = this;
4038 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.args;
4039 _deprecation.default.deprecated('requireContainer()', '3.7.0', 'Extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase`');
4040 if (!args.container && !args.containers) {
4041 throw Error('container or containers are required.');
4042 }
4043 if (args.container && args.containers) {
4044 throw Error('container and containers cannot go together please select one of them.');
4045 }
4046 var containers = args.containers || [args.container];
4047 containers.forEach(function (container) {
4048 _this.requireArgumentInstance('container', elementorModules.editor.Container, {
4049 container: container
4050 });
4051 });
4052 }
4053 }], [{
4054 key: "getInstanceType",
4055 value: function getInstanceType() {
4056 return 'CommandBase';
4057 }
4058 }]);
4059 }(_commandInfra.default);
4060
4061 /***/ }),
4062
4063 /***/ "../modules/web-cli/assets/js/modules/command-callback-base.js":
4064 /*!*********************************************************************!*\
4065 !*** ../modules/web-cli/assets/js/modules/command-callback-base.js ***!
4066 \*********************************************************************/
4067 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4068
4069 "use strict";
4070
4071
4072 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4073 Object.defineProperty(exports, "__esModule", ({
4074 value: true
4075 }));
4076 exports["default"] = void 0;
4077 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4078 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4079 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4080 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4081 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4082 var _commandBase = _interopRequireDefault(__webpack_require__(/*! ./command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4083 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4084 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4085 /**
4086 * To support pure callbacks in the API(commands.js), to ensure they have registered with the proper context.
4087 */
4088 var CommandCallbackBase = exports["default"] = /*#__PURE__*/function (_CommandBase) {
4089 function CommandCallbackBase() {
4090 (0, _classCallCheck2.default)(this, CommandCallbackBase);
4091 return _callSuper(this, CommandCallbackBase, arguments);
4092 }
4093 (0, _inherits2.default)(CommandCallbackBase, _CommandBase);
4094 return (0, _createClass2.default)(CommandCallbackBase, [{
4095 key: "apply",
4096 value: function apply() {
4097 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4098 return this.constructor.getCallback()(args);
4099 }
4100 }], [{
4101 key: "getInstanceType",
4102 value: function getInstanceType() {
4103 return 'CommandCallbackBase';
4104 }
4105
4106 /**
4107 * Get original callback of the command.
4108 *
4109 * Support pure callbacks ( Non command-base ).
4110 *
4111 * @return {()=>{}} Command Results.
4112 */
4113 }, {
4114 key: "getCallback",
4115 value: function getCallback() {
4116 return this.registerConfig.callback;
4117 }
4118 }]);
4119 }(_commandBase.default);
4120
4121 /***/ }),
4122
4123 /***/ "../modules/web-cli/assets/js/modules/command-data.js":
4124 /*!************************************************************!*\
4125 !*** ../modules/web-cli/assets/js/modules/command-data.js ***!
4126 \************************************************************/
4127 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4128
4129 "use strict";
4130
4131
4132 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4133 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
4134 Object.defineProperty(exports, "__esModule", ({
4135 value: true
4136 }));
4137 exports["default"] = void 0;
4138 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4139 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4140 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4141 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4142 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4143 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4144 var _commandBase = _interopRequireDefault(__webpack_require__(/*! ./command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4145 var errors = _interopRequireWildcard(__webpack_require__(/*! ../core/data/errors/ */ "../modules/web-cli/assets/js/core/data/errors/index.js"));
4146 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
4147 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4148 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4149 /**
4150 * @name $e.modules.CommandData
4151 */
4152 /**
4153 * @typedef {('create'|'delete'|'get'|'update'|'options')} DataTypes
4154 */
4155 /**
4156 * @typedef {{}} RequestData
4157 */
4158 /**
4159 * @typedef {import('../core/data/errors/base-error')} BaseError
4160 */
4161 var CommandData = exports["default"] = /*#__PURE__*/function (_CommandBase) {
4162 function CommandData(args) {
4163 var _this$args$options;
4164 var _this;
4165 var commandsAPI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : $e.data;
4166 (0, _classCallCheck2.default)(this, CommandData);
4167 _this = _callSuper(this, CommandData, [args, commandsAPI]);
4168 /**
4169 * Data returned from remote.
4170 *
4171 * @type {*}
4172 */
4173 (0, _defineProperty2.default)(_this, "data", void 0);
4174 /**
4175 * Fetch type.
4176 *
4177 * @type {DataTypes}
4178 */
4179 (0, _defineProperty2.default)(_this, "type", void 0);
4180 if ((_this$args$options = _this.args.options) !== null && _this$args$options !== void 0 && _this$args$options.type) {
4181 _this.type = _this.args.options.type;
4182 }
4183 return _this;
4184 }
4185
4186 /**
4187 * Function getEndpointFormat().
4188 *
4189 * @return {null|string} endpoint format
4190 */
4191 (0, _inherits2.default)(CommandData, _CommandBase);
4192 return (0, _createClass2.default)(CommandData, [{
4193 key: "getApplyMethods",
4194 value:
4195 /**
4196 * @param {DataTypes} type
4197 *
4198 * @return {boolean|{before: (function(*=): {}), after: (function({}, *=): {})}} apply methods
4199 */
4200 function getApplyMethods() {
4201 var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.type;
4202 var before, after;
4203 switch (type) {
4204 case 'create':
4205 before = this.applyBeforeCreate;
4206 after = this.applyAfterCreate;
4207 break;
4208 case 'delete':
4209 before = this.applyBeforeDelete;
4210 after = this.applyAfterDelete;
4211 break;
4212 case 'get':
4213 before = this.applyBeforeGet;
4214 after = this.applyAfterGet;
4215 break;
4216 case 'update':
4217 before = this.applyBeforeUpdate;
4218 after = this.applyAfterUpdate;
4219 break;
4220 case 'options':
4221 before = this.applyBeforeOptions;
4222 after = this.applyAfterOptions;
4223 break;
4224 default:
4225 return false;
4226 }
4227 return {
4228 before: before.bind(this),
4229 after: after.bind(this)
4230 };
4231 }
4232
4233 /**
4234 * Function getRequestData().
4235 *
4236 * @return {RequestData} request data
4237 */
4238 }, {
4239 key: "getRequestData",
4240 value: function getRequestData() {
4241 return {
4242 type: this.type,
4243 args: this.args,
4244 timestamp: new Date().getTime(),
4245 component: this.component,
4246 command: this.command,
4247 endpoint: $e.data.commandToEndpoint(this.command, JSON.parse(JSON.stringify(this.args)), this.constructor.getEndpointFormat())
4248 };
4249 }
4250 }, {
4251 key: "apply",
4252 value: function apply() {
4253 var _this2 = this;
4254 var applyMethods = this.getApplyMethods();
4255
4256 // Run 'before' method.
4257 this.args = applyMethods.before(this.args);
4258 var requestData = this.getRequestData();
4259 return $e.data.fetch(requestData).then(function (data) {
4260 _this2.data = data;
4261
4262 // Run 'after' method.
4263 _this2.data = applyMethods.after(data, _this2.args);
4264 _this2.data = {
4265 data: _this2.data
4266 };
4267
4268 // Append requestData.
4269 _this2.data = Object.assign({
4270 __requestData__: requestData
4271 }, _this2.data);
4272 return _this2.data;
4273 });
4274 }
4275
4276 /**
4277 * @param {*} [args={}]
4278 * @return {{}} filtered args
4279 */
4280 }, {
4281 key: "applyBeforeCreate",
4282 value: function applyBeforeCreate() {
4283 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4284 return args;
4285 }
4286
4287 /**
4288 * @param {{}} data
4289 * @param {*} [args={}]
4290 * @return {{}} filtered result
4291 */
4292 }, {
4293 key: "applyAfterCreate",
4294 value: function applyAfterCreate(data) {
4295 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4296 // eslint-disable-line no-unused-vars
4297 return data;
4298 }
4299
4300 /**
4301 * @param {*} [args={}]
4302 * @return {{}} filtered args
4303 */
4304 }, {
4305 key: "applyBeforeDelete",
4306 value: function applyBeforeDelete() {
4307 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4308 return args;
4309 }
4310
4311 /**
4312 * @param {{}} data
4313 * @param {*} [args={}]
4314 * @return {{}} filtered result
4315 */
4316 }, {
4317 key: "applyAfterDelete",
4318 value: function applyAfterDelete(data) {
4319 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4320 // eslint-disable-line no-unused-vars
4321 return data;
4322 }
4323
4324 /**
4325 * @param {*} [args={}]
4326 * @return {{}} filtered args
4327 */
4328 }, {
4329 key: "applyBeforeGet",
4330 value: function applyBeforeGet() {
4331 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4332 return args;
4333 }
4334
4335 /**
4336 * @param {{}} data
4337 * @param {*} [args={}]
4338 * @return {{}} filtered result
4339 */
4340 }, {
4341 key: "applyAfterGet",
4342 value: function applyAfterGet(data) {
4343 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4344 // eslint-disable-line no-unused-vars
4345 return data;
4346 }
4347
4348 /**
4349 * @param {*} [args={}]
4350 * @return {{}} filtered args
4351 */
4352 }, {
4353 key: "applyBeforeUpdate",
4354 value: function applyBeforeUpdate() {
4355 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4356 return args;
4357 }
4358
4359 /**
4360 * @param {{}} data
4361 * @param {*} [args={}]
4362 * @return {{}} filtered result
4363 */
4364 }, {
4365 key: "applyAfterUpdate",
4366 value: function applyAfterUpdate(data) {
4367 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4368 // eslint-disable-line no-unused-vars
4369 return data;
4370 }
4371
4372 /**
4373 * @param {*} [args={}]
4374 * @return {{}} filtered args
4375 */
4376 }, {
4377 key: "applyBeforeOptions",
4378 value: function applyBeforeOptions() {
4379 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4380 return args;
4381 }
4382
4383 /**
4384 * @param {{}} data
4385 * @param {*} [args={}]
4386 * @return {{}} filtered result
4387 */
4388 }, {
4389 key: "applyAfterOptions",
4390 value: function applyAfterOptions(data) {
4391 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4392 // eslint-disable-line no-unused-vars
4393 return data;
4394 }
4395
4396 /**
4397 * @param {BaseError} e
4398 */
4399 }, {
4400 key: "applyAfterCatch",
4401 value: function applyAfterCatch(e) {
4402 e.notify();
4403 }
4404 }, {
4405 key: "onCatchApply",
4406 value: function onCatchApply(e) {
4407 var _e;
4408 // TODO: If the errors that returns from the server is consistent remove the '?' from 'e'
4409 var httpErrorCode = ((_e = e) === null || _e === void 0 || (_e = _e.data) === null || _e === void 0 ? void 0 : _e.status) || 501;
4410 var dataError = Object.values(errors).find(function (error) {
4411 return error.getHTTPErrorCode() === httpErrorCode;
4412 });
4413 if (!dataError) {
4414 dataError = errors.DefaultError;
4415 }
4416 e = dataError.create(e.message, e.code, e.data || []);
4417 this.runCatchHooks(e);
4418 this.applyAfterCatch(e);
4419 }
4420 }], [{
4421 key: "getInstanceType",
4422 value: function getInstanceType() {
4423 return 'CommandData';
4424 }
4425 }, {
4426 key: "getEndpointFormat",
4427 value: function getEndpointFormat() {
4428 return null;
4429 }
4430 }]);
4431 }(_commandBase.default);
4432
4433 /***/ }),
4434
4435 /***/ "../modules/web-cli/assets/js/modules/command-infra.js":
4436 /*!*************************************************************!*\
4437 !*** ../modules/web-cli/assets/js/modules/command-infra.js ***!
4438 \*************************************************************/
4439 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4440
4441 "use strict";
4442
4443
4444 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4445 Object.defineProperty(exports, "__esModule", ({
4446 value: true
4447 }));
4448 exports["default"] = void 0;
4449 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4450 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4451 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4452 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4453 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4454 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4455 var _argsObject = _interopRequireDefault(__webpack_require__(/*! elementor-assets-js/modules/imports/args-object */ "../assets/dev/js/modules/imports/args-object.js"));
4456 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
4457 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4458 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4459 /**
4460 * @typedef {import('../modules/component-base')} ComponentBase
4461 */
4462 var CommandInfra = exports["default"] = /*#__PURE__*/function (_ArgsObject) {
4463 /**
4464 * Function constructor().
4465 *
4466 * Create Commands Base.
4467 *
4468 * @param {{}} args
4469 */
4470 function CommandInfra() {
4471 var _this;
4472 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4473 (0, _classCallCheck2.default)(this, CommandInfra);
4474 _this = _callSuper(this, CommandInfra, [args]);
4475 if (!_this.constructor.registerConfig) {
4476 throw RangeError('Doing it wrong: Each command type should have `registerConfig`.');
4477 }
4478
4479 // Acknowledge self about which command it run.
4480 _this.command = _this.constructor.getCommand();
4481
4482 // Assign instance of current component.
4483 _this.component = _this.constructor.getComponent();
4484
4485 // Who ever need do something before without `super` the constructor can use `initialize` method.
4486 _this.initialize(args);
4487
4488 // Refresh args, maybe the changed via `initialize`.
4489 args = _this.args;
4490
4491 // Validate args before run.
4492 _this.validateArgs(args);
4493 return _this;
4494 }
4495
4496 /**
4497 * Function initialize().
4498 *
4499 * Initialize command, called after construction.
4500 *
4501 * @param {{}} args
4502 */
4503 (0, _inherits2.default)(CommandInfra, _ArgsObject);
4504 return (0, _createClass2.default)(CommandInfra, [{
4505 key: "currentCommand",
4506 get:
4507 /**
4508 * @deprecated since 3.7.0, use `this.command` instead.
4509 */
4510 function get() {
4511 _deprecation.default.deprecated('this.currentCommand', '3.7.0', 'this.command');
4512 return this.command;
4513 }
4514 }, {
4515 key: "initialize",
4516 value: function initialize() {
4517 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4518 } // eslint-disable-line no-unused-vars
4519
4520 /**
4521 * Function validateArgs().
4522 *
4523 * Validate command arguments.
4524 *
4525 * @param {{}} args
4526 */
4527 }, {
4528 key: "validateArgs",
4529 value: function validateArgs() {
4530 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4531 } // eslint-disable-line no-unused-vars
4532
4533 // eslint-disable-next-line jsdoc/require-returns-check
4534 /**
4535 * Function apply().
4536 *
4537 * Do the actual command.
4538 *
4539 * @param {{}} args
4540 *
4541 * @return {*} Command results.
4542 */
4543 }, {
4544 key: "apply",
4545 value: function apply() {
4546 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4547 // eslint-disable-line no-unused-vars
4548 elementorModules.ForceMethodImplementation();
4549 }
4550
4551 /**
4552 * Function run().
4553 *
4554 * Run command with history & hooks.
4555 *
4556 * @return {*} Command results.
4557 */
4558 }, {
4559 key: "run",
4560 value: function run() {
4561 return this.apply(this.args);
4562 }
4563
4564 /**
4565 * Function onBeforeRun.
4566 *
4567 * Called before run().
4568 *
4569 * @param {{}} args
4570 */
4571 }, {
4572 key: "onBeforeRun",
4573 value: function onBeforeRun() {
4574 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4575 } // eslint-disable-line no-unused-vars
4576
4577 /**
4578 * Function onAfterRun.
4579 *
4580 * Called after run().
4581 *
4582 * @param {{}} args
4583 * @param {*} result
4584 */
4585 }, {
4586 key: "onAfterRun",
4587 value: function onAfterRun() {
4588 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4589 var result = arguments.length > 1 ? arguments[1] : undefined;
4590 } // eslint-disable-line no-unused-vars
4591
4592 /**
4593 * Function onBeforeApply.
4594 *
4595 * Called before apply().
4596 *
4597 * @param {{}} args
4598 */
4599 }, {
4600 key: "onBeforeApply",
4601 value: function onBeforeApply() {
4602 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4603 } // eslint-disable-line no-unused-vars
4604
4605 /**
4606 * Function onAfterApply.
4607 *
4608 * Called after apply().
4609 *
4610 * @param {{}} args
4611 * @param {*} result
4612 */
4613 }, {
4614 key: "onAfterApply",
4615 value: function onAfterApply() {
4616 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4617 var result = arguments.length > 1 ? arguments[1] : undefined;
4618 } // eslint-disable-line no-unused-vars
4619
4620 /**
4621 * Function onCatchApply.
4622 *
4623 * Called after apply() failed.
4624 *
4625 * @param {Error} e
4626 */
4627 }, {
4628 key: "onCatchApply",
4629 value: function onCatchApply(e) {} // eslint-disable-line no-unused-vars
4630 }], [{
4631 key: "getInstanceType",
4632 value: function getInstanceType() {
4633 return 'CommandInfra';
4634 }
4635
4636 /**
4637 * Get info of command.
4638 *
4639 * @return {Object} Extra information about the command.
4640 */
4641 }, {
4642 key: "getInfo",
4643 value: function getInfo() {
4644 return {};
4645 }
4646
4647 /**
4648 * @return {string} Self command name.
4649 */
4650 }, {
4651 key: "getCommand",
4652 value: function getCommand() {
4653 return this.registerConfig.command;
4654 }
4655
4656 /**
4657 * @return {ComponentBase} Self component
4658 */
4659 }, {
4660 key: "getComponent",
4661 value: function getComponent() {
4662 return this.registerConfig.component;
4663 }
4664 }, {
4665 key: "setRegisterConfig",
4666 value: function setRegisterConfig(config) {
4667 this.registerConfig = Object.freeze(config);
4668 }
4669 }]);
4670 }(_argsObject.default);
4671 /**
4672 * @type {Object}
4673 */
4674 (0, _defineProperty2.default)(CommandInfra, "registerConfig", null);
4675
4676 /***/ }),
4677
4678 /***/ "../modules/web-cli/assets/js/modules/commands/close.js":
4679 /*!**************************************************************!*\
4680 !*** ../modules/web-cli/assets/js/modules/commands/close.js ***!
4681 \**************************************************************/
4682 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4683
4684 "use strict";
4685
4686
4687 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4688 Object.defineProperty(exports, "__esModule", ({
4689 value: true
4690 }));
4691 exports["default"] = exports.Close = void 0;
4692 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4693 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4694 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4695 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4696 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4697 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4698 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4699 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4700 var Close = exports.Close = /*#__PURE__*/function (_CommandBase) {
4701 function Close() {
4702 (0, _classCallCheck2.default)(this, Close);
4703 return _callSuper(this, Close, arguments);
4704 }
4705 (0, _inherits2.default)(Close, _CommandBase);
4706 return (0, _createClass2.default)(Close, [{
4707 key: "apply",
4708 value: function apply() {
4709 this.component.close();
4710 }
4711 }]);
4712 }(_commandBase.default);
4713 var _default = exports["default"] = Close;
4714
4715 /***/ }),
4716
4717 /***/ "../modules/web-cli/assets/js/modules/commands/index.js":
4718 /*!**************************************************************!*\
4719 !*** ../modules/web-cli/assets/js/modules/commands/index.js ***!
4720 \**************************************************************/
4721 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4722
4723 "use strict";
4724
4725
4726 Object.defineProperty(exports, "__esModule", ({
4727 value: true
4728 }));
4729 Object.defineProperty(exports, "Close", ({
4730 enumerable: true,
4731 get: function get() {
4732 return _close.Close;
4733 }
4734 }));
4735 Object.defineProperty(exports, "Open", ({
4736 enumerable: true,
4737 get: function get() {
4738 return _open.Open;
4739 }
4740 }));
4741 Object.defineProperty(exports, "Toggle", ({
4742 enumerable: true,
4743 get: function get() {
4744 return _toggle.Toggle;
4745 }
4746 }));
4747 var _close = __webpack_require__(/*! ./close */ "../modules/web-cli/assets/js/modules/commands/close.js");
4748 var _open = __webpack_require__(/*! ./open */ "../modules/web-cli/assets/js/modules/commands/open.js");
4749 var _toggle = __webpack_require__(/*! ./toggle */ "../modules/web-cli/assets/js/modules/commands/toggle.js");
4750
4751 /***/ }),
4752
4753 /***/ "../modules/web-cli/assets/js/modules/commands/open.js":
4754 /*!*************************************************************!*\
4755 !*** ../modules/web-cli/assets/js/modules/commands/open.js ***!
4756 \*************************************************************/
4757 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4758
4759 "use strict";
4760
4761
4762 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4763 Object.defineProperty(exports, "__esModule", ({
4764 value: true
4765 }));
4766 exports["default"] = exports.Open = void 0;
4767 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4768 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4769 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4770 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4771 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4772 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4773 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4774 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4775 var Open = exports.Open = /*#__PURE__*/function (_CommandBase) {
4776 function Open() {
4777 (0, _classCallCheck2.default)(this, Open);
4778 return _callSuper(this, Open, arguments);
4779 }
4780 (0, _inherits2.default)(Open, _CommandBase);
4781 return (0, _createClass2.default)(Open, [{
4782 key: "apply",
4783 value: function apply() {
4784 $e.route(this.component.getNamespace());
4785 }
4786 }]);
4787 }(_commandBase.default);
4788 var _default = exports["default"] = Open;
4789
4790 /***/ }),
4791
4792 /***/ "../modules/web-cli/assets/js/modules/commands/toggle.js":
4793 /*!***************************************************************!*\
4794 !*** ../modules/web-cli/assets/js/modules/commands/toggle.js ***!
4795 \***************************************************************/
4796 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4797
4798 "use strict";
4799
4800
4801 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4802 Object.defineProperty(exports, "__esModule", ({
4803 value: true
4804 }));
4805 exports["default"] = exports.Toggle = void 0;
4806 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4807 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4808 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4809 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4810 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4811 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4812 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4813 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4814 var Toggle = exports.Toggle = /*#__PURE__*/function (_CommandBase) {
4815 function Toggle() {
4816 (0, _classCallCheck2.default)(this, Toggle);
4817 return _callSuper(this, Toggle, arguments);
4818 }
4819 (0, _inherits2.default)(Toggle, _CommandBase);
4820 return (0, _createClass2.default)(Toggle, [{
4821 key: "apply",
4822 value: function apply() {
4823 if (this.component.isOpen) {
4824 this.component.close();
4825 } else {
4826 $e.route(this.component.getNamespace());
4827 }
4828 }
4829 }]);
4830 }(_commandBase.default);
4831 var _default = exports["default"] = Toggle;
4832
4833 /***/ }),
4834
4835 /***/ "../modules/web-cli/assets/js/modules/component-base.js":
4836 /*!**************************************************************!*\
4837 !*** ../modules/web-cli/assets/js/modules/component-base.js ***!
4838 \**************************************************************/
4839 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4840
4841 "use strict";
4842
4843
4844 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4845 Object.defineProperty(exports, "__esModule", ({
4846 value: true
4847 }));
4848 exports["default"] = void 0;
4849 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4850 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
4851 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4852 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4853 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4854 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4855 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4856 var _commandCallbackBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-callback-base */ "../modules/web-cli/assets/js/modules/command-callback-base.js"));
4857 var _toolkit = __webpack_require__(/*! @reduxjs/toolkit */ "@reduxjs/toolkit");
4858 var _module = _interopRequireDefault(__webpack_require__(/*! elementor/assets/dev/js/modules/imports/module.js */ "../assets/dev/js/modules/imports/module.js"));
4859 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
4860 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
4861 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
4862 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
4863 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
4864 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4865 /**
4866 * @typedef {import('./command-infra')} CommandInfra
4867 * @typedef {import('./hook-base')} HookBase
4868 * @typedef {import('../core/states/ui-state-base')} UiStateBase
4869 */
4870 var ComponentBase = exports["default"] = /*#__PURE__*/function (_Module) {
4871 function ComponentBase() {
4872 (0, _classCallCheck2.default)(this, ComponentBase);
4873 return _callSuper(this, ComponentBase, arguments);
4874 }
4875 (0, _inherits2.default)(ComponentBase, _Module);
4876 return (0, _createClass2.default)(ComponentBase, [{
4877 key: "__construct",
4878 value: function __construct() {
4879 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4880 if (args.manager) {
4881 this.manager = args.manager;
4882 }
4883 this.commands = this.defaultCommands();
4884 this.commandsInternal = this.defaultCommandsInternal();
4885 this.hooks = this.defaultHooks();
4886 this.routes = this.defaultRoutes();
4887 this.tabs = this.defaultTabs();
4888 this.shortcuts = this.defaultShortcuts();
4889 this.utils = this.defaultUtils();
4890 this.data = this.defaultData();
4891 this.uiStates = this.defaultUiStates();
4892 this.states = this.defaultStates();
4893 this.defaultRoute = '';
4894 this.currentTab = '';
4895 }
4896 }, {
4897 key: "registerAPI",
4898 value: function registerAPI() {
4899 var _this = this;
4900 Object.entries(this.getTabs()).forEach(function (tab) {
4901 return _this.registerTabRoute(tab[0]);
4902 });
4903 Object.entries(this.getRoutes()).forEach(function (_ref) {
4904 var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
4905 route = _ref2[0],
4906 callback = _ref2[1];
4907 return _this.registerRoute(route, callback);
4908 });
4909 Object.entries(this.getCommands()).forEach(function (_ref3) {
4910 var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
4911 command = _ref4[0],
4912 callback = _ref4[1];
4913 return _this.registerCommand(command, callback);
4914 });
4915 Object.entries(this.getCommandsInternal()).forEach(function (_ref5) {
4916 var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
4917 command = _ref6[0],
4918 callback = _ref6[1];
4919 return _this.registerCommandInternal(command, callback);
4920 });
4921 Object.values(this.getHooks()).forEach(function (instance) {
4922 return _this.registerHook(instance);
4923 });
4924 Object.entries(this.getData()).forEach(function (_ref7) {
4925 var _ref8 = (0, _slicedToArray2.default)(_ref7, 2),
4926 command = _ref8[0],
4927 callback = _ref8[1];
4928 return _this.registerData(command, callback);
4929 });
4930 Object.values(this.getUiStates()).forEach(function (instance) {
4931 return _this.registerUiState(instance);
4932 });
4933 Object.entries(this.getStates()).forEach(function (_ref9) {
4934 var _ref0 = (0, _slicedToArray2.default)(_ref9, 2),
4935 id = _ref0[0],
4936 state = _ref0[1];
4937 return _this.registerState(id, state);
4938 });
4939 }
4940
4941 // eslint-disable-next-line jsdoc/require-returns-check
4942 /**
4943 * @return {string} namespace
4944 */
4945 }, {
4946 key: "getNamespace",
4947 value: function getNamespace() {
4948 (0, _forceMethodImplementation.default)();
4949 }
4950
4951 /**
4952 * @deprecated since 3.7.0, use `getServiceName()` instead.
4953 */
4954 }, {
4955 key: "getRootContainer",
4956 value: function getRootContainer() {
4957 _deprecation.default.deprecated('getRootContainer()', '3.7.0', 'getServiceName()');
4958 return this.getServiceName();
4959 }
4960 }, {
4961 key: "getServiceName",
4962 value: function getServiceName() {
4963 return this.getNamespace().split('/')[0];
4964 }
4965 }, {
4966 key: "store",
4967 get: function get() {
4968 return $e.store.get(this.getNamespace());
4969 }
4970 }, {
4971 key: "defaultTabs",
4972 value: function defaultTabs() {
4973 return {};
4974 }
4975 }, {
4976 key: "defaultRoutes",
4977 value: function defaultRoutes() {
4978 return {};
4979 }
4980 }, {
4981 key: "defaultCommands",
4982 value: function defaultCommands() {
4983 return {};
4984 }
4985 }, {
4986 key: "defaultCommandsInternal",
4987 value: function defaultCommandsInternal() {
4988 return {};
4989 }
4990 }, {
4991 key: "defaultHooks",
4992 value: function defaultHooks() {
4993 return {};
4994 }
4995
4996 /**
4997 * Get the component's default UI states.
4998 *
4999 * @return {Object} default UI states
5000 */
5001 }, {
5002 key: "defaultUiStates",
5003 value: function defaultUiStates() {
5004 return {};
5005 }
5006
5007 /**
5008 * Get the component's Redux slice settings.
5009 *
5010 * @return {Object} Redux slice settings
5011 */
5012 }, {
5013 key: "defaultStates",
5014 value: function defaultStates() {
5015 return {};
5016 }
5017 }, {
5018 key: "defaultShortcuts",
5019 value: function defaultShortcuts() {
5020 return {};
5021 }
5022 }, {
5023 key: "defaultUtils",
5024 value: function defaultUtils() {
5025 return {};
5026 }
5027 }, {
5028 key: "defaultData",
5029 value: function defaultData() {
5030 return {};
5031 }
5032 }, {
5033 key: "getCommands",
5034 value: function getCommands() {
5035 return this.commands;
5036 }
5037 }, {
5038 key: "getCommandsInternal",
5039 value: function getCommandsInternal() {
5040 return this.commandsInternal;
5041 }
5042 }, {
5043 key: "getHooks",
5044 value: function getHooks() {
5045 return this.hooks;
5046 }
5047
5048 /**
5049 * Retrieve the component's UI states.
5050 *
5051 * @return {Object} UI states
5052 */
5053 }, {
5054 key: "getUiStates",
5055 value: function getUiStates() {
5056 return this.uiStates;
5057 }
5058
5059 /**
5060 * Retrieve the component's Redux Slice.
5061 *
5062 * @return {Object} Redux Slice
5063 */
5064 }, {
5065 key: "getStates",
5066 value: function getStates() {
5067 return this.states;
5068 }
5069 }, {
5070 key: "getRoutes",
5071 value: function getRoutes() {
5072 return this.routes;
5073 }
5074 }, {
5075 key: "getTabs",
5076 value: function getTabs() {
5077 return this.tabs;
5078 }
5079 }, {
5080 key: "getShortcuts",
5081 value: function getShortcuts() {
5082 return this.shortcuts;
5083 }
5084 }, {
5085 key: "getData",
5086 value: function getData() {
5087 return this.data;
5088 }
5089
5090 /**
5091 * @param {string} command
5092 * @param {(()=>{}|CommandInfra)} context
5093 * @param {'default'|'internal'|'data'} commandsType
5094 */
5095 }, {
5096 key: "registerCommand",
5097 value: function registerCommand(command, context) {
5098 var commandsType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'default';
5099 var commandsManager;
5100 switch (commandsType) {
5101 case 'default':
5102 commandsManager = $e.commands;
5103 break;
5104 case 'internal':
5105 commandsManager = $e.commandsInternal;
5106 break;
5107 case 'data':
5108 commandsManager = $e.data;
5109 break;
5110 default:
5111 throw new Error("Invalid commands type: '".concat(command, "'"));
5112 }
5113 var fullCommand = this.getNamespace() + '/' + command,
5114 instanceType = context.getInstanceType ? context.getInstanceType() : false,
5115 registerConfig = {
5116 command: fullCommand,
5117 component: this
5118 };
5119
5120 // Support pure callback.
5121 if (!instanceType) {
5122 if ($e.devTools) {
5123 $e.devTools.log.warn("Attach command-callback-base, on command: '".concat(fullCommand, "', context is unknown type."));
5124 }
5125 registerConfig.callback = context;
5126
5127 // Unique class.
5128 context = /*#__PURE__*/function (_CommandCallbackBase) {
5129 function context() {
5130 (0, _classCallCheck2.default)(this, context);
5131 return _callSuper(this, context, arguments);
5132 }
5133 (0, _inherits2.default)(context, _CommandCallbackBase);
5134 return (0, _createClass2.default)(context);
5135 }(_commandCallbackBase.default);
5136 }
5137 context.setRegisterConfig(registerConfig);
5138 commandsManager.register(this, command, context);
5139 }
5140
5141 /**
5142 * @param {HookBase} instance
5143 */
5144 }, {
5145 key: "registerHook",
5146 value: function registerHook(instance) {
5147 return instance.register();
5148 }
5149 }, {
5150 key: "registerCommandInternal",
5151 value: function registerCommandInternal(command, context) {
5152 this.registerCommand(command, context, 'internal');
5153 }
5154
5155 /**
5156 * Register a UI state.
5157 *
5158 * @param {UiStateBase} instance - UI state instance.
5159 *
5160 * @return {void}
5161 */
5162 }, {
5163 key: "registerUiState",
5164 value: function registerUiState(instance) {
5165 $e.uiStates.register(instance);
5166 }
5167
5168 /**
5169 * Register a Redux Slice.
5170 *
5171 * @param {string} id - State id.
5172 * @param {Object} stateConfig - The state config.
5173 *
5174 * @return {void}
5175 */
5176 }, {
5177 key: "registerState",
5178 value: function registerState(id, stateConfig) {
5179 id = this.getNamespace() + (id ? "/".concat(id) : '');
5180 var slice = (0, _toolkit.createSlice)(_objectSpread(_objectSpread({}, stateConfig), {}, {
5181 name: id
5182 }));
5183 $e.store.register(id, slice);
5184 }
5185 }, {
5186 key: "registerRoute",
5187 value: function registerRoute(route, callback) {
5188 $e.routes.register(this, route, callback);
5189 }
5190 }, {
5191 key: "registerData",
5192 value: function registerData(command, context) {
5193 this.registerCommand(command, context, 'data');
5194 }
5195 }, {
5196 key: "unregisterRoute",
5197 value: function unregisterRoute(route) {
5198 $e.routes.unregister(this, route);
5199 }
5200 }, {
5201 key: "registerTabRoute",
5202 value: function registerTabRoute(tab) {
5203 var _this2 = this;
5204 this.registerRoute(tab, function (args) {
5205 return _this2.activateTab(tab, args);
5206 });
5207 }
5208 }, {
5209 key: "dependency",
5210 value: function dependency() {
5211 return true;
5212 }
5213 }, {
5214 key: "open",
5215 value: function open() {
5216 return true;
5217 }
5218 }, {
5219 key: "close",
5220 value: function close() {
5221 if (!this.isOpen) {
5222 return false;
5223 }
5224 this.isOpen = false;
5225 this.inactivate();
5226 $e.routes.clearCurrent(this.getNamespace());
5227 $e.routes.clearHistory(this.getServiceName());
5228 return true;
5229 }
5230 }, {
5231 key: "activate",
5232 value: function activate() {
5233 $e.components.activate(this.getNamespace());
5234 }
5235 }, {
5236 key: "inactivate",
5237 value: function inactivate() {
5238 $e.components.inactivate(this.getNamespace());
5239 }
5240 }, {
5241 key: "isActive",
5242 value: function isActive() {
5243 return $e.components.isActive(this.getNamespace());
5244 }
5245 }, {
5246 key: "onRoute",
5247 value: function onRoute(route) {
5248 this.toggleRouteClass(route, true);
5249 this.toggleHistoryClass();
5250 this.activate();
5251 this.trigger('route/open', route);
5252 }
5253 }, {
5254 key: "onCloseRoute",
5255 value: function onCloseRoute(route) {
5256 this.toggleRouteClass(route, false);
5257 this.inactivate();
5258 this.trigger('route/close', route);
5259 }
5260 }, {
5261 key: "setDefaultRoute",
5262 value: function setDefaultRoute(route) {
5263 this.defaultRoute = this.getNamespace() + '/' + route;
5264 }
5265 }, {
5266 key: "getDefaultRoute",
5267 value: function getDefaultRoute() {
5268 return this.defaultRoute;
5269 }
5270 }, {
5271 key: "removeTab",
5272 value: function removeTab(tab) {
5273 delete this.tabs[tab];
5274 this.unregisterRoute(tab);
5275 }
5276 }, {
5277 key: "hasTab",
5278 value: function hasTab(tab) {
5279 return !!this.tabs[tab];
5280 }
5281 }, {
5282 key: "addTab",
5283 value: function addTab(tab, args, position) {
5284 var _this3 = this;
5285 this.tabs[tab] = args;
5286 // It can be 0.
5287 if ('undefined' !== typeof position) {
5288 var newTabs = {};
5289 var ids = Object.keys(this.tabs);
5290 // Remove new tab
5291 ids.pop();
5292
5293 // Add it to position.
5294 ids.splice(position, 0, tab);
5295 ids.forEach(function (id) {
5296 newTabs[id] = _this3.tabs[id];
5297 });
5298 this.tabs = newTabs;
5299 }
5300 this.registerTabRoute(tab);
5301 }
5302 }, {
5303 key: "getTabsWrapperSelector",
5304 value: function getTabsWrapperSelector() {
5305 return '';
5306 }
5307 }, {
5308 key: "getTabRoute",
5309 value: function getTabRoute(tab) {
5310 return this.getNamespace() + '/' + tab;
5311 }
5312 }, {
5313 key: "renderTab",
5314 value: function renderTab(tab) {} // eslint-disable-line
5315 }, {
5316 key: "activateTab",
5317 value: function activateTab(tab, args) {
5318 var _this4 = this;
5319 this.renderTab(tab, args);
5320 jQuery(this.getTabsWrapperSelector() + ' .elementor-component-tab').off('click').on('click', function (event) {
5321 $e.route(_this4.getTabRoute(event.currentTarget.dataset.tab), args);
5322 }).removeClass('elementor-active').filter('[data-tab="' + tab + '"]').addClass('elementor-active');
5323 }
5324 }, {
5325 key: "getActiveTabConfig",
5326 value: function getActiveTabConfig() {
5327 return this.tabs[this.currentTab] || {};
5328 }
5329 }, {
5330 key: "getBodyClass",
5331 value: function getBodyClass(route) {
5332 return 'e-route-' + route.replace(/\//g, '-');
5333 }
5334
5335 /**
5336 * If command includes uppercase character convert it to lowercase and add `-`.
5337 * e.g: `CopyAll` is converted to `copy-all`.
5338 *
5339 * @param {string} commandName
5340 */
5341 }, {
5342 key: "normalizeCommandName",
5343 value: function normalizeCommandName(commandName) {
5344 return commandName.replace(/[A-Z]/g, function (match, offset) {
5345 return (offset > 0 ? '-' : '') + match.toLowerCase();
5346 });
5347 }
5348
5349 /**
5350 * @param {{}} commandsFromImport
5351 * @return {{}} imported commands
5352 */
5353 }, {
5354 key: "importCommands",
5355 value: function importCommands(commandsFromImport) {
5356 var _this5 = this;
5357 var commands = {};
5358
5359 // Convert `Commands` to `ComponentBase` workable format.
5360 Object.entries(commandsFromImport).forEach(function (_ref1) {
5361 var _ref10 = (0, _slicedToArray2.default)(_ref1, 2),
5362 className = _ref10[0],
5363 Class = _ref10[1];
5364 var command = _this5.normalizeCommandName(className);
5365 commands[command] = Class;
5366 });
5367 return commands;
5368 }
5369 }, {
5370 key: "importHooks",
5371 value: function importHooks(hooksFromImport) {
5372 var hooks = {};
5373 for (var key in hooksFromImport) {
5374 var hook = new hooksFromImport[key]();
5375 hooks[hook.getId()] = hook;
5376 }
5377 return hooks;
5378 }
5379
5380 /**
5381 * Import & initialize the component's UI states.
5382 * Should be used inside `defaultUiState()`.
5383 *
5384 * @param {Object} statesFromImport - UI states from import.
5385 *
5386 * @return {Object} UI States
5387 */
5388 }, {
5389 key: "importUiStates",
5390 value: function importUiStates(statesFromImport) {
5391 var _this6 = this;
5392 var uiStates = {};
5393 Object.values(statesFromImport).forEach(function (className) {
5394 var uiState = new className(_this6);
5395 uiStates[uiState.getId()] = uiState;
5396 });
5397 return uiStates;
5398 }
5399
5400 /**
5401 * Set a UI state value.
5402 * TODO: Should we provide such function? Maybe the developer should implicitly pass the full state ID?
5403 *
5404 * @param {string} state - Non-prefixed state ID.
5405 * @param {*} value - New state value.
5406 *
5407 * @return {void}
5408 */
5409 }, {
5410 key: "setUiState",
5411 value: function setUiState(state, value) {
5412 $e.uiStates.set("".concat(this.getNamespace(), "/").concat(state), value);
5413 }
5414 }, {
5415 key: "toggleRouteClass",
5416 value: function toggleRouteClass(route, state) {
5417 document.body.classList.toggle(this.getBodyClass(route), state);
5418 }
5419 }, {
5420 key: "toggleHistoryClass",
5421 value: function toggleHistoryClass() {
5422 document.body.classList.toggle('e-routes-has-history', !!$e.routes.getHistory(this.getServiceName()).length);
5423 }
5424 }]);
5425 }(_module.default);
5426
5427 /***/ }),
5428
5429 /***/ "../modules/web-cli/assets/js/modules/component-modal-base.js":
5430 /*!********************************************************************!*\
5431 !*** ../modules/web-cli/assets/js/modules/component-modal-base.js ***!
5432 \********************************************************************/
5433 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5434
5435 "use strict";
5436
5437
5438 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5439 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
5440 Object.defineProperty(exports, "__esModule", ({
5441 value: true
5442 }));
5443 exports["default"] = void 0;
5444 var _readOnlyError2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/readOnlyError */ "../node_modules/@babel/runtime/helpers/readOnlyError.js"));
5445 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5446 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5447 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
5448 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
5449 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
5450 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
5451 var _componentBase = _interopRequireDefault(__webpack_require__(/*! ./component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
5452 var commands = _interopRequireWildcard(__webpack_require__(/*! ./commands/ */ "../modules/web-cli/assets/js/modules/commands/index.js"));
5453 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
5454 function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
5455 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
5456 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
5457 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
5458 var ComponentModalBase = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
5459 function ComponentModalBase() {
5460 (0, _classCallCheck2.default)(this, ComponentModalBase);
5461 return _callSuper(this, ComponentModalBase, arguments);
5462 }
5463 (0, _inherits2.default)(ComponentModalBase, _ComponentBase);
5464 return (0, _createClass2.default)(ComponentModalBase, [{
5465 key: "registerAPI",
5466 value: function registerAPI() {
5467 var _this = this;
5468 _superPropGet(ComponentModalBase, "registerAPI", this, 3)([]);
5469 $e.shortcuts.register('esc', {
5470 scopes: [this.getNamespace()],
5471 callback: function callback() {
5472 return _this.close();
5473 }
5474 });
5475 }
5476 }, {
5477 key: "defaultCommands",
5478 value: function defaultCommands() {
5479 return this.importCommands(commands);
5480 }
5481 }, {
5482 key: "defaultRoutes",
5483 value: function defaultRoutes() {
5484 return {
5485 '': function _() {/* Nothing to do, it's already rendered. */}
5486 };
5487 }
5488 }, {
5489 key: "open",
5490 value: function open() {
5491 var _this2 = this;
5492 if (!this.layout) {
5493 var layout = this.getModalLayout();
5494 this.layout = new layout({
5495 component: this
5496 });
5497 this.layout.getModal().on('hide', function () {
5498 return _this2.close();
5499 });
5500 }
5501 this.layout.showModal();
5502 return true;
5503 }
5504 }, {
5505 key: "close",
5506 value: function close() {
5507 if (!_superPropGet(ComponentModalBase, "close", this, 3)([])) {
5508 return false;
5509 }
5510 var close = elementor.hooks.applyFilters('component/modal/close', this.layout.getModal().hide.bind(this.layout.getModal()), this);
5511 close();
5512 return true;
5513 }
5514 }, {
5515 key: "getModalLayout",
5516 value: function getModalLayout() {
5517 (0, _forceMethodImplementation.default)();
5518 }
5519 }]);
5520 }(_componentBase.default);
5521
5522 /***/ }),
5523
5524 /***/ "../modules/web-cli/assets/js/utils/console.js":
5525 /*!*****************************************************!*\
5526 !*** ../modules/web-cli/assets/js/utils/console.js ***!
5527 \*****************************************************/
5528 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5529
5530 "use strict";
5531
5532
5533 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5534 Object.defineProperty(exports, "__esModule", ({
5535 value: true
5536 }));
5537 exports["default"] = void 0;
5538 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5539 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5540 var Console = exports["default"] = /*#__PURE__*/function () {
5541 function Console() {
5542 (0, _classCallCheck2.default)(this, Console);
5543 }
5544 return (0, _createClass2.default)(Console, null, [{
5545 key: "error",
5546 value: function error(message) {
5547 // Show an error if devTools is available.
5548 if ($e.devTools) {
5549 $e.devTools.log.error(message);
5550 }
5551
5552 // If not a 'Hook-Break' then show error.
5553 if (!(message instanceof $e.modules.HookBreak)) {
5554 // eslint-disable-next-line no-console
5555 console.error(message);
5556 }
5557 }
5558 }, {
5559 key: "warn",
5560 value: function warn() {
5561 var _console;
5562 var style = "font-size: 12px; background-image: url(\"".concat(elementorWebCliConfig.urls.assets, "images/logo-icon.png\"); background-repeat: no-repeat; background-size: contain;");
5563 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
5564 args[_key] = arguments[_key];
5565 }
5566 args.unshift('%c %c', style, '');
5567 (_console = console).warn.apply(_console, args); // eslint-disable-line no-console
5568 }
5569 }]);
5570 }();
5571
5572 /***/ }),
5573
5574 /***/ "../modules/web-cli/assets/js/utils/deprecation.js":
5575 /*!*********************************************************!*\
5576 !*** ../modules/web-cli/assets/js/utils/deprecation.js ***!
5577 \*********************************************************/
5578 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5579
5580 "use strict";
5581
5582
5583 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5584 Object.defineProperty(exports, "__esModule", ({
5585 value: true
5586 }));
5587 exports["default"] = void 0;
5588 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
5589 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5590 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5591 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
5592 // Copied from `modules/dev-tools/assets/js/deprecation.js`
5593 /**
5594 * @typedef {Object} Version
5595 * @property {number} major1 The first number
5596 * @property {number} major2 The second number
5597 * @property {number} minor The third number
5598 * @property {string} build The fourth number
5599 */
5600
5601 var softDeprecated = function softDeprecated(name, version, replacement) {
5602 if (elementorWebCliConfig.isDebug) {
5603 deprecatedMessage('soft', name, version, replacement);
5604 }
5605 };
5606 var hardDeprecated = function hardDeprecated(name, version, replacement) {
5607 deprecatedMessage('hard', name, version, replacement);
5608 };
5609 var deprecatedMessage = function deprecatedMessage(type, name, version, replacement) {
5610 var message = "`".concat(name, "` is ").concat(type, " deprecated since ").concat(version);
5611 if (replacement) {
5612 message += " - Use `".concat(replacement, "` instead");
5613 }
5614 _console.default.warn(message);
5615 };
5616 var Deprecation = exports["default"] = /*#__PURE__*/function () {
5617 function Deprecation() {
5618 (0, _classCallCheck2.default)(this, Deprecation);
5619 }
5620 return (0, _createClass2.default)(Deprecation, null, [{
5621 key: "deprecated",
5622 value: function deprecated(name, version, replacement) {
5623 if (this.isHardDeprecated(version)) {
5624 hardDeprecated(name, version, replacement);
5625 } else {
5626 softDeprecated(name, version, replacement);
5627 }
5628 }
5629
5630 /**
5631 * @param {string} version
5632 *
5633 * @return {Version}
5634 */
5635 }, {
5636 key: "parseVersion",
5637 value: function parseVersion(version) {
5638 var versionParts = version.split('.');
5639 if (versionParts.length < 3 || versionParts.length > 4) {
5640 throw new RangeError('Invalid Semantic Version string provided');
5641 }
5642 var _versionParts = (0, _slicedToArray2.default)(versionParts, 4),
5643 major1 = _versionParts[0],
5644 major2 = _versionParts[1],
5645 minor = _versionParts[2],
5646 _versionParts$ = _versionParts[3],
5647 build = _versionParts$ === void 0 ? '' : _versionParts$;
5648 return {
5649 major1: parseInt(major1),
5650 major2: parseInt(major2),
5651 minor: parseInt(minor),
5652 build: build
5653 };
5654 }
5655
5656 /**
5657 * Get total of major.
5658 *
5659 * Since `get_total_major` cannot determine how much really versions between 2.9.0 and 3.3.0 if there is 2.10.0 version for example,
5660 * versions with major2 more then 9 will be added to total.
5661 *
5662 * @param {Version} versionObj
5663 *
5664 * @return {number}
5665 */
5666 }, {
5667 key: "getTotalMajor",
5668 value: function getTotalMajor(versionObj) {
5669 var total = parseInt("".concat(versionObj.major1).concat(versionObj.major2, "0"));
5670 total = Number((total / 10).toFixed(0));
5671 if (versionObj.major2 > 9) {
5672 total = versionObj.major2 - 9;
5673 }
5674 return total;
5675 }
5676
5677 /**
5678 * @param {string} version1
5679 * @param {string} version2
5680 *
5681 * @return {number}
5682 */
5683 }, {
5684 key: "compareVersion",
5685 value: function compareVersion(version1, version2) {
5686 var _this = this;
5687 return [this.parseVersion(version1), this.parseVersion(version2)].map(function (versionObj) {
5688 return _this.getTotalMajor(versionObj);
5689 }).reduce(function (acc, major) {
5690 return acc - major;
5691 });
5692 }
5693
5694 /**
5695 * @param {string} version
5696 *
5697 * @return {boolean}
5698 */
5699 }, {
5700 key: "isSoftDeprecated",
5701 value: function isSoftDeprecated(version) {
5702 var total = this.compareVersion(version, elementorWebCliConfig.version);
5703 return total <= 4;
5704 }
5705
5706 /**
5707 * @param {string} version
5708 * @return {boolean}
5709 */
5710 }, {
5711 key: "isHardDeprecated",
5712 value: function isHardDeprecated(version) {
5713 var total = this.compareVersion(version, elementorWebCliConfig.version);
5714 return total < 0 || total >= 8;
5715 }
5716 }]);
5717 }();
5718
5719 /***/ }),
5720
5721 /***/ "../modules/web-cli/assets/js/utils/force-method-implementation.js":
5722 /*!*************************************************************************!*\
5723 !*** ../modules/web-cli/assets/js/utils/force-method-implementation.js ***!
5724 \*************************************************************************/
5725 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5726
5727 "use strict";
5728
5729
5730 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5731 Object.defineProperty(exports, "__esModule", ({
5732 value: true
5733 }));
5734 exports["default"] = exports.ForceMethodImplementation = void 0;
5735 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5736 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5737 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
5738 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
5739 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
5740 var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js"));
5741 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
5742 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
5743 // TODO: Copied from `assets/dev/js/modules/imports/force-method-implementation.js`;
5744 var ForceMethodImplementation = exports.ForceMethodImplementation = /*#__PURE__*/function (_Error) {
5745 function ForceMethodImplementation() {
5746 var _this;
5747 var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
5748 (0, _classCallCheck2.default)(this, ForceMethodImplementation);
5749 _this = _callSuper(this, ForceMethodImplementation, ["".concat(info.isStatic ? 'static ' : '').concat(info.fullName, "() should be implemented, please provide '").concat(info.functionName || info.fullName, "' functionality.")]);
5750 Error.captureStackTrace(_this, ForceMethodImplementation);
5751 return _this;
5752 }
5753 (0, _inherits2.default)(ForceMethodImplementation, _Error);
5754 return (0, _createClass2.default)(ForceMethodImplementation);
5755 }(/*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
5756 var _default = exports["default"] = function _default() {
5757 var stack = Error().stack,
5758 caller = stack.split('\n')[2].trim(),
5759 callerName = caller.startsWith('at new') ? 'constructor' : caller.split(' ')[1],
5760 info = {};
5761 info.functionName = callerName;
5762 info.fullName = callerName;
5763 if (info.functionName.includes('.')) {
5764 var parts = info.functionName.split('.');
5765 info.className = parts[0];
5766 info.functionName = parts[1];
5767 } else {
5768 info.isStatic = true;
5769 }
5770 throw new ForceMethodImplementation(info);
5771 };
5772
5773 /***/ }),
5774
5775 /***/ "../node_modules/@babel/runtime/helpers/OverloadYield.js":
5776 /*!***************************************************************!*\
5777 !*** ../node_modules/@babel/runtime/helpers/OverloadYield.js ***!
5778 \***************************************************************/
5779 /***/ ((module) => {
5780
5781 function _OverloadYield(e, d) {
5782 this.v = e, this.k = d;
5783 }
5784 module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
5785
5786 /***/ }),
5787
5788 /***/ "../node_modules/@babel/runtime/helpers/arrayLikeToArray.js":
5789 /*!******************************************************************!*\
5790 !*** ../node_modules/@babel/runtime/helpers/arrayLikeToArray.js ***!
5791 \******************************************************************/
5792 /***/ ((module) => {
5793
5794 function _arrayLikeToArray(r, a) {
5795 (null == a || a > r.length) && (a = r.length);
5796 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
5797 return n;
5798 }
5799 module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
5800
5801 /***/ }),
5802
5803 /***/ "../node_modules/@babel/runtime/helpers/arrayWithHoles.js":
5804 /*!****************************************************************!*\
5805 !*** ../node_modules/@babel/runtime/helpers/arrayWithHoles.js ***!
5806 \****************************************************************/
5807 /***/ ((module) => {
5808
5809 function _arrayWithHoles(r) {
5810 if (Array.isArray(r)) return r;
5811 }
5812 module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
5813
5814 /***/ }),
5815
5816 /***/ "../node_modules/@babel/runtime/helpers/assertThisInitialized.js":
5817 /*!***********************************************************************!*\
5818 !*** ../node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
5819 \***********************************************************************/
5820 /***/ ((module) => {
5821
5822 function _assertThisInitialized(e) {
5823 if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
5824 return e;
5825 }
5826 module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
5827
5828 /***/ }),
5829
5830 /***/ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js":
5831 /*!******************************************************************!*\
5832 !*** ../node_modules/@babel/runtime/helpers/asyncToGenerator.js ***!
5833 \******************************************************************/
5834 /***/ ((module) => {
5835
5836 function asyncGeneratorStep(n, t, e, r, o, a, c) {
5837 try {
5838 var i = n[a](c),
5839 u = i.value;
5840 } catch (n) {
5841 return void e(n);
5842 }
5843 i.done ? t(u) : Promise.resolve(u).then(r, o);
5844 }
5845 function _asyncToGenerator(n) {
5846 return function () {
5847 var t = this,
5848 e = arguments;
5849 return new Promise(function (r, o) {
5850 var a = n.apply(t, e);
5851 function _next(n) {
5852 asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
5853 }
5854 function _throw(n) {
5855 asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
5856 }
5857 _next(void 0);
5858 });
5859 };
5860 }
5861 module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
5862
5863 /***/ }),
5864
5865 /***/ "../node_modules/@babel/runtime/helpers/classCallCheck.js":
5866 /*!****************************************************************!*\
5867 !*** ../node_modules/@babel/runtime/helpers/classCallCheck.js ***!
5868 \****************************************************************/
5869 /***/ ((module) => {
5870
5871 function _classCallCheck(a, n) {
5872 if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
5873 }
5874 module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
5875
5876 /***/ }),
5877
5878 /***/ "../node_modules/@babel/runtime/helpers/construct.js":
5879 /*!***********************************************************!*\
5880 !*** ../node_modules/@babel/runtime/helpers/construct.js ***!
5881 \***********************************************************/
5882 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5883
5884 var isNativeReflectConstruct = __webpack_require__(/*! ./isNativeReflectConstruct.js */ "../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js");
5885 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
5886 function _construct(t, e, r) {
5887 if (isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
5888 var o = [null];
5889 o.push.apply(o, e);
5890 var p = new (t.bind.apply(t, o))();
5891 return r && setPrototypeOf(p, r.prototype), p;
5892 }
5893 module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports;
5894
5895 /***/ }),
5896
5897 /***/ "../node_modules/@babel/runtime/helpers/createClass.js":
5898 /*!*************************************************************!*\
5899 !*** ../node_modules/@babel/runtime/helpers/createClass.js ***!
5900 \*************************************************************/
5901 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5902
5903 var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/toPropertyKey.js");
5904 function _defineProperties(e, r) {
5905 for (var t = 0; t < r.length; t++) {
5906 var o = r[t];
5907 o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);
5908 }
5909 }
5910 function _createClass(e, r, t) {
5911 return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
5912 writable: !1
5913 }), e;
5914 }
5915 module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
5916
5917 /***/ }),
5918
5919 /***/ "../node_modules/@babel/runtime/helpers/defineProperty.js":
5920 /*!****************************************************************!*\
5921 !*** ../node_modules/@babel/runtime/helpers/defineProperty.js ***!
5922 \****************************************************************/
5923 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5924
5925 var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/toPropertyKey.js");
5926 function _defineProperty(e, r, t) {
5927 return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
5928 value: t,
5929 enumerable: !0,
5930 configurable: !0,
5931 writable: !0
5932 }) : e[r] = t, e;
5933 }
5934 module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
5935
5936 /***/ }),
5937
5938 /***/ "../node_modules/@babel/runtime/helpers/get.js":
5939 /*!*****************************************************!*\
5940 !*** ../node_modules/@babel/runtime/helpers/get.js ***!
5941 \*****************************************************/
5942 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5943
5944 var superPropBase = __webpack_require__(/*! ./superPropBase.js */ "../node_modules/@babel/runtime/helpers/superPropBase.js");
5945 function _get() {
5946 return module.exports = _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
5947 var p = superPropBase(e, t);
5948 if (p) {
5949 var n = Object.getOwnPropertyDescriptor(p, t);
5950 return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
5951 }
5952 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _get.apply(null, arguments);
5953 }
5954 module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports;
5955
5956 /***/ }),
5957
5958 /***/ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js":
5959 /*!****************************************************************!*\
5960 !*** ../node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
5961 \****************************************************************/
5962 /***/ ((module) => {
5963
5964 function _getPrototypeOf(t) {
5965 return module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
5966 return t.__proto__ || Object.getPrototypeOf(t);
5967 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _getPrototypeOf(t);
5968 }
5969 module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
5970
5971 /***/ }),
5972
5973 /***/ "../node_modules/@babel/runtime/helpers/inherits.js":
5974 /*!**********************************************************!*\
5975 !*** ../node_modules/@babel/runtime/helpers/inherits.js ***!
5976 \**********************************************************/
5977 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5978
5979 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
5980 function _inherits(t, e) {
5981 if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
5982 t.prototype = Object.create(e && e.prototype, {
5983 constructor: {
5984 value: t,
5985 writable: !0,
5986 configurable: !0
5987 }
5988 }), Object.defineProperty(t, "prototype", {
5989 writable: !1
5990 }), e && setPrototypeOf(t, e);
5991 }
5992 module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports;
5993
5994 /***/ }),
5995
5996 /***/ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js":
5997 /*!***********************************************************************!*\
5998 !*** ../node_modules/@babel/runtime/helpers/interopRequireDefault.js ***!
5999 \***********************************************************************/
6000 /***/ ((module) => {
6001
6002 function _interopRequireDefault(e) {
6003 return e && e.__esModule ? e : {
6004 "default": e
6005 };
6006 }
6007 module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
6008
6009 /***/ }),
6010
6011 /***/ "../node_modules/@babel/runtime/helpers/isNativeFunction.js":
6012 /*!******************************************************************!*\
6013 !*** ../node_modules/@babel/runtime/helpers/isNativeFunction.js ***!
6014 \******************************************************************/
6015 /***/ ((module) => {
6016
6017 function _isNativeFunction(t) {
6018 try {
6019 return -1 !== Function.toString.call(t).indexOf("[native code]");
6020 } catch (n) {
6021 return "function" == typeof t;
6022 }
6023 }
6024 module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports;
6025
6026 /***/ }),
6027
6028 /***/ "../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js":
6029 /*!**************************************************************************!*\
6030 !*** ../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js ***!
6031 \**************************************************************************/
6032 /***/ ((module) => {
6033
6034 function _isNativeReflectConstruct() {
6035 try {
6036 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
6037 } catch (t) {}
6038 return (module.exports = _isNativeReflectConstruct = function _isNativeReflectConstruct() {
6039 return !!t;
6040 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6041 }
6042 module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports;
6043
6044 /***/ }),
6045
6046 /***/ "../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js":
6047 /*!**********************************************************************!*\
6048 !*** ../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js ***!
6049 \**********************************************************************/
6050 /***/ ((module) => {
6051
6052 function _iterableToArrayLimit(r, l) {
6053 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
6054 if (null != t) {
6055 var e,
6056 n,
6057 i,
6058 u,
6059 a = [],
6060 f = !0,
6061 o = !1;
6062 try {
6063 if (i = (t = t.call(r)).next, 0 === l) {
6064 if (Object(t) !== t) return;
6065 f = !1;
6066 } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
6067 } catch (r) {
6068 o = !0, n = r;
6069 } finally {
6070 try {
6071 if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
6072 } finally {
6073 if (o) throw n;
6074 }
6075 }
6076 return a;
6077 }
6078 }
6079 module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
6080
6081 /***/ }),
6082
6083 /***/ "../node_modules/@babel/runtime/helpers/nonIterableRest.js":
6084 /*!*****************************************************************!*\
6085 !*** ../node_modules/@babel/runtime/helpers/nonIterableRest.js ***!
6086 \*****************************************************************/
6087 /***/ ((module) => {
6088
6089 function _nonIterableRest() {
6090 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6091 }
6092 module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
6093
6094 /***/ }),
6095
6096 /***/ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js":
6097 /*!***************************************************************************!*\
6098 !*** ../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
6099 \***************************************************************************/
6100 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6101
6102 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6103 var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized.js */ "../node_modules/@babel/runtime/helpers/assertThisInitialized.js");
6104 function _possibleConstructorReturn(t, e) {
6105 if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
6106 if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
6107 return assertThisInitialized(t);
6108 }
6109 module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports;
6110
6111 /***/ }),
6112
6113 /***/ "../node_modules/@babel/runtime/helpers/readOnlyError.js":
6114 /*!***************************************************************!*\
6115 !*** ../node_modules/@babel/runtime/helpers/readOnlyError.js ***!
6116 \***************************************************************/
6117 /***/ ((module) => {
6118
6119 function _readOnlyError(r) {
6120 throw new TypeError('"' + r + '" is read-only');
6121 }
6122 module.exports = _readOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports;
6123
6124 /***/ }),
6125
6126 /***/ "../node_modules/@babel/runtime/helpers/regenerator.js":
6127 /*!*************************************************************!*\
6128 !*** ../node_modules/@babel/runtime/helpers/regenerator.js ***!
6129 \*************************************************************/
6130 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6131
6132 var regeneratorDefine = __webpack_require__(/*! ./regeneratorDefine.js */ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js");
6133 function _regenerator() {
6134 /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
6135 var e,
6136 t,
6137 r = "function" == typeof Symbol ? Symbol : {},
6138 n = r.iterator || "@@iterator",
6139 o = r.toStringTag || "@@toStringTag";
6140 function i(r, n, o, i) {
6141 var c = n && n.prototype instanceof Generator ? n : Generator,
6142 u = Object.create(c.prototype);
6143 return regeneratorDefine(u, "_invoke", function (r, n, o) {
6144 var i,
6145 c,
6146 u,
6147 f = 0,
6148 p = o || [],
6149 y = !1,
6150 G = {
6151 p: 0,
6152 n: 0,
6153 v: e,
6154 a: d,
6155 f: d.bind(e, 4),
6156 d: function d(t, r) {
6157 return i = t, c = 0, u = e, G.n = r, a;
6158 }
6159 };
6160 function d(r, n) {
6161 for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
6162 var o,
6163 i = p[t],
6164 d = G.p,
6165 l = i[2];
6166 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));
6167 }
6168 if (o || r > 1) return a;
6169 throw y = !0, n;
6170 }
6171 return function (o, p, l) {
6172 if (f > 1) throw TypeError("Generator is already running");
6173 for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
6174 i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
6175 try {
6176 if (f = 2, i) {
6177 if (c || (o = "next"), t = i[o]) {
6178 if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
6179 if (!t.done) return t;
6180 u = t.value, c < 2 && (c = 0);
6181 } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
6182 i = e;
6183 } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
6184 } catch (t) {
6185 i = e, c = 1, u = t;
6186 } finally {
6187 f = 1;
6188 }
6189 }
6190 return {
6191 value: t,
6192 done: y
6193 };
6194 };
6195 }(r, o, i), !0), u;
6196 }
6197 var a = {};
6198 function Generator() {}
6199 function GeneratorFunction() {}
6200 function GeneratorFunctionPrototype() {}
6201 t = Object.getPrototypeOf;
6202 var c = [][n] ? t(t([][n]())) : (regeneratorDefine(t = {}, n, function () {
6203 return this;
6204 }), t),
6205 u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
6206 function f(e) {
6207 return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
6208 }
6209 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 () {
6210 return this;
6211 }), regeneratorDefine(u, "toString", function () {
6212 return "[object Generator]";
6213 }), (module.exports = _regenerator = function _regenerator() {
6214 return {
6215 w: i,
6216 m: f
6217 };
6218 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6219 }
6220 module.exports = _regenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
6221
6222 /***/ }),
6223
6224 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsync.js":
6225 /*!******************************************************************!*\
6226 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsync.js ***!
6227 \******************************************************************/
6228 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6229
6230 var regeneratorAsyncGen = __webpack_require__(/*! ./regeneratorAsyncGen.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");
6231 function _regeneratorAsync(n, e, r, t, o) {
6232 var a = regeneratorAsyncGen(n, e, r, t, o);
6233 return a.next().then(function (n) {
6234 return n.done ? n.value : a.next();
6235 });
6236 }
6237 module.exports = _regeneratorAsync, module.exports.__esModule = true, module.exports["default"] = module.exports;
6238
6239 /***/ }),
6240
6241 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js":
6242 /*!*********************************************************************!*\
6243 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js ***!
6244 \*********************************************************************/
6245 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6246
6247 var regenerator = __webpack_require__(/*! ./regenerator.js */ "../node_modules/@babel/runtime/helpers/regenerator.js");
6248 var regeneratorAsyncIterator = __webpack_require__(/*! ./regeneratorAsyncIterator.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");
6249 function _regeneratorAsyncGen(r, e, t, o, n) {
6250 return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise);
6251 }
6252 module.exports = _regeneratorAsyncGen, module.exports.__esModule = true, module.exports["default"] = module.exports;
6253
6254 /***/ }),
6255
6256 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js":
6257 /*!**************************************************************************!*\
6258 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js ***!
6259 \**************************************************************************/
6260 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6261
6262 var OverloadYield = __webpack_require__(/*! ./OverloadYield.js */ "../node_modules/@babel/runtime/helpers/OverloadYield.js");
6263 var regeneratorDefine = __webpack_require__(/*! ./regeneratorDefine.js */ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js");
6264 function AsyncIterator(t, e) {
6265 function n(r, o, i, f) {
6266 try {
6267 var c = t[r](o),
6268 u = c.value;
6269 return u instanceof OverloadYield ? e.resolve(u.v).then(function (t) {
6270 n("next", t, i, f);
6271 }, function (t) {
6272 n("throw", t, i, f);
6273 }) : e.resolve(u).then(function (t) {
6274 c.value = t, i(c);
6275 }, function (t) {
6276 return n("throw", t, i, f);
6277 });
6278 } catch (t) {
6279 f(t);
6280 }
6281 }
6282 var r;
6283 this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () {
6284 return this;
6285 })), regeneratorDefine(this, "_invoke", function (t, o, i) {
6286 function f() {
6287 return new e(function (e, r) {
6288 n(t, i, e, r);
6289 });
6290 }
6291 return r = r ? r.then(f, f) : f();
6292 }, !0);
6293 }
6294 module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;
6295
6296 /***/ }),
6297
6298 /***/ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js":
6299 /*!*******************************************************************!*\
6300 !*** ../node_modules/@babel/runtime/helpers/regeneratorDefine.js ***!
6301 \*******************************************************************/
6302 /***/ ((module) => {
6303
6304 function _regeneratorDefine(e, r, n, t) {
6305 var i = Object.defineProperty;
6306 try {
6307 i({}, "", {});
6308 } catch (e) {
6309 i = 0;
6310 }
6311 module.exports = _regeneratorDefine = function regeneratorDefine(e, r, n, t) {
6312 function o(r, n) {
6313 _regeneratorDefine(e, r, function (e) {
6314 return this._invoke(r, n, e);
6315 });
6316 }
6317 r ? i ? i(e, r, {
6318 value: n,
6319 enumerable: !t,
6320 configurable: !t,
6321 writable: !t
6322 }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
6323 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _regeneratorDefine(e, r, n, t);
6324 }
6325 module.exports = _regeneratorDefine, module.exports.__esModule = true, module.exports["default"] = module.exports;
6326
6327 /***/ }),
6328
6329 /***/ "../node_modules/@babel/runtime/helpers/regeneratorKeys.js":
6330 /*!*****************************************************************!*\
6331 !*** ../node_modules/@babel/runtime/helpers/regeneratorKeys.js ***!
6332 \*****************************************************************/
6333 /***/ ((module) => {
6334
6335 function _regeneratorKeys(e) {
6336 var n = Object(e),
6337 r = [];
6338 for (var t in n) r.unshift(t);
6339 return function e() {
6340 for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e;
6341 return e.done = !0, e;
6342 };
6343 }
6344 module.exports = _regeneratorKeys, module.exports.__esModule = true, module.exports["default"] = module.exports;
6345
6346 /***/ }),
6347
6348 /***/ "../node_modules/@babel/runtime/helpers/regeneratorRuntime.js":
6349 /*!********************************************************************!*\
6350 !*** ../node_modules/@babel/runtime/helpers/regeneratorRuntime.js ***!
6351 \********************************************************************/
6352 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6353
6354 var OverloadYield = __webpack_require__(/*! ./OverloadYield.js */ "../node_modules/@babel/runtime/helpers/OverloadYield.js");
6355 var regenerator = __webpack_require__(/*! ./regenerator.js */ "../node_modules/@babel/runtime/helpers/regenerator.js");
6356 var regeneratorAsync = __webpack_require__(/*! ./regeneratorAsync.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsync.js");
6357 var regeneratorAsyncGen = __webpack_require__(/*! ./regeneratorAsyncGen.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");
6358 var regeneratorAsyncIterator = __webpack_require__(/*! ./regeneratorAsyncIterator.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");
6359 var regeneratorKeys = __webpack_require__(/*! ./regeneratorKeys.js */ "../node_modules/@babel/runtime/helpers/regeneratorKeys.js");
6360 var regeneratorValues = __webpack_require__(/*! ./regeneratorValues.js */ "../node_modules/@babel/runtime/helpers/regeneratorValues.js");
6361 function _regeneratorRuntime() {
6362 "use strict";
6363
6364 var r = regenerator(),
6365 e = r.m(_regeneratorRuntime),
6366 t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor;
6367 function n(r) {
6368 var e = "function" == typeof r && r.constructor;
6369 return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name));
6370 }
6371 var o = {
6372 "throw": 1,
6373 "return": 2,
6374 "break": 3,
6375 "continue": 3
6376 };
6377 function a(r) {
6378 var e, t;
6379 return function (n) {
6380 e || (e = {
6381 stop: function stop() {
6382 return t(n.a, 2);
6383 },
6384 "catch": function _catch() {
6385 return n.v;
6386 },
6387 abrupt: function abrupt(r, e) {
6388 return t(n.a, o[r], e);
6389 },
6390 delegateYield: function delegateYield(r, o, a) {
6391 return e.resultName = o, t(n.d, regeneratorValues(r), a);
6392 },
6393 finish: function finish(r) {
6394 return t(n.f, r);
6395 }
6396 }, t = function t(r, _t, o) {
6397 n.p = e.prev, n.n = e.next;
6398 try {
6399 return r(_t, o);
6400 } finally {
6401 e.next = n.n;
6402 }
6403 }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n;
6404 try {
6405 return r.call(this, e);
6406 } finally {
6407 n.p = e.prev, n.n = e.next;
6408 }
6409 };
6410 }
6411 return (module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
6412 return {
6413 wrap: function wrap(e, t, n, o) {
6414 return r.w(a(e), t, n, o && o.reverse());
6415 },
6416 isGeneratorFunction: n,
6417 mark: r.m,
6418 awrap: function awrap(r, e) {
6419 return new OverloadYield(r, e);
6420 },
6421 AsyncIterator: regeneratorAsyncIterator,
6422 async: function async(r, e, t, o, u) {
6423 return (n(e) ? regeneratorAsyncGen : regeneratorAsync)(a(r), e, t, o, u);
6424 },
6425 keys: regeneratorKeys,
6426 values: regeneratorValues
6427 };
6428 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6429 }
6430 module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
6431
6432 /***/ }),
6433
6434 /***/ "../node_modules/@babel/runtime/helpers/regeneratorValues.js":
6435 /*!*******************************************************************!*\
6436 !*** ../node_modules/@babel/runtime/helpers/regeneratorValues.js ***!
6437 \*******************************************************************/
6438 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6439
6440 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6441 function _regeneratorValues(e) {
6442 if (null != e) {
6443 var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
6444 r = 0;
6445 if (t) return t.call(e);
6446 if ("function" == typeof e.next) return e;
6447 if (!isNaN(e.length)) return {
6448 next: function next() {
6449 return e && r >= e.length && (e = void 0), {
6450 value: e && e[r++],
6451 done: !e
6452 };
6453 }
6454 };
6455 }
6456 throw new TypeError(_typeof(e) + " is not iterable");
6457 }
6458 module.exports = _regeneratorValues, module.exports.__esModule = true, module.exports["default"] = module.exports;
6459
6460 /***/ }),
6461
6462 /***/ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js":
6463 /*!****************************************************************!*\
6464 !*** ../node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
6465 \****************************************************************/
6466 /***/ ((module) => {
6467
6468 function _setPrototypeOf(t, e) {
6469 return module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
6470 return t.__proto__ = e, t;
6471 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _setPrototypeOf(t, e);
6472 }
6473 module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
6474
6475 /***/ }),
6476
6477 /***/ "../node_modules/@babel/runtime/helpers/slicedToArray.js":
6478 /*!***************************************************************!*\
6479 !*** ../node_modules/@babel/runtime/helpers/slicedToArray.js ***!
6480 \***************************************************************/
6481 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6482
6483 var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles.js */ "../node_modules/@babel/runtime/helpers/arrayWithHoles.js");
6484 var iterableToArrayLimit = __webpack_require__(/*! ./iterableToArrayLimit.js */ "../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js");
6485 var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray.js */ "../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js");
6486 var nonIterableRest = __webpack_require__(/*! ./nonIterableRest.js */ "../node_modules/@babel/runtime/helpers/nonIterableRest.js");
6487 function _slicedToArray(r, e) {
6488 return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();
6489 }
6490 module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
6491
6492 /***/ }),
6493
6494 /***/ "../node_modules/@babel/runtime/helpers/superPropBase.js":
6495 /*!***************************************************************!*\
6496 !*** ../node_modules/@babel/runtime/helpers/superPropBase.js ***!
6497 \***************************************************************/
6498 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6499
6500 var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js");
6501 function _superPropBase(t, o) {
6502 for (; !{}.hasOwnProperty.call(t, o) && null !== (t = getPrototypeOf(t)););
6503 return t;
6504 }
6505 module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports;
6506
6507 /***/ }),
6508
6509 /***/ "../node_modules/@babel/runtime/helpers/toPrimitive.js":
6510 /*!*************************************************************!*\
6511 !*** ../node_modules/@babel/runtime/helpers/toPrimitive.js ***!
6512 \*************************************************************/
6513 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6514
6515 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6516 function toPrimitive(t, r) {
6517 if ("object" != _typeof(t) || !t) return t;
6518 var e = t[Symbol.toPrimitive];
6519 if (void 0 !== e) {
6520 var i = e.call(t, r || "default");
6521 if ("object" != _typeof(i)) return i;
6522 throw new TypeError("@@toPrimitive must return a primitive value.");
6523 }
6524 return ("string" === r ? String : Number)(t);
6525 }
6526 module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
6527
6528 /***/ }),
6529
6530 /***/ "../node_modules/@babel/runtime/helpers/toPropertyKey.js":
6531 /*!***************************************************************!*\
6532 !*** ../node_modules/@babel/runtime/helpers/toPropertyKey.js ***!
6533 \***************************************************************/
6534 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6535
6536 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6537 var toPrimitive = __webpack_require__(/*! ./toPrimitive.js */ "../node_modules/@babel/runtime/helpers/toPrimitive.js");
6538 function toPropertyKey(t) {
6539 var i = toPrimitive(t, "string");
6540 return "symbol" == _typeof(i) ? i : i + "";
6541 }
6542 module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
6543
6544 /***/ }),
6545
6546 /***/ "../node_modules/@babel/runtime/helpers/typeof.js":
6547 /*!********************************************************!*\
6548 !*** ../node_modules/@babel/runtime/helpers/typeof.js ***!
6549 \********************************************************/
6550 /***/ ((module) => {
6551
6552 function _typeof(o) {
6553 "@babel/helpers - typeof";
6554
6555 return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
6556 return typeof o;
6557 } : function (o) {
6558 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
6559 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
6560 }
6561 module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
6562
6563 /***/ }),
6564
6565 /***/ "../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js":
6566 /*!****************************************************************************!*\
6567 !*** ../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js ***!
6568 \****************************************************************************/
6569 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6570
6571 var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray.js */ "../node_modules/@babel/runtime/helpers/arrayLikeToArray.js");
6572 function _unsupportedIterableToArray(r, a) {
6573 if (r) {
6574 if ("string" == typeof r) return arrayLikeToArray(r, a);
6575 var t = {}.toString.call(r).slice(8, -1);
6576 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;
6577 }
6578 }
6579 module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
6580
6581 /***/ }),
6582
6583 /***/ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js":
6584 /*!*****************************************************************!*\
6585 !*** ../node_modules/@babel/runtime/helpers/wrapNativeSuper.js ***!
6586 \*****************************************************************/
6587 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6588
6589 var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js");
6590 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
6591 var isNativeFunction = __webpack_require__(/*! ./isNativeFunction.js */ "../node_modules/@babel/runtime/helpers/isNativeFunction.js");
6592 var construct = __webpack_require__(/*! ./construct.js */ "../node_modules/@babel/runtime/helpers/construct.js");
6593 function _wrapNativeSuper(t) {
6594 var r = "function" == typeof Map ? new Map() : void 0;
6595 return module.exports = _wrapNativeSuper = function _wrapNativeSuper(t) {
6596 if (null === t || !isNativeFunction(t)) return t;
6597 if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
6598 if (void 0 !== r) {
6599 if (r.has(t)) return r.get(t);
6600 r.set(t, Wrapper);
6601 }
6602 function Wrapper() {
6603 return construct(t, arguments, getPrototypeOf(this).constructor);
6604 }
6605 return Wrapper.prototype = Object.create(t.prototype, {
6606 constructor: {
6607 value: Wrapper,
6608 enumerable: !1,
6609 writable: !0,
6610 configurable: !0
6611 }
6612 }), setPrototypeOf(Wrapper, t);
6613 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _wrapNativeSuper(t);
6614 }
6615 module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports;
6616
6617 /***/ }),
6618
6619 /***/ "../node_modules/@babel/runtime/regenerator/index.js":
6620 /*!***********************************************************!*\
6621 !*** ../node_modules/@babel/runtime/regenerator/index.js ***!
6622 \***********************************************************/
6623 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6624
6625 // TODO(Babel 8): Remove this file.
6626
6627 var runtime = __webpack_require__(/*! ../helpers/regeneratorRuntime */ "../node_modules/@babel/runtime/helpers/regeneratorRuntime.js")();
6628 module.exports = runtime;
6629
6630 // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
6631 try {
6632 regeneratorRuntime = runtime;
6633 } catch (accidentalStrictMode) {
6634 if (typeof globalThis === "object") {
6635 globalThis.regeneratorRuntime = runtime;
6636 } else {
6637 Function("r", "regeneratorRuntime = r")(runtime);
6638 }
6639 }
6640
6641
6642 /***/ }),
6643
6644 /***/ "../node_modules/mixpanel-browser/dist/mixpanel.module.js":
6645 /*!****************************************************************!*\
6646 !*** ../node_modules/mixpanel-browser/dist/mixpanel.module.js ***!
6647 \****************************************************************/
6648 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
6649
6650 "use strict";
6651 __webpack_require__.r(__webpack_exports__);
6652 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6653 /* harmony export */ "default": () => (/* binding */ mixpanel)
6654 /* harmony export */ });
6655 // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
6656 var win;
6657 if (typeof(window) === 'undefined') {
6658 var loc = {
6659 hostname: ''
6660 };
6661 win = {
6662 crypto: {randomUUID: function() {throw Error('unsupported');}},
6663 navigator: { userAgent: '', onLine: true },
6664 document: {
6665 createElement: function() { return {}; },
6666 location: loc,
6667 referrer: ''
6668 },
6669 screen: { width: 0, height: 0 },
6670 location: loc,
6671 addEventListener: function() {},
6672 removeEventListener: function() {}
6673 };
6674 } else {
6675 win = window;
6676 }
6677
6678 function _array_like_to_array(arr, len) {
6679 if (len == null || len > arr.length) len = arr.length;
6680 for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
6681 return arr2;
6682 }
6683 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
6684 try {
6685 var info = gen[key](arg);
6686 var value = info.value;
6687 } catch (error) {
6688 reject(error);
6689 return;
6690 }
6691 if (info.done) {
6692 resolve(value);
6693 } else {
6694 Promise.resolve(value).then(_next, _throw);
6695 }
6696 }
6697 function _async_to_generator(fn) {
6698 return function() {
6699 var self = this, args = arguments;
6700 return new Promise(function(resolve, reject) {
6701 var gen = fn.apply(self, args);
6702 function _next(value) {
6703 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
6704 }
6705 function _throw(err) {
6706 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
6707 }
6708 _next(undefined);
6709 });
6710 };
6711 }
6712 function _construct(Parent, args, Class) {
6713 if (_is_native_reflect_construct()) {
6714 _construct = Reflect.construct;
6715 } else {
6716 _construct = function construct(Parent, args, Class) {
6717 var a = [
6718 null
6719 ];
6720 a.push.apply(a, args);
6721 var Constructor = Function.bind.apply(Parent, a);
6722 var instance = new Constructor();
6723 if (Class) _set_prototype_of(instance, Class.prototype);
6724 return instance;
6725 };
6726 }
6727 return _construct.apply(null, arguments);
6728 }
6729 function _defineProperties(target, props) {
6730 for(var i = 0; i < props.length; i++){
6731 var descriptor = props[i];
6732 descriptor.enumerable = descriptor.enumerable || false;
6733 descriptor.configurable = true;
6734 if ("value" in descriptor) descriptor.writable = true;
6735 Object.defineProperty(target, descriptor.key, descriptor);
6736 }
6737 }
6738 function _create_class(Constructor, protoProps, staticProps) {
6739 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
6740 return Constructor;
6741 }
6742 function _extends() {
6743 _extends = Object.assign || function(target) {
6744 for(var i = 1; i < arguments.length; i++){
6745 var source = arguments[i];
6746 for(var key in source){
6747 if (Object.prototype.hasOwnProperty.call(source, key)) {
6748 target[key] = source[key];
6749 }
6750 }
6751 }
6752 return target;
6753 };
6754 return _extends.apply(this, arguments);
6755 }
6756 function _get_prototype_of(o) {
6757 _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
6758 return o.__proto__ || Object.getPrototypeOf(o);
6759 };
6760 return _get_prototype_of(o);
6761 }
6762 function _inherits(subClass, superClass) {
6763 if (typeof superClass !== "function" && superClass !== null) {
6764 throw new TypeError("Super expression must either be null or a function");
6765 }
6766 subClass.prototype = Object.create(superClass && superClass.prototype, {
6767 constructor: {
6768 value: subClass,
6769 writable: true,
6770 configurable: true
6771 }
6772 });
6773 if (superClass) _set_prototype_of(subClass, superClass);
6774 }
6775 function _instanceof(left, right) {
6776 if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
6777 return !!right[Symbol.hasInstance](left);
6778 } else {
6779 return left instanceof right;
6780 }
6781 }
6782 function _is_native_function(fn) {
6783 return Function.toString.call(fn).indexOf("[native code]") !== -1;
6784 }
6785 function _object_without_properties_loose(source, excluded) {
6786 if (source == null) return {};
6787 var target = {};
6788 var sourceKeys = Object.keys(source);
6789 var key, i;
6790 for(i = 0; i < sourceKeys.length; i++){
6791 key = sourceKeys[i];
6792 if (excluded.indexOf(key) >= 0) continue;
6793 target[key] = source[key];
6794 }
6795 return target;
6796 }
6797 function _set_prototype_of(o, p) {
6798 _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
6799 o.__proto__ = p;
6800 return o;
6801 };
6802 return _set_prototype_of(o, p);
6803 }
6804 function _type_of(obj) {
6805 "@swc/helpers - typeof";
6806 return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
6807 }
6808 function _unsupported_iterable_to_array(o, minLen) {
6809 if (!o) return;
6810 if (typeof o === "string") return _array_like_to_array(o, minLen);
6811 var n = Object.prototype.toString.call(o).slice(8, -1);
6812 if (n === "Object" && o.constructor) n = o.constructor.name;
6813 if (n === "Map" || n === "Set") return Array.from(n);
6814 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
6815 }
6816 function _wrap_native_super(Class) {
6817 var _cache = typeof Map === "function" ? new Map() : undefined;
6818 _wrap_native_super = function wrapNativeSuper(Class) {
6819 if (Class === null || !_is_native_function(Class)) return Class;
6820 if (typeof Class !== "function") {
6821 throw new TypeError("Super expression must either be null or a function");
6822 }
6823 if (typeof _cache !== "undefined") {
6824 if (_cache.has(Class)) return _cache.get(Class);
6825 _cache.set(Class, Wrapper);
6826 }
6827 function Wrapper() {
6828 return _construct(Class, arguments, _get_prototype_of(this).constructor);
6829 }
6830 Wrapper.prototype = Object.create(Class.prototype, {
6831 constructor: {
6832 value: Wrapper,
6833 enumerable: false,
6834 writable: true,
6835 configurable: true
6836 }
6837 });
6838 return _set_prototype_of(Wrapper, Class);
6839 };
6840 return _wrap_native_super(Class);
6841 }
6842 function _is_native_reflect_construct() {
6843 try {
6844 var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
6845 } catch (_) {}
6846 return (_is_native_reflect_construct = function() {
6847 return !!result;
6848 })();
6849 }
6850 function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
6851 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
6852 if (it) return (it = it.call(o)).next.bind(it);
6853 if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike) {
6854 if (it) o = it;
6855 var i = 0;
6856 return function() {
6857 if (i >= o.length) {
6858 return {
6859 done: true
6860 };
6861 }
6862 return {
6863 done: false,
6864 value: o[i++]
6865 };
6866 };
6867 }
6868 throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6869 }
6870 function _ts_generator(thisArg, body) {
6871 var f, y, t, g, _ = {
6872 label: 0,
6873 sent: function() {
6874 if (t[0] & 1) throw t[1];
6875 return t[1];
6876 },
6877 trys: [],
6878 ops: []
6879 };
6880 return g = {
6881 next: verb(0),
6882 "throw": verb(1),
6883 "return": verb(2)
6884 }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
6885 return this;
6886 }), g;
6887 function verb(n) {
6888 return function(v) {
6889 return step([
6890 n,
6891 v
6892 ]);
6893 };
6894 }
6895 function step(op) {
6896 if (f) throw new TypeError("Generator is already executing.");
6897 while(_)try {
6898 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;
6899 if (y = 0, t) op = [
6900 op[0] & 2,
6901 t.value
6902 ];
6903 switch(op[0]){
6904 case 0:
6905 case 1:
6906 t = op;
6907 break;
6908 case 4:
6909 _.label++;
6910 return {
6911 value: op[1],
6912 done: false
6913 };
6914 case 5:
6915 _.label++;
6916 y = op[1];
6917 op = [
6918 0
6919 ];
6920 continue;
6921 case 7:
6922 op = _.ops.pop();
6923 _.trys.pop();
6924 continue;
6925 default:
6926 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
6927 _ = 0;
6928 continue;
6929 }
6930 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
6931 _.label = op[1];
6932 break;
6933 }
6934 if (op[0] === 6 && _.label < t[1]) {
6935 _.label = t[1];
6936 t = op;
6937 break;
6938 }
6939 if (t && _.label < t[2]) {
6940 _.label = t[2];
6941 _.ops.push(op);
6942 break;
6943 }
6944 if (t[2]) _.ops.pop();
6945 _.trys.pop();
6946 continue;
6947 }
6948 op = body.call(thisArg, _);
6949 } catch (e) {
6950 op = [
6951 6,
6952 e
6953 ];
6954 y = 0;
6955 } finally{
6956 f = t = 0;
6957 }
6958 if (op[0] & 5) throw op[1];
6959 return {
6960 value: op[0] ? op[1] : void 0,
6961 done: true
6962 };
6963 }
6964 }
6965 function _ts_values(o) {
6966 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
6967 if (m) return m.call(o);
6968 if (o && typeof o.length === "number") return {
6969 next: function() {
6970 if (o && i >= o.length) o = void 0;
6971 return {
6972 value: o && o[i++],
6973 done: !o
6974 };
6975 }
6976 };
6977 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
6978 }
6979 var __defProp = Object.defineProperty;
6980 var __defNormalProp = function(obj, key, value) {
6981 return key in obj ? __defProp(obj, key, {
6982 enumerable: true,
6983 configurable: true,
6984 writable: true,
6985 value: value
6986 }) : obj[key] = value;
6987 };
6988 var __publicField = function(obj, key, value) {
6989 return __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
6990 };
6991 var _a;
6992 var __defProp$1 = Object.defineProperty;
6993 var __defNormalProp$1 = function(obj, key, value) {
6994 return key in obj ? __defProp$1(obj, key, {
6995 enumerable: true,
6996 configurable: true,
6997 writable: true,
6998 value: value
6999 }) : obj[key] = value;
7000 };
7001 var __publicField$1 = function(obj, key, value) {
7002 return __defNormalProp$1(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
7003 };
7004 var NodeType$3 = /* @__PURE__ */ function(NodeType2) {
7005 NodeType2[NodeType2["Document"] = 0] = "Document";
7006 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
7007 NodeType2[NodeType2["Element"] = 2] = "Element";
7008 NodeType2[NodeType2["Text"] = 3] = "Text";
7009 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
7010 NodeType2[NodeType2["Comment"] = 5] = "Comment";
7011 return NodeType2;
7012 }(NodeType$3 || {});
7013 var testableAccessors$1 = {
7014 Node: [
7015 "childNodes",
7016 "parentNode",
7017 "parentElement",
7018 "textContent"
7019 ],
7020 ShadowRoot: [
7021 "host",
7022 "styleSheets"
7023 ],
7024 Element: [
7025 "shadowRoot",
7026 "querySelector",
7027 "querySelectorAll"
7028 ],
7029 MutationObserver: []
7030 };
7031 var testableMethods$1 = {
7032 Node: [
7033 "contains",
7034 "getRootNode"
7035 ],
7036 ShadowRoot: [
7037 "getSelection"
7038 ],
7039 Element: [],
7040 MutationObserver: [
7041 "constructor"
7042 ]
7043 };
7044 var untaintedBasePrototype$1 = {};
7045 var isAngularZonePresent$1 = function() {
7046 return !!globalThis.Zone;
7047 };
7048 function getUntaintedPrototype$1(key) {
7049 if (untaintedBasePrototype$1[key]) return untaintedBasePrototype$1[key];
7050 var defaultObj = globalThis[key];
7051 var defaultPrototype = defaultObj.prototype;
7052 var accessorNames = key in testableAccessors$1 ? testableAccessors$1[key] : void 0;
7053 var isUntaintedAccessors = Boolean(accessorNames && // @ts-expect-error 2345
7054 accessorNames.every(function(accessor) {
7055 var _a2, _b;
7056 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
7057 }));
7058 var methodNames = key in testableMethods$1 ? testableMethods$1[key] : void 0;
7059 var isUntaintedMethods = Boolean(methodNames && methodNames.every(// @ts-expect-error 2345
7060 function(method) {
7061 var _a2;
7062 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
7063 }));
7064 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent$1()) {
7065 untaintedBasePrototype$1[key] = defaultObj.prototype;
7066 return defaultObj.prototype;
7067 }
7068 try {
7069 var iframeEl = document.createElement("iframe");
7070 document.body.appendChild(iframeEl);
7071 var win = iframeEl.contentWindow;
7072 if (!win) return defaultObj.prototype;
7073 var untaintedObject = win[key].prototype;
7074 document.body.removeChild(iframeEl);
7075 if (!untaintedObject) return defaultPrototype;
7076 return untaintedBasePrototype$1[key] = untaintedObject;
7077 } catch (e) {
7078 return defaultPrototype;
7079 }
7080 }
7081 var untaintedAccessorCache$1 = {};
7082 function getUntaintedAccessor$1(key, instance, accessor) {
7083 var _a2;
7084 var cacheKey = key + "." + String(accessor);
7085 if (untaintedAccessorCache$1[cacheKey]) return untaintedAccessorCache$1[cacheKey].call(instance);
7086 var untaintedPrototype = getUntaintedPrototype$1(key);
7087 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
7088 if (!untaintedAccessor) return instance[accessor];
7089 untaintedAccessorCache$1[cacheKey] = untaintedAccessor;
7090 return untaintedAccessor.call(instance);
7091 }
7092 var untaintedMethodCache$1 = {};
7093 function getUntaintedMethod$1(key, instance, method) {
7094 var cacheKey = key + "." + String(method);
7095 if (untaintedMethodCache$1[cacheKey]) return untaintedMethodCache$1[cacheKey].bind(instance);
7096 var untaintedPrototype = getUntaintedPrototype$1(key);
7097 var untaintedMethod = untaintedPrototype[method];
7098 if (typeof untaintedMethod !== "function") return instance[method];
7099 untaintedMethodCache$1[cacheKey] = untaintedMethod;
7100 return untaintedMethod.bind(instance);
7101 }
7102 function childNodes$1(n2) {
7103 return getUntaintedAccessor$1("Node", n2, "childNodes");
7104 }
7105 function parentNode$1(n2) {
7106 return getUntaintedAccessor$1("Node", n2, "parentNode");
7107 }
7108 function parentElement$1(n2) {
7109 return getUntaintedAccessor$1("Node", n2, "parentElement");
7110 }
7111 function textContent$1(n2) {
7112 return getUntaintedAccessor$1("Node", n2, "textContent");
7113 }
7114 function contains$1(n2, other) {
7115 return getUntaintedMethod$1("Node", n2, "contains")(other);
7116 }
7117 function getRootNode$1(n2) {
7118 return getUntaintedMethod$1("Node", n2, "getRootNode")();
7119 }
7120 function host$1(n2) {
7121 if (!n2 || !("host" in n2)) return null;
7122 return getUntaintedAccessor$1("ShadowRoot", n2, "host");
7123 }
7124 function styleSheets$1(n2) {
7125 return n2.styleSheets;
7126 }
7127 function shadowRoot$1(n2) {
7128 if (!n2 || !("shadowRoot" in n2)) return null;
7129 return getUntaintedAccessor$1("Element", n2, "shadowRoot");
7130 }
7131 function querySelector$1(n2, selectors) {
7132 return getUntaintedAccessor$1("Element", n2, "querySelector")(selectors);
7133 }
7134 function querySelectorAll$1(n2, selectors) {
7135 return getUntaintedAccessor$1("Element", n2, "querySelectorAll")(selectors);
7136 }
7137 function mutationObserverCtor$1() {
7138 return getUntaintedPrototype$1("MutationObserver").constructor;
7139 }
7140 function patch$1(source, name, replacement) {
7141 try {
7142 if (!(name in source)) {
7143 return function() {};
7144 }
7145 var original = source[name];
7146 var wrapped = replacement(original);
7147 if (typeof wrapped === "function") {
7148 wrapped.prototype = wrapped.prototype || {};
7149 Object.defineProperties(wrapped, {
7150 __rrweb_original__: {
7151 enumerable: false,
7152 value: original
7153 }
7154 });
7155 }
7156 source[name] = wrapped;
7157 return function() {
7158 source[name] = original;
7159 };
7160 } catch (e) {
7161 return function() {};
7162 }
7163 }
7164 var index$1 = {
7165 childNodes: childNodes$1,
7166 parentNode: parentNode$1,
7167 parentElement: parentElement$1,
7168 textContent: textContent$1,
7169 contains: contains$1,
7170 getRootNode: getRootNode$1,
7171 host: host$1,
7172 styleSheets: styleSheets$1,
7173 shadowRoot: shadowRoot$1,
7174 querySelector: querySelector$1,
7175 querySelectorAll: querySelectorAll$1,
7176 mutationObserver: mutationObserverCtor$1,
7177 patch: patch$1
7178 };
7179 function isElement(n2) {
7180 return n2.nodeType === n2.ELEMENT_NODE;
7181 }
7182 function isShadowRoot(n2) {
7183 var hostEl = // anchor and textarea elements also have a `host` property
7184 // but only shadow roots have a `mode` property
7185 n2 && "host" in n2 && "mode" in n2 && index$1.host(n2) || null;
7186 return Boolean(hostEl && "shadowRoot" in hostEl && index$1.shadowRoot(hostEl) === n2);
7187 }
7188 function isNativeShadowDom(shadowRoot2) {
7189 return Object.prototype.toString.call(shadowRoot2) === "[object ShadowRoot]";
7190 }
7191 function fixBrowserCompatibilityIssuesInCSS(cssText) {
7192 if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) {
7193 cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;");
7194 }
7195 return cssText;
7196 }
7197 function escapeImportStatement(rule2) {
7198 var cssText = rule2.cssText;
7199 if (cssText.split('"').length < 3) return cssText;
7200 var statement = [
7201 "@import",
7202 "url(" + JSON.stringify(rule2.href) + ")"
7203 ];
7204 if (rule2.layerName === "") {
7205 statement.push("layer");
7206 } else if (rule2.layerName) {
7207 statement.push("layer(" + rule2.layerName + ")");
7208 }
7209 if (rule2.supportsText) {
7210 statement.push("supports(" + rule2.supportsText + ")");
7211 }
7212 if (rule2.media.length) {
7213 statement.push(rule2.media.mediaText);
7214 }
7215 return statement.join(" ") + ";";
7216 }
7217 function stringifyStylesheet(s2) {
7218 try {
7219 var rules2 = s2.rules || s2.cssRules;
7220 if (!rules2) {
7221 return null;
7222 }
7223 var sheetHref = s2.href;
7224 if (!sheetHref && s2.ownerNode && s2.ownerNode.ownerDocument) {
7225 sheetHref = s2.ownerNode.ownerDocument.location.href;
7226 }
7227 var stringifiedRules = Array.from(rules2, function(rule2) {
7228 return stringifyRule(rule2, sheetHref);
7229 }).join("");
7230 return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);
7231 } catch (error) {
7232 return null;
7233 }
7234 }
7235 function stringifyRule(rule2, sheetHref) {
7236 if (isCSSImportRule(rule2)) {
7237 var importStringified;
7238 try {
7239 importStringified = // we can access the imported stylesheet rules directly
7240 stringifyStylesheet(rule2.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement
7241 escapeImportStatement(rule2);
7242 } catch (error) {
7243 importStringified = rule2.cssText;
7244 }
7245 if (rule2.styleSheet.href) {
7246 return absolutifyURLs(importStringified, rule2.styleSheet.href);
7247 }
7248 return importStringified;
7249 } else {
7250 var ruleStringified = rule2.cssText;
7251 if (isCSSStyleRule(rule2) && rule2.selectorText.includes(":")) {
7252 ruleStringified = fixSafariColons(ruleStringified);
7253 }
7254 if (sheetHref) {
7255 return absolutifyURLs(ruleStringified, sheetHref);
7256 }
7257 return ruleStringified;
7258 }
7259 }
7260 function fixSafariColons(cssStringified) {
7261 var regex = /(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;
7262 return cssStringified.replace(regex, "$1\\$2");
7263 }
7264 function isCSSImportRule(rule2) {
7265 return "styleSheet" in rule2;
7266 }
7267 function isCSSStyleRule(rule2) {
7268 return "selectorText" in rule2;
7269 }
7270 var Mirror = /*#__PURE__*/ function() {
7271 function Mirror() {
7272 __publicField$1(this, "idNodeMap", /* @__PURE__ */ new Map());
7273 __publicField$1(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap());
7274 }
7275 var _proto = Mirror.prototype;
7276 _proto.getId = function getId(n2) {
7277 var _a2;
7278 if (!n2) return -1;
7279 var id = (_a2 = this.getMeta(n2)) == null ? void 0 : _a2.id;
7280 return id != null ? id : -1;
7281 };
7282 _proto.getNode = function getNode(id) {
7283 return this.idNodeMap.get(id) || null;
7284 };
7285 _proto.getIds = function getIds() {
7286 return Array.from(this.idNodeMap.keys());
7287 };
7288 _proto.getMeta = function getMeta(n2) {
7289 return this.nodeMetaMap.get(n2) || null;
7290 };
7291 // removes the node from idNodeMap
7292 // doesn't remove the node from nodeMetaMap
7293 _proto.removeNodeFromMap = function removeNodeFromMap(n2) {
7294 var _this = this;
7295 var id = this.getId(n2);
7296 this.idNodeMap.delete(id);
7297 if (n2.childNodes) {
7298 n2.childNodes.forEach(function(childNode) {
7299 return _this.removeNodeFromMap(childNode);
7300 });
7301 }
7302 };
7303 _proto.has = function has(id) {
7304 return this.idNodeMap.has(id);
7305 };
7306 _proto.hasNode = function hasNode(node2) {
7307 return this.nodeMetaMap.has(node2);
7308 };
7309 _proto.add = function add(n2, meta) {
7310 var id = meta.id;
7311 this.idNodeMap.set(id, n2);
7312 this.nodeMetaMap.set(n2, meta);
7313 };
7314 _proto.replace = function replace(id, n2) {
7315 var oldNode = this.getNode(id);
7316 if (oldNode) {
7317 var meta = this.nodeMetaMap.get(oldNode);
7318 if (meta) this.nodeMetaMap.set(n2, meta);
7319 }
7320 this.idNodeMap.set(id, n2);
7321 };
7322 _proto.reset = function reset() {
7323 this.idNodeMap = /* @__PURE__ */ new Map();
7324 this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
7325 };
7326 return Mirror;
7327 }();
7328 function createMirror$2() {
7329 return new Mirror();
7330 }
7331 function maskInputValue(param) {
7332 var element = param.element, maskInputOptions = param.maskInputOptions, tagName = param.tagName, type = param.type, value = param.value, maskInputFn = param.maskInputFn;
7333 var text = value || "";
7334 var actualType = type && toLowerCase(type);
7335 if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {
7336 if (maskInputFn) {
7337 text = maskInputFn(text, element);
7338 } else {
7339 text = "*".repeat(text.length);
7340 }
7341 }
7342 return text;
7343 }
7344 function toLowerCase(str) {
7345 return str.toLowerCase();
7346 }
7347 var ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
7348 function is2DCanvasBlank(canvas) {
7349 var ctx = canvas.getContext("2d");
7350 if (!ctx) return true;
7351 var chunkSize = 50;
7352 for(var x2 = 0; x2 < canvas.width; x2 += chunkSize){
7353 for(var y = 0; y < canvas.height; y += chunkSize){
7354 var getImageData = ctx.getImageData;
7355 var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
7356 var pixelBuffer = new Uint32Array(// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
7357 originalGetImageData.call(ctx, x2, y, Math.min(chunkSize, canvas.width - x2), Math.min(chunkSize, canvas.height - y)).data.buffer);
7358 if (pixelBuffer.some(function(pixel) {
7359 return pixel !== 0;
7360 })) return false;
7361 }
7362 }
7363 return true;
7364 }
7365 function getInputType(element) {
7366 var type = element.type;
7367 return element.hasAttribute("data-rr-is-password") ? "password" : type ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
7368 toLowerCase(type) : null;
7369 }
7370 function extractFileExtension(path, baseURL) {
7371 var url;
7372 try {
7373 url = new URL(path, baseURL != null ? baseURL : window.location.href);
7374 } catch (err) {
7375 return null;
7376 }
7377 var regex = /\.([0-9a-z]+)(?:$)/i;
7378 var match = url.pathname.match(regex);
7379 var _ref;
7380 return (_ref = match == null ? void 0 : match[1]) != null ? _ref : null;
7381 }
7382 function extractOrigin(url) {
7383 var origin = "";
7384 if (url.indexOf("//") > -1) {
7385 origin = url.split("/").slice(0, 3).join("/");
7386 } else {
7387 origin = url.split("/")[0];
7388 }
7389 origin = origin.split("?")[0];
7390 return origin;
7391 }
7392 var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
7393 var URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
7394 var URL_WWW_MATCH = /^www\..*/i;
7395 var DATA_URI = /^(data:)([^,]*),(.*)/i;
7396 function absolutifyURLs(cssText, href) {
7397 return (cssText || "").replace(URL_IN_CSS_REF, function(origin, quote1, path1, quote2, path2, path3) {
7398 var filePath = path1 || path2 || path3;
7399 var maybeQuote = quote1 || quote2 || "";
7400 if (!filePath) {
7401 return origin;
7402 }
7403 if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {
7404 return "url(" + maybeQuote + filePath + maybeQuote + ")";
7405 }
7406 if (DATA_URI.test(filePath)) {
7407 return "url(" + maybeQuote + filePath + maybeQuote + ")";
7408 }
7409 if (filePath[0] === "/") {
7410 return "url(" + maybeQuote + (extractOrigin(href) + filePath) + maybeQuote + ")";
7411 }
7412 var stack = href.split("/");
7413 var parts = filePath.split("/");
7414 stack.pop();
7415 for(var _iterator = _create_for_of_iterator_helper_loose(parts), _step; !(_step = _iterator()).done;){
7416 var part = _step.value;
7417 if (part === ".") {
7418 continue;
7419 } else if (part === "..") {
7420 stack.pop();
7421 } else {
7422 stack.push(part);
7423 }
7424 }
7425 return "url(" + maybeQuote + stack.join("/") + maybeQuote + ")";
7426 });
7427 }
7428 function normalizeCssString(cssText, _testNoPxNorm) {
7429 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
7430 if (_testNoPxNorm) {
7431 return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "");
7432 } else {
7433 return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "").replace(/0px/g, "0");
7434 }
7435 }
7436 function splitCssText(cssText, style, _testNoPxNorm) {
7437 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
7438 var childNodes2 = Array.from(style.childNodes);
7439 var splits = [];
7440 var iterCount = 0;
7441 if (childNodes2.length > 1 && cssText && typeof cssText === "string") {
7442 var cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);
7443 var normFactor = cssTextNorm.length / cssText.length;
7444 for(var i2 = 1; i2 < childNodes2.length; i2++){
7445 if (childNodes2[i2].textContent && typeof childNodes2[i2].textContent === "string") {
7446 var textContentNorm = normalizeCssString(childNodes2[i2].textContent, _testNoPxNorm);
7447 var jLimit = 100;
7448 var j = 3;
7449 for(; j < textContentNorm.length; j++){
7450 if (// keep consuming css identifiers (to get a decent chunk more quickly)
7451 textContentNorm[j].match(/[a-zA-Z0-9]/) || // substring needs to be unique to this section
7452 textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1) {
7453 continue;
7454 }
7455 break;
7456 }
7457 for(; j < textContentNorm.length; j++){
7458 var startSubstring = textContentNorm.substring(0, j);
7459 var cssNormSplits = cssTextNorm.split(startSubstring);
7460 var splitNorm = -1;
7461 if (cssNormSplits.length === 2) {
7462 splitNorm = cssNormSplits[0].length;
7463 } else if (cssNormSplits.length > 2 && cssNormSplits[0] === "" && childNodes2[i2 - 1].textContent !== "") {
7464 splitNorm = cssTextNorm.indexOf(startSubstring, 1);
7465 } else if (cssNormSplits.length === 1) {
7466 startSubstring = startSubstring.substring(0, startSubstring.length - 1);
7467 cssNormSplits = cssTextNorm.split(startSubstring);
7468 if (cssNormSplits.length <= 1) {
7469 splits.push(cssText);
7470 return splits;
7471 }
7472 j = jLimit + 1;
7473 } else if (j === textContentNorm.length - 1) {
7474 splitNorm = cssTextNorm.indexOf(startSubstring);
7475 }
7476 if (cssNormSplits.length >= 2 && j > jLimit) {
7477 var prevTextContent = childNodes2[i2 - 1].textContent;
7478 if (prevTextContent && typeof prevTextContent === "string") {
7479 var prevMinLength = normalizeCssString(prevTextContent).length;
7480 splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);
7481 }
7482 if (splitNorm === -1) {
7483 splitNorm = cssNormSplits[0].length;
7484 }
7485 }
7486 if (splitNorm !== -1) {
7487 var k = Math.floor(splitNorm / normFactor);
7488 for(; k > 0 && k < cssText.length;){
7489 iterCount += 1;
7490 if (iterCount > 50 * childNodes2.length) {
7491 splits.push(cssText);
7492 return splits;
7493 }
7494 var normPart = normalizeCssString(cssText.substring(0, k), _testNoPxNorm);
7495 if (normPart.length === splitNorm) {
7496 splits.push(cssText.substring(0, k));
7497 cssText = cssText.substring(k);
7498 cssTextNorm = cssTextNorm.substring(splitNorm);
7499 break;
7500 } else if (normPart.length < splitNorm) {
7501 k += Math.max(1, Math.floor((splitNorm - normPart.length) / normFactor));
7502 } else {
7503 k -= Math.max(1, Math.floor((normPart.length - splitNorm) * normFactor));
7504 }
7505 }
7506 break;
7507 }
7508 }
7509 }
7510 }
7511 }
7512 splits.push(cssText);
7513 return splits;
7514 }
7515 function markCssSplits(cssText, style) {
7516 return splitCssText(cssText, style).join("/* rr_split */");
7517 }
7518 var _id = 1;
7519 var tagNameRegex = new RegExp("[^a-z0-9-_:]");
7520 var IGNORED_NODE = -2;
7521 function genId() {
7522 return _id++;
7523 }
7524 function getValidTagName$1(element) {
7525 if (_instanceof(element, HTMLFormElement)) {
7526 return "form";
7527 }
7528 var processedTagName = toLowerCase(element.tagName);
7529 if (tagNameRegex.test(processedTagName)) {
7530 return "div";
7531 }
7532 return processedTagName;
7533 }
7534 var canvasService;
7535 var canvasCtx;
7536 var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
7537 var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
7538 function getAbsoluteSrcsetString(doc, attributeValue) {
7539 if (attributeValue.trim() === "") {
7540 return attributeValue;
7541 }
7542 var pos = 0;
7543 function collectCharacters(regEx) {
7544 var chars2;
7545 var match = regEx.exec(attributeValue.substring(pos));
7546 if (match) {
7547 chars2 = match[0];
7548 pos += chars2.length;
7549 return chars2;
7550 }
7551 return "";
7552 }
7553 var output = [];
7554 while(true){
7555 collectCharacters(SRCSET_COMMAS_OR_SPACES);
7556 if (pos >= attributeValue.length) {
7557 break;
7558 }
7559 var url = collectCharacters(SRCSET_NOT_SPACES);
7560 if (url.slice(-1) === ",") {
7561 url = absoluteToDoc(doc, url.substring(0, url.length - 1));
7562 output.push(url);
7563 } else {
7564 var descriptorsStr = "";
7565 url = absoluteToDoc(doc, url);
7566 var inParens = false;
7567 while(true){
7568 var c2 = attributeValue.charAt(pos);
7569 if (c2 === "") {
7570 output.push((url + descriptorsStr).trim());
7571 break;
7572 } else if (!inParens) {
7573 if (c2 === ",") {
7574 pos += 1;
7575 output.push((url + descriptorsStr).trim());
7576 break;
7577 } else if (c2 === "(") {
7578 inParens = true;
7579 }
7580 } else {
7581 if (c2 === ")") {
7582 inParens = false;
7583 }
7584 }
7585 descriptorsStr += c2;
7586 pos += 1;
7587 }
7588 }
7589 }
7590 return output.join(", ");
7591 }
7592 var cachedDocument = /* @__PURE__ */ new WeakMap();
7593 function absoluteToDoc(doc, attributeValue) {
7594 if (!attributeValue || attributeValue.trim() === "") {
7595 return attributeValue;
7596 }
7597 return getHref(doc, attributeValue);
7598 }
7599 function isSVGElement(el) {
7600 return Boolean(el.tagName === "svg" || el.ownerSVGElement);
7601 }
7602 function getHref(doc, customHref) {
7603 var a2 = cachedDocument.get(doc);
7604 if (!a2) {
7605 a2 = doc.createElement("a");
7606 cachedDocument.set(doc, a2);
7607 }
7608 if (!customHref) {
7609 customHref = "";
7610 } else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) {
7611 return customHref;
7612 }
7613 a2.setAttribute("href", customHref);
7614 return a2.href;
7615 }
7616 function transformAttribute(doc, tagName, name, value) {
7617 if (!value) {
7618 return value;
7619 }
7620 if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) {
7621 return absoluteToDoc(doc, value);
7622 } else if (name === "xlink:href" && value[0] !== "#") {
7623 return absoluteToDoc(doc, value);
7624 } else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) {
7625 return absoluteToDoc(doc, value);
7626 } else if (name === "srcset") {
7627 return getAbsoluteSrcsetString(doc, value);
7628 } else if (name === "style") {
7629 return absolutifyURLs(value, getHref(doc));
7630 } else if (tagName === "object" && name === "data") {
7631 return absoluteToDoc(doc, value);
7632 }
7633 return value;
7634 }
7635 function ignoreAttribute(tagName, name, _value) {
7636 return (tagName === "video" || tagName === "audio") && name === "autoplay";
7637 }
7638 function _isBlockedElement(element, blockClass, blockSelector) {
7639 try {
7640 if (typeof blockClass === "string") {
7641 if (element.classList.contains(blockClass)) {
7642 return true;
7643 }
7644 } else {
7645 for(var eIndex = element.classList.length; eIndex--;){
7646 var className = element.classList[eIndex];
7647 if (blockClass.test(className)) {
7648 return true;
7649 }
7650 }
7651 }
7652 if (blockSelector) {
7653 return element.matches(blockSelector);
7654 }
7655 } catch (e2) {}
7656 return false;
7657 }
7658 function classMatchesRegex(node2, regex, checkAncestors) {
7659 if (!node2) return false;
7660 if (node2.nodeType !== node2.ELEMENT_NODE) {
7661 if (!checkAncestors) return false;
7662 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
7663 }
7664 for(var eIndex = node2.classList.length; eIndex--;){
7665 var className = node2.classList[eIndex];
7666 if (regex.test(className)) {
7667 return true;
7668 }
7669 }
7670 if (!checkAncestors) return false;
7671 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
7672 }
7673 function needMaskingText(node2, maskTextClass, maskTextSelector, checkAncestors) {
7674 var el;
7675 if (isElement(node2)) {
7676 el = node2;
7677 if (!index$1.childNodes(el).length) {
7678 return false;
7679 }
7680 } else if (index$1.parentElement(node2) === null) {
7681 return false;
7682 } else {
7683 el = index$1.parentElement(node2);
7684 }
7685 try {
7686 if (typeof maskTextClass === "string") {
7687 if (checkAncestors) {
7688 if (el.closest("." + maskTextClass)) return true;
7689 } else {
7690 if (el.classList.contains(maskTextClass)) return true;
7691 }
7692 } else {
7693 if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;
7694 }
7695 if (maskTextSelector) {
7696 if (checkAncestors) {
7697 if (el.closest(maskTextSelector)) return true;
7698 } else {
7699 if (el.matches(maskTextSelector)) return true;
7700 }
7701 }
7702 } catch (e2) {}
7703 return false;
7704 }
7705 function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
7706 var win = iframeEl.contentWindow;
7707 if (!win) {
7708 return;
7709 }
7710 var fired = false;
7711 var readyState;
7712 try {
7713 readyState = win.document.readyState;
7714 } catch (error) {
7715 return;
7716 }
7717 if (readyState !== "complete") {
7718 var timer = setTimeout(function() {
7719 if (!fired) {
7720 listener();
7721 fired = true;
7722 }
7723 }, iframeLoadTimeout);
7724 iframeEl.addEventListener("load", function() {
7725 clearTimeout(timer);
7726 fired = true;
7727 listener();
7728 });
7729 return;
7730 }
7731 var blankUrl = "about:blank";
7732 if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
7733 setTimeout(listener, 0);
7734 return iframeEl.addEventListener("load", listener);
7735 }
7736 iframeEl.addEventListener("load", listener);
7737 }
7738 function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
7739 var fired = false;
7740 var styleSheetLoaded;
7741 try {
7742 styleSheetLoaded = link.sheet;
7743 } catch (error) {
7744 return;
7745 }
7746 if (styleSheetLoaded) return;
7747 var timer = setTimeout(function() {
7748 if (!fired) {
7749 listener();
7750 fired = true;
7751 }
7752 }, styleSheetLoadTimeout);
7753 link.addEventListener("load", function() {
7754 clearTimeout(timer);
7755 fired = true;
7756 listener();
7757 });
7758 }
7759 function serializeNode(n2, options) {
7760 var doc = options.doc, mirror2 = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, needsMask = options.needsMask, inlineStylesheet = options.inlineStylesheet, _options_maskInputOptions = options.maskInputOptions, maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, _options_dataURLOptions = options.dataURLOptions, dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _options_newlyAddedElement = options.newlyAddedElement, newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement, _options_cssCaptured = options.cssCaptured, cssCaptured = _options_cssCaptured === void 0 ? false : _options_cssCaptured;
7761 var rootId = getRootId(doc, mirror2);
7762 switch(n2.nodeType){
7763 case n2.DOCUMENT_NODE:
7764 if (n2.compatMode !== "CSS1Compat") {
7765 return {
7766 type: NodeType$3.Document,
7767 childNodes: [],
7768 compatMode: n2.compatMode
7769 };
7770 } else {
7771 return {
7772 type: NodeType$3.Document,
7773 childNodes: []
7774 };
7775 }
7776 case n2.DOCUMENT_TYPE_NODE:
7777 return {
7778 type: NodeType$3.DocumentType,
7779 name: n2.name,
7780 publicId: n2.publicId,
7781 systemId: n2.systemId,
7782 rootId: rootId
7783 };
7784 case n2.ELEMENT_NODE:
7785 return serializeElementNode(n2, {
7786 doc: doc,
7787 blockClass: blockClass,
7788 blockSelector: blockSelector,
7789 inlineStylesheet: inlineStylesheet,
7790 maskInputOptions: maskInputOptions,
7791 maskInputFn: maskInputFn,
7792 dataURLOptions: dataURLOptions,
7793 inlineImages: inlineImages,
7794 recordCanvas: recordCanvas,
7795 keepIframeSrcFn: keepIframeSrcFn,
7796 newlyAddedElement: newlyAddedElement,
7797 rootId: rootId
7798 });
7799 case n2.TEXT_NODE:
7800 return serializeTextNode(n2, {
7801 doc: doc,
7802 needsMask: needsMask,
7803 maskTextFn: maskTextFn,
7804 rootId: rootId,
7805 cssCaptured: cssCaptured
7806 });
7807 case n2.CDATA_SECTION_NODE:
7808 return {
7809 type: NodeType$3.CDATA,
7810 textContent: "",
7811 rootId: rootId
7812 };
7813 case n2.COMMENT_NODE:
7814 return {
7815 type: NodeType$3.Comment,
7816 textContent: index$1.textContent(n2) || "",
7817 rootId: rootId
7818 };
7819 default:
7820 return false;
7821 }
7822 }
7823 function getRootId(doc, mirror2) {
7824 if (!mirror2.hasNode(doc)) return void 0;
7825 var docId = mirror2.getId(doc);
7826 return docId === 1 ? void 0 : docId;
7827 }
7828 function serializeTextNode(n2, options) {
7829 var needsMask = options.needsMask, maskTextFn = options.maskTextFn, rootId = options.rootId, cssCaptured = options.cssCaptured;
7830 var parent = index$1.parentNode(n2);
7831 var parentTagName = parent && parent.tagName;
7832 var textContent2 = "";
7833 var isStyle = parentTagName === "STYLE" ? true : void 0;
7834 var isScript = parentTagName === "SCRIPT" ? true : void 0;
7835 if (isScript) {
7836 textContent2 = "SCRIPT_PLACEHOLDER";
7837 } else if (!cssCaptured) {
7838 textContent2 = index$1.textContent(n2);
7839 if (isStyle && textContent2) {
7840 textContent2 = absolutifyURLs(textContent2, getHref(options.doc));
7841 }
7842 }
7843 if (!isStyle && !isScript && textContent2 && needsMask) {
7844 textContent2 = maskTextFn ? maskTextFn(textContent2, index$1.parentElement(n2)) : textContent2.replace(/[\S]/g, "*");
7845 }
7846 return {
7847 type: NodeType$3.Text,
7848 textContent: textContent2 || "",
7849 rootId: rootId
7850 };
7851 }
7852 function serializeElementNode(n2, options) {
7853 var doc = options.doc, blockClass = options.blockClass, blockSelector = options.blockSelector, inlineStylesheet = options.inlineStylesheet, _options_maskInputOptions = options.maskInputOptions, maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions, maskInputFn = options.maskInputFn, _options_dataURLOptions = options.dataURLOptions, dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions, inlineImages = options.inlineImages, recordCanvas = options.recordCanvas, keepIframeSrcFn = options.keepIframeSrcFn, _options_newlyAddedElement = options.newlyAddedElement, newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement, rootId = options.rootId;
7854 var needBlock = _isBlockedElement(n2, blockClass, blockSelector);
7855 var tagName = getValidTagName$1(n2);
7856 var attributes = {};
7857 var len = n2.attributes.length;
7858 for(var i2 = 0; i2 < len; i2++){
7859 var attr = n2.attributes[i2];
7860 if (!ignoreAttribute(tagName, attr.name, attr.value)) {
7861 attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value);
7862 }
7863 }
7864 if (tagName === "link" && inlineStylesheet) {
7865 var stylesheet = Array.from(doc.styleSheets).find(function(s2) {
7866 return s2.href === n2.href;
7867 });
7868 var cssText = null;
7869 if (stylesheet) {
7870 cssText = stringifyStylesheet(stylesheet);
7871 }
7872 if (cssText) {
7873 delete attributes.rel;
7874 delete attributes.href;
7875 attributes._cssText = cssText;
7876 }
7877 }
7878 if (tagName === "style" && n2.sheet) {
7879 var cssText1 = stringifyStylesheet(n2.sheet);
7880 if (cssText1) {
7881 if (n2.childNodes.length > 1) {
7882 cssText1 = markCssSplits(cssText1, n2);
7883 }
7884 attributes._cssText = cssText1;
7885 }
7886 }
7887 if (tagName === "input" || tagName === "textarea" || tagName === "select") {
7888 var value = n2.value;
7889 var checked = n2.checked;
7890 if (attributes.type !== "radio" && attributes.type !== "checkbox" && attributes.type !== "submit" && attributes.type !== "button" && value) {
7891 attributes.value = maskInputValue({
7892 element: n2,
7893 type: getInputType(n2),
7894 tagName: tagName,
7895 value: value,
7896 maskInputOptions: maskInputOptions,
7897 maskInputFn: maskInputFn
7898 });
7899 } else if (checked) {
7900 attributes.checked = checked;
7901 }
7902 }
7903 if (tagName === "option") {
7904 if (n2.selected && !maskInputOptions["select"]) {
7905 attributes.selected = true;
7906 } else {
7907 delete attributes.selected;
7908 }
7909 }
7910 if (tagName === "dialog" && n2.open) {
7911 attributes.rr_open_mode = n2.matches("dialog:modal") ? "modal" : "non-modal";
7912 }
7913 if (tagName === "canvas" && recordCanvas) {
7914 if (n2.__context === "2d") {
7915 if (!is2DCanvasBlank(n2)) {
7916 attributes.rr_dataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7917 }
7918 } else if (!("__context" in n2)) {
7919 var canvasDataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7920 var blankCanvas = doc.createElement("canvas");
7921 blankCanvas.width = n2.width;
7922 blankCanvas.height = n2.height;
7923 var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7924 if (canvasDataURL !== blankCanvasDataURL) {
7925 attributes.rr_dataURL = canvasDataURL;
7926 }
7927 }
7928 }
7929 if (tagName === "img" && inlineImages) {
7930 if (!canvasService) {
7931 canvasService = doc.createElement("canvas");
7932 canvasCtx = canvasService.getContext("2d");
7933 }
7934 var image = n2;
7935 var imageSrc = image.currentSrc || image.getAttribute("src") || "<unknown-src>";
7936 var priorCrossOrigin = image.crossOrigin;
7937 var recordInlineImage = function() {
7938 image.removeEventListener("load", recordInlineImage);
7939 try {
7940 canvasService.width = image.naturalWidth;
7941 canvasService.height = image.naturalHeight;
7942 canvasCtx.drawImage(image, 0, 0);
7943 attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7944 } catch (err) {
7945 if (image.crossOrigin !== "anonymous") {
7946 image.crossOrigin = "anonymous";
7947 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
7948 else image.addEventListener("load", recordInlineImage);
7949 return;
7950 } else {
7951 console.warn("Cannot inline img src=" + imageSrc + "! Error: " + err);
7952 }
7953 }
7954 if (image.crossOrigin === "anonymous") {
7955 priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute("crossorigin");
7956 }
7957 };
7958 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
7959 else image.addEventListener("load", recordInlineImage);
7960 }
7961 if (tagName === "audio" || tagName === "video") {
7962 var mediaAttributes = attributes;
7963 mediaAttributes.rr_mediaState = n2.paused ? "paused" : "played";
7964 mediaAttributes.rr_mediaCurrentTime = n2.currentTime;
7965 mediaAttributes.rr_mediaPlaybackRate = n2.playbackRate;
7966 mediaAttributes.rr_mediaMuted = n2.muted;
7967 mediaAttributes.rr_mediaLoop = n2.loop;
7968 mediaAttributes.rr_mediaVolume = n2.volume;
7969 }
7970 if (!newlyAddedElement) {
7971 if (n2.scrollLeft) {
7972 attributes.rr_scrollLeft = n2.scrollLeft;
7973 }
7974 if (n2.scrollTop) {
7975 attributes.rr_scrollTop = n2.scrollTop;
7976 }
7977 }
7978 if (needBlock) {
7979 var _n2_getBoundingClientRect = n2.getBoundingClientRect(), width = _n2_getBoundingClientRect.width, height = _n2_getBoundingClientRect.height;
7980 attributes = {
7981 class: attributes.class,
7982 rr_width: "" + width + "px",
7983 rr_height: "" + height + "px"
7984 };
7985 }
7986 if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
7987 if (!n2.contentDocument) {
7988 attributes.rr_src = attributes.src;
7989 }
7990 delete attributes.src;
7991 }
7992 var isCustomElement;
7993 try {
7994 if (customElements.get(tagName)) isCustomElement = true;
7995 } catch (e2) {}
7996 return {
7997 type: NodeType$3.Element,
7998 tagName: tagName,
7999 attributes: attributes,
8000 childNodes: [],
8001 isSVG: isSVGElement(n2) || void 0,
8002 needBlock: needBlock,
8003 rootId: rootId,
8004 isCustom: isCustomElement
8005 };
8006 }
8007 function lowerIfExists(maybeAttr) {
8008 if (maybeAttr === void 0 || maybeAttr === null) {
8009 return "";
8010 } else {
8011 return maybeAttr.toLowerCase();
8012 }
8013 }
8014 function slimDOMExcluded(sn, slimDOMOptions) {
8015 if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) {
8016 return true;
8017 } else if (sn.type === NodeType$3.Element) {
8018 if (slimDOMOptions.script && // script tag
8019 (sn.tagName === "script" || // (module)preload link
8020 sn.tagName === "link" && (sn.attributes.rel === "preload" && sn.attributes.as === "script" || sn.attributes.rel === "modulepreload") || // prefetch link
8021 sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) {
8022 return true;
8023 } 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"))) {
8024 return true;
8025 } else if (sn.tagName === "meta") {
8026 if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
8027 return true;
8028 } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)
8029 lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) {
8030 return true;
8031 } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) {
8032 return true;
8033 } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) {
8034 return true;
8035 } 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:/))) {
8036 return true;
8037 } 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")) {
8038 return true;
8039 }
8040 }
8041 }
8042 return false;
8043 }
8044 function serializeNodeWithId(n2, options) {
8045 var doc = options.doc, mirror2 = options.mirror, blockClass = options.blockClass, blockSelector = options.blockSelector, maskTextClass = options.maskTextClass, maskTextSelector = options.maskTextSelector, _options_skipChild = options.skipChild, skipChild = _options_skipChild === void 0 ? false : _options_skipChild, _options_inlineStylesheet = options.inlineStylesheet, inlineStylesheet = _options_inlineStylesheet === void 0 ? true : _options_inlineStylesheet, _options_maskInputOptions = options.maskInputOptions, maskInputOptions = _options_maskInputOptions === void 0 ? {} : _options_maskInputOptions, maskTextFn = options.maskTextFn, maskInputFn = options.maskInputFn, slimDOMOptions = options.slimDOMOptions, _options_dataURLOptions = options.dataURLOptions, dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions, _options_inlineImages = options.inlineImages, inlineImages = _options_inlineImages === void 0 ? false : _options_inlineImages, _options_recordCanvas = options.recordCanvas, recordCanvas = _options_recordCanvas === void 0 ? false : _options_recordCanvas, onSerialize = options.onSerialize, onIframeLoad = options.onIframeLoad, _options_iframeLoadTimeout = options.iframeLoadTimeout, iframeLoadTimeout = _options_iframeLoadTimeout === void 0 ? 5e3 : _options_iframeLoadTimeout, onStylesheetLoad = options.onStylesheetLoad, _options_stylesheetLoadTimeout = options.stylesheetLoadTimeout, stylesheetLoadTimeout = _options_stylesheetLoadTimeout === void 0 ? 5e3 : _options_stylesheetLoadTimeout, _options_keepIframeSrcFn = options.keepIframeSrcFn, keepIframeSrcFn = _options_keepIframeSrcFn === void 0 ? function() {
8046 return false;
8047 } : _options_keepIframeSrcFn, _options_newlyAddedElement = options.newlyAddedElement, newlyAddedElement = _options_newlyAddedElement === void 0 ? false : _options_newlyAddedElement, _options_cssCaptured = options.cssCaptured, cssCaptured = _options_cssCaptured === void 0 ? false : _options_cssCaptured;
8048 var needsMask = options.needsMask;
8049 var _options_preserveWhiteSpace = options.preserveWhiteSpace, preserveWhiteSpace = _options_preserveWhiteSpace === void 0 ? true : _options_preserveWhiteSpace;
8050 if (!needsMask) {
8051 var checkAncestors = needsMask === void 0;
8052 needsMask = needMaskingText(n2, maskTextClass, maskTextSelector, checkAncestors);
8053 }
8054 var _serializedNode = serializeNode(n2, {
8055 doc: doc,
8056 mirror: mirror2,
8057 blockClass: blockClass,
8058 blockSelector: blockSelector,
8059 needsMask: needsMask,
8060 inlineStylesheet: inlineStylesheet,
8061 maskInputOptions: maskInputOptions,
8062 maskTextFn: maskTextFn,
8063 maskInputFn: maskInputFn,
8064 dataURLOptions: dataURLOptions,
8065 inlineImages: inlineImages,
8066 recordCanvas: recordCanvas,
8067 keepIframeSrcFn: keepIframeSrcFn,
8068 newlyAddedElement: newlyAddedElement,
8069 cssCaptured: cssCaptured
8070 });
8071 if (!_serializedNode) {
8072 console.warn(n2, "not serialized");
8073 return null;
8074 }
8075 var id;
8076 if (mirror2.hasNode(n2)) {
8077 id = mirror2.getId(n2);
8078 } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$3.Text && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) {
8079 id = IGNORED_NODE;
8080 } else {
8081 id = genId();
8082 }
8083 var serializedNode = Object.assign(_serializedNode, {
8084 id: id
8085 });
8086 mirror2.add(n2, serializedNode);
8087 if (id === IGNORED_NODE) {
8088 return null;
8089 }
8090 if (onSerialize) {
8091 onSerialize(n2);
8092 }
8093 var recordChild = !skipChild;
8094 if (serializedNode.type === NodeType$3.Element) {
8095 recordChild = recordChild && !serializedNode.needBlock;
8096 delete serializedNode.needBlock;
8097 var shadowRootEl = index$1.shadowRoot(n2);
8098 if (shadowRootEl && isNativeShadowDom(shadowRootEl)) serializedNode.isShadowHost = true;
8099 }
8100 if ((serializedNode.type === NodeType$3.Document || serializedNode.type === NodeType$3.Element) && recordChild) {
8101 if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType$3.Element && serializedNode.tagName === "head") {
8102 preserveWhiteSpace = false;
8103 }
8104 var bypassOptions = {
8105 doc: doc,
8106 mirror: mirror2,
8107 blockClass: blockClass,
8108 blockSelector: blockSelector,
8109 needsMask: needsMask,
8110 maskTextClass: maskTextClass,
8111 maskTextSelector: maskTextSelector,
8112 skipChild: skipChild,
8113 inlineStylesheet: inlineStylesheet,
8114 maskInputOptions: maskInputOptions,
8115 maskTextFn: maskTextFn,
8116 maskInputFn: maskInputFn,
8117 slimDOMOptions: slimDOMOptions,
8118 dataURLOptions: dataURLOptions,
8119 inlineImages: inlineImages,
8120 recordCanvas: recordCanvas,
8121 preserveWhiteSpace: preserveWhiteSpace,
8122 onSerialize: onSerialize,
8123 onIframeLoad: onIframeLoad,
8124 iframeLoadTimeout: iframeLoadTimeout,
8125 onStylesheetLoad: onStylesheetLoad,
8126 stylesheetLoadTimeout: stylesheetLoadTimeout,
8127 keepIframeSrcFn: keepIframeSrcFn,
8128 cssCaptured: false
8129 };
8130 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "textarea" && serializedNode.attributes.value !== void 0) ;
8131 else {
8132 if (serializedNode.type === NodeType$3.Element && serializedNode.attributes._cssText !== void 0 && typeof serializedNode.attributes._cssText === "string") {
8133 bypassOptions.cssCaptured = true;
8134 }
8135 for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(n2))), _step; !(_step = _iterator()).done;){
8136 var childN = _step.value;
8137 var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
8138 if (serializedChildNode) {
8139 serializedNode.childNodes.push(serializedChildNode);
8140 }
8141 }
8142 }
8143 var shadowRootEl1 = null;
8144 if (isElement(n2) && (shadowRootEl1 = index$1.shadowRoot(n2))) {
8145 for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(shadowRootEl1))), _step1; !(_step1 = _iterator1()).done;){
8146 var childN1 = _step1.value;
8147 var serializedChildNode1 = serializeNodeWithId(childN1, bypassOptions);
8148 if (serializedChildNode1) {
8149 isNativeShadowDom(shadowRootEl1) && (serializedChildNode1.isShadow = true);
8150 serializedNode.childNodes.push(serializedChildNode1);
8151 }
8152 }
8153 }
8154 }
8155 var parent = index$1.parentNode(n2);
8156 if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {
8157 serializedNode.isShadow = true;
8158 }
8159 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "iframe") {
8160 onceIframeLoaded(n2, function() {
8161 var iframeDoc = n2.contentDocument;
8162 if (iframeDoc && onIframeLoad) {
8163 var serializedIframeNode = serializeNodeWithId(iframeDoc, {
8164 doc: iframeDoc,
8165 mirror: mirror2,
8166 blockClass: blockClass,
8167 blockSelector: blockSelector,
8168 needsMask: needsMask,
8169 maskTextClass: maskTextClass,
8170 maskTextSelector: maskTextSelector,
8171 skipChild: false,
8172 inlineStylesheet: inlineStylesheet,
8173 maskInputOptions: maskInputOptions,
8174 maskTextFn: maskTextFn,
8175 maskInputFn: maskInputFn,
8176 slimDOMOptions: slimDOMOptions,
8177 dataURLOptions: dataURLOptions,
8178 inlineImages: inlineImages,
8179 recordCanvas: recordCanvas,
8180 preserveWhiteSpace: preserveWhiteSpace,
8181 onSerialize: onSerialize,
8182 onIframeLoad: onIframeLoad,
8183 iframeLoadTimeout: iframeLoadTimeout,
8184 onStylesheetLoad: onStylesheetLoad,
8185 stylesheetLoadTimeout: stylesheetLoadTimeout,
8186 keepIframeSrcFn: keepIframeSrcFn
8187 });
8188 if (serializedIframeNode) {
8189 onIframeLoad(n2, serializedIframeNode);
8190 }
8191 }
8192 }, iframeLoadTimeout);
8193 }
8194 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")) {
8195 onceStylesheetLoaded(n2, function() {
8196 if (onStylesheetLoad) {
8197 var serializedLinkNode = serializeNodeWithId(n2, {
8198 doc: doc,
8199 mirror: mirror2,
8200 blockClass: blockClass,
8201 blockSelector: blockSelector,
8202 needsMask: needsMask,
8203 maskTextClass: maskTextClass,
8204 maskTextSelector: maskTextSelector,
8205 skipChild: false,
8206 inlineStylesheet: inlineStylesheet,
8207 maskInputOptions: maskInputOptions,
8208 maskTextFn: maskTextFn,
8209 maskInputFn: maskInputFn,
8210 slimDOMOptions: slimDOMOptions,
8211 dataURLOptions: dataURLOptions,
8212 inlineImages: inlineImages,
8213 recordCanvas: recordCanvas,
8214 preserveWhiteSpace: preserveWhiteSpace,
8215 onSerialize: onSerialize,
8216 onIframeLoad: onIframeLoad,
8217 iframeLoadTimeout: iframeLoadTimeout,
8218 onStylesheetLoad: onStylesheetLoad,
8219 stylesheetLoadTimeout: stylesheetLoadTimeout,
8220 keepIframeSrcFn: keepIframeSrcFn
8221 });
8222 if (serializedLinkNode) {
8223 onStylesheetLoad(n2, serializedLinkNode);
8224 }
8225 }
8226 }, stylesheetLoadTimeout);
8227 }
8228 return serializedNode;
8229 }
8230 function snapshot(n2, options) {
8231 var _ref = options || {}, tmp = _ref.mirror, mirror2 = tmp === void 0 ? new Mirror() : tmp, _ref_blockClass = _ref.blockClass, blockClass = _ref_blockClass === void 0 ? "rr-block" : _ref_blockClass, _ref_blockSelector = _ref.blockSelector, blockSelector = _ref_blockSelector === void 0 ? null : _ref_blockSelector, _ref_maskTextClass = _ref.maskTextClass, maskTextClass = _ref_maskTextClass === void 0 ? "rr-mask" : _ref_maskTextClass, _ref_maskTextSelector = _ref.maskTextSelector, maskTextSelector = _ref_maskTextSelector === void 0 ? null : _ref_maskTextSelector, _ref_inlineStylesheet = _ref.inlineStylesheet, inlineStylesheet = _ref_inlineStylesheet === void 0 ? true : _ref_inlineStylesheet, _ref_inlineImages = _ref.inlineImages, inlineImages = _ref_inlineImages === void 0 ? false : _ref_inlineImages, _ref_recordCanvas = _ref.recordCanvas, recordCanvas = _ref_recordCanvas === void 0 ? false : _ref_recordCanvas, _ref_maskAllInputs = _ref.maskAllInputs, maskAllInputs = _ref_maskAllInputs === void 0 ? false : _ref_maskAllInputs, maskTextFn = _ref.maskTextFn, maskInputFn = _ref.maskInputFn, _ref_slimDOM = _ref.slimDOM, slimDOM = _ref_slimDOM === void 0 ? false : _ref_slimDOM, dataURLOptions = _ref.dataURLOptions, preserveWhiteSpace = _ref.preserveWhiteSpace, onSerialize = _ref.onSerialize, onIframeLoad = _ref.onIframeLoad, iframeLoadTimeout = _ref.iframeLoadTimeout, onStylesheetLoad = _ref.onStylesheetLoad, stylesheetLoadTimeout = _ref.stylesheetLoadTimeout, _ref_keepIframeSrcFn = _ref.keepIframeSrcFn, keepIframeSrcFn = _ref_keepIframeSrcFn === void 0 ? function() {
8232 return false;
8233 } : _ref_keepIframeSrcFn;
8234 var maskInputOptions = maskAllInputs === true ? {
8235 color: true,
8236 date: true,
8237 "datetime-local": true,
8238 email: true,
8239 month: true,
8240 number: true,
8241 range: true,
8242 search: true,
8243 tel: true,
8244 text: true,
8245 time: true,
8246 url: true,
8247 week: true,
8248 textarea: true,
8249 select: true,
8250 password: true,
8251 hidden: true
8252 } : maskAllInputs === false ? {
8253 password: true
8254 } : maskAllInputs;
8255 var slimDOMOptions = slimDOM === true || slimDOM === "all" ? // if true: set of sensible options that should not throw away any information
8256 {
8257 script: true,
8258 comment: true,
8259 headFavicon: true,
8260 headWhitespace: true,
8261 headMetaDescKeywords: slimDOM === "all",
8262 // destructive
8263 headMetaSocial: true,
8264 headMetaRobots: true,
8265 headMetaHttpEquiv: true,
8266 headMetaAuthorship: true,
8267 headMetaVerification: true
8268 } : slimDOM === false ? {} : slimDOM;
8269 return serializeNodeWithId(n2, {
8270 doc: n2,
8271 mirror: mirror2,
8272 blockClass: blockClass,
8273 blockSelector: blockSelector,
8274 maskTextClass: maskTextClass,
8275 maskTextSelector: maskTextSelector,
8276 skipChild: false,
8277 inlineStylesheet: inlineStylesheet,
8278 maskInputOptions: maskInputOptions,
8279 maskTextFn: maskTextFn,
8280 maskInputFn: maskInputFn,
8281 slimDOMOptions: slimDOMOptions,
8282 dataURLOptions: dataURLOptions,
8283 inlineImages: inlineImages,
8284 recordCanvas: recordCanvas,
8285 preserveWhiteSpace: preserveWhiteSpace,
8286 onSerialize: onSerialize,
8287 onIframeLoad: onIframeLoad,
8288 iframeLoadTimeout: iframeLoadTimeout,
8289 onStylesheetLoad: onStylesheetLoad,
8290 stylesheetLoadTimeout: stylesheetLoadTimeout,
8291 keepIframeSrcFn: keepIframeSrcFn,
8292 newlyAddedElement: false
8293 });
8294 }
8295 function getDefaultExportFromCjs$1(x2) {
8296 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
8297 }
8298 function getAugmentedNamespace$1(n2) {
8299 if (n2.__esModule) return n2;
8300 var f2 = n2.default;
8301 if (typeof f2 == "function") {
8302 var a2 = function a22() {
8303 if (_instanceof(this, a22)) {
8304 return Reflect.construct(f2, arguments, this.constructor);
8305 }
8306 return f2.apply(this, arguments);
8307 };
8308 a2.prototype = f2.prototype;
8309 } else a2 = {};
8310 Object.defineProperty(a2, "__esModule", {
8311 value: true
8312 });
8313 Object.keys(n2).forEach(function(k) {
8314 var d = Object.getOwnPropertyDescriptor(n2, k);
8315 Object.defineProperty(a2, k, d.get ? d : {
8316 enumerable: true,
8317 get: function get() {
8318 return n2[k];
8319 }
8320 });
8321 });
8322 return a2;
8323 }
8324 var picocolors_browser$1 = {
8325 exports: {}
8326 };
8327 var x$1 = String;
8328 var create$1 = function create$1() {
8329 return {
8330 isColorSupported: false,
8331 reset: x$1,
8332 bold: x$1,
8333 dim: x$1,
8334 italic: x$1,
8335 underline: x$1,
8336 inverse: x$1,
8337 hidden: x$1,
8338 strikethrough: x$1,
8339 black: x$1,
8340 red: x$1,
8341 green: x$1,
8342 yellow: x$1,
8343 blue: x$1,
8344 magenta: x$1,
8345 cyan: x$1,
8346 white: x$1,
8347 gray: x$1,
8348 bgBlack: x$1,
8349 bgRed: x$1,
8350 bgGreen: x$1,
8351 bgYellow: x$1,
8352 bgBlue: x$1,
8353 bgMagenta: x$1,
8354 bgCyan: x$1,
8355 bgWhite: x$1
8356 };
8357 };
8358 picocolors_browser$1.exports = create$1();
8359 picocolors_browser$1.exports.createColors = create$1;
8360 var picocolors_browserExports$1 = picocolors_browser$1.exports;
8361 var __viteBrowserExternal$2 = {};
8362 var __viteBrowserExternal$1$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
8363 __proto__: null,
8364 default: __viteBrowserExternal$2
8365 }, Symbol.toStringTag, {
8366 value: "Module"
8367 }));
8368 var require$$2$1 = /* @__PURE__ */ getAugmentedNamespace$1(__viteBrowserExternal$1$1);
8369 var pico$1 = picocolors_browserExports$1;
8370 var terminalHighlight$1$1 = require$$2$1;
8371 var CssSyntaxError$3$1 = /*#__PURE__*/ function(Error1) {
8372 _inherits(CssSyntaxError, Error1);
8373 function CssSyntaxError(message, line, column, source, file, plugin22) {
8374 var _this;
8375 _this = Error1.call(this, message) || this;
8376 _this.name = "CssSyntaxError";
8377 _this.reason = message;
8378 if (file) {
8379 _this.file = file;
8380 }
8381 if (source) {
8382 _this.source = source;
8383 }
8384 if (plugin22) {
8385 _this.plugin = plugin22;
8386 }
8387 if (typeof line !== "undefined" && typeof column !== "undefined") {
8388 if (typeof line === "number") {
8389 _this.line = line;
8390 _this.column = column;
8391 } else {
8392 _this.line = line.line;
8393 _this.column = line.column;
8394 _this.endLine = column.line;
8395 _this.endColumn = column.column;
8396 }
8397 }
8398 _this.setMessage();
8399 if (Error.captureStackTrace) {
8400 Error.captureStackTrace(_this, CssSyntaxError);
8401 }
8402 return _this;
8403 }
8404 var _proto = CssSyntaxError.prototype;
8405 _proto.setMessage = function setMessage() {
8406 this.message = this.plugin ? this.plugin + ": " : "";
8407 this.message += this.file ? this.file : "<css input>";
8408 if (typeof this.line !== "undefined") {
8409 this.message += ":" + this.line + ":" + this.column;
8410 }
8411 this.message += ": " + this.reason;
8412 };
8413 _proto.showSourceCode = function showSourceCode(color) {
8414 var _this = this;
8415 if (!this.source) return "";
8416 var css = this.source;
8417 if (color == null) color = pico$1.isColorSupported;
8418 if (terminalHighlight$1$1) {
8419 if (color) css = terminalHighlight$1$1(css);
8420 }
8421 var lines = css.split(/\r?\n/);
8422 var start = Math.max(this.line - 3, 0);
8423 var end = Math.min(this.line + 2, lines.length);
8424 var maxWidth = String(end).length;
8425 var mark, aside;
8426 if (color) {
8427 var _pico$1_createColors = pico$1.createColors(true), bold = _pico$1_createColors.bold, gray = _pico$1_createColors.gray, red = _pico$1_createColors.red;
8428 mark = function(text) {
8429 return bold(red(text));
8430 };
8431 aside = function(text) {
8432 return gray(text);
8433 };
8434 } else {
8435 mark = aside = function(str) {
8436 return str;
8437 };
8438 }
8439 return lines.slice(start, end).map(function(line, index2) {
8440 var number = start + 1 + index2;
8441 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
8442 if (number === _this.line) {
8443 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
8444 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
8445 }
8446 return " " + aside(gutter) + line;
8447 }).join("\n");
8448 };
8449 _proto.toString = function toString() {
8450 var code = this.showSourceCode();
8451 if (code) {
8452 code = "\n\n" + code + "\n";
8453 }
8454 return this.name + ": " + this.message + code;
8455 };
8456 return CssSyntaxError;
8457 }(_wrap_native_super(Error));
8458 var cssSyntaxError$1 = CssSyntaxError$3$1;
8459 CssSyntaxError$3$1.default = CssSyntaxError$3$1;
8460 var symbols$1 = {};
8461 symbols$1.isClean = Symbol("isClean");
8462 symbols$1.my = Symbol("my");
8463 var DEFAULT_RAW$1 = {
8464 after: "\n",
8465 beforeClose: "\n",
8466 beforeComment: "\n",
8467 beforeDecl: "\n",
8468 beforeOpen: " ",
8469 beforeRule: "\n",
8470 colon: ": ",
8471 commentLeft: " ",
8472 commentRight: " ",
8473 emptyBody: "",
8474 indent: " ",
8475 semicolon: false
8476 };
8477 function capitalize$1(str) {
8478 return str[0].toUpperCase() + str.slice(1);
8479 }
8480 var Stringifier$2$1 = /*#__PURE__*/ function() {
8481 function Stringifier(builder) {
8482 this.builder = builder;
8483 }
8484 var _proto = Stringifier.prototype;
8485 _proto.atrule = function atrule(node2, semicolon) {
8486 var name = "@" + node2.name;
8487 var params = node2.params ? this.rawValue(node2, "params") : "";
8488 if (typeof node2.raws.afterName !== "undefined") {
8489 name += node2.raws.afterName;
8490 } else if (params) {
8491 name += " ";
8492 }
8493 if (node2.nodes) {
8494 this.block(node2, name + params);
8495 } else {
8496 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
8497 this.builder(name + params + end, node2);
8498 }
8499 };
8500 _proto.beforeAfter = function beforeAfter(node2, detect) {
8501 var value;
8502 if (node2.type === "decl") {
8503 value = this.raw(node2, null, "beforeDecl");
8504 } else if (node2.type === "comment") {
8505 value = this.raw(node2, null, "beforeComment");
8506 } else if (detect === "before") {
8507 value = this.raw(node2, null, "beforeRule");
8508 } else {
8509 value = this.raw(node2, null, "beforeClose");
8510 }
8511 var buf = node2.parent;
8512 var depth = 0;
8513 while(buf && buf.type !== "root"){
8514 depth += 1;
8515 buf = buf.parent;
8516 }
8517 if (value.includes("\n")) {
8518 var indent = this.raw(node2, null, "indent");
8519 if (indent.length) {
8520 for(var step = 0; step < depth; step++)value += indent;
8521 }
8522 }
8523 return value;
8524 };
8525 _proto.block = function block(node2, start) {
8526 var between = this.raw(node2, "between", "beforeOpen");
8527 this.builder(start + between + "{", node2, "start");
8528 var after;
8529 if (node2.nodes && node2.nodes.length) {
8530 this.body(node2);
8531 after = this.raw(node2, "after");
8532 } else {
8533 after = this.raw(node2, "after", "emptyBody");
8534 }
8535 if (after) this.builder(after);
8536 this.builder("}", node2, "end");
8537 };
8538 _proto.body = function body(node2) {
8539 var last = node2.nodes.length - 1;
8540 while(last > 0){
8541 if (node2.nodes[last].type !== "comment") break;
8542 last -= 1;
8543 }
8544 var semicolon = this.raw(node2, "semicolon");
8545 for(var i2 = 0; i2 < node2.nodes.length; i2++){
8546 var child = node2.nodes[i2];
8547 var before = this.raw(child, "before");
8548 if (before) this.builder(before);
8549 this.stringify(child, last !== i2 || semicolon);
8550 }
8551 };
8552 _proto.comment = function comment(node2) {
8553 var left = this.raw(node2, "left", "commentLeft");
8554 var right = this.raw(node2, "right", "commentRight");
8555 this.builder("/*" + left + node2.text + right + "*/", node2);
8556 };
8557 _proto.decl = function decl(node2, semicolon) {
8558 var between = this.raw(node2, "between", "colon");
8559 var string = node2.prop + between + this.rawValue(node2, "value");
8560 if (node2.important) {
8561 string += node2.raws.important || " !important";
8562 }
8563 if (semicolon) string += ";";
8564 this.builder(string, node2);
8565 };
8566 _proto.document = function document1(node2) {
8567 this.body(node2);
8568 };
8569 _proto.raw = function raw(node2, own, detect) {
8570 var value;
8571 if (!detect) detect = own;
8572 if (own) {
8573 value = node2.raws[own];
8574 if (typeof value !== "undefined") return value;
8575 }
8576 var parent = node2.parent;
8577 if (detect === "before") {
8578 if (!parent || parent.type === "root" && parent.first === node2) {
8579 return "";
8580 }
8581 if (parent && parent.type === "document") {
8582 return "";
8583 }
8584 }
8585 if (!parent) return DEFAULT_RAW$1[detect];
8586 var root2 = node2.root();
8587 if (!root2.rawCache) root2.rawCache = {};
8588 if (typeof root2.rawCache[detect] !== "undefined") {
8589 return root2.rawCache[detect];
8590 }
8591 if (detect === "before" || detect === "after") {
8592 return this.beforeAfter(node2, detect);
8593 } else {
8594 var method = "raw" + capitalize$1(detect);
8595 if (this[method]) {
8596 value = this[method](root2, node2);
8597 } else {
8598 root2.walk(function(i2) {
8599 value = i2.raws[own];
8600 if (typeof value !== "undefined") return false;
8601 });
8602 }
8603 }
8604 if (typeof value === "undefined") value = DEFAULT_RAW$1[detect];
8605 root2.rawCache[detect] = value;
8606 return value;
8607 };
8608 _proto.rawBeforeClose = function rawBeforeClose(root2) {
8609 var value;
8610 root2.walk(function(i2) {
8611 if (i2.nodes && i2.nodes.length > 0) {
8612 if (typeof i2.raws.after !== "undefined") {
8613 value = i2.raws.after;
8614 if (value.includes("\n")) {
8615 value = value.replace(/[^\n]+$/, "");
8616 }
8617 return false;
8618 }
8619 }
8620 });
8621 if (value) value = value.replace(/\S/g, "");
8622 return value;
8623 };
8624 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
8625 var value;
8626 root2.walkComments(function(i2) {
8627 if (typeof i2.raws.before !== "undefined") {
8628 value = i2.raws.before;
8629 if (value.includes("\n")) {
8630 value = value.replace(/[^\n]+$/, "");
8631 }
8632 return false;
8633 }
8634 });
8635 if (typeof value === "undefined") {
8636 value = this.raw(node2, null, "beforeDecl");
8637 } else if (value) {
8638 value = value.replace(/\S/g, "");
8639 }
8640 return value;
8641 };
8642 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
8643 var value;
8644 root2.walkDecls(function(i2) {
8645 if (typeof i2.raws.before !== "undefined") {
8646 value = i2.raws.before;
8647 if (value.includes("\n")) {
8648 value = value.replace(/[^\n]+$/, "");
8649 }
8650 return false;
8651 }
8652 });
8653 if (typeof value === "undefined") {
8654 value = this.raw(node2, null, "beforeRule");
8655 } else if (value) {
8656 value = value.replace(/\S/g, "");
8657 }
8658 return value;
8659 };
8660 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
8661 var value;
8662 root2.walk(function(i2) {
8663 if (i2.type !== "decl") {
8664 value = i2.raws.between;
8665 if (typeof value !== "undefined") return false;
8666 }
8667 });
8668 return value;
8669 };
8670 _proto.rawBeforeRule = function rawBeforeRule(root2) {
8671 var value;
8672 root2.walk(function(i2) {
8673 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
8674 if (typeof i2.raws.before !== "undefined") {
8675 value = i2.raws.before;
8676 if (value.includes("\n")) {
8677 value = value.replace(/[^\n]+$/, "");
8678 }
8679 return false;
8680 }
8681 }
8682 });
8683 if (value) value = value.replace(/\S/g, "");
8684 return value;
8685 };
8686 _proto.rawColon = function rawColon(root2) {
8687 var value;
8688 root2.walkDecls(function(i2) {
8689 if (typeof i2.raws.between !== "undefined") {
8690 value = i2.raws.between.replace(/[^\s:]/g, "");
8691 return false;
8692 }
8693 });
8694 return value;
8695 };
8696 _proto.rawEmptyBody = function rawEmptyBody(root2) {
8697 var value;
8698 root2.walk(function(i2) {
8699 if (i2.nodes && i2.nodes.length === 0) {
8700 value = i2.raws.after;
8701 if (typeof value !== "undefined") return false;
8702 }
8703 });
8704 return value;
8705 };
8706 _proto.rawIndent = function rawIndent(root2) {
8707 if (root2.raws.indent) return root2.raws.indent;
8708 var value;
8709 root2.walk(function(i2) {
8710 var p = i2.parent;
8711 if (p && p !== root2 && p.parent && p.parent === root2) {
8712 if (typeof i2.raws.before !== "undefined") {
8713 var parts = i2.raws.before.split("\n");
8714 value = parts[parts.length - 1];
8715 value = value.replace(/\S/g, "");
8716 return false;
8717 }
8718 }
8719 });
8720 return value;
8721 };
8722 _proto.rawSemicolon = function rawSemicolon(root2) {
8723 var value;
8724 root2.walk(function(i2) {
8725 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
8726 value = i2.raws.semicolon;
8727 if (typeof value !== "undefined") return false;
8728 }
8729 });
8730 return value;
8731 };
8732 _proto.rawValue = function rawValue(node2, prop) {
8733 var value = node2[prop];
8734 var raw = node2.raws[prop];
8735 if (raw && raw.value === value) {
8736 return raw.raw;
8737 }
8738 return value;
8739 };
8740 _proto.root = function root(node2) {
8741 this.body(node2);
8742 if (node2.raws.after) this.builder(node2.raws.after);
8743 };
8744 _proto.rule = function rule(node2) {
8745 this.block(node2, this.rawValue(node2, "selector"));
8746 if (node2.raws.ownSemicolon) {
8747 this.builder(node2.raws.ownSemicolon, node2, "end");
8748 }
8749 };
8750 _proto.stringify = function stringify(node2, semicolon) {
8751 if (!this[node2.type]) {
8752 throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
8753 }
8754 this[node2.type](node2, semicolon);
8755 };
8756 return Stringifier;
8757 }();
8758 var stringifier$1 = Stringifier$2$1;
8759 Stringifier$2$1.default = Stringifier$2$1;
8760 var Stringifier$1$1 = stringifier$1;
8761 function stringify$4$1(node2, builder) {
8762 var str = new Stringifier$1$1(builder);
8763 str.stringify(node2);
8764 }
8765 var stringify_1$1 = stringify$4$1;
8766 stringify$4$1.default = stringify$4$1;
8767 var isClean$2$1 = symbols$1.isClean, my$2$1 = symbols$1.my;
8768 var CssSyntaxError$2$1 = cssSyntaxError$1;
8769 var Stringifier2$1 = stringifier$1;
8770 var stringify$3$1 = stringify_1$1;
8771 function cloneNode$1(obj, parent) {
8772 var cloned = new obj.constructor();
8773 for(var i2 in obj){
8774 if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
8775 continue;
8776 }
8777 if (i2 === "proxyCache") continue;
8778 var value = obj[i2];
8779 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
8780 if (i2 === "parent" && type === "object") {
8781 if (parent) cloned[i2] = parent;
8782 } else if (i2 === "source") {
8783 cloned[i2] = value;
8784 } else if (Array.isArray(value)) {
8785 cloned[i2] = value.map(function(j) {
8786 return cloneNode$1(j, cloned);
8787 });
8788 } else {
8789 if (type === "object" && value !== null) value = cloneNode$1(value);
8790 cloned[i2] = value;
8791 }
8792 }
8793 return cloned;
8794 }
8795 var Node$4$1 = /*#__PURE__*/ function() {
8796 function Node2(defaults) {
8797 if (defaults === void 0) defaults = {};
8798 this.raws = {};
8799 this[isClean$2$1] = false;
8800 this[my$2$1] = true;
8801 for(var name in defaults){
8802 if (name === "nodes") {
8803 this.nodes = [];
8804 for(var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;){
8805 var node2 = _step.value;
8806 if (typeof node2.clone === "function") {
8807 this.append(node2.clone());
8808 } else {
8809 this.append(node2);
8810 }
8811 }
8812 } else {
8813 this[name] = defaults[name];
8814 }
8815 }
8816 }
8817 var _proto = Node2.prototype;
8818 _proto.addToError = function addToError(error) {
8819 error.postcssNode = this;
8820 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
8821 var s2 = this.source;
8822 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
8823 }
8824 return error;
8825 };
8826 _proto.after = function after(add) {
8827 this.parent.insertAfter(this, add);
8828 return this;
8829 };
8830 _proto.assign = function assign(overrides) {
8831 if (overrides === void 0) overrides = {};
8832 for(var name in overrides){
8833 this[name] = overrides[name];
8834 }
8835 return this;
8836 };
8837 _proto.before = function before(add) {
8838 this.parent.insertBefore(this, add);
8839 return this;
8840 };
8841 _proto.cleanRaws = function cleanRaws(keepBetween) {
8842 delete this.raws.before;
8843 delete this.raws.after;
8844 if (!keepBetween) delete this.raws.between;
8845 };
8846 _proto.clone = function clone(overrides) {
8847 if (overrides === void 0) overrides = {};
8848 var cloned = cloneNode$1(this);
8849 for(var name in overrides){
8850 cloned[name] = overrides[name];
8851 }
8852 return cloned;
8853 };
8854 _proto.cloneAfter = function cloneAfter(overrides) {
8855 if (overrides === void 0) overrides = {};
8856 var cloned = this.clone(overrides);
8857 this.parent.insertAfter(this, cloned);
8858 return cloned;
8859 };
8860 _proto.cloneBefore = function cloneBefore(overrides) {
8861 if (overrides === void 0) overrides = {};
8862 var cloned = this.clone(overrides);
8863 this.parent.insertBefore(this, cloned);
8864 return cloned;
8865 };
8866 _proto.error = function error(message, opts) {
8867 if (opts === void 0) opts = {};
8868 if (this.source) {
8869 var _this_rangeBy = this.rangeBy(opts), end = _this_rangeBy.end, start = _this_rangeBy.start;
8870 return this.source.input.error(message, {
8871 column: start.column,
8872 line: start.line
8873 }, {
8874 column: end.column,
8875 line: end.line
8876 }, opts);
8877 }
8878 return new CssSyntaxError$2$1(message);
8879 };
8880 _proto.getProxyProcessor = function getProxyProcessor() {
8881 return {
8882 get: function get(node2, prop) {
8883 if (prop === "proxyOf") {
8884 return node2;
8885 } else if (prop === "root") {
8886 return function() {
8887 return node2.root().toProxy();
8888 };
8889 } else {
8890 return node2[prop];
8891 }
8892 },
8893 set: function set(node2, prop, value) {
8894 if (node2[prop] === value) return true;
8895 node2[prop] = value;
8896 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */ prop === "text") {
8897 node2.markDirty();
8898 }
8899 return true;
8900 }
8901 };
8902 };
8903 _proto.markDirty = function markDirty() {
8904 if (this[isClean$2$1]) {
8905 this[isClean$2$1] = false;
8906 var next = this;
8907 while(next = next.parent){
8908 next[isClean$2$1] = false;
8909 }
8910 }
8911 };
8912 _proto.next = function next() {
8913 if (!this.parent) return void 0;
8914 var index2 = this.parent.index(this);
8915 return this.parent.nodes[index2 + 1];
8916 };
8917 _proto.positionBy = function positionBy(opts, stringRepresentation) {
8918 var pos = this.source.start;
8919 if (opts.index) {
8920 pos = this.positionInside(opts.index, stringRepresentation);
8921 } else if (opts.word) {
8922 stringRepresentation = this.toString();
8923 var index2 = stringRepresentation.indexOf(opts.word);
8924 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
8925 }
8926 return pos;
8927 };
8928 _proto.positionInside = function positionInside(index2, stringRepresentation) {
8929 var string = stringRepresentation || this.toString();
8930 var column = this.source.start.column;
8931 var line = this.source.start.line;
8932 for(var i2 = 0; i2 < index2; i2++){
8933 if (string[i2] === "\n") {
8934 column = 1;
8935 line += 1;
8936 } else {
8937 column += 1;
8938 }
8939 }
8940 return {
8941 column: column,
8942 line: line
8943 };
8944 };
8945 _proto.prev = function prev() {
8946 if (!this.parent) return void 0;
8947 var index2 = this.parent.index(this);
8948 return this.parent.nodes[index2 - 1];
8949 };
8950 _proto.rangeBy = function rangeBy(opts) {
8951 var start = {
8952 column: this.source.start.column,
8953 line: this.source.start.line
8954 };
8955 var end = this.source.end ? {
8956 column: this.source.end.column + 1,
8957 line: this.source.end.line
8958 } : {
8959 column: start.column + 1,
8960 line: start.line
8961 };
8962 if (opts.word) {
8963 var stringRepresentation = this.toString();
8964 var index2 = stringRepresentation.indexOf(opts.word);
8965 if (index2 !== -1) {
8966 start = this.positionInside(index2, stringRepresentation);
8967 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
8968 }
8969 } else {
8970 if (opts.start) {
8971 start = {
8972 column: opts.start.column,
8973 line: opts.start.line
8974 };
8975 } else if (opts.index) {
8976 start = this.positionInside(opts.index);
8977 }
8978 if (opts.end) {
8979 end = {
8980 column: opts.end.column,
8981 line: opts.end.line
8982 };
8983 } else if (typeof opts.endIndex === "number") {
8984 end = this.positionInside(opts.endIndex);
8985 } else if (opts.index) {
8986 end = this.positionInside(opts.index + 1);
8987 }
8988 }
8989 if (end.line < start.line || end.line === start.line && end.column <= start.column) {
8990 end = {
8991 column: start.column + 1,
8992 line: start.line
8993 };
8994 }
8995 return {
8996 end: end,
8997 start: start
8998 };
8999 };
9000 _proto.raw = function raw(prop, defaultType) {
9001 var str = new Stringifier2$1();
9002 return str.raw(this, prop, defaultType);
9003 };
9004 _proto.remove = function remove() {
9005 if (this.parent) {
9006 this.parent.removeChild(this);
9007 }
9008 this.parent = void 0;
9009 return this;
9010 };
9011 _proto.replaceWith = function replaceWith() {
9012 for(var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++){
9013 nodes[_key] = arguments[_key];
9014 }
9015 if (this.parent) {
9016 var bookmark = this;
9017 var foundSelf = false;
9018 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
9019 var node2 = _step.value;
9020 if (node2 === this) {
9021 foundSelf = true;
9022 } else if (foundSelf) {
9023 this.parent.insertAfter(bookmark, node2);
9024 bookmark = node2;
9025 } else {
9026 this.parent.insertBefore(bookmark, node2);
9027 }
9028 }
9029 if (!foundSelf) {
9030 this.remove();
9031 }
9032 }
9033 return this;
9034 };
9035 _proto.root = function root() {
9036 var result2 = this;
9037 while(result2.parent && result2.parent.type !== "document"){
9038 result2 = result2.parent;
9039 }
9040 return result2;
9041 };
9042 _proto.toJSON = function toJSON(_, inputs) {
9043 var fixed = {};
9044 var emitInputs = inputs == null;
9045 inputs = inputs || /* @__PURE__ */ new Map();
9046 var inputsNextIndex = 0;
9047 for(var name in this){
9048 if (!Object.prototype.hasOwnProperty.call(this, name)) {
9049 continue;
9050 }
9051 if (name === "parent" || name === "proxyCache") continue;
9052 var value = this[name];
9053 if (Array.isArray(value)) {
9054 fixed[name] = value.map(function(i2) {
9055 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) {
9056 return i2.toJSON(null, inputs);
9057 } else {
9058 return i2;
9059 }
9060 });
9061 } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) {
9062 fixed[name] = value.toJSON(null, inputs);
9063 } else if (name === "source") {
9064 var inputId = inputs.get(value.input);
9065 if (inputId == null) {
9066 inputId = inputsNextIndex;
9067 inputs.set(value.input, inputsNextIndex);
9068 inputsNextIndex++;
9069 }
9070 fixed[name] = {
9071 end: value.end,
9072 inputId: inputId,
9073 start: value.start
9074 };
9075 } else {
9076 fixed[name] = value;
9077 }
9078 }
9079 if (emitInputs) {
9080 fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
9081 return input2.toJSON();
9082 });
9083 }
9084 return fixed;
9085 };
9086 _proto.toProxy = function toProxy() {
9087 if (!this.proxyCache) {
9088 this.proxyCache = new Proxy(this, this.getProxyProcessor());
9089 }
9090 return this.proxyCache;
9091 };
9092 _proto.toString = function toString(stringifier2) {
9093 if (stringifier2 === void 0) stringifier2 = stringify$3$1;
9094 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
9095 var result2 = "";
9096 stringifier2(this, function(i2) {
9097 result2 += i2;
9098 });
9099 return result2;
9100 };
9101 _proto.warn = function warn(result2, text, opts) {
9102 var data = {
9103 node: this
9104 };
9105 for(var i2 in opts)data[i2] = opts[i2];
9106 return result2.warn(text, data);
9107 };
9108 _create_class(Node2, [
9109 {
9110 key: "proxyOf",
9111 get: function get() {
9112 return this;
9113 }
9114 }
9115 ]);
9116 return Node2;
9117 }();
9118 var node$1 = Node$4$1;
9119 Node$4$1.default = Node$4$1;
9120 var Node$3$1 = node$1;
9121 var Declaration$4$1 = /*#__PURE__*/ function(Node$3$1) {
9122 _inherits(Declaration, Node$3$1);
9123 function Declaration(defaults) {
9124 var _this;
9125 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
9126 defaults = _extends({}, defaults, {
9127 value: String(defaults.value)
9128 });
9129 }
9130 _this = Node$3$1.call(this, defaults) || this;
9131 _this.type = "decl";
9132 return _this;
9133 }
9134 _create_class(Declaration, [
9135 {
9136 key: "variable",
9137 get: function get() {
9138 return this.prop.startsWith("--") || this.prop[0] === "$";
9139 }
9140 }
9141 ]);
9142 return Declaration;
9143 }(Node$3$1);
9144 var declaration$1 = Declaration$4$1;
9145 Declaration$4$1.default = Declaration$4$1;
9146 var urlAlphabet$1 = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
9147 var nanoid$1$1 = function(size) {
9148 if (size === void 0) size = 21;
9149 var id = "";
9150 var i2 = size;
9151 while(i2--){
9152 id += urlAlphabet$1[Math.random() * 64 | 0];
9153 }
9154 return id;
9155 };
9156 var nonSecure$1 = {
9157 nanoid: nanoid$1$1};
9158 var SourceMapConsumer$2$1 = require$$2$1.SourceMapConsumer, SourceMapGenerator$2$1 = require$$2$1.SourceMapGenerator;
9159 var existsSync$1 = require$$2$1.existsSync, readFileSync$1 = require$$2$1.readFileSync;
9160 var dirname$1$1 = require$$2$1.dirname, join$1 = require$$2$1.join;
9161 function fromBase64$1(str) {
9162 if (Buffer) {
9163 return Buffer.from(str, "base64").toString();
9164 } else {
9165 return window.atob(str);
9166 }
9167 }
9168 var PreviousMap$2$1 = /*#__PURE__*/ function() {
9169 function PreviousMap(css, opts) {
9170 if (opts.map === false) return;
9171 this.loadAnnotation(css);
9172 this.inline = this.startWith(this.annotation, "data:");
9173 var prev = opts.map ? opts.map.prev : void 0;
9174 var text = this.loadMap(opts.from, prev);
9175 if (!this.mapFile && opts.from) {
9176 this.mapFile = opts.from;
9177 }
9178 if (this.mapFile) this.root = dirname$1$1(this.mapFile);
9179 if (text) this.text = text;
9180 }
9181 var _proto = PreviousMap.prototype;
9182 _proto.consumer = function consumer() {
9183 if (!this.consumerCache) {
9184 this.consumerCache = new SourceMapConsumer$2$1(this.text);
9185 }
9186 return this.consumerCache;
9187 };
9188 _proto.decodeInline = function decodeInline(text) {
9189 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
9190 var baseUri = /^data:application\/json;base64,/;
9191 var charsetUri = /^data:application\/json;charset=utf-?8,/;
9192 var uri = /^data:application\/json,/;
9193 if (charsetUri.test(text) || uri.test(text)) {
9194 return decodeURIComponent(text.substr(RegExp.lastMatch.length));
9195 }
9196 if (baseCharsetUri.test(text) || baseUri.test(text)) {
9197 return fromBase64$1(text.substr(RegExp.lastMatch.length));
9198 }
9199 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
9200 throw new Error("Unsupported source map encoding " + encoding);
9201 };
9202 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
9203 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
9204 };
9205 _proto.isMap = function isMap(map) {
9206 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
9207 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
9208 };
9209 _proto.loadAnnotation = function loadAnnotation(css) {
9210 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
9211 if (!comments) return;
9212 var start = css.lastIndexOf(comments.pop());
9213 var end = css.indexOf("*/", start);
9214 if (start > -1 && end > -1) {
9215 this.annotation = this.getAnnotationURL(css.substring(start, end));
9216 }
9217 };
9218 _proto.loadFile = function loadFile(path) {
9219 this.root = dirname$1$1(path);
9220 if (existsSync$1(path)) {
9221 this.mapFile = path;
9222 return readFileSync$1(path, "utf-8").toString().trim();
9223 }
9224 };
9225 _proto.loadMap = function loadMap(file, prev) {
9226 if (prev === false) return false;
9227 if (prev) {
9228 if (typeof prev === "string") {
9229 return prev;
9230 } else if (typeof prev === "function") {
9231 var prevPath = prev(file);
9232 if (prevPath) {
9233 var map = this.loadFile(prevPath);
9234 if (!map) {
9235 throw new Error("Unable to load previous source map: " + prevPath.toString());
9236 }
9237 return map;
9238 }
9239 } else if (_instanceof(prev, SourceMapConsumer$2$1)) {
9240 return SourceMapGenerator$2$1.fromSourceMap(prev).toString();
9241 } else if (_instanceof(prev, SourceMapGenerator$2$1)) {
9242 return prev.toString();
9243 } else if (this.isMap(prev)) {
9244 return JSON.stringify(prev);
9245 } else {
9246 throw new Error("Unsupported previous source map format: " + prev.toString());
9247 }
9248 } else if (this.inline) {
9249 return this.decodeInline(this.annotation);
9250 } else if (this.annotation) {
9251 var map1 = this.annotation;
9252 if (file) map1 = join$1(dirname$1$1(file), map1);
9253 return this.loadFile(map1);
9254 }
9255 };
9256 _proto.startWith = function startWith(string, start) {
9257 if (!string) return false;
9258 return string.substr(0, start.length) === start;
9259 };
9260 _proto.withContent = function withContent() {
9261 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
9262 };
9263 return PreviousMap;
9264 }();
9265 var previousMap$1 = PreviousMap$2$1;
9266 PreviousMap$2$1.default = PreviousMap$2$1;
9267 var SourceMapConsumer$1$1 = require$$2$1.SourceMapConsumer, SourceMapGenerator$1$1 = require$$2$1.SourceMapGenerator;
9268 var fileURLToPath$1 = require$$2$1.fileURLToPath, pathToFileURL$1$1 = require$$2$1.pathToFileURL;
9269 var isAbsolute$1 = require$$2$1.isAbsolute, resolve$1$1 = require$$2$1.resolve;
9270 var nanoid$2 = nonSecure$1.nanoid;
9271 var terminalHighlight$2 = require$$2$1;
9272 var CssSyntaxError$1$1 = cssSyntaxError$1;
9273 var PreviousMap$1$1 = previousMap$1;
9274 var fromOffsetCache$1 = Symbol("fromOffsetCache");
9275 var sourceMapAvailable$1$1 = Boolean(SourceMapConsumer$1$1 && SourceMapGenerator$1$1);
9276 var pathAvailable$1$1 = Boolean(resolve$1$1 && isAbsolute$1);
9277 var Input$4$1 = /*#__PURE__*/ function() {
9278 function Input(css, opts) {
9279 if (opts === void 0) opts = {};
9280 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) {
9281 throw new Error("PostCSS received " + css + " instead of CSS string");
9282 }
9283 this.css = css.toString();
9284 if (this.css[0] === "\uFEFF" || this.css[0] === "￾") {
9285 this.hasBOM = true;
9286 this.css = this.css.slice(1);
9287 } else {
9288 this.hasBOM = false;
9289 }
9290 if (opts.from) {
9291 if (!pathAvailable$1$1 || /^\w+:\/\//.test(opts.from) || isAbsolute$1(opts.from)) {
9292 this.file = opts.from;
9293 } else {
9294 this.file = resolve$1$1(opts.from);
9295 }
9296 }
9297 if (pathAvailable$1$1 && sourceMapAvailable$1$1) {
9298 var map = new PreviousMap$1$1(this.css, opts);
9299 if (map.text) {
9300 this.map = map;
9301 var file = map.consumer().file;
9302 if (!this.file && file) this.file = this.mapResolve(file);
9303 }
9304 }
9305 if (!this.file) {
9306 this.id = "<input css " + nanoid$2(6) + ">";
9307 }
9308 if (this.map) this.map.file = this.from;
9309 }
9310 var _proto = Input.prototype;
9311 _proto.error = function error(message, line, column, opts) {
9312 if (opts === void 0) opts = {};
9313 var result2, endLine, endColumn;
9314 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
9315 var start = line;
9316 var end = column;
9317 if (typeof start.offset === "number") {
9318 var pos = this.fromOffset(start.offset);
9319 line = pos.line;
9320 column = pos.col;
9321 } else {
9322 line = start.line;
9323 column = start.column;
9324 }
9325 if (typeof end.offset === "number") {
9326 var pos1 = this.fromOffset(end.offset);
9327 endLine = pos1.line;
9328 endColumn = pos1.col;
9329 } else {
9330 endLine = end.line;
9331 endColumn = end.column;
9332 }
9333 } else if (!column) {
9334 var pos2 = this.fromOffset(line);
9335 line = pos2.line;
9336 column = pos2.col;
9337 }
9338 var origin = this.origin(line, column, endLine, endColumn);
9339 if (origin) {
9340 result2 = new CssSyntaxError$1$1(message, origin.endLine === void 0 ? origin.line : {
9341 column: origin.column,
9342 line: origin.line
9343 }, origin.endLine === void 0 ? origin.column : {
9344 column: origin.endColumn,
9345 line: origin.endLine
9346 }, origin.source, origin.file, opts.plugin);
9347 } else {
9348 result2 = new CssSyntaxError$1$1(message, endLine === void 0 ? line : {
9349 column: column,
9350 line: line
9351 }, endLine === void 0 ? column : {
9352 column: endColumn,
9353 line: endLine
9354 }, this.css, this.file, opts.plugin);
9355 }
9356 result2.input = {
9357 column: column,
9358 endColumn: endColumn,
9359 endLine: endLine,
9360 line: line,
9361 source: this.css
9362 };
9363 if (this.file) {
9364 if (pathToFileURL$1$1) {
9365 result2.input.url = pathToFileURL$1$1(this.file).toString();
9366 }
9367 result2.input.file = this.file;
9368 }
9369 return result2;
9370 };
9371 _proto.fromOffset = function fromOffset(offset) {
9372 var lastLine, lineToIndex;
9373 if (!this[fromOffsetCache$1]) {
9374 var lines = this.css.split("\n");
9375 lineToIndex = new Array(lines.length);
9376 var prevIndex = 0;
9377 for(var i2 = 0, l2 = lines.length; i2 < l2; i2++){
9378 lineToIndex[i2] = prevIndex;
9379 prevIndex += lines[i2].length + 1;
9380 }
9381 this[fromOffsetCache$1] = lineToIndex;
9382 } else {
9383 lineToIndex = this[fromOffsetCache$1];
9384 }
9385 lastLine = lineToIndex[lineToIndex.length - 1];
9386 var min = 0;
9387 if (offset >= lastLine) {
9388 min = lineToIndex.length - 1;
9389 } else {
9390 var max = lineToIndex.length - 2;
9391 var mid;
9392 while(min < max){
9393 mid = min + (max - min >> 1);
9394 if (offset < lineToIndex[mid]) {
9395 max = mid - 1;
9396 } else if (offset >= lineToIndex[mid + 1]) {
9397 min = mid + 1;
9398 } else {
9399 min = mid;
9400 break;
9401 }
9402 }
9403 }
9404 return {
9405 col: offset - lineToIndex[min] + 1,
9406 line: min + 1
9407 };
9408 };
9409 _proto.mapResolve = function mapResolve(file) {
9410 if (/^\w+:\/\//.test(file)) {
9411 return file;
9412 }
9413 return resolve$1$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
9414 };
9415 _proto.origin = function origin(line, column, endLine, endColumn) {
9416 if (!this.map) return false;
9417 var consumer = this.map.consumer();
9418 var from = consumer.originalPositionFor({
9419 column: column,
9420 line: line
9421 });
9422 if (!from.source) return false;
9423 var to;
9424 if (typeof endLine === "number") {
9425 to = consumer.originalPositionFor({
9426 column: endColumn,
9427 line: endLine
9428 });
9429 }
9430 var fromUrl;
9431 if (isAbsolute$1(from.source)) {
9432 fromUrl = pathToFileURL$1$1(from.source);
9433 } else {
9434 fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1$1(this.map.mapFile));
9435 }
9436 var result2 = {
9437 column: from.column,
9438 endColumn: to && to.column,
9439 endLine: to && to.line,
9440 line: from.line,
9441 url: fromUrl.toString()
9442 };
9443 if (fromUrl.protocol === "file:") {
9444 if (fileURLToPath$1) {
9445 result2.file = fileURLToPath$1(fromUrl);
9446 } else {
9447 throw new Error("file: protocol is not available in this PostCSS build");
9448 }
9449 }
9450 var source = consumer.sourceContentFor(from.source);
9451 if (source) result2.source = source;
9452 return result2;
9453 };
9454 _proto.toJSON = function toJSON() {
9455 var json = {};
9456 for(var _i = 0, _iter = [
9457 "hasBOM",
9458 "css",
9459 "file",
9460 "id"
9461 ]; _i < _iter.length; _i++){
9462 var name = _iter[_i];
9463 if (this[name] != null) {
9464 json[name] = this[name];
9465 }
9466 }
9467 if (this.map) {
9468 json.map = _extends({}, this.map);
9469 if (json.map.consumerCache) {
9470 json.map.consumerCache = void 0;
9471 }
9472 }
9473 return json;
9474 };
9475 _create_class(Input, [
9476 {
9477 key: "from",
9478 get: function get() {
9479 return this.file || this.id;
9480 }
9481 }
9482 ]);
9483 return Input;
9484 }();
9485 var input$1 = Input$4$1;
9486 Input$4$1.default = Input$4$1;
9487 if (terminalHighlight$2 && terminalHighlight$2.registerInput) {
9488 terminalHighlight$2.registerInput(Input$4$1);
9489 }
9490 var SourceMapConsumer$3 = require$$2$1.SourceMapConsumer, SourceMapGenerator$3 = require$$2$1.SourceMapGenerator;
9491 var dirname$2 = require$$2$1.dirname, relative$1 = require$$2$1.relative, resolve$2 = require$$2$1.resolve, sep$1 = require$$2$1.sep;
9492 var pathToFileURL$2 = require$$2$1.pathToFileURL;
9493 var Input$3$1 = input$1;
9494 var sourceMapAvailable$2 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$3);
9495 var pathAvailable$2 = Boolean(dirname$2 && resolve$2 && relative$1 && sep$1);
9496 var MapGenerator$2$1 = /*#__PURE__*/ function() {
9497 function MapGenerator(stringify2, root2, opts, cssString) {
9498 this.stringify = stringify2;
9499 this.mapOpts = opts.map || {};
9500 this.root = root2;
9501 this.opts = opts;
9502 this.css = cssString;
9503 this.originalCSS = cssString;
9504 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
9505 this.memoizedFileURLs = /* @__PURE__ */ new Map();
9506 this.memoizedPaths = /* @__PURE__ */ new Map();
9507 this.memoizedURLs = /* @__PURE__ */ new Map();
9508 }
9509 var _proto = MapGenerator.prototype;
9510 _proto.addAnnotation = function addAnnotation() {
9511 var content;
9512 if (this.isInline()) {
9513 content = "data:application/json;base64," + this.toBase64(this.map.toString());
9514 } else if (typeof this.mapOpts.annotation === "string") {
9515 content = this.mapOpts.annotation;
9516 } else if (typeof this.mapOpts.annotation === "function") {
9517 content = this.mapOpts.annotation(this.opts.to, this.root);
9518 } else {
9519 content = this.outputFile() + ".map";
9520 }
9521 var eol = "\n";
9522 if (this.css.includes("\r\n")) eol = "\r\n";
9523 this.css += eol + "/*# sourceMappingURL=" + content + " */";
9524 };
9525 _proto.applyPrevMaps = function applyPrevMaps() {
9526 for(var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;){
9527 var prev = _step.value;
9528 var from = this.toUrl(this.path(prev.file));
9529 var root2 = prev.root || dirname$2(prev.file);
9530 var map = void 0;
9531 if (this.mapOpts.sourcesContent === false) {
9532 map = new SourceMapConsumer$3(prev.text);
9533 if (map.sourcesContent) {
9534 map.sourcesContent = null;
9535 }
9536 } else {
9537 map = prev.consumer();
9538 }
9539 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
9540 }
9541 };
9542 _proto.clearAnnotation = function clearAnnotation() {
9543 if (this.mapOpts.annotation === false) return;
9544 if (this.root) {
9545 var node2;
9546 for(var i2 = this.root.nodes.length - 1; i2 >= 0; i2--){
9547 node2 = this.root.nodes[i2];
9548 if (node2.type !== "comment") continue;
9549 if (node2.text.indexOf("# sourceMappingURL=") === 0) {
9550 this.root.removeChild(i2);
9551 }
9552 }
9553 } else if (this.css) {
9554 this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
9555 }
9556 };
9557 _proto.generate = function generate() {
9558 this.clearAnnotation();
9559 if (pathAvailable$2 && sourceMapAvailable$2 && this.isMap()) {
9560 return this.generateMap();
9561 } else {
9562 var result2 = "";
9563 this.stringify(this.root, function(i2) {
9564 result2 += i2;
9565 });
9566 return [
9567 result2
9568 ];
9569 }
9570 };
9571 _proto.generateMap = function generateMap() {
9572 if (this.root) {
9573 this.generateString();
9574 } else if (this.previous().length === 1) {
9575 var prev = this.previous()[0].consumer();
9576 prev.file = this.outputFile();
9577 this.map = SourceMapGenerator$3.fromSourceMap(prev, {
9578 ignoreInvalidMapping: true
9579 });
9580 } else {
9581 this.map = new SourceMapGenerator$3({
9582 file: this.outputFile(),
9583 ignoreInvalidMapping: true
9584 });
9585 this.map.addMapping({
9586 generated: {
9587 column: 0,
9588 line: 1
9589 },
9590 original: {
9591 column: 0,
9592 line: 1
9593 },
9594 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
9595 });
9596 }
9597 if (this.isSourcesContent()) this.setSourcesContent();
9598 if (this.root && this.previous().length > 0) this.applyPrevMaps();
9599 if (this.isAnnotation()) this.addAnnotation();
9600 if (this.isInline()) {
9601 return [
9602 this.css
9603 ];
9604 } else {
9605 return [
9606 this.css,
9607 this.map
9608 ];
9609 }
9610 };
9611 _proto.generateString = function generateString() {
9612 var _this = this;
9613 this.css = "";
9614 this.map = new SourceMapGenerator$3({
9615 file: this.outputFile(),
9616 ignoreInvalidMapping: true
9617 });
9618 var line = 1;
9619 var column = 1;
9620 var noSource = "<no source>";
9621 var mapping = {
9622 generated: {
9623 column: 0,
9624 line: 0
9625 },
9626 original: {
9627 column: 0,
9628 line: 0
9629 },
9630 source: ""
9631 };
9632 var lines, last;
9633 this.stringify(this.root, function(str, node2, type) {
9634 _this.css += str;
9635 if (node2 && type !== "end") {
9636 mapping.generated.line = line;
9637 mapping.generated.column = column - 1;
9638 if (node2.source && node2.source.start) {
9639 mapping.source = _this.sourcePath(node2);
9640 mapping.original.line = node2.source.start.line;
9641 mapping.original.column = node2.source.start.column - 1;
9642 _this.map.addMapping(mapping);
9643 } else {
9644 mapping.source = noSource;
9645 mapping.original.line = 1;
9646 mapping.original.column = 0;
9647 _this.map.addMapping(mapping);
9648 }
9649 }
9650 lines = str.match(/\n/g);
9651 if (lines) {
9652 line += lines.length;
9653 last = str.lastIndexOf("\n");
9654 column = str.length - last;
9655 } else {
9656 column += str.length;
9657 }
9658 if (node2 && type !== "start") {
9659 var p = node2.parent || {
9660 raws: {}
9661 };
9662 var childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
9663 if (!childless || node2 !== p.last || p.raws.semicolon) {
9664 if (node2.source && node2.source.end) {
9665 mapping.source = _this.sourcePath(node2);
9666 mapping.original.line = node2.source.end.line;
9667 mapping.original.column = node2.source.end.column - 1;
9668 mapping.generated.line = line;
9669 mapping.generated.column = column - 2;
9670 _this.map.addMapping(mapping);
9671 } else {
9672 mapping.source = noSource;
9673 mapping.original.line = 1;
9674 mapping.original.column = 0;
9675 mapping.generated.line = line;
9676 mapping.generated.column = column - 1;
9677 _this.map.addMapping(mapping);
9678 }
9679 }
9680 }
9681 });
9682 };
9683 _proto.isAnnotation = function isAnnotation() {
9684 if (this.isInline()) {
9685 return true;
9686 }
9687 if (typeof this.mapOpts.annotation !== "undefined") {
9688 return this.mapOpts.annotation;
9689 }
9690 if (this.previous().length) {
9691 return this.previous().some(function(i2) {
9692 return i2.annotation;
9693 });
9694 }
9695 return true;
9696 };
9697 _proto.isInline = function isInline() {
9698 if (typeof this.mapOpts.inline !== "undefined") {
9699 return this.mapOpts.inline;
9700 }
9701 var annotation = this.mapOpts.annotation;
9702 if (typeof annotation !== "undefined" && annotation !== true) {
9703 return false;
9704 }
9705 if (this.previous().length) {
9706 return this.previous().some(function(i2) {
9707 return i2.inline;
9708 });
9709 }
9710 return true;
9711 };
9712 _proto.isMap = function isMap() {
9713 if (typeof this.opts.map !== "undefined") {
9714 return !!this.opts.map;
9715 }
9716 return this.previous().length > 0;
9717 };
9718 _proto.isSourcesContent = function isSourcesContent() {
9719 if (typeof this.mapOpts.sourcesContent !== "undefined") {
9720 return this.mapOpts.sourcesContent;
9721 }
9722 if (this.previous().length) {
9723 return this.previous().some(function(i2) {
9724 return i2.withContent();
9725 });
9726 }
9727 return true;
9728 };
9729 _proto.outputFile = function outputFile() {
9730 if (this.opts.to) {
9731 return this.path(this.opts.to);
9732 } else if (this.opts.from) {
9733 return this.path(this.opts.from);
9734 } else {
9735 return "to.css";
9736 }
9737 };
9738 _proto.path = function path(file) {
9739 if (this.mapOpts.absolute) return file;
9740 if (file.charCodeAt(0) === 60) return file;
9741 if (/^\w+:\/\//.test(file)) return file;
9742 var cached = this.memoizedPaths.get(file);
9743 if (cached) return cached;
9744 var from = this.opts.to ? dirname$2(this.opts.to) : ".";
9745 if (typeof this.mapOpts.annotation === "string") {
9746 from = dirname$2(resolve$2(from, this.mapOpts.annotation));
9747 }
9748 var path = relative$1(from, file);
9749 this.memoizedPaths.set(file, path);
9750 return path;
9751 };
9752 _proto.previous = function previous() {
9753 var _this = this;
9754 if (!this.previousMaps) {
9755 this.previousMaps = [];
9756 if (this.root) {
9757 this.root.walk(function(node2) {
9758 if (node2.source && node2.source.input.map) {
9759 var map = node2.source.input.map;
9760 if (!_this.previousMaps.includes(map)) {
9761 _this.previousMaps.push(map);
9762 }
9763 }
9764 });
9765 } else {
9766 var input2 = new Input$3$1(this.originalCSS, this.opts);
9767 if (input2.map) this.previousMaps.push(input2.map);
9768 }
9769 }
9770 return this.previousMaps;
9771 };
9772 _proto.setSourcesContent = function setSourcesContent() {
9773 var _this = this;
9774 var already = {};
9775 if (this.root) {
9776 this.root.walk(function(node2) {
9777 if (node2.source) {
9778 var from = node2.source.input.from;
9779 if (from && !already[from]) {
9780 already[from] = true;
9781 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
9782 _this.map.setSourceContent(fromUrl, node2.source.input.css);
9783 }
9784 }
9785 });
9786 } else if (this.css) {
9787 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
9788 this.map.setSourceContent(from, this.css);
9789 }
9790 };
9791 _proto.sourcePath = function sourcePath(node2) {
9792 if (this.mapOpts.from) {
9793 return this.toUrl(this.mapOpts.from);
9794 } else if (this.usesFileUrls) {
9795 return this.toFileUrl(node2.source.input.from);
9796 } else {
9797 return this.toUrl(this.path(node2.source.input.from));
9798 }
9799 };
9800 _proto.toBase64 = function toBase64(str) {
9801 if (Buffer) {
9802 return Buffer.from(str).toString("base64");
9803 } else {
9804 return window.btoa(unescape(encodeURIComponent(str)));
9805 }
9806 };
9807 _proto.toFileUrl = function toFileUrl(path) {
9808 var cached = this.memoizedFileURLs.get(path);
9809 if (cached) return cached;
9810 if (pathToFileURL$2) {
9811 var fileURL = pathToFileURL$2(path).toString();
9812 this.memoizedFileURLs.set(path, fileURL);
9813 return fileURL;
9814 } else {
9815 throw new Error("`map.absolute` option is not available in this PostCSS build");
9816 }
9817 };
9818 _proto.toUrl = function toUrl(path) {
9819 var cached = this.memoizedURLs.get(path);
9820 if (cached) return cached;
9821 if (sep$1 === "\\") {
9822 path = path.replace(/\\/g, "/");
9823 }
9824 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
9825 this.memoizedURLs.set(path, url);
9826 return url;
9827 };
9828 return MapGenerator;
9829 }();
9830 var mapGenerator$1 = MapGenerator$2$1;
9831 var Node$2$1 = node$1;
9832 var Comment$4$1 = /*#__PURE__*/ function(Node$2$1) {
9833 _inherits(Comment, Node$2$1);
9834 function Comment(defaults) {
9835 var _this;
9836 _this = Node$2$1.call(this, defaults) || this;
9837 _this.type = "comment";
9838 return _this;
9839 }
9840 return Comment;
9841 }(Node$2$1);
9842 var comment$1 = Comment$4$1;
9843 Comment$4$1.default = Comment$4$1;
9844 var isClean$1$1 = symbols$1.isClean, my$1$1 = symbols$1.my;
9845 var Declaration$3$1 = declaration$1;
9846 var Comment$3$1 = comment$1;
9847 var Node$1$1 = node$1;
9848 var parse$4$1, Rule$4$1, AtRule$4$1, Root$6$1;
9849 function cleanSource$1(nodes) {
9850 return nodes.map(function(i2) {
9851 if (i2.nodes) i2.nodes = cleanSource$1(i2.nodes);
9852 delete i2.source;
9853 return i2;
9854 });
9855 }
9856 function markDirtyUp$1(node2) {
9857 node2[isClean$1$1] = false;
9858 if (node2.proxyOf.nodes) {
9859 for(var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;){
9860 var i2 = _step.value;
9861 markDirtyUp$1(i2);
9862 }
9863 }
9864 }
9865 var Container$7$1 = /*#__PURE__*/ function(Node$1$1) {
9866 _inherits(Container, Node$1$1);
9867 function Container() {
9868 return Node$1$1.apply(this, arguments) || this;
9869 }
9870 var _proto = Container.prototype;
9871 _proto.append = function append() {
9872 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
9873 children[_key] = arguments[_key];
9874 }
9875 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
9876 var child = _step.value;
9877 var nodes = this.normalize(child, this.last);
9878 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
9879 var node2 = _step1.value;
9880 this.proxyOf.nodes.push(node2);
9881 }
9882 }
9883 this.markDirty();
9884 return this;
9885 };
9886 _proto.cleanRaws = function cleanRaws(keepBetween) {
9887 Node$1$1.prototype.cleanRaws.call(this, keepBetween);
9888 if (this.nodes) {
9889 for(var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;){
9890 var node2 = _step.value;
9891 node2.cleanRaws(keepBetween);
9892 }
9893 }
9894 };
9895 _proto.each = function each(callback) {
9896 if (!this.proxyOf.nodes) return void 0;
9897 var iterator = this.getIterator();
9898 var index2, result2;
9899 while(this.indexes[iterator] < this.proxyOf.nodes.length){
9900 index2 = this.indexes[iterator];
9901 result2 = callback(this.proxyOf.nodes[index2], index2);
9902 if (result2 === false) break;
9903 this.indexes[iterator] += 1;
9904 }
9905 delete this.indexes[iterator];
9906 return result2;
9907 };
9908 _proto.every = function every(condition) {
9909 return this.nodes.every(condition);
9910 };
9911 _proto.getIterator = function getIterator() {
9912 if (!this.lastEach) this.lastEach = 0;
9913 if (!this.indexes) this.indexes = {};
9914 this.lastEach += 1;
9915 var iterator = this.lastEach;
9916 this.indexes[iterator] = 0;
9917 return iterator;
9918 };
9919 _proto.getProxyProcessor = function getProxyProcessor() {
9920 return {
9921 get: function get(node2, prop) {
9922 if (prop === "proxyOf") {
9923 return node2;
9924 } else if (!node2[prop]) {
9925 return node2[prop];
9926 } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
9927 return function() {
9928 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
9929 args[_key] = arguments[_key];
9930 }
9931 var _node2;
9932 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
9933 if (typeof i2 === "function") {
9934 return function(child, index2) {
9935 return i2(child.toProxy(), index2);
9936 };
9937 } else {
9938 return i2;
9939 }
9940 })));
9941 };
9942 } else if (prop === "every" || prop === "some") {
9943 return function(cb) {
9944 return node2[prop](function(child) {
9945 for(var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
9946 other[_key - 1] = arguments[_key];
9947 }
9948 return cb.apply(void 0, [].concat([
9949 child.toProxy()
9950 ], other));
9951 });
9952 };
9953 } else if (prop === "root") {
9954 return function() {
9955 return node2.root().toProxy();
9956 };
9957 } else if (prop === "nodes") {
9958 return node2.nodes.map(function(i2) {
9959 return i2.toProxy();
9960 });
9961 } else if (prop === "first" || prop === "last") {
9962 return node2[prop].toProxy();
9963 } else {
9964 return node2[prop];
9965 }
9966 },
9967 set: function set(node2, prop, value) {
9968 if (node2[prop] === value) return true;
9969 node2[prop] = value;
9970 if (prop === "name" || prop === "params" || prop === "selector") {
9971 node2.markDirty();
9972 }
9973 return true;
9974 }
9975 };
9976 };
9977 _proto.index = function index(child) {
9978 if (typeof child === "number") return child;
9979 if (child.proxyOf) child = child.proxyOf;
9980 return this.proxyOf.nodes.indexOf(child);
9981 };
9982 _proto.insertAfter = function insertAfter(exist, add) {
9983 var existIndex = this.index(exist);
9984 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
9985 existIndex = this.index(exist);
9986 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
9987 var node2 = _step.value;
9988 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
9989 }
9990 var index2;
9991 for(var id in this.indexes){
9992 index2 = this.indexes[id];
9993 if (existIndex < index2) {
9994 this.indexes[id] = index2 + nodes.length;
9995 }
9996 }
9997 this.markDirty();
9998 return this;
9999 };
10000 _proto.insertBefore = function insertBefore(exist, add) {
10001 var existIndex = this.index(exist);
10002 var type = existIndex === 0 ? "prepend" : false;
10003 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
10004 existIndex = this.index(exist);
10005 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
10006 var node2 = _step.value;
10007 this.proxyOf.nodes.splice(existIndex, 0, node2);
10008 }
10009 var index2;
10010 for(var id in this.indexes){
10011 index2 = this.indexes[id];
10012 if (existIndex <= index2) {
10013 this.indexes[id] = index2 + nodes.length;
10014 }
10015 }
10016 this.markDirty();
10017 return this;
10018 };
10019 _proto.normalize = function normalize(nodes, sample) {
10020 var _this = this;
10021 if (typeof nodes === "string") {
10022 nodes = cleanSource$1(parse$4$1(nodes).nodes);
10023 } else if (typeof nodes === "undefined") {
10024 nodes = [];
10025 } else if (Array.isArray(nodes)) {
10026 nodes = nodes.slice(0);
10027 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
10028 var i2 = _step.value;
10029 if (i2.parent) i2.parent.removeChild(i2, "ignore");
10030 }
10031 } else if (nodes.type === "root" && this.type !== "document") {
10032 nodes = nodes.nodes.slice(0);
10033 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
10034 var i21 = _step1.value;
10035 if (i21.parent) i21.parent.removeChild(i21, "ignore");
10036 }
10037 } else if (nodes.type) {
10038 nodes = [
10039 nodes
10040 ];
10041 } else if (nodes.prop) {
10042 if (typeof nodes.value === "undefined") {
10043 throw new Error("Value field is missed in node creation");
10044 } else if (typeof nodes.value !== "string") {
10045 nodes.value = String(nodes.value);
10046 }
10047 nodes = [
10048 new Declaration$3$1(nodes)
10049 ];
10050 } else if (nodes.selector) {
10051 nodes = [
10052 new Rule$4$1(nodes)
10053 ];
10054 } else if (nodes.name) {
10055 nodes = [
10056 new AtRule$4$1(nodes)
10057 ];
10058 } else if (nodes.text) {
10059 nodes = [
10060 new Comment$3$1(nodes)
10061 ];
10062 } else {
10063 throw new Error("Unknown node type in node creation");
10064 }
10065 var processed = nodes.map(function(i2) {
10066 if (!i2[my$1$1]) Container.rebuild(i2);
10067 i2 = i2.proxyOf;
10068 if (i2.parent) i2.parent.removeChild(i2);
10069 if (i2[isClean$1$1]) markDirtyUp$1(i2);
10070 if (typeof i2.raws.before === "undefined") {
10071 if (sample && typeof sample.raws.before !== "undefined") {
10072 i2.raws.before = sample.raws.before.replace(/\S/g, "");
10073 }
10074 }
10075 i2.parent = _this.proxyOf;
10076 return i2;
10077 });
10078 return processed;
10079 };
10080 _proto.prepend = function prepend() {
10081 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
10082 children[_key] = arguments[_key];
10083 }
10084 children = children.reverse();
10085 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
10086 var child = _step.value;
10087 var nodes = this.normalize(child, this.first, "prepend").reverse();
10088 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
10089 var node2 = _step1.value;
10090 this.proxyOf.nodes.unshift(node2);
10091 }
10092 for(var id in this.indexes){
10093 this.indexes[id] = this.indexes[id] + nodes.length;
10094 }
10095 }
10096 this.markDirty();
10097 return this;
10098 };
10099 _proto.push = function push(child) {
10100 child.parent = this;
10101 this.proxyOf.nodes.push(child);
10102 return this;
10103 };
10104 _proto.removeAll = function removeAll() {
10105 for(var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;){
10106 var node2 = _step.value;
10107 node2.parent = void 0;
10108 }
10109 this.proxyOf.nodes = [];
10110 this.markDirty();
10111 return this;
10112 };
10113 _proto.removeChild = function removeChild(child) {
10114 child = this.index(child);
10115 this.proxyOf.nodes[child].parent = void 0;
10116 this.proxyOf.nodes.splice(child, 1);
10117 var index2;
10118 for(var id in this.indexes){
10119 index2 = this.indexes[id];
10120 if (index2 >= child) {
10121 this.indexes[id] = index2 - 1;
10122 }
10123 }
10124 this.markDirty();
10125 return this;
10126 };
10127 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
10128 if (!callback) {
10129 callback = opts;
10130 opts = {};
10131 }
10132 this.walkDecls(function(decl) {
10133 if (opts.props && !opts.props.includes(decl.prop)) return;
10134 if (opts.fast && !decl.value.includes(opts.fast)) return;
10135 decl.value = decl.value.replace(pattern, callback);
10136 });
10137 this.markDirty();
10138 return this;
10139 };
10140 _proto.some = function some(condition) {
10141 return this.nodes.some(condition);
10142 };
10143 _proto.walk = function walk(callback) {
10144 return this.each(function(child, i2) {
10145 var result2;
10146 try {
10147 result2 = callback(child, i2);
10148 } catch (e2) {
10149 throw child.addToError(e2);
10150 }
10151 if (result2 !== false && child.walk) {
10152 result2 = child.walk(callback);
10153 }
10154 return result2;
10155 });
10156 };
10157 _proto.walkAtRules = function walkAtRules(name, callback) {
10158 if (!callback) {
10159 callback = name;
10160 return this.walk(function(child, i2) {
10161 if (child.type === "atrule") {
10162 return callback(child, i2);
10163 }
10164 });
10165 }
10166 if (_instanceof(name, RegExp)) {
10167 return this.walk(function(child, i2) {
10168 if (child.type === "atrule" && name.test(child.name)) {
10169 return callback(child, i2);
10170 }
10171 });
10172 }
10173 return this.walk(function(child, i2) {
10174 if (child.type === "atrule" && child.name === name) {
10175 return callback(child, i2);
10176 }
10177 });
10178 };
10179 _proto.walkComments = function walkComments(callback) {
10180 return this.walk(function(child, i2) {
10181 if (child.type === "comment") {
10182 return callback(child, i2);
10183 }
10184 });
10185 };
10186 _proto.walkDecls = function walkDecls(prop, callback) {
10187 if (!callback) {
10188 callback = prop;
10189 return this.walk(function(child, i2) {
10190 if (child.type === "decl") {
10191 return callback(child, i2);
10192 }
10193 });
10194 }
10195 if (_instanceof(prop, RegExp)) {
10196 return this.walk(function(child, i2) {
10197 if (child.type === "decl" && prop.test(child.prop)) {
10198 return callback(child, i2);
10199 }
10200 });
10201 }
10202 return this.walk(function(child, i2) {
10203 if (child.type === "decl" && child.prop === prop) {
10204 return callback(child, i2);
10205 }
10206 });
10207 };
10208 _proto.walkRules = function walkRules(selector, callback) {
10209 if (!callback) {
10210 callback = selector;
10211 return this.walk(function(child, i2) {
10212 if (child.type === "rule") {
10213 return callback(child, i2);
10214 }
10215 });
10216 }
10217 if (_instanceof(selector, RegExp)) {
10218 return this.walk(function(child, i2) {
10219 if (child.type === "rule" && selector.test(child.selector)) {
10220 return callback(child, i2);
10221 }
10222 });
10223 }
10224 return this.walk(function(child, i2) {
10225 if (child.type === "rule" && child.selector === selector) {
10226 return callback(child, i2);
10227 }
10228 });
10229 };
10230 _create_class(Container, [
10231 {
10232 key: "first",
10233 get: function get() {
10234 if (!this.proxyOf.nodes) return void 0;
10235 return this.proxyOf.nodes[0];
10236 }
10237 },
10238 {
10239 key: "last",
10240 get: function get() {
10241 if (!this.proxyOf.nodes) return void 0;
10242 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
10243 }
10244 }
10245 ]);
10246 return Container;
10247 }(Node$1$1);
10248 Container$7$1.registerParse = function(dependant) {
10249 parse$4$1 = dependant;
10250 };
10251 Container$7$1.registerRule = function(dependant) {
10252 Rule$4$1 = dependant;
10253 };
10254 Container$7$1.registerAtRule = function(dependant) {
10255 AtRule$4$1 = dependant;
10256 };
10257 Container$7$1.registerRoot = function(dependant) {
10258 Root$6$1 = dependant;
10259 };
10260 var container$1 = Container$7$1;
10261 Container$7$1.default = Container$7$1;
10262 Container$7$1.rebuild = function(node2) {
10263 if (node2.type === "atrule") {
10264 Object.setPrototypeOf(node2, AtRule$4$1.prototype);
10265 } else if (node2.type === "rule") {
10266 Object.setPrototypeOf(node2, Rule$4$1.prototype);
10267 } else if (node2.type === "decl") {
10268 Object.setPrototypeOf(node2, Declaration$3$1.prototype);
10269 } else if (node2.type === "comment") {
10270 Object.setPrototypeOf(node2, Comment$3$1.prototype);
10271 } else if (node2.type === "root") {
10272 Object.setPrototypeOf(node2, Root$6$1.prototype);
10273 }
10274 node2[my$1$1] = true;
10275 if (node2.nodes) {
10276 node2.nodes.forEach(function(child) {
10277 Container$7$1.rebuild(child);
10278 });
10279 }
10280 };
10281 var Container$6$1 = container$1;
10282 var LazyResult$4$1, Processor$3$1;
10283 var Document$3$1 = /*#__PURE__*/ function(Container$6$1) {
10284 _inherits(Document2, Container$6$1);
10285 function Document2(defaults) {
10286 var _this;
10287 _this = Container$6$1.call(this, _extends({
10288 type: "document"
10289 }, defaults)) || this;
10290 if (!_this.nodes) {
10291 _this.nodes = [];
10292 }
10293 return _this;
10294 }
10295 var _proto = Document2.prototype;
10296 _proto.toResult = function toResult(opts) {
10297 if (opts === void 0) opts = {};
10298 var lazy = new LazyResult$4$1(new Processor$3$1(), this, opts);
10299 return lazy.stringify();
10300 };
10301 return Document2;
10302 }(Container$6$1);
10303 Document$3$1.registerLazyResult = function(dependant) {
10304 LazyResult$4$1 = dependant;
10305 };
10306 Document$3$1.registerProcessor = function(dependant) {
10307 Processor$3$1 = dependant;
10308 };
10309 var document$1$1 = Document$3$1;
10310 Document$3$1.default = Document$3$1;
10311 var printed$1 = {};
10312 var warnOnce$2$1 = function warnOnce(message) {
10313 if (printed$1[message]) return;
10314 printed$1[message] = true;
10315 if (typeof console !== "undefined" && console.warn) {
10316 console.warn(message);
10317 }
10318 };
10319 var Warning$2$1 = /*#__PURE__*/ function() {
10320 function Warning(text, opts) {
10321 if (opts === void 0) opts = {};
10322 this.type = "warning";
10323 this.text = text;
10324 if (opts.node && opts.node.source) {
10325 var range = opts.node.rangeBy(opts);
10326 this.line = range.start.line;
10327 this.column = range.start.column;
10328 this.endLine = range.end.line;
10329 this.endColumn = range.end.column;
10330 }
10331 for(var opt in opts)this[opt] = opts[opt];
10332 }
10333 var _proto = Warning.prototype;
10334 _proto.toString = function toString() {
10335 if (this.node) {
10336 return this.node.error(this.text, {
10337 index: this.index,
10338 plugin: this.plugin,
10339 word: this.word
10340 }).message;
10341 }
10342 if (this.plugin) {
10343 return this.plugin + ": " + this.text;
10344 }
10345 return this.text;
10346 };
10347 return Warning;
10348 }();
10349 var warning$1 = Warning$2$1;
10350 Warning$2$1.default = Warning$2$1;
10351 var Warning$1$1 = warning$1;
10352 var Result$3$1 = /*#__PURE__*/ function() {
10353 function Result(processor2, root2, opts) {
10354 this.processor = processor2;
10355 this.messages = [];
10356 this.root = root2;
10357 this.opts = opts;
10358 this.css = void 0;
10359 this.map = void 0;
10360 }
10361 var _proto = Result.prototype;
10362 _proto.toString = function toString() {
10363 return this.css;
10364 };
10365 _proto.warn = function warn(text, opts) {
10366 if (opts === void 0) opts = {};
10367 if (!opts.plugin) {
10368 if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
10369 opts.plugin = this.lastPlugin.postcssPlugin;
10370 }
10371 }
10372 var warning2 = new Warning$1$1(text, opts);
10373 this.messages.push(warning2);
10374 return warning2;
10375 };
10376 _proto.warnings = function warnings() {
10377 return this.messages.filter(function(i2) {
10378 return i2.type === "warning";
10379 });
10380 };
10381 _create_class(Result, [
10382 {
10383 key: "content",
10384 get: function get() {
10385 return this.css;
10386 }
10387 }
10388 ]);
10389 return Result;
10390 }();
10391 var result$1 = Result$3$1;
10392 Result$3$1.default = Result$3$1;
10393 var SINGLE_QUOTE$1 = "'".charCodeAt(0);
10394 var DOUBLE_QUOTE$1 = '"'.charCodeAt(0);
10395 var BACKSLASH$1 = "\\".charCodeAt(0);
10396 var SLASH$1 = "/".charCodeAt(0);
10397 var NEWLINE$1 = "\n".charCodeAt(0);
10398 var SPACE$1 = " ".charCodeAt(0);
10399 var FEED$1 = "\f".charCodeAt(0);
10400 var TAB$1 = " ".charCodeAt(0);
10401 var CR$1 = "\r".charCodeAt(0);
10402 var OPEN_SQUARE$1 = "[".charCodeAt(0);
10403 var CLOSE_SQUARE$1 = "]".charCodeAt(0);
10404 var OPEN_PARENTHESES$1 = "(".charCodeAt(0);
10405 var CLOSE_PARENTHESES$1 = ")".charCodeAt(0);
10406 var OPEN_CURLY$1 = "{".charCodeAt(0);
10407 var CLOSE_CURLY$1 = "}".charCodeAt(0);
10408 var SEMICOLON$1 = ";".charCodeAt(0);
10409 var ASTERISK$1 = "*".charCodeAt(0);
10410 var COLON$1 = ":".charCodeAt(0);
10411 var AT$1 = "@".charCodeAt(0);
10412 var RE_AT_END$1 = /[\t\n\f\r "#'()/;[\\\]{}]/g;
10413 var RE_WORD_END$1 = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
10414 var RE_BAD_BRACKET$1 = /.[\r\n"'(/\\]/;
10415 var RE_HEX_ESCAPE$1 = /[\da-f]/i;
10416 var tokenize$1 = function tokenizer(input2, options) {
10417 if (options === void 0) options = {};
10418 var css = input2.css.valueOf();
10419 var ignore = options.ignoreErrors;
10420 var code, next, quote, content, escape;
10421 var escaped, escapePos, prev, n2, currentToken;
10422 var length = css.length;
10423 var pos = 0;
10424 var buffer = [];
10425 var returned = [];
10426 function position() {
10427 return pos;
10428 }
10429 function unclosed(what) {
10430 throw input2.error("Unclosed " + what, pos);
10431 }
10432 function endOfFile() {
10433 return returned.length === 0 && pos >= length;
10434 }
10435 function nextToken(opts) {
10436 if (returned.length) return returned.pop();
10437 if (pos >= length) return;
10438 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
10439 code = css.charCodeAt(pos);
10440 switch(code){
10441 case NEWLINE$1:
10442 case SPACE$1:
10443 case TAB$1:
10444 case CR$1:
10445 case FEED$1:
10446 {
10447 next = pos;
10448 do {
10449 next += 1;
10450 code = css.charCodeAt(next);
10451 }while (code === SPACE$1 || code === NEWLINE$1 || code === TAB$1 || code === CR$1 || code === FEED$1);
10452 currentToken = [
10453 "space",
10454 css.slice(pos, next)
10455 ];
10456 pos = next - 1;
10457 break;
10458 }
10459 case OPEN_SQUARE$1:
10460 case CLOSE_SQUARE$1:
10461 case OPEN_CURLY$1:
10462 case CLOSE_CURLY$1:
10463 case COLON$1:
10464 case SEMICOLON$1:
10465 case CLOSE_PARENTHESES$1:
10466 {
10467 var controlChar = String.fromCharCode(code);
10468 currentToken = [
10469 controlChar,
10470 controlChar,
10471 pos
10472 ];
10473 break;
10474 }
10475 case OPEN_PARENTHESES$1:
10476 {
10477 prev = buffer.length ? buffer.pop()[1] : "";
10478 n2 = css.charCodeAt(pos + 1);
10479 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) {
10480 next = pos;
10481 do {
10482 escaped = false;
10483 next = css.indexOf(")", next + 1);
10484 if (next === -1) {
10485 if (ignore || ignoreUnclosed) {
10486 next = pos;
10487 break;
10488 } else {
10489 unclosed("bracket");
10490 }
10491 }
10492 escapePos = next;
10493 while(css.charCodeAt(escapePos - 1) === BACKSLASH$1){
10494 escapePos -= 1;
10495 escaped = !escaped;
10496 }
10497 }while (escaped);
10498 currentToken = [
10499 "brackets",
10500 css.slice(pos, next + 1),
10501 pos,
10502 next
10503 ];
10504 pos = next;
10505 } else {
10506 next = css.indexOf(")", pos + 1);
10507 content = css.slice(pos, next + 1);
10508 if (next === -1 || RE_BAD_BRACKET$1.test(content)) {
10509 currentToken = [
10510 "(",
10511 "(",
10512 pos
10513 ];
10514 } else {
10515 currentToken = [
10516 "brackets",
10517 content,
10518 pos,
10519 next
10520 ];
10521 pos = next;
10522 }
10523 }
10524 break;
10525 }
10526 case SINGLE_QUOTE$1:
10527 case DOUBLE_QUOTE$1:
10528 {
10529 quote = code === SINGLE_QUOTE$1 ? "'" : '"';
10530 next = pos;
10531 do {
10532 escaped = false;
10533 next = css.indexOf(quote, next + 1);
10534 if (next === -1) {
10535 if (ignore || ignoreUnclosed) {
10536 next = pos + 1;
10537 break;
10538 } else {
10539 unclosed("string");
10540 }
10541 }
10542 escapePos = next;
10543 while(css.charCodeAt(escapePos - 1) === BACKSLASH$1){
10544 escapePos -= 1;
10545 escaped = !escaped;
10546 }
10547 }while (escaped);
10548 currentToken = [
10549 "string",
10550 css.slice(pos, next + 1),
10551 pos,
10552 next
10553 ];
10554 pos = next;
10555 break;
10556 }
10557 case AT$1:
10558 {
10559 RE_AT_END$1.lastIndex = pos + 1;
10560 RE_AT_END$1.test(css);
10561 if (RE_AT_END$1.lastIndex === 0) {
10562 next = css.length - 1;
10563 } else {
10564 next = RE_AT_END$1.lastIndex - 2;
10565 }
10566 currentToken = [
10567 "at-word",
10568 css.slice(pos, next + 1),
10569 pos,
10570 next
10571 ];
10572 pos = next;
10573 break;
10574 }
10575 case BACKSLASH$1:
10576 {
10577 next = pos;
10578 escape = true;
10579 while(css.charCodeAt(next + 1) === BACKSLASH$1){
10580 next += 1;
10581 escape = !escape;
10582 }
10583 code = css.charCodeAt(next + 1);
10584 if (escape && code !== SLASH$1 && code !== SPACE$1 && code !== NEWLINE$1 && code !== TAB$1 && code !== CR$1 && code !== FEED$1) {
10585 next += 1;
10586 if (RE_HEX_ESCAPE$1.test(css.charAt(next))) {
10587 while(RE_HEX_ESCAPE$1.test(css.charAt(next + 1))){
10588 next += 1;
10589 }
10590 if (css.charCodeAt(next + 1) === SPACE$1) {
10591 next += 1;
10592 }
10593 }
10594 }
10595 currentToken = [
10596 "word",
10597 css.slice(pos, next + 1),
10598 pos,
10599 next
10600 ];
10601 pos = next;
10602 break;
10603 }
10604 default:
10605 {
10606 if (code === SLASH$1 && css.charCodeAt(pos + 1) === ASTERISK$1) {
10607 next = css.indexOf("*/", pos + 2) + 1;
10608 if (next === 0) {
10609 if (ignore || ignoreUnclosed) {
10610 next = css.length;
10611 } else {
10612 unclosed("comment");
10613 }
10614 }
10615 currentToken = [
10616 "comment",
10617 css.slice(pos, next + 1),
10618 pos,
10619 next
10620 ];
10621 pos = next;
10622 } else {
10623 RE_WORD_END$1.lastIndex = pos + 1;
10624 RE_WORD_END$1.test(css);
10625 if (RE_WORD_END$1.lastIndex === 0) {
10626 next = css.length - 1;
10627 } else {
10628 next = RE_WORD_END$1.lastIndex - 2;
10629 }
10630 currentToken = [
10631 "word",
10632 css.slice(pos, next + 1),
10633 pos,
10634 next
10635 ];
10636 buffer.push(currentToken);
10637 pos = next;
10638 }
10639 break;
10640 }
10641 }
10642 pos++;
10643 return currentToken;
10644 }
10645 function back(token) {
10646 returned.push(token);
10647 }
10648 return {
10649 back: back,
10650 endOfFile: endOfFile,
10651 nextToken: nextToken,
10652 position: position
10653 };
10654 };
10655 var Container$5$1 = container$1;
10656 var AtRule$3$1 = /*#__PURE__*/ function(Container$5$1) {
10657 _inherits(AtRule, Container$5$1);
10658 function AtRule(defaults) {
10659 var _this;
10660 _this = Container$5$1.call(this, defaults) || this;
10661 _this.type = "atrule";
10662 return _this;
10663 }
10664 var _proto = AtRule.prototype;
10665 _proto.append = function append() {
10666 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
10667 children[_key] = arguments[_key];
10668 }
10669 var _Container$5$1_prototype_append;
10670 if (!this.proxyOf.nodes) this.nodes = [];
10671 return (_Container$5$1_prototype_append = Container$5$1.prototype.append).call.apply(_Container$5$1_prototype_append, [].concat([
10672 this
10673 ], children));
10674 };
10675 _proto.prepend = function prepend() {
10676 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
10677 children[_key] = arguments[_key];
10678 }
10679 var _Container$5$1_prototype_prepend;
10680 if (!this.proxyOf.nodes) this.nodes = [];
10681 return (_Container$5$1_prototype_prepend = Container$5$1.prototype.prepend).call.apply(_Container$5$1_prototype_prepend, [].concat([
10682 this
10683 ], children));
10684 };
10685 return AtRule;
10686 }(Container$5$1);
10687 var atRule$1 = AtRule$3$1;
10688 AtRule$3$1.default = AtRule$3$1;
10689 Container$5$1.registerAtRule(AtRule$3$1);
10690 var Container$4$1 = container$1;
10691 var LazyResult$3$1, Processor$2$1;
10692 var Root$5$1 = /*#__PURE__*/ function(Container$4$1) {
10693 _inherits(Root, Container$4$1);
10694 function Root(defaults) {
10695 var _this;
10696 _this = Container$4$1.call(this, defaults) || this;
10697 _this.type = "root";
10698 if (!_this.nodes) _this.nodes = [];
10699 return _this;
10700 }
10701 var _proto = Root.prototype;
10702 _proto.normalize = function normalize(child, sample, type) {
10703 var nodes = Container$4$1.prototype.normalize.call(this, child);
10704 if (sample) {
10705 if (type === "prepend") {
10706 if (this.nodes.length > 1) {
10707 sample.raws.before = this.nodes[1].raws.before;
10708 } else {
10709 delete sample.raws.before;
10710 }
10711 } else if (this.first !== sample) {
10712 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
10713 var node2 = _step.value;
10714 node2.raws.before = sample.raws.before;
10715 }
10716 }
10717 }
10718 return nodes;
10719 };
10720 _proto.removeChild = function removeChild(child, ignore) {
10721 var index2 = this.index(child);
10722 if (!ignore && index2 === 0 && this.nodes.length > 1) {
10723 this.nodes[1].raws.before = this.nodes[index2].raws.before;
10724 }
10725 return Container$4$1.prototype.removeChild.call(this, child);
10726 };
10727 _proto.toResult = function toResult(opts) {
10728 if (opts === void 0) opts = {};
10729 var lazy = new LazyResult$3$1(new Processor$2$1(), this, opts);
10730 return lazy.stringify();
10731 };
10732 return Root;
10733 }(Container$4$1);
10734 Root$5$1.registerLazyResult = function(dependant) {
10735 LazyResult$3$1 = dependant;
10736 };
10737 Root$5$1.registerProcessor = function(dependant) {
10738 Processor$2$1 = dependant;
10739 };
10740 var root$1 = Root$5$1;
10741 Root$5$1.default = Root$5$1;
10742 Container$4$1.registerRoot(Root$5$1);
10743 var list$2$1 = {
10744 comma: function comma(string) {
10745 return list$2$1.split(string, [
10746 ","
10747 ], true);
10748 },
10749 space: function space(string) {
10750 var spaces = [
10751 " ",
10752 "\n",
10753 " "
10754 ];
10755 return list$2$1.split(string, spaces);
10756 },
10757 split: function split(string, separators, last) {
10758 var array = [];
10759 var current = "";
10760 var split = false;
10761 var func = 0;
10762 var inQuote = false;
10763 var prevQuote = "";
10764 var escape = false;
10765 for(var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;){
10766 var letter = _step.value;
10767 if (escape) {
10768 escape = false;
10769 } else if (letter === "\\") {
10770 escape = true;
10771 } else if (inQuote) {
10772 if (letter === prevQuote) {
10773 inQuote = false;
10774 }
10775 } else if (letter === '"' || letter === "'") {
10776 inQuote = true;
10777 prevQuote = letter;
10778 } else if (letter === "(") {
10779 func += 1;
10780 } else if (letter === ")") {
10781 if (func > 0) func -= 1;
10782 } else if (func === 0) {
10783 if (separators.includes(letter)) split = true;
10784 }
10785 if (split) {
10786 if (current !== "") array.push(current.trim());
10787 current = "";
10788 split = false;
10789 } else {
10790 current += letter;
10791 }
10792 }
10793 if (last || current !== "") array.push(current.trim());
10794 return array;
10795 }
10796 };
10797 var list_1$1 = list$2$1;
10798 list$2$1.default = list$2$1;
10799 var Container$3$1 = container$1;
10800 var list$1$1 = list_1$1;
10801 var Rule$3$1 = /*#__PURE__*/ function(Container$3$1) {
10802 _inherits(Rule, Container$3$1);
10803 function Rule(defaults) {
10804 var _this;
10805 _this = Container$3$1.call(this, defaults) || this;
10806 _this.type = "rule";
10807 if (!_this.nodes) _this.nodes = [];
10808 return _this;
10809 }
10810 _create_class(Rule, [
10811 {
10812 key: "selectors",
10813 get: function get() {
10814 return list$1$1.comma(this.selector);
10815 },
10816 set: function set(values) {
10817 var match = this.selector ? this.selector.match(/,\s*/) : null;
10818 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
10819 this.selector = values.join(sep2);
10820 }
10821 }
10822 ]);
10823 return Rule;
10824 }(Container$3$1);
10825 var rule$1 = Rule$3$1;
10826 Rule$3$1.default = Rule$3$1;
10827 Container$3$1.registerRule(Rule$3$1);
10828 var Declaration$2$1 = declaration$1;
10829 var tokenizer2$1 = tokenize$1;
10830 var Comment$2$1 = comment$1;
10831 var AtRule$2$1 = atRule$1;
10832 var Root$4$1 = root$1;
10833 var Rule$2$1 = rule$1;
10834 var SAFE_COMMENT_NEIGHBOR$1 = {
10835 empty: true,
10836 space: true
10837 };
10838 function findLastWithPosition$1(tokens) {
10839 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
10840 var token = tokens[i2];
10841 var pos = token[3] || token[2];
10842 if (pos) return pos;
10843 }
10844 }
10845 var Parser$1$1 = /*#__PURE__*/ function() {
10846 function Parser(input2) {
10847 this.input = input2;
10848 this.root = new Root$4$1();
10849 this.current = this.root;
10850 this.spaces = "";
10851 this.semicolon = false;
10852 this.createTokenizer();
10853 this.root.source = {
10854 input: input2,
10855 start: {
10856 column: 1,
10857 line: 1,
10858 offset: 0
10859 }
10860 };
10861 }
10862 var _proto = Parser.prototype;
10863 _proto.atrule = function atrule(token) {
10864 var node2 = new AtRule$2$1();
10865 node2.name = token[1].slice(1);
10866 if (node2.name === "") {
10867 this.unnamedAtrule(node2, token);
10868 }
10869 this.init(node2, token[2]);
10870 var type;
10871 var prev;
10872 var shift;
10873 var last = false;
10874 var open = false;
10875 var params = [];
10876 var brackets = [];
10877 while(!this.tokenizer.endOfFile()){
10878 token = this.tokenizer.nextToken();
10879 type = token[0];
10880 if (type === "(" || type === "[") {
10881 brackets.push(type === "(" ? ")" : "]");
10882 } else if (type === "{" && brackets.length > 0) {
10883 brackets.push("}");
10884 } else if (type === brackets[brackets.length - 1]) {
10885 brackets.pop();
10886 }
10887 if (brackets.length === 0) {
10888 if (type === ";") {
10889 node2.source.end = this.getPosition(token[2]);
10890 node2.source.end.offset++;
10891 this.semicolon = true;
10892 break;
10893 } else if (type === "{") {
10894 open = true;
10895 break;
10896 } else if (type === "}") {
10897 if (params.length > 0) {
10898 shift = params.length - 1;
10899 prev = params[shift];
10900 while(prev && prev[0] === "space"){
10901 prev = params[--shift];
10902 }
10903 if (prev) {
10904 node2.source.end = this.getPosition(prev[3] || prev[2]);
10905 node2.source.end.offset++;
10906 }
10907 }
10908 this.end(token);
10909 break;
10910 } else {
10911 params.push(token);
10912 }
10913 } else {
10914 params.push(token);
10915 }
10916 if (this.tokenizer.endOfFile()) {
10917 last = true;
10918 break;
10919 }
10920 }
10921 node2.raws.between = this.spacesAndCommentsFromEnd(params);
10922 if (params.length) {
10923 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
10924 this.raw(node2, "params", params);
10925 if (last) {
10926 token = params[params.length - 1];
10927 node2.source.end = this.getPosition(token[3] || token[2]);
10928 node2.source.end.offset++;
10929 this.spaces = node2.raws.between;
10930 node2.raws.between = "";
10931 }
10932 } else {
10933 node2.raws.afterName = "";
10934 node2.params = "";
10935 }
10936 if (open) {
10937 node2.nodes = [];
10938 this.current = node2;
10939 }
10940 };
10941 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
10942 var colon = this.colon(tokens);
10943 if (colon === false) return;
10944 var founded = 0;
10945 var token;
10946 for(var j = colon - 1; j >= 0; j--){
10947 token = tokens[j];
10948 if (token[0] !== "space") {
10949 founded += 1;
10950 if (founded === 2) break;
10951 }
10952 }
10953 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
10954 };
10955 _proto.colon = function colon(tokens) {
10956 var brackets = 0;
10957 var token, type, prev;
10958 for(var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;){
10959 var _step_value = _step.value, i2 = _step_value[0], element = _step_value[1];
10960 token = element;
10961 type = token[0];
10962 if (type === "(") {
10963 brackets += 1;
10964 }
10965 if (type === ")") {
10966 brackets -= 1;
10967 }
10968 if (brackets === 0 && type === ":") {
10969 if (!prev) {
10970 this.doubleColon(token);
10971 } else if (prev[0] === "word" && prev[1] === "progid") {
10972 continue;
10973 } else {
10974 return i2;
10975 }
10976 }
10977 prev = token;
10978 }
10979 return false;
10980 };
10981 _proto.comment = function comment(token) {
10982 var node2 = new Comment$2$1();
10983 this.init(node2, token[2]);
10984 node2.source.end = this.getPosition(token[3] || token[2]);
10985 node2.source.end.offset++;
10986 var text = token[1].slice(2, -2);
10987 if (/^\s*$/.test(text)) {
10988 node2.text = "";
10989 node2.raws.left = text;
10990 node2.raws.right = "";
10991 } else {
10992 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
10993 node2.text = match[2];
10994 node2.raws.left = match[1];
10995 node2.raws.right = match[3];
10996 }
10997 };
10998 _proto.createTokenizer = function createTokenizer() {
10999 this.tokenizer = tokenizer2$1(this.input);
11000 };
11001 _proto.decl = function decl(tokens, customProperty) {
11002 var node2 = new Declaration$2$1();
11003 this.init(node2, tokens[0][2]);
11004 var last = tokens[tokens.length - 1];
11005 if (last[0] === ";") {
11006 this.semicolon = true;
11007 tokens.pop();
11008 }
11009 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition$1(tokens));
11010 node2.source.end.offset++;
11011 while(tokens[0][0] !== "word"){
11012 if (tokens.length === 1) this.unknownWord(tokens);
11013 node2.raws.before += tokens.shift()[1];
11014 }
11015 node2.source.start = this.getPosition(tokens[0][2]);
11016 node2.prop = "";
11017 while(tokens.length){
11018 var type = tokens[0][0];
11019 if (type === ":" || type === "space" || type === "comment") {
11020 break;
11021 }
11022 node2.prop += tokens.shift()[1];
11023 }
11024 node2.raws.between = "";
11025 var token;
11026 while(tokens.length){
11027 token = tokens.shift();
11028 if (token[0] === ":") {
11029 node2.raws.between += token[1];
11030 break;
11031 } else {
11032 if (token[0] === "word" && /\w/.test(token[1])) {
11033 this.unknownWord([
11034 token
11035 ]);
11036 }
11037 node2.raws.between += token[1];
11038 }
11039 }
11040 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
11041 node2.raws.before += node2.prop[0];
11042 node2.prop = node2.prop.slice(1);
11043 }
11044 var firstSpaces = [];
11045 var next;
11046 while(tokens.length){
11047 next = tokens[0][0];
11048 if (next !== "space" && next !== "comment") break;
11049 firstSpaces.push(tokens.shift());
11050 }
11051 this.precheckMissedSemicolon(tokens);
11052 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
11053 token = tokens[i2];
11054 if (token[1].toLowerCase() === "!important") {
11055 node2.important = true;
11056 var string = this.stringFrom(tokens, i2);
11057 string = this.spacesFromEnd(tokens) + string;
11058 if (string !== " !important") node2.raws.important = string;
11059 break;
11060 } else if (token[1].toLowerCase() === "important") {
11061 var cache = tokens.slice(0);
11062 var str = "";
11063 for(var j = i2; j > 0; j--){
11064 var type1 = cache[j][0];
11065 if (str.trim().indexOf("!") === 0 && type1 !== "space") {
11066 break;
11067 }
11068 str = cache.pop()[1] + str;
11069 }
11070 if (str.trim().indexOf("!") === 0) {
11071 node2.important = true;
11072 node2.raws.important = str;
11073 tokens = cache;
11074 }
11075 }
11076 if (token[0] !== "space" && token[0] !== "comment") {
11077 break;
11078 }
11079 }
11080 var hasWord = tokens.some(function(i2) {
11081 return i2[0] !== "space" && i2[0] !== "comment";
11082 });
11083 if (hasWord) {
11084 node2.raws.between += firstSpaces.map(function(i2) {
11085 return i2[1];
11086 }).join("");
11087 firstSpaces = [];
11088 }
11089 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
11090 if (node2.value.includes(":") && !customProperty) {
11091 this.checkMissedSemicolon(tokens);
11092 }
11093 };
11094 _proto.doubleColon = function doubleColon(token) {
11095 throw this.input.error("Double colon", {
11096 offset: token[2]
11097 }, {
11098 offset: token[2] + token[1].length
11099 });
11100 };
11101 _proto.emptyRule = function emptyRule(token) {
11102 var node2 = new Rule$2$1();
11103 this.init(node2, token[2]);
11104 node2.selector = "";
11105 node2.raws.between = "";
11106 this.current = node2;
11107 };
11108 _proto.end = function end(token) {
11109 if (this.current.nodes && this.current.nodes.length) {
11110 this.current.raws.semicolon = this.semicolon;
11111 }
11112 this.semicolon = false;
11113 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
11114 this.spaces = "";
11115 if (this.current.parent) {
11116 this.current.source.end = this.getPosition(token[2]);
11117 this.current.source.end.offset++;
11118 this.current = this.current.parent;
11119 } else {
11120 this.unexpectedClose(token);
11121 }
11122 };
11123 _proto.endFile = function endFile() {
11124 if (this.current.parent) this.unclosedBlock();
11125 if (this.current.nodes && this.current.nodes.length) {
11126 this.current.raws.semicolon = this.semicolon;
11127 }
11128 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
11129 this.root.source.end = this.getPosition(this.tokenizer.position());
11130 };
11131 _proto.freeSemicolon = function freeSemicolon(token) {
11132 this.spaces += token[1];
11133 if (this.current.nodes) {
11134 var prev = this.current.nodes[this.current.nodes.length - 1];
11135 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
11136 prev.raws.ownSemicolon = this.spaces;
11137 this.spaces = "";
11138 }
11139 }
11140 };
11141 // Helpers
11142 _proto.getPosition = function getPosition(offset) {
11143 var pos = this.input.fromOffset(offset);
11144 return {
11145 column: pos.col,
11146 line: pos.line,
11147 offset: offset
11148 };
11149 };
11150 _proto.init = function init(node2, offset) {
11151 this.current.push(node2);
11152 node2.source = {
11153 input: this.input,
11154 start: this.getPosition(offset)
11155 };
11156 node2.raws.before = this.spaces;
11157 this.spaces = "";
11158 if (node2.type !== "comment") this.semicolon = false;
11159 };
11160 _proto.other = function other(start) {
11161 var end = false;
11162 var type = null;
11163 var colon = false;
11164 var bracket = null;
11165 var brackets = [];
11166 var customProperty = start[1].startsWith("--");
11167 var tokens = [];
11168 var token = start;
11169 while(token){
11170 type = token[0];
11171 tokens.push(token);
11172 if (type === "(" || type === "[") {
11173 if (!bracket) bracket = token;
11174 brackets.push(type === "(" ? ")" : "]");
11175 } else if (customProperty && colon && type === "{") {
11176 if (!bracket) bracket = token;
11177 brackets.push("}");
11178 } else if (brackets.length === 0) {
11179 if (type === ";") {
11180 if (colon) {
11181 this.decl(tokens, customProperty);
11182 return;
11183 } else {
11184 break;
11185 }
11186 } else if (type === "{") {
11187 this.rule(tokens);
11188 return;
11189 } else if (type === "}") {
11190 this.tokenizer.back(tokens.pop());
11191 end = true;
11192 break;
11193 } else if (type === ":") {
11194 colon = true;
11195 }
11196 } else if (type === brackets[brackets.length - 1]) {
11197 brackets.pop();
11198 if (brackets.length === 0) bracket = null;
11199 }
11200 token = this.tokenizer.nextToken();
11201 }
11202 if (this.tokenizer.endOfFile()) end = true;
11203 if (brackets.length > 0) this.unclosedBracket(bracket);
11204 if (end && colon) {
11205 if (!customProperty) {
11206 while(tokens.length){
11207 token = tokens[tokens.length - 1][0];
11208 if (token !== "space" && token !== "comment") break;
11209 this.tokenizer.back(tokens.pop());
11210 }
11211 }
11212 this.decl(tokens, customProperty);
11213 } else {
11214 this.unknownWord(tokens);
11215 }
11216 };
11217 _proto.parse = function parse() {
11218 var token;
11219 while(!this.tokenizer.endOfFile()){
11220 token = this.tokenizer.nextToken();
11221 switch(token[0]){
11222 case "space":
11223 this.spaces += token[1];
11224 break;
11225 case ";":
11226 this.freeSemicolon(token);
11227 break;
11228 case "}":
11229 this.end(token);
11230 break;
11231 case "comment":
11232 this.comment(token);
11233 break;
11234 case "at-word":
11235 this.atrule(token);
11236 break;
11237 case "{":
11238 this.emptyRule(token);
11239 break;
11240 default:
11241 this.other(token);
11242 break;
11243 }
11244 }
11245 this.endFile();
11246 };
11247 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
11248 _proto.raw = function raw(node2, prop, tokens, customProperty) {
11249 var token, type;
11250 var length = tokens.length;
11251 var value = "";
11252 var clean = true;
11253 var next, prev;
11254 for(var i2 = 0; i2 < length; i2 += 1){
11255 token = tokens[i2];
11256 type = token[0];
11257 if (type === "space" && i2 === length - 1 && !customProperty) {
11258 clean = false;
11259 } else if (type === "comment") {
11260 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
11261 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
11262 if (!SAFE_COMMENT_NEIGHBOR$1[prev] && !SAFE_COMMENT_NEIGHBOR$1[next]) {
11263 if (value.slice(-1) === ",") {
11264 clean = false;
11265 } else {
11266 value += token[1];
11267 }
11268 } else {
11269 clean = false;
11270 }
11271 } else {
11272 value += token[1];
11273 }
11274 }
11275 if (!clean) {
11276 var raw = tokens.reduce(function(all, i2) {
11277 return all + i2[1];
11278 }, "");
11279 node2.raws[prop] = {
11280 raw: raw,
11281 value: value
11282 };
11283 }
11284 node2[prop] = value;
11285 };
11286 _proto.rule = function rule(tokens) {
11287 tokens.pop();
11288 var node2 = new Rule$2$1();
11289 this.init(node2, tokens[0][2]);
11290 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
11291 this.raw(node2, "selector", tokens);
11292 this.current = node2;
11293 };
11294 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
11295 var lastTokenType;
11296 var spaces = "";
11297 while(tokens.length){
11298 lastTokenType = tokens[tokens.length - 1][0];
11299 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
11300 spaces = tokens.pop()[1] + spaces;
11301 }
11302 return spaces;
11303 };
11304 // Errors
11305 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
11306 var next;
11307 var spaces = "";
11308 while(tokens.length){
11309 next = tokens[0][0];
11310 if (next !== "space" && next !== "comment") break;
11311 spaces += tokens.shift()[1];
11312 }
11313 return spaces;
11314 };
11315 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
11316 var lastTokenType;
11317 var spaces = "";
11318 while(tokens.length){
11319 lastTokenType = tokens[tokens.length - 1][0];
11320 if (lastTokenType !== "space") break;
11321 spaces = tokens.pop()[1] + spaces;
11322 }
11323 return spaces;
11324 };
11325 _proto.stringFrom = function stringFrom(tokens, from) {
11326 var result2 = "";
11327 for(var i2 = from; i2 < tokens.length; i2++){
11328 result2 += tokens[i2][1];
11329 }
11330 tokens.splice(from, tokens.length - from);
11331 return result2;
11332 };
11333 _proto.unclosedBlock = function unclosedBlock() {
11334 var pos = this.current.source.start;
11335 throw this.input.error("Unclosed block", pos.line, pos.column);
11336 };
11337 _proto.unclosedBracket = function unclosedBracket(bracket) {
11338 throw this.input.error("Unclosed bracket", {
11339 offset: bracket[2]
11340 }, {
11341 offset: bracket[2] + 1
11342 });
11343 };
11344 _proto.unexpectedClose = function unexpectedClose(token) {
11345 throw this.input.error("Unexpected }", {
11346 offset: token[2]
11347 }, {
11348 offset: token[2] + 1
11349 });
11350 };
11351 _proto.unknownWord = function unknownWord(tokens) {
11352 throw this.input.error("Unknown word", {
11353 offset: tokens[0][2]
11354 }, {
11355 offset: tokens[0][2] + tokens[0][1].length
11356 });
11357 };
11358 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
11359 throw this.input.error("At-rule without name", {
11360 offset: token[2]
11361 }, {
11362 offset: token[2] + token[1].length
11363 });
11364 };
11365 return Parser;
11366 }();
11367 var parser$1 = Parser$1$1;
11368 var Container$2$1 = container$1;
11369 var Parser2$1 = parser$1;
11370 var Input$2$1 = input$1;
11371 function parse$3$1(css, opts) {
11372 var input2 = new Input$2$1(css, opts);
11373 var parser2 = new Parser2$1(input2);
11374 try {
11375 parser2.parse();
11376 } catch (e2) {
11377 if (true) {
11378 if (e2.name === "CssSyntaxError" && opts && opts.from) {
11379 if (/\.scss$/i.test(opts.from)) {
11380 e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
11381 } else if (/\.sass/i.test(opts.from)) {
11382 e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
11383 } else if (/\.less$/i.test(opts.from)) {
11384 e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
11385 }
11386 }
11387 }
11388 throw e2;
11389 }
11390 return parser2.root;
11391 }
11392 var parse_1$1 = parse$3$1;
11393 parse$3$1.default = parse$3$1;
11394 Container$2$1.registerParse(parse$3$1);
11395 var isClean$3 = symbols$1.isClean, my$3 = symbols$1.my;
11396 var MapGenerator$1$1 = mapGenerator$1;
11397 var stringify$2$1 = stringify_1$1;
11398 var Container$1$1 = container$1;
11399 var Document$2$1 = document$1$1;
11400 var warnOnce$1$1 = warnOnce$2$1;
11401 var Result$2$1 = result$1;
11402 var parse$2$1 = parse_1$1;
11403 var Root$3$1 = root$1;
11404 var TYPE_TO_CLASS_NAME$1 = {
11405 atrule: "AtRule",
11406 comment: "Comment",
11407 decl: "Declaration",
11408 document: "Document",
11409 root: "Root",
11410 rule: "Rule"
11411 };
11412 var PLUGIN_PROPS$1 = {
11413 AtRule: true,
11414 AtRuleExit: true,
11415 Comment: true,
11416 CommentExit: true,
11417 Declaration: true,
11418 DeclarationExit: true,
11419 Document: true,
11420 DocumentExit: true,
11421 Once: true,
11422 OnceExit: true,
11423 postcssPlugin: true,
11424 prepare: true,
11425 Root: true,
11426 RootExit: true,
11427 Rule: true,
11428 RuleExit: true
11429 };
11430 var NOT_VISITORS$1 = {
11431 Once: true,
11432 postcssPlugin: true,
11433 prepare: true
11434 };
11435 var CHILDREN$1 = 0;
11436 function isPromise$1(obj) {
11437 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
11438 }
11439 function getEvents$1(node2) {
11440 var key = false;
11441 var type = TYPE_TO_CLASS_NAME$1[node2.type];
11442 if (node2.type === "decl") {
11443 key = node2.prop.toLowerCase();
11444 } else if (node2.type === "atrule") {
11445 key = node2.name.toLowerCase();
11446 }
11447 if (key && node2.append) {
11448 return [
11449 type,
11450 type + "-" + key,
11451 CHILDREN$1,
11452 type + "Exit",
11453 type + "Exit-" + key
11454 ];
11455 } else if (key) {
11456 return [
11457 type,
11458 type + "-" + key,
11459 type + "Exit",
11460 type + "Exit-" + key
11461 ];
11462 } else if (node2.append) {
11463 return [
11464 type,
11465 CHILDREN$1,
11466 type + "Exit"
11467 ];
11468 } else {
11469 return [
11470 type,
11471 type + "Exit"
11472 ];
11473 }
11474 }
11475 function toStack$1(node2) {
11476 var events;
11477 if (node2.type === "document") {
11478 events = [
11479 "Document",
11480 CHILDREN$1,
11481 "DocumentExit"
11482 ];
11483 } else if (node2.type === "root") {
11484 events = [
11485 "Root",
11486 CHILDREN$1,
11487 "RootExit"
11488 ];
11489 } else {
11490 events = getEvents$1(node2);
11491 }
11492 return {
11493 eventIndex: 0,
11494 events: events,
11495 iterator: 0,
11496 node: node2,
11497 visitorIndex: 0,
11498 visitors: []
11499 };
11500 }
11501 function cleanMarks$1(node2) {
11502 node2[isClean$3] = false;
11503 if (node2.nodes) node2.nodes.forEach(function(i2) {
11504 return cleanMarks$1(i2);
11505 });
11506 return node2;
11507 }
11508 var postcss$2$1 = {};
11509 var LazyResult$2$1 = /*#__PURE__*/ function() {
11510 function LazyResult(processor2, css, opts) {
11511 var _this = this;
11512 this.stringified = false;
11513 this.processed = false;
11514 var root2;
11515 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) {
11516 root2 = cleanMarks$1(css);
11517 } else if (_instanceof(css, LazyResult) || _instanceof(css, Result$2$1)) {
11518 root2 = cleanMarks$1(css.root);
11519 if (css.map) {
11520 if (typeof opts.map === "undefined") opts.map = {};
11521 if (!opts.map.inline) opts.map.inline = false;
11522 opts.map.prev = css.map;
11523 }
11524 } else {
11525 var parser2 = parse$2$1;
11526 if (opts.syntax) parser2 = opts.syntax.parse;
11527 if (opts.parser) parser2 = opts.parser;
11528 if (parser2.parse) parser2 = parser2.parse;
11529 try {
11530 root2 = parser2(css, opts);
11531 } catch (error) {
11532 this.processed = true;
11533 this.error = error;
11534 }
11535 if (root2 && !root2[my$3]) {
11536 Container$1$1.rebuild(root2);
11537 }
11538 }
11539 this.result = new Result$2$1(processor2, root2, opts);
11540 this.helpers = _extends({}, postcss$2$1, {
11541 postcss: postcss$2$1,
11542 result: this.result
11543 });
11544 this.plugins = this.processor.plugins.map(function(plugin22) {
11545 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) {
11546 return _extends({}, plugin22, plugin22.prepare(_this.result));
11547 } else {
11548 return plugin22;
11549 }
11550 });
11551 }
11552 var _proto = LazyResult.prototype;
11553 _proto.async = function async() {
11554 if (this.error) return Promise.reject(this.error);
11555 if (this.processed) return Promise.resolve(this.result);
11556 if (!this.processing) {
11557 this.processing = this.runAsync();
11558 }
11559 return this.processing;
11560 };
11561 _proto.catch = function _catch(onRejected) {
11562 return this.async().catch(onRejected);
11563 };
11564 _proto.finally = function _finally(onFinally) {
11565 return this.async().then(onFinally, onFinally);
11566 };
11567 _proto.getAsyncError = function getAsyncError() {
11568 throw new Error("Use process(css).then(cb) to work with async plugins");
11569 };
11570 _proto.handleError = function handleError(error, node2) {
11571 var plugin22 = this.result.lastPlugin;
11572 try {
11573 if (node2) node2.addToError(error);
11574 this.error = error;
11575 if (error.name === "CssSyntaxError" && !error.plugin) {
11576 error.plugin = plugin22.postcssPlugin;
11577 error.setMessage();
11578 } else if (plugin22.postcssVersion) {
11579 if (true) {
11580 var pluginName = plugin22.postcssPlugin;
11581 var pluginVer = plugin22.postcssVersion;
11582 var runtimeVer = this.result.processor.version;
11583 var a2 = pluginVer.split(".");
11584 var b = runtimeVer.split(".");
11585 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) {
11586 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.");
11587 }
11588 }
11589 }
11590 } catch (err) {
11591 if (console && console.error) console.error(err);
11592 }
11593 return error;
11594 };
11595 _proto.prepareVisitors = function prepareVisitors() {
11596 var _this = this;
11597 this.listeners = {};
11598 var add = function(plugin22, type, cb) {
11599 if (!_this.listeners[type]) _this.listeners[type] = [];
11600 _this.listeners[type].push([
11601 plugin22,
11602 cb
11603 ]);
11604 };
11605 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
11606 var plugin22 = _step.value;
11607 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") {
11608 for(var event in plugin22){
11609 if (!PLUGIN_PROPS$1[event] && /^[A-Z]/.test(event)) {
11610 throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
11611 }
11612 if (!NOT_VISITORS$1[event]) {
11613 if (_type_of(plugin22[event]) === "object") {
11614 for(var filter in plugin22[event]){
11615 if (filter === "*") {
11616 add(plugin22, event, plugin22[event][filter]);
11617 } else {
11618 add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
11619 }
11620 }
11621 } else if (typeof plugin22[event] === "function") {
11622 add(plugin22, event, plugin22[event]);
11623 }
11624 }
11625 }
11626 }
11627 }
11628 this.hasListener = Object.keys(this.listeners).length > 0;
11629 };
11630 _proto.runAsync = function runAsync() {
11631 var _this = this;
11632 return _async_to_generator(function() {
11633 var i2, plugin22, promise, error, root2, stack, promise1, e2, node2, _loop, _iterator, _step;
11634 return _ts_generator(this, function(_state) {
11635 switch(_state.label){
11636 case 0:
11637 _this.plugin = 0;
11638 i2 = 0;
11639 _state.label = 1;
11640 case 1:
11641 if (!(i2 < _this.plugins.length)) return [
11642 3,
11643 6
11644 ];
11645 plugin22 = _this.plugins[i2];
11646 promise = _this.runOnRoot(plugin22);
11647 if (!isPromise$1(promise)) return [
11648 3,
11649 5
11650 ];
11651 _state.label = 2;
11652 case 2:
11653 _state.trys.push([
11654 2,
11655 4,
11656 ,
11657 5
11658 ]);
11659 return [
11660 4,
11661 promise
11662 ];
11663 case 3:
11664 _state.sent();
11665 return [
11666 3,
11667 5
11668 ];
11669 case 4:
11670 error = _state.sent();
11671 throw _this.handleError(error);
11672 case 5:
11673 i2++;
11674 return [
11675 3,
11676 1
11677 ];
11678 case 6:
11679 _this.prepareVisitors();
11680 if (!_this.hasListener) return [
11681 3,
11682 18
11683 ];
11684 root2 = _this.result.root;
11685 _state.label = 7;
11686 case 7:
11687 if (!!root2[isClean$3]) return [
11688 3,
11689 14
11690 ];
11691 root2[isClean$3] = true;
11692 stack = [
11693 toStack$1(root2)
11694 ];
11695 _state.label = 8;
11696 case 8:
11697 if (!(stack.length > 0)) return [
11698 3,
11699 13
11700 ];
11701 promise1 = _this.visitTick(stack);
11702 if (!isPromise$1(promise1)) return [
11703 3,
11704 12
11705 ];
11706 _state.label = 9;
11707 case 9:
11708 _state.trys.push([
11709 9,
11710 11,
11711 ,
11712 12
11713 ]);
11714 return [
11715 4,
11716 promise1
11717 ];
11718 case 10:
11719 _state.sent();
11720 return [
11721 3,
11722 12
11723 ];
11724 case 11:
11725 e2 = _state.sent();
11726 node2 = stack[stack.length - 1].node;
11727 throw _this.handleError(e2, node2);
11728 case 12:
11729 return [
11730 3,
11731 8
11732 ];
11733 case 13:
11734 return [
11735 3,
11736 7
11737 ];
11738 case 14:
11739 if (!_this.listeners.OnceExit) return [
11740 3,
11741 18
11742 ];
11743 _loop = function() {
11744 var _step_value, plugin22, visitor, roots, e2;
11745 return _ts_generator(this, function(_state) {
11746 switch(_state.label){
11747 case 0:
11748 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
11749 _this.result.lastPlugin = plugin22;
11750 _state.label = 1;
11751 case 1:
11752 _state.trys.push([
11753 1,
11754 6,
11755 ,
11756 7
11757 ]);
11758 if (!(root2.type === "document")) return [
11759 3,
11760 3
11761 ];
11762 roots = root2.nodes.map(function(subRoot) {
11763 return visitor(subRoot, _this.helpers);
11764 });
11765 return [
11766 4,
11767 Promise.all(roots)
11768 ];
11769 case 2:
11770 _state.sent();
11771 return [
11772 3,
11773 5
11774 ];
11775 case 3:
11776 return [
11777 4,
11778 visitor(root2, _this.helpers)
11779 ];
11780 case 4:
11781 _state.sent();
11782 _state.label = 5;
11783 case 5:
11784 return [
11785 3,
11786 7
11787 ];
11788 case 6:
11789 e2 = _state.sent();
11790 throw _this.handleError(e2);
11791 case 7:
11792 return [
11793 2
11794 ];
11795 }
11796 });
11797 };
11798 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
11799 _state.label = 15;
11800 case 15:
11801 if (!!(_step = _iterator()).done) return [
11802 3,
11803 18
11804 ];
11805 return [
11806 5,
11807 _ts_values(_loop())
11808 ];
11809 case 16:
11810 _state.sent();
11811 _state.label = 17;
11812 case 17:
11813 return [
11814 3,
11815 15
11816 ];
11817 case 18:
11818 _this.processed = true;
11819 return [
11820 2,
11821 _this.stringify()
11822 ];
11823 }
11824 });
11825 })();
11826 };
11827 _proto.runOnRoot = function runOnRoot(plugin22) {
11828 var _this = this;
11829 this.result.lastPlugin = plugin22;
11830 try {
11831 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
11832 if (this.result.root.type === "document") {
11833 var roots = this.result.root.nodes.map(function(root2) {
11834 return plugin22.Once(root2, _this.helpers);
11835 });
11836 if (isPromise$1(roots[0])) {
11837 return Promise.all(roots);
11838 }
11839 return roots;
11840 }
11841 return plugin22.Once(this.result.root, this.helpers);
11842 } else if (typeof plugin22 === "function") {
11843 return plugin22(this.result.root, this.result);
11844 }
11845 } catch (error) {
11846 throw this.handleError(error);
11847 }
11848 };
11849 _proto.stringify = function stringify() {
11850 if (this.error) throw this.error;
11851 if (this.stringified) return this.result;
11852 this.stringified = true;
11853 this.sync();
11854 var opts = this.result.opts;
11855 var str = stringify$2$1;
11856 if (opts.syntax) str = opts.syntax.stringify;
11857 if (opts.stringifier) str = opts.stringifier;
11858 if (str.stringify) str = str.stringify;
11859 var map = new MapGenerator$1$1(str, this.result.root, this.result.opts);
11860 var data = map.generate();
11861 this.result.css = data[0];
11862 this.result.map = data[1];
11863 return this.result;
11864 };
11865 _proto.sync = function sync() {
11866 if (this.error) throw this.error;
11867 if (this.processed) return this.result;
11868 this.processed = true;
11869 if (this.processing) {
11870 throw this.getAsyncError();
11871 }
11872 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
11873 var plugin22 = _step.value;
11874 var promise = this.runOnRoot(plugin22);
11875 if (isPromise$1(promise)) {
11876 throw this.getAsyncError();
11877 }
11878 }
11879 this.prepareVisitors();
11880 if (this.hasListener) {
11881 var root2 = this.result.root;
11882 while(!root2[isClean$3]){
11883 root2[isClean$3] = true;
11884 this.walkSync(root2);
11885 }
11886 if (this.listeners.OnceExit) {
11887 if (root2.type === "document") {
11888 for(var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;){
11889 var subRoot = _step1.value;
11890 this.visitSync(this.listeners.OnceExit, subRoot);
11891 }
11892 } else {
11893 this.visitSync(this.listeners.OnceExit, root2);
11894 }
11895 }
11896 }
11897 return this.result;
11898 };
11899 _proto.then = function then(onFulfilled, onRejected) {
11900 if (true) {
11901 if (!("from" in this.opts)) {
11902 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.");
11903 }
11904 }
11905 return this.async().then(onFulfilled, onRejected);
11906 };
11907 _proto.toString = function toString() {
11908 return this.css;
11909 };
11910 _proto.visitSync = function visitSync(visitors, node2) {
11911 for(var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;){
11912 var _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
11913 this.result.lastPlugin = plugin22;
11914 var promise = void 0;
11915 try {
11916 promise = visitor(node2, this.helpers);
11917 } catch (e2) {
11918 throw this.handleError(e2, node2.proxyOf);
11919 }
11920 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
11921 return true;
11922 }
11923 if (isPromise$1(promise)) {
11924 throw this.getAsyncError();
11925 }
11926 }
11927 };
11928 _proto.visitTick = function visitTick(stack) {
11929 var visit2 = stack[stack.length - 1];
11930 var node2 = visit2.node, visitors = visit2.visitors;
11931 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
11932 stack.pop();
11933 return;
11934 }
11935 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
11936 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex], plugin22 = _visitors_visit2_visitorIndex[0], visitor = _visitors_visit2_visitorIndex[1];
11937 visit2.visitorIndex += 1;
11938 if (visit2.visitorIndex === visitors.length) {
11939 visit2.visitors = [];
11940 visit2.visitorIndex = 0;
11941 }
11942 this.result.lastPlugin = plugin22;
11943 try {
11944 return visitor(node2.toProxy(), this.helpers);
11945 } catch (e2) {
11946 throw this.handleError(e2, node2);
11947 }
11948 }
11949 if (visit2.iterator !== 0) {
11950 var iterator = visit2.iterator;
11951 var child;
11952 while(child = node2.nodes[node2.indexes[iterator]]){
11953 node2.indexes[iterator] += 1;
11954 if (!child[isClean$3]) {
11955 child[isClean$3] = true;
11956 stack.push(toStack$1(child));
11957 return;
11958 }
11959 }
11960 visit2.iterator = 0;
11961 delete node2.indexes[iterator];
11962 }
11963 var events = visit2.events;
11964 while(visit2.eventIndex < events.length){
11965 var event = events[visit2.eventIndex];
11966 visit2.eventIndex += 1;
11967 if (event === CHILDREN$1) {
11968 if (node2.nodes && node2.nodes.length) {
11969 node2[isClean$3] = true;
11970 visit2.iterator = node2.getIterator();
11971 }
11972 return;
11973 } else if (this.listeners[event]) {
11974 visit2.visitors = this.listeners[event];
11975 return;
11976 }
11977 }
11978 stack.pop();
11979 };
11980 _proto.walkSync = function walkSync(node2) {
11981 var _this = this;
11982 node2[isClean$3] = true;
11983 var events = getEvents$1(node2);
11984 for(var _iterator = _create_for_of_iterator_helper_loose(events), _step; !(_step = _iterator()).done;){
11985 var event = _step.value;
11986 if (event === CHILDREN$1) {
11987 if (node2.nodes) {
11988 node2.each(function(child) {
11989 if (!child[isClean$3]) _this.walkSync(child);
11990 });
11991 }
11992 } else {
11993 var visitors = this.listeners[event];
11994 if (visitors) {
11995 if (this.visitSync(visitors, node2.toProxy())) return;
11996 }
11997 }
11998 }
11999 };
12000 _proto.warnings = function warnings() {
12001 return this.sync().warnings();
12002 };
12003 _create_class(LazyResult, [
12004 {
12005 key: "content",
12006 get: function get() {
12007 return this.stringify().content;
12008 }
12009 },
12010 {
12011 key: "css",
12012 get: function get() {
12013 return this.stringify().css;
12014 }
12015 },
12016 {
12017 key: "map",
12018 get: function get() {
12019 return this.stringify().map;
12020 }
12021 },
12022 {
12023 key: "messages",
12024 get: function get() {
12025 return this.sync().messages;
12026 }
12027 },
12028 {
12029 key: "opts",
12030 get: function get() {
12031 return this.result.opts;
12032 }
12033 },
12034 {
12035 key: "processor",
12036 get: function get() {
12037 return this.result.processor;
12038 }
12039 },
12040 {
12041 key: "root",
12042 get: function get() {
12043 return this.sync().root;
12044 }
12045 },
12046 {
12047 key: Symbol.toStringTag,
12048 get: function get() {
12049 return "LazyResult";
12050 }
12051 }
12052 ]);
12053 return LazyResult;
12054 }();
12055 LazyResult$2$1.registerPostcss = function(dependant) {
12056 postcss$2$1 = dependant;
12057 };
12058 var lazyResult$1 = LazyResult$2$1;
12059 LazyResult$2$1.default = LazyResult$2$1;
12060 Root$3$1.registerLazyResult(LazyResult$2$1);
12061 Document$2$1.registerLazyResult(LazyResult$2$1);
12062 var MapGenerator2$1 = mapGenerator$1;
12063 var stringify$1$1 = stringify_1$1;
12064 var warnOnce2$1 = warnOnce$2$1;
12065 var parse$1$1 = parse_1$1;
12066 var Result$1$1 = result$1;
12067 var NoWorkResult$1$1 = /*#__PURE__*/ function() {
12068 function NoWorkResult(processor2, css, opts) {
12069 css = css.toString();
12070 this.stringified = false;
12071 this._processor = processor2;
12072 this._css = css;
12073 this._opts = opts;
12074 this._map = void 0;
12075 var root2;
12076 var str = stringify$1$1;
12077 this.result = new Result$1$1(this._processor, root2, this._opts);
12078 this.result.css = css;
12079 var self = this;
12080 Object.defineProperty(this.result, "root", {
12081 get: function get() {
12082 return self.root;
12083 }
12084 });
12085 var map = new MapGenerator2$1(str, root2, this._opts, css);
12086 if (map.isMap()) {
12087 var _map_generate = map.generate(), generatedCSS = _map_generate[0], generatedMap = _map_generate[1];
12088 if (generatedCSS) {
12089 this.result.css = generatedCSS;
12090 }
12091 if (generatedMap) {
12092 this.result.map = generatedMap;
12093 }
12094 } else {
12095 map.clearAnnotation();
12096 this.result.css = map.css;
12097 }
12098 }
12099 var _proto = NoWorkResult.prototype;
12100 _proto.async = function async() {
12101 if (this.error) return Promise.reject(this.error);
12102 return Promise.resolve(this.result);
12103 };
12104 _proto.catch = function _catch(onRejected) {
12105 return this.async().catch(onRejected);
12106 };
12107 _proto.finally = function _finally(onFinally) {
12108 return this.async().then(onFinally, onFinally);
12109 };
12110 _proto.sync = function sync() {
12111 if (this.error) throw this.error;
12112 return this.result;
12113 };
12114 _proto.then = function then(onFulfilled, onRejected) {
12115 if (true) {
12116 if (!("from" in this._opts)) {
12117 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.");
12118 }
12119 }
12120 return this.async().then(onFulfilled, onRejected);
12121 };
12122 _proto.toString = function toString() {
12123 return this._css;
12124 };
12125 _proto.warnings = function warnings() {
12126 return [];
12127 };
12128 _create_class(NoWorkResult, [
12129 {
12130 key: "content",
12131 get: function get() {
12132 return this.result.css;
12133 }
12134 },
12135 {
12136 key: "css",
12137 get: function get() {
12138 return this.result.css;
12139 }
12140 },
12141 {
12142 key: "map",
12143 get: function get() {
12144 return this.result.map;
12145 }
12146 },
12147 {
12148 key: "messages",
12149 get: function get() {
12150 return [];
12151 }
12152 },
12153 {
12154 key: "opts",
12155 get: function get() {
12156 return this.result.opts;
12157 }
12158 },
12159 {
12160 key: "processor",
12161 get: function get() {
12162 return this.result.processor;
12163 }
12164 },
12165 {
12166 key: "root",
12167 get: function get() {
12168 if (this._root) {
12169 return this._root;
12170 }
12171 var root2;
12172 var parser2 = parse$1$1;
12173 try {
12174 root2 = parser2(this._css, this._opts);
12175 } catch (error) {
12176 this.error = error;
12177 }
12178 if (this.error) {
12179 throw this.error;
12180 } else {
12181 this._root = root2;
12182 return root2;
12183 }
12184 }
12185 },
12186 {
12187 key: Symbol.toStringTag,
12188 get: function get() {
12189 return "NoWorkResult";
12190 }
12191 }
12192 ]);
12193 return NoWorkResult;
12194 }();
12195 var noWorkResult$1 = NoWorkResult$1$1;
12196 NoWorkResult$1$1.default = NoWorkResult$1$1;
12197 var NoWorkResult2$1 = noWorkResult$1;
12198 var LazyResult$1$1 = lazyResult$1;
12199 var Document$1$1 = document$1$1;
12200 var Root$2$1 = root$1;
12201 var Processor$1$1 = /*#__PURE__*/ function() {
12202 function Processor(plugins) {
12203 if (plugins === void 0) plugins = [];
12204 this.version = "8.4.38";
12205 this.plugins = this.normalize(plugins);
12206 }
12207 var _proto = Processor.prototype;
12208 _proto.normalize = function normalize(plugins) {
12209 var normalized = [];
12210 for(var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;){
12211 var i2 = _step.value;
12212 if (i2.postcss === true) {
12213 i2 = i2();
12214 } else if (i2.postcss) {
12215 i2 = i2.postcss;
12216 }
12217 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) {
12218 normalized = normalized.concat(i2.plugins);
12219 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) {
12220 normalized.push(i2);
12221 } else if (typeof i2 === "function") {
12222 normalized.push(i2);
12223 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) {
12224 if (true) {
12225 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.");
12226 }
12227 } else {
12228 throw new Error(i2 + " is not a PostCSS plugin");
12229 }
12230 }
12231 return normalized;
12232 };
12233 _proto.process = function process1(css, opts) {
12234 if (opts === void 0) opts = {};
12235 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
12236 return new NoWorkResult2$1(this, css, opts);
12237 } else {
12238 return new LazyResult$1$1(this, css, opts);
12239 }
12240 };
12241 _proto.use = function use(plugin22) {
12242 this.plugins = this.plugins.concat(this.normalize([
12243 plugin22
12244 ]));
12245 return this;
12246 };
12247 return Processor;
12248 }();
12249 var processor$1 = Processor$1$1;
12250 Processor$1$1.default = Processor$1$1;
12251 Root$2$1.registerProcessor(Processor$1$1);
12252 Document$1$1.registerProcessor(Processor$1$1);
12253 var Declaration$1$1 = declaration$1;
12254 var PreviousMap2$1 = previousMap$1;
12255 var Comment$1$1 = comment$1;
12256 var AtRule$1$1 = atRule$1;
12257 var Input$1$1 = input$1;
12258 var Root$1$1 = root$1;
12259 var Rule$1$1 = rule$1;
12260 function fromJSON$1$1(json, inputs) {
12261 if (Array.isArray(json)) return json.map(function(n2) {
12262 return fromJSON$1$1(n2);
12263 });
12264 var ownInputs = json.inputs, defaults = _object_without_properties_loose(json, [
12265 "inputs"
12266 ]);
12267 if (ownInputs) {
12268 inputs = [];
12269 for(var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;){
12270 var input2 = _step.value;
12271 var inputHydrated = _extends({}, input2, {
12272 __proto__: Input$1$1.prototype
12273 });
12274 if (inputHydrated.map) {
12275 inputHydrated.map = _extends({}, inputHydrated.map, {
12276 __proto__: PreviousMap2$1.prototype
12277 });
12278 }
12279 inputs.push(inputHydrated);
12280 }
12281 }
12282 if (defaults.nodes) {
12283 defaults.nodes = json.nodes.map(function(n2) {
12284 return fromJSON$1$1(n2, inputs);
12285 });
12286 }
12287 if (defaults.source) {
12288 var _defaults_source = defaults.source, inputId = _defaults_source.inputId, source = _object_without_properties_loose(_defaults_source, [
12289 "inputId"
12290 ]);
12291 defaults.source = source;
12292 if (inputId != null) {
12293 defaults.source.input = inputs[inputId];
12294 }
12295 }
12296 if (defaults.type === "root") {
12297 return new Root$1$1(defaults);
12298 } else if (defaults.type === "decl") {
12299 return new Declaration$1$1(defaults);
12300 } else if (defaults.type === "rule") {
12301 return new Rule$1$1(defaults);
12302 } else if (defaults.type === "comment") {
12303 return new Comment$1$1(defaults);
12304 } else if (defaults.type === "atrule") {
12305 return new AtRule$1$1(defaults);
12306 } else {
12307 throw new Error("Unknown node type: " + json.type);
12308 }
12309 }
12310 var fromJSON_1$1 = fromJSON$1$1;
12311 fromJSON$1$1.default = fromJSON$1$1;
12312 var CssSyntaxError2$1 = cssSyntaxError$1;
12313 var Declaration2$1 = declaration$1;
12314 var LazyResult2$1 = lazyResult$1;
12315 var Container2$1 = container$1;
12316 var Processor2$1 = processor$1;
12317 var stringify$5 = stringify_1$1;
12318 var fromJSON$2 = fromJSON_1$1;
12319 var Document22 = document$1$1;
12320 var Warning2$1 = warning$1;
12321 var Comment2$1 = comment$1;
12322 var AtRule2$1 = atRule$1;
12323 var Result2$1 = result$1;
12324 var Input2$1 = input$1;
12325 var parse$5 = parse_1$1;
12326 var list$3 = list_1$1;
12327 var Rule2$1 = rule$1;
12328 var Root2$1 = root$1;
12329 var Node2$1 = node$1;
12330 function postcss$3() {
12331 for(var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++){
12332 plugins[_key] = arguments[_key];
12333 }
12334 if (plugins.length === 1 && Array.isArray(plugins[0])) {
12335 plugins = plugins[0];
12336 }
12337 return new Processor2$1(plugins);
12338 }
12339 postcss$3.plugin = function plugin(name, initializer) {
12340 var warningPrinted = false;
12341 function creator() {
12342 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
12343 args[_key] = arguments[_key];
12344 }
12345 if (console && console.warn && !warningPrinted) {
12346 warningPrinted = true;
12347 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
12348 if (process.env.LANG && process.env.LANG.startsWith("cn")) {
12349 console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
12350 }
12351 }
12352 var transformer = initializer.apply(void 0, [].concat(args));
12353 transformer.postcssPlugin = name;
12354 transformer.postcssVersion = new Processor2$1().version;
12355 return transformer;
12356 }
12357 var cache;
12358 Object.defineProperty(creator, "postcss", {
12359 get: function get() {
12360 if (!cache) cache = creator();
12361 return cache;
12362 }
12363 });
12364 creator.process = function(css, processOpts, pluginOpts) {
12365 return postcss$3([
12366 creator(pluginOpts)
12367 ]).process(css, processOpts);
12368 };
12369 return creator;
12370 };
12371 postcss$3.stringify = stringify$5;
12372 postcss$3.parse = parse$5;
12373 postcss$3.fromJSON = fromJSON$2;
12374 postcss$3.list = list$3;
12375 postcss$3.comment = function(defaults) {
12376 return new Comment2$1(defaults);
12377 };
12378 postcss$3.atRule = function(defaults) {
12379 return new AtRule2$1(defaults);
12380 };
12381 postcss$3.decl = function(defaults) {
12382 return new Declaration2$1(defaults);
12383 };
12384 postcss$3.rule = function(defaults) {
12385 return new Rule2$1(defaults);
12386 };
12387 postcss$3.root = function(defaults) {
12388 return new Root2$1(defaults);
12389 };
12390 postcss$3.document = function(defaults) {
12391 return new Document22(defaults);
12392 };
12393 postcss$3.CssSyntaxError = CssSyntaxError2$1;
12394 postcss$3.Declaration = Declaration2$1;
12395 postcss$3.Container = Container2$1;
12396 postcss$3.Processor = Processor2$1;
12397 postcss$3.Document = Document22;
12398 postcss$3.Comment = Comment2$1;
12399 postcss$3.Warning = Warning2$1;
12400 postcss$3.AtRule = AtRule2$1;
12401 postcss$3.Result = Result2$1;
12402 postcss$3.Input = Input2$1;
12403 postcss$3.Rule = Rule2$1;
12404 postcss$3.Root = Root2$1;
12405 postcss$3.Node = Node2$1;
12406 LazyResult2$1.registerPostcss(postcss$3);
12407 var postcss_1$1 = postcss$3;
12408 postcss$3.default = postcss$3;
12409 var postcss$1$1 = /* @__PURE__ */ getDefaultExportFromCjs$1(postcss_1$1);
12410 postcss$1$1.stringify;
12411 postcss$1$1.fromJSON;
12412 postcss$1$1.plugin;
12413 postcss$1$1.parse;
12414 postcss$1$1.list;
12415 postcss$1$1.document;
12416 postcss$1$1.comment;
12417 postcss$1$1.atRule;
12418 postcss$1$1.rule;
12419 postcss$1$1.decl;
12420 postcss$1$1.root;
12421 postcss$1$1.CssSyntaxError;
12422 postcss$1$1.Declaration;
12423 postcss$1$1.Container;
12424 postcss$1$1.Processor;
12425 postcss$1$1.Document;
12426 postcss$1$1.Comment;
12427 postcss$1$1.Warning;
12428 postcss$1$1.AtRule;
12429 postcss$1$1.Result;
12430 postcss$1$1.Input;
12431 postcss$1$1.Rule;
12432 postcss$1$1.Root;
12433 postcss$1$1.Node;
12434 var __defProp2 = Object.defineProperty;
12435 var __defNormalProp2 = function(obj, key, value) {
12436 return key in obj ? __defProp2(obj, key, {
12437 enumerable: true,
12438 configurable: true,
12439 writable: true,
12440 value: value
12441 }) : obj[key] = value;
12442 };
12443 var __publicField2 = function(obj, key, value) {
12444 return __defNormalProp2(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
12445 };
12446 function getDefaultExportFromCjs(x2) {
12447 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
12448 }
12449 function getAugmentedNamespace(n2) {
12450 if (n2.__esModule) return n2;
12451 var f2 = n2.default;
12452 if (typeof f2 == "function") {
12453 var a2 = function a22() {
12454 if (_instanceof(this, a22)) {
12455 return Reflect.construct(f2, arguments, this.constructor);
12456 }
12457 return f2.apply(this, arguments);
12458 };
12459 a2.prototype = f2.prototype;
12460 } else a2 = {};
12461 Object.defineProperty(a2, "__esModule", {
12462 value: true
12463 });
12464 Object.keys(n2).forEach(function(k) {
12465 var d = Object.getOwnPropertyDescriptor(n2, k);
12466 Object.defineProperty(a2, k, d.get ? d : {
12467 enumerable: true,
12468 get: function get() {
12469 return n2[k];
12470 }
12471 });
12472 });
12473 return a2;
12474 }
12475 var picocolors_browser = {
12476 exports: {}
12477 };
12478 var x = String;
12479 var create = function create() {
12480 return {
12481 isColorSupported: false,
12482 reset: x,
12483 bold: x,
12484 dim: x,
12485 italic: x,
12486 underline: x,
12487 inverse: x,
12488 hidden: x,
12489 strikethrough: x,
12490 black: x,
12491 red: x,
12492 green: x,
12493 yellow: x,
12494 blue: x,
12495 magenta: x,
12496 cyan: x,
12497 white: x,
12498 gray: x,
12499 bgBlack: x,
12500 bgRed: x,
12501 bgGreen: x,
12502 bgYellow: x,
12503 bgBlue: x,
12504 bgMagenta: x,
12505 bgCyan: x,
12506 bgWhite: x
12507 };
12508 };
12509 picocolors_browser.exports = create();
12510 picocolors_browser.exports.createColors = create;
12511 var picocolors_browserExports = picocolors_browser.exports;
12512 var __viteBrowserExternal = {};
12513 var __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
12514 __proto__: null,
12515 default: __viteBrowserExternal
12516 }, Symbol.toStringTag, {
12517 value: "Module"
12518 }));
12519 var require$$2 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
12520 var pico = picocolors_browserExports;
12521 var terminalHighlight$1 = require$$2;
12522 var CssSyntaxError$3 = /*#__PURE__*/ function(Error1) {
12523 _inherits(CssSyntaxError2, Error1);
12524 function CssSyntaxError2(message, line, column, source, file, plugin22) {
12525 var _this;
12526 _this = Error1.call(this, message) || this;
12527 _this.name = "CssSyntaxError";
12528 _this.reason = message;
12529 if (file) {
12530 _this.file = file;
12531 }
12532 if (source) {
12533 _this.source = source;
12534 }
12535 if (plugin22) {
12536 _this.plugin = plugin22;
12537 }
12538 if (typeof line !== "undefined" && typeof column !== "undefined") {
12539 if (typeof line === "number") {
12540 _this.line = line;
12541 _this.column = column;
12542 } else {
12543 _this.line = line.line;
12544 _this.column = line.column;
12545 _this.endLine = column.line;
12546 _this.endColumn = column.column;
12547 }
12548 }
12549 _this.setMessage();
12550 if (Error.captureStackTrace) {
12551 Error.captureStackTrace(_this, CssSyntaxError2);
12552 }
12553 return _this;
12554 }
12555 var _proto = CssSyntaxError2.prototype;
12556 _proto.setMessage = function setMessage() {
12557 this.message = this.plugin ? this.plugin + ": " : "";
12558 this.message += this.file ? this.file : "<css input>";
12559 if (typeof this.line !== "undefined") {
12560 this.message += ":" + this.line + ":" + this.column;
12561 }
12562 this.message += ": " + this.reason;
12563 };
12564 _proto.showSourceCode = function showSourceCode(color) {
12565 var _this = this;
12566 if (!this.source) return "";
12567 var css = this.source;
12568 if (color == null) color = pico.isColorSupported;
12569 if (terminalHighlight$1) {
12570 if (color) css = terminalHighlight$1(css);
12571 }
12572 var lines = css.split(/\r?\n/);
12573 var start = Math.max(this.line - 3, 0);
12574 var end = Math.min(this.line + 2, lines.length);
12575 var maxWidth = String(end).length;
12576 var mark, aside;
12577 if (color) {
12578 var _pico_createColors = pico.createColors(true), bold = _pico_createColors.bold, gray = _pico_createColors.gray, red = _pico_createColors.red;
12579 mark = function(text) {
12580 return bold(red(text));
12581 };
12582 aside = function(text) {
12583 return gray(text);
12584 };
12585 } else {
12586 mark = aside = function(str) {
12587 return str;
12588 };
12589 }
12590 return lines.slice(start, end).map(function(line, index2) {
12591 var number = start + 1 + index2;
12592 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
12593 if (number === _this.line) {
12594 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
12595 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
12596 }
12597 return " " + aside(gutter) + line;
12598 }).join("\n");
12599 };
12600 _proto.toString = function toString() {
12601 var code = this.showSourceCode();
12602 if (code) {
12603 code = "\n\n" + code + "\n";
12604 }
12605 return this.name + ": " + this.message + code;
12606 };
12607 return CssSyntaxError2;
12608 }(_wrap_native_super(Error));
12609 var cssSyntaxError = CssSyntaxError$3;
12610 CssSyntaxError$3.default = CssSyntaxError$3;
12611 var symbols = {};
12612 symbols.isClean = Symbol("isClean");
12613 symbols.my = Symbol("my");
12614 var DEFAULT_RAW = {
12615 after: "\n",
12616 beforeClose: "\n",
12617 beforeComment: "\n",
12618 beforeDecl: "\n",
12619 beforeOpen: " ",
12620 beforeRule: "\n",
12621 colon: ": ",
12622 commentLeft: " ",
12623 commentRight: " ",
12624 emptyBody: "",
12625 indent: " ",
12626 semicolon: false
12627 };
12628 function capitalize(str) {
12629 return str[0].toUpperCase() + str.slice(1);
12630 }
12631 var Stringifier$2 = /*#__PURE__*/ function() {
12632 function Stringifier2(builder) {
12633 this.builder = builder;
12634 }
12635 var _proto = Stringifier2.prototype;
12636 _proto.atrule = function atrule(node2, semicolon) {
12637 var name = "@" + node2.name;
12638 var params = node2.params ? this.rawValue(node2, "params") : "";
12639 if (typeof node2.raws.afterName !== "undefined") {
12640 name += node2.raws.afterName;
12641 } else if (params) {
12642 name += " ";
12643 }
12644 if (node2.nodes) {
12645 this.block(node2, name + params);
12646 } else {
12647 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
12648 this.builder(name + params + end, node2);
12649 }
12650 };
12651 _proto.beforeAfter = function beforeAfter(node2, detect) {
12652 var value;
12653 if (node2.type === "decl") {
12654 value = this.raw(node2, null, "beforeDecl");
12655 } else if (node2.type === "comment") {
12656 value = this.raw(node2, null, "beforeComment");
12657 } else if (detect === "before") {
12658 value = this.raw(node2, null, "beforeRule");
12659 } else {
12660 value = this.raw(node2, null, "beforeClose");
12661 }
12662 var buf = node2.parent;
12663 var depth = 0;
12664 while(buf && buf.type !== "root"){
12665 depth += 1;
12666 buf = buf.parent;
12667 }
12668 if (value.includes("\n")) {
12669 var indent = this.raw(node2, null, "indent");
12670 if (indent.length) {
12671 for(var step = 0; step < depth; step++)value += indent;
12672 }
12673 }
12674 return value;
12675 };
12676 _proto.block = function block(node2, start) {
12677 var between = this.raw(node2, "between", "beforeOpen");
12678 this.builder(start + between + "{", node2, "start");
12679 var after;
12680 if (node2.nodes && node2.nodes.length) {
12681 this.body(node2);
12682 after = this.raw(node2, "after");
12683 } else {
12684 after = this.raw(node2, "after", "emptyBody");
12685 }
12686 if (after) this.builder(after);
12687 this.builder("}", node2, "end");
12688 };
12689 _proto.body = function body(node2) {
12690 var last = node2.nodes.length - 1;
12691 while(last > 0){
12692 if (node2.nodes[last].type !== "comment") break;
12693 last -= 1;
12694 }
12695 var semicolon = this.raw(node2, "semicolon");
12696 for(var i2 = 0; i2 < node2.nodes.length; i2++){
12697 var child = node2.nodes[i2];
12698 var before = this.raw(child, "before");
12699 if (before) this.builder(before);
12700 this.stringify(child, last !== i2 || semicolon);
12701 }
12702 };
12703 _proto.comment = function comment(node2) {
12704 var left = this.raw(node2, "left", "commentLeft");
12705 var right = this.raw(node2, "right", "commentRight");
12706 this.builder("/*" + left + node2.text + right + "*/", node2);
12707 };
12708 _proto.decl = function decl(node2, semicolon) {
12709 var between = this.raw(node2, "between", "colon");
12710 var string = node2.prop + between + this.rawValue(node2, "value");
12711 if (node2.important) {
12712 string += node2.raws.important || " !important";
12713 }
12714 if (semicolon) string += ";";
12715 this.builder(string, node2);
12716 };
12717 _proto.document = function document1(node2) {
12718 this.body(node2);
12719 };
12720 _proto.raw = function raw(node2, own, detect) {
12721 var value;
12722 if (!detect) detect = own;
12723 if (own) {
12724 value = node2.raws[own];
12725 if (typeof value !== "undefined") return value;
12726 }
12727 var parent = node2.parent;
12728 if (detect === "before") {
12729 if (!parent || parent.type === "root" && parent.first === node2) {
12730 return "";
12731 }
12732 if (parent && parent.type === "document") {
12733 return "";
12734 }
12735 }
12736 if (!parent) return DEFAULT_RAW[detect];
12737 var root2 = node2.root();
12738 if (!root2.rawCache) root2.rawCache = {};
12739 if (typeof root2.rawCache[detect] !== "undefined") {
12740 return root2.rawCache[detect];
12741 }
12742 if (detect === "before" || detect === "after") {
12743 return this.beforeAfter(node2, detect);
12744 } else {
12745 var method = "raw" + capitalize(detect);
12746 if (this[method]) {
12747 value = this[method](root2, node2);
12748 } else {
12749 root2.walk(function(i2) {
12750 value = i2.raws[own];
12751 if (typeof value !== "undefined") return false;
12752 });
12753 }
12754 }
12755 if (typeof value === "undefined") value = DEFAULT_RAW[detect];
12756 root2.rawCache[detect] = value;
12757 return value;
12758 };
12759 _proto.rawBeforeClose = function rawBeforeClose(root2) {
12760 var value;
12761 root2.walk(function(i2) {
12762 if (i2.nodes && i2.nodes.length > 0) {
12763 if (typeof i2.raws.after !== "undefined") {
12764 value = i2.raws.after;
12765 if (value.includes("\n")) {
12766 value = value.replace(/[^\n]+$/, "");
12767 }
12768 return false;
12769 }
12770 }
12771 });
12772 if (value) value = value.replace(/\S/g, "");
12773 return value;
12774 };
12775 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
12776 var value;
12777 root2.walkComments(function(i2) {
12778 if (typeof i2.raws.before !== "undefined") {
12779 value = i2.raws.before;
12780 if (value.includes("\n")) {
12781 value = value.replace(/[^\n]+$/, "");
12782 }
12783 return false;
12784 }
12785 });
12786 if (typeof value === "undefined") {
12787 value = this.raw(node2, null, "beforeDecl");
12788 } else if (value) {
12789 value = value.replace(/\S/g, "");
12790 }
12791 return value;
12792 };
12793 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
12794 var value;
12795 root2.walkDecls(function(i2) {
12796 if (typeof i2.raws.before !== "undefined") {
12797 value = i2.raws.before;
12798 if (value.includes("\n")) {
12799 value = value.replace(/[^\n]+$/, "");
12800 }
12801 return false;
12802 }
12803 });
12804 if (typeof value === "undefined") {
12805 value = this.raw(node2, null, "beforeRule");
12806 } else if (value) {
12807 value = value.replace(/\S/g, "");
12808 }
12809 return value;
12810 };
12811 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
12812 var value;
12813 root2.walk(function(i2) {
12814 if (i2.type !== "decl") {
12815 value = i2.raws.between;
12816 if (typeof value !== "undefined") return false;
12817 }
12818 });
12819 return value;
12820 };
12821 _proto.rawBeforeRule = function rawBeforeRule(root2) {
12822 var value;
12823 root2.walk(function(i2) {
12824 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
12825 if (typeof i2.raws.before !== "undefined") {
12826 value = i2.raws.before;
12827 if (value.includes("\n")) {
12828 value = value.replace(/[^\n]+$/, "");
12829 }
12830 return false;
12831 }
12832 }
12833 });
12834 if (value) value = value.replace(/\S/g, "");
12835 return value;
12836 };
12837 _proto.rawColon = function rawColon(root2) {
12838 var value;
12839 root2.walkDecls(function(i2) {
12840 if (typeof i2.raws.between !== "undefined") {
12841 value = i2.raws.between.replace(/[^\s:]/g, "");
12842 return false;
12843 }
12844 });
12845 return value;
12846 };
12847 _proto.rawEmptyBody = function rawEmptyBody(root2) {
12848 var value;
12849 root2.walk(function(i2) {
12850 if (i2.nodes && i2.nodes.length === 0) {
12851 value = i2.raws.after;
12852 if (typeof value !== "undefined") return false;
12853 }
12854 });
12855 return value;
12856 };
12857 _proto.rawIndent = function rawIndent(root2) {
12858 if (root2.raws.indent) return root2.raws.indent;
12859 var value;
12860 root2.walk(function(i2) {
12861 var p = i2.parent;
12862 if (p && p !== root2 && p.parent && p.parent === root2) {
12863 if (typeof i2.raws.before !== "undefined") {
12864 var parts = i2.raws.before.split("\n");
12865 value = parts[parts.length - 1];
12866 value = value.replace(/\S/g, "");
12867 return false;
12868 }
12869 }
12870 });
12871 return value;
12872 };
12873 _proto.rawSemicolon = function rawSemicolon(root2) {
12874 var value;
12875 root2.walk(function(i2) {
12876 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
12877 value = i2.raws.semicolon;
12878 if (typeof value !== "undefined") return false;
12879 }
12880 });
12881 return value;
12882 };
12883 _proto.rawValue = function rawValue(node2, prop) {
12884 var value = node2[prop];
12885 var raw = node2.raws[prop];
12886 if (raw && raw.value === value) {
12887 return raw.raw;
12888 }
12889 return value;
12890 };
12891 _proto.root = function root(node2) {
12892 this.body(node2);
12893 if (node2.raws.after) this.builder(node2.raws.after);
12894 };
12895 _proto.rule = function rule(node2) {
12896 this.block(node2, this.rawValue(node2, "selector"));
12897 if (node2.raws.ownSemicolon) {
12898 this.builder(node2.raws.ownSemicolon, node2, "end");
12899 }
12900 };
12901 _proto.stringify = function stringify(node2, semicolon) {
12902 if (!this[node2.type]) {
12903 throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
12904 }
12905 this[node2.type](node2, semicolon);
12906 };
12907 return Stringifier2;
12908 }();
12909 var stringifier = Stringifier$2;
12910 Stringifier$2.default = Stringifier$2;
12911 var Stringifier$1 = stringifier;
12912 function stringify$4(node2, builder) {
12913 var str = new Stringifier$1(builder);
12914 str.stringify(node2);
12915 }
12916 var stringify_1 = stringify$4;
12917 stringify$4.default = stringify$4;
12918 var isClean$2 = symbols.isClean, my$2 = symbols.my;
12919 var CssSyntaxError$2 = cssSyntaxError;
12920 var Stringifier22 = stringifier;
12921 var stringify$3 = stringify_1;
12922 function cloneNode(obj, parent) {
12923 var cloned = new obj.constructor();
12924 for(var i2 in obj){
12925 if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
12926 continue;
12927 }
12928 if (i2 === "proxyCache") continue;
12929 var value = obj[i2];
12930 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
12931 if (i2 === "parent" && type === "object") {
12932 if (parent) cloned[i2] = parent;
12933 } else if (i2 === "source") {
12934 cloned[i2] = value;
12935 } else if (Array.isArray(value)) {
12936 cloned[i2] = value.map(function(j) {
12937 return cloneNode(j, cloned);
12938 });
12939 } else {
12940 if (type === "object" && value !== null) value = cloneNode(value);
12941 cloned[i2] = value;
12942 }
12943 }
12944 return cloned;
12945 }
12946 var Node$4 = /*#__PURE__*/ function() {
12947 function Node3(defaults) {
12948 if (defaults === void 0) defaults = {};
12949 this.raws = {};
12950 this[isClean$2] = false;
12951 this[my$2] = true;
12952 for(var name in defaults){
12953 if (name === "nodes") {
12954 this.nodes = [];
12955 for(var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;){
12956 var node2 = _step.value;
12957 if (typeof node2.clone === "function") {
12958 this.append(node2.clone());
12959 } else {
12960 this.append(node2);
12961 }
12962 }
12963 } else {
12964 this[name] = defaults[name];
12965 }
12966 }
12967 }
12968 var _proto = Node3.prototype;
12969 _proto.addToError = function addToError(error) {
12970 error.postcssNode = this;
12971 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
12972 var s2 = this.source;
12973 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
12974 }
12975 return error;
12976 };
12977 _proto.after = function after(add) {
12978 this.parent.insertAfter(this, add);
12979 return this;
12980 };
12981 _proto.assign = function assign(overrides) {
12982 if (overrides === void 0) overrides = {};
12983 for(var name in overrides){
12984 this[name] = overrides[name];
12985 }
12986 return this;
12987 };
12988 _proto.before = function before(add) {
12989 this.parent.insertBefore(this, add);
12990 return this;
12991 };
12992 _proto.cleanRaws = function cleanRaws(keepBetween) {
12993 delete this.raws.before;
12994 delete this.raws.after;
12995 if (!keepBetween) delete this.raws.between;
12996 };
12997 _proto.clone = function clone(overrides) {
12998 if (overrides === void 0) overrides = {};
12999 var cloned = cloneNode(this);
13000 for(var name in overrides){
13001 cloned[name] = overrides[name];
13002 }
13003 return cloned;
13004 };
13005 _proto.cloneAfter = function cloneAfter(overrides) {
13006 if (overrides === void 0) overrides = {};
13007 var cloned = this.clone(overrides);
13008 this.parent.insertAfter(this, cloned);
13009 return cloned;
13010 };
13011 _proto.cloneBefore = function cloneBefore(overrides) {
13012 if (overrides === void 0) overrides = {};
13013 var cloned = this.clone(overrides);
13014 this.parent.insertBefore(this, cloned);
13015 return cloned;
13016 };
13017 _proto.error = function error(message, opts) {
13018 if (opts === void 0) opts = {};
13019 if (this.source) {
13020 var _this_rangeBy = this.rangeBy(opts), end = _this_rangeBy.end, start = _this_rangeBy.start;
13021 return this.source.input.error(message, {
13022 column: start.column,
13023 line: start.line
13024 }, {
13025 column: end.column,
13026 line: end.line
13027 }, opts);
13028 }
13029 return new CssSyntaxError$2(message);
13030 };
13031 _proto.getProxyProcessor = function getProxyProcessor() {
13032 return {
13033 get: function get(node2, prop) {
13034 if (prop === "proxyOf") {
13035 return node2;
13036 } else if (prop === "root") {
13037 return function() {
13038 return node2.root().toProxy();
13039 };
13040 } else {
13041 return node2[prop];
13042 }
13043 },
13044 set: function set(node2, prop, value) {
13045 if (node2[prop] === value) return true;
13046 node2[prop] = value;
13047 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */ prop === "text") {
13048 node2.markDirty();
13049 }
13050 return true;
13051 }
13052 };
13053 };
13054 _proto.markDirty = function markDirty() {
13055 if (this[isClean$2]) {
13056 this[isClean$2] = false;
13057 var next = this;
13058 while(next = next.parent){
13059 next[isClean$2] = false;
13060 }
13061 }
13062 };
13063 _proto.next = function next() {
13064 if (!this.parent) return void 0;
13065 var index2 = this.parent.index(this);
13066 return this.parent.nodes[index2 + 1];
13067 };
13068 _proto.positionBy = function positionBy(opts, stringRepresentation) {
13069 var pos = this.source.start;
13070 if (opts.index) {
13071 pos = this.positionInside(opts.index, stringRepresentation);
13072 } else if (opts.word) {
13073 stringRepresentation = this.toString();
13074 var index2 = stringRepresentation.indexOf(opts.word);
13075 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
13076 }
13077 return pos;
13078 };
13079 _proto.positionInside = function positionInside(index2, stringRepresentation) {
13080 var string = stringRepresentation || this.toString();
13081 var column = this.source.start.column;
13082 var line = this.source.start.line;
13083 for(var i2 = 0; i2 < index2; i2++){
13084 if (string[i2] === "\n") {
13085 column = 1;
13086 line += 1;
13087 } else {
13088 column += 1;
13089 }
13090 }
13091 return {
13092 column: column,
13093 line: line
13094 };
13095 };
13096 _proto.prev = function prev() {
13097 if (!this.parent) return void 0;
13098 var index2 = this.parent.index(this);
13099 return this.parent.nodes[index2 - 1];
13100 };
13101 _proto.rangeBy = function rangeBy(opts) {
13102 var start = {
13103 column: this.source.start.column,
13104 line: this.source.start.line
13105 };
13106 var end = this.source.end ? {
13107 column: this.source.end.column + 1,
13108 line: this.source.end.line
13109 } : {
13110 column: start.column + 1,
13111 line: start.line
13112 };
13113 if (opts.word) {
13114 var stringRepresentation = this.toString();
13115 var index2 = stringRepresentation.indexOf(opts.word);
13116 if (index2 !== -1) {
13117 start = this.positionInside(index2, stringRepresentation);
13118 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
13119 }
13120 } else {
13121 if (opts.start) {
13122 start = {
13123 column: opts.start.column,
13124 line: opts.start.line
13125 };
13126 } else if (opts.index) {
13127 start = this.positionInside(opts.index);
13128 }
13129 if (opts.end) {
13130 end = {
13131 column: opts.end.column,
13132 line: opts.end.line
13133 };
13134 } else if (typeof opts.endIndex === "number") {
13135 end = this.positionInside(opts.endIndex);
13136 } else if (opts.index) {
13137 end = this.positionInside(opts.index + 1);
13138 }
13139 }
13140 if (end.line < start.line || end.line === start.line && end.column <= start.column) {
13141 end = {
13142 column: start.column + 1,
13143 line: start.line
13144 };
13145 }
13146 return {
13147 end: end,
13148 start: start
13149 };
13150 };
13151 _proto.raw = function raw(prop, defaultType) {
13152 var str = new Stringifier22();
13153 return str.raw(this, prop, defaultType);
13154 };
13155 _proto.remove = function remove() {
13156 if (this.parent) {
13157 this.parent.removeChild(this);
13158 }
13159 this.parent = void 0;
13160 return this;
13161 };
13162 _proto.replaceWith = function replaceWith() {
13163 for(var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++){
13164 nodes[_key] = arguments[_key];
13165 }
13166 if (this.parent) {
13167 var bookmark = this;
13168 var foundSelf = false;
13169 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
13170 var node2 = _step.value;
13171 if (node2 === this) {
13172 foundSelf = true;
13173 } else if (foundSelf) {
13174 this.parent.insertAfter(bookmark, node2);
13175 bookmark = node2;
13176 } else {
13177 this.parent.insertBefore(bookmark, node2);
13178 }
13179 }
13180 if (!foundSelf) {
13181 this.remove();
13182 }
13183 }
13184 return this;
13185 };
13186 _proto.root = function root() {
13187 var result2 = this;
13188 while(result2.parent && result2.parent.type !== "document"){
13189 result2 = result2.parent;
13190 }
13191 return result2;
13192 };
13193 _proto.toJSON = function toJSON(_, inputs) {
13194 var fixed = {};
13195 var emitInputs = inputs == null;
13196 inputs = inputs || /* @__PURE__ */ new Map();
13197 var inputsNextIndex = 0;
13198 for(var name in this){
13199 if (!Object.prototype.hasOwnProperty.call(this, name)) {
13200 continue;
13201 }
13202 if (name === "parent" || name === "proxyCache") continue;
13203 var value = this[name];
13204 if (Array.isArray(value)) {
13205 fixed[name] = value.map(function(i2) {
13206 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) {
13207 return i2.toJSON(null, inputs);
13208 } else {
13209 return i2;
13210 }
13211 });
13212 } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) {
13213 fixed[name] = value.toJSON(null, inputs);
13214 } else if (name === "source") {
13215 var inputId = inputs.get(value.input);
13216 if (inputId == null) {
13217 inputId = inputsNextIndex;
13218 inputs.set(value.input, inputsNextIndex);
13219 inputsNextIndex++;
13220 }
13221 fixed[name] = {
13222 end: value.end,
13223 inputId: inputId,
13224 start: value.start
13225 };
13226 } else {
13227 fixed[name] = value;
13228 }
13229 }
13230 if (emitInputs) {
13231 fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
13232 return input2.toJSON();
13233 });
13234 }
13235 return fixed;
13236 };
13237 _proto.toProxy = function toProxy() {
13238 if (!this.proxyCache) {
13239 this.proxyCache = new Proxy(this, this.getProxyProcessor());
13240 }
13241 return this.proxyCache;
13242 };
13243 _proto.toString = function toString(stringifier2) {
13244 if (stringifier2 === void 0) stringifier2 = stringify$3;
13245 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
13246 var result2 = "";
13247 stringifier2(this, function(i2) {
13248 result2 += i2;
13249 });
13250 return result2;
13251 };
13252 _proto.warn = function warn(result2, text, opts) {
13253 var data = {
13254 node: this
13255 };
13256 for(var i2 in opts)data[i2] = opts[i2];
13257 return result2.warn(text, data);
13258 };
13259 _create_class(Node3, [
13260 {
13261 key: "proxyOf",
13262 get: function get() {
13263 return this;
13264 }
13265 }
13266 ]);
13267 return Node3;
13268 }();
13269 var node = Node$4;
13270 Node$4.default = Node$4;
13271 var Node$3 = node;
13272 var Declaration$4 = /*#__PURE__*/ function(Node$3) {
13273 _inherits(Declaration2, Node$3);
13274 function Declaration2(defaults) {
13275 var _this;
13276 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
13277 defaults = _extends({}, defaults, {
13278 value: String(defaults.value)
13279 });
13280 }
13281 _this = Node$3.call(this, defaults) || this;
13282 _this.type = "decl";
13283 return _this;
13284 }
13285 _create_class(Declaration2, [
13286 {
13287 key: "variable",
13288 get: function get() {
13289 return this.prop.startsWith("--") || this.prop[0] === "$";
13290 }
13291 }
13292 ]);
13293 return Declaration2;
13294 }(Node$3);
13295 var declaration = Declaration$4;
13296 Declaration$4.default = Declaration$4;
13297 var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
13298 var nanoid$1 = function(size) {
13299 if (size === void 0) size = 21;
13300 var id = "";
13301 var i2 = size;
13302 while(i2--){
13303 id += urlAlphabet[Math.random() * 64 | 0];
13304 }
13305 return id;
13306 };
13307 var nonSecure = {
13308 nanoid: nanoid$1};
13309 var SourceMapConsumer$2 = require$$2.SourceMapConsumer, SourceMapGenerator$2 = require$$2.SourceMapGenerator;
13310 var existsSync = require$$2.existsSync, readFileSync = require$$2.readFileSync;
13311 var dirname$1 = require$$2.dirname, join = require$$2.join;
13312 function fromBase64(str) {
13313 if (Buffer) {
13314 return Buffer.from(str, "base64").toString();
13315 } else {
13316 return window.atob(str);
13317 }
13318 }
13319 var PreviousMap$2 = /*#__PURE__*/ function() {
13320 function PreviousMap2(css, opts) {
13321 if (opts.map === false) return;
13322 this.loadAnnotation(css);
13323 this.inline = this.startWith(this.annotation, "data:");
13324 var prev = opts.map ? opts.map.prev : void 0;
13325 var text = this.loadMap(opts.from, prev);
13326 if (!this.mapFile && opts.from) {
13327 this.mapFile = opts.from;
13328 }
13329 if (this.mapFile) this.root = dirname$1(this.mapFile);
13330 if (text) this.text = text;
13331 }
13332 var _proto = PreviousMap2.prototype;
13333 _proto.consumer = function consumer() {
13334 if (!this.consumerCache) {
13335 this.consumerCache = new SourceMapConsumer$2(this.text);
13336 }
13337 return this.consumerCache;
13338 };
13339 _proto.decodeInline = function decodeInline(text) {
13340 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
13341 var baseUri = /^data:application\/json;base64,/;
13342 var charsetUri = /^data:application\/json;charset=utf-?8,/;
13343 var uri = /^data:application\/json,/;
13344 if (charsetUri.test(text) || uri.test(text)) {
13345 return decodeURIComponent(text.substr(RegExp.lastMatch.length));
13346 }
13347 if (baseCharsetUri.test(text) || baseUri.test(text)) {
13348 return fromBase64(text.substr(RegExp.lastMatch.length));
13349 }
13350 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
13351 throw new Error("Unsupported source map encoding " + encoding);
13352 };
13353 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
13354 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
13355 };
13356 _proto.isMap = function isMap(map) {
13357 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
13358 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
13359 };
13360 _proto.loadAnnotation = function loadAnnotation(css) {
13361 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
13362 if (!comments) return;
13363 var start = css.lastIndexOf(comments.pop());
13364 var end = css.indexOf("*/", start);
13365 if (start > -1 && end > -1) {
13366 this.annotation = this.getAnnotationURL(css.substring(start, end));
13367 }
13368 };
13369 _proto.loadFile = function loadFile(path) {
13370 this.root = dirname$1(path);
13371 if (existsSync(path)) {
13372 this.mapFile = path;
13373 return readFileSync(path, "utf-8").toString().trim();
13374 }
13375 };
13376 _proto.loadMap = function loadMap(file, prev) {
13377 if (prev === false) return false;
13378 if (prev) {
13379 if (typeof prev === "string") {
13380 return prev;
13381 } else if (typeof prev === "function") {
13382 var prevPath = prev(file);
13383 if (prevPath) {
13384 var map = this.loadFile(prevPath);
13385 if (!map) {
13386 throw new Error("Unable to load previous source map: " + prevPath.toString());
13387 }
13388 return map;
13389 }
13390 } else if (_instanceof(prev, SourceMapConsumer$2)) {
13391 return SourceMapGenerator$2.fromSourceMap(prev).toString();
13392 } else if (_instanceof(prev, SourceMapGenerator$2)) {
13393 return prev.toString();
13394 } else if (this.isMap(prev)) {
13395 return JSON.stringify(prev);
13396 } else {
13397 throw new Error("Unsupported previous source map format: " + prev.toString());
13398 }
13399 } else if (this.inline) {
13400 return this.decodeInline(this.annotation);
13401 } else if (this.annotation) {
13402 var map1 = this.annotation;
13403 if (file) map1 = join(dirname$1(file), map1);
13404 return this.loadFile(map1);
13405 }
13406 };
13407 _proto.startWith = function startWith(string, start) {
13408 if (!string) return false;
13409 return string.substr(0, start.length) === start;
13410 };
13411 _proto.withContent = function withContent() {
13412 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
13413 };
13414 return PreviousMap2;
13415 }();
13416 var previousMap = PreviousMap$2;
13417 PreviousMap$2.default = PreviousMap$2;
13418 var SourceMapConsumer$1 = require$$2.SourceMapConsumer, SourceMapGenerator$1 = require$$2.SourceMapGenerator;
13419 var fileURLToPath = require$$2.fileURLToPath, pathToFileURL$1 = require$$2.pathToFileURL;
13420 var isAbsolute = require$$2.isAbsolute, resolve$1 = require$$2.resolve;
13421 var nanoid = nonSecure.nanoid;
13422 var terminalHighlight = require$$2;
13423 var CssSyntaxError$1 = cssSyntaxError;
13424 var PreviousMap$1 = previousMap;
13425 var fromOffsetCache = Symbol("fromOffsetCache");
13426 var sourceMapAvailable$1 = Boolean(SourceMapConsumer$1 && SourceMapGenerator$1);
13427 var pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
13428 var Input$4 = /*#__PURE__*/ function() {
13429 function Input2(css, opts) {
13430 if (opts === void 0) opts = {};
13431 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) {
13432 throw new Error("PostCSS received " + css + " instead of CSS string");
13433 }
13434 this.css = css.toString();
13435 if (this.css[0] === "\uFEFF" || this.css[0] === "￾") {
13436 this.hasBOM = true;
13437 this.css = this.css.slice(1);
13438 } else {
13439 this.hasBOM = false;
13440 }
13441 if (opts.from) {
13442 if (!pathAvailable$1 || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from)) {
13443 this.file = opts.from;
13444 } else {
13445 this.file = resolve$1(opts.from);
13446 }
13447 }
13448 if (pathAvailable$1 && sourceMapAvailable$1) {
13449 var map = new PreviousMap$1(this.css, opts);
13450 if (map.text) {
13451 this.map = map;
13452 var file = map.consumer().file;
13453 if (!this.file && file) this.file = this.mapResolve(file);
13454 }
13455 }
13456 if (!this.file) {
13457 this.id = "<input css " + nanoid(6) + ">";
13458 }
13459 if (this.map) this.map.file = this.from;
13460 }
13461 var _proto = Input2.prototype;
13462 _proto.error = function error(message, line, column, opts) {
13463 if (opts === void 0) opts = {};
13464 var result2, endLine, endColumn;
13465 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
13466 var start = line;
13467 var end = column;
13468 if (typeof start.offset === "number") {
13469 var pos = this.fromOffset(start.offset);
13470 line = pos.line;
13471 column = pos.col;
13472 } else {
13473 line = start.line;
13474 column = start.column;
13475 }
13476 if (typeof end.offset === "number") {
13477 var pos1 = this.fromOffset(end.offset);
13478 endLine = pos1.line;
13479 endColumn = pos1.col;
13480 } else {
13481 endLine = end.line;
13482 endColumn = end.column;
13483 }
13484 } else if (!column) {
13485 var pos2 = this.fromOffset(line);
13486 line = pos2.line;
13487 column = pos2.col;
13488 }
13489 var origin = this.origin(line, column, endLine, endColumn);
13490 if (origin) {
13491 result2 = new CssSyntaxError$1(message, origin.endLine === void 0 ? origin.line : {
13492 column: origin.column,
13493 line: origin.line
13494 }, origin.endLine === void 0 ? origin.column : {
13495 column: origin.endColumn,
13496 line: origin.endLine
13497 }, origin.source, origin.file, opts.plugin);
13498 } else {
13499 result2 = new CssSyntaxError$1(message, endLine === void 0 ? line : {
13500 column: column,
13501 line: line
13502 }, endLine === void 0 ? column : {
13503 column: endColumn,
13504 line: endLine
13505 }, this.css, this.file, opts.plugin);
13506 }
13507 result2.input = {
13508 column: column,
13509 endColumn: endColumn,
13510 endLine: endLine,
13511 line: line,
13512 source: this.css
13513 };
13514 if (this.file) {
13515 if (pathToFileURL$1) {
13516 result2.input.url = pathToFileURL$1(this.file).toString();
13517 }
13518 result2.input.file = this.file;
13519 }
13520 return result2;
13521 };
13522 _proto.fromOffset = function fromOffset(offset) {
13523 var lastLine, lineToIndex;
13524 if (!this[fromOffsetCache]) {
13525 var lines = this.css.split("\n");
13526 lineToIndex = new Array(lines.length);
13527 var prevIndex = 0;
13528 for(var i2 = 0, l2 = lines.length; i2 < l2; i2++){
13529 lineToIndex[i2] = prevIndex;
13530 prevIndex += lines[i2].length + 1;
13531 }
13532 this[fromOffsetCache] = lineToIndex;
13533 } else {
13534 lineToIndex = this[fromOffsetCache];
13535 }
13536 lastLine = lineToIndex[lineToIndex.length - 1];
13537 var min = 0;
13538 if (offset >= lastLine) {
13539 min = lineToIndex.length - 1;
13540 } else {
13541 var max = lineToIndex.length - 2;
13542 var mid;
13543 while(min < max){
13544 mid = min + (max - min >> 1);
13545 if (offset < lineToIndex[mid]) {
13546 max = mid - 1;
13547 } else if (offset >= lineToIndex[mid + 1]) {
13548 min = mid + 1;
13549 } else {
13550 min = mid;
13551 break;
13552 }
13553 }
13554 }
13555 return {
13556 col: offset - lineToIndex[min] + 1,
13557 line: min + 1
13558 };
13559 };
13560 _proto.mapResolve = function mapResolve(file) {
13561 if (/^\w+:\/\//.test(file)) {
13562 return file;
13563 }
13564 return resolve$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
13565 };
13566 _proto.origin = function origin(line, column, endLine, endColumn) {
13567 if (!this.map) return false;
13568 var consumer = this.map.consumer();
13569 var from = consumer.originalPositionFor({
13570 column: column,
13571 line: line
13572 });
13573 if (!from.source) return false;
13574 var to;
13575 if (typeof endLine === "number") {
13576 to = consumer.originalPositionFor({
13577 column: endColumn,
13578 line: endLine
13579 });
13580 }
13581 var fromUrl;
13582 if (isAbsolute(from.source)) {
13583 fromUrl = pathToFileURL$1(from.source);
13584 } else {
13585 fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile));
13586 }
13587 var result2 = {
13588 column: from.column,
13589 endColumn: to && to.column,
13590 endLine: to && to.line,
13591 line: from.line,
13592 url: fromUrl.toString()
13593 };
13594 if (fromUrl.protocol === "file:") {
13595 if (fileURLToPath) {
13596 result2.file = fileURLToPath(fromUrl);
13597 } else {
13598 throw new Error("file: protocol is not available in this PostCSS build");
13599 }
13600 }
13601 var source = consumer.sourceContentFor(from.source);
13602 if (source) result2.source = source;
13603 return result2;
13604 };
13605 _proto.toJSON = function toJSON() {
13606 var json = {};
13607 for(var _i = 0, _iter = [
13608 "hasBOM",
13609 "css",
13610 "file",
13611 "id"
13612 ]; _i < _iter.length; _i++){
13613 var name = _iter[_i];
13614 if (this[name] != null) {
13615 json[name] = this[name];
13616 }
13617 }
13618 if (this.map) {
13619 json.map = _extends({}, this.map);
13620 if (json.map.consumerCache) {
13621 json.map.consumerCache = void 0;
13622 }
13623 }
13624 return json;
13625 };
13626 _create_class(Input2, [
13627 {
13628 key: "from",
13629 get: function get() {
13630 return this.file || this.id;
13631 }
13632 }
13633 ]);
13634 return Input2;
13635 }();
13636 var input = Input$4;
13637 Input$4.default = Input$4;
13638 if (terminalHighlight && terminalHighlight.registerInput) {
13639 terminalHighlight.registerInput(Input$4);
13640 }
13641 var SourceMapConsumer = require$$2.SourceMapConsumer, SourceMapGenerator = require$$2.SourceMapGenerator;
13642 var dirname = require$$2.dirname, relative = require$$2.relative, resolve$3 = require$$2.resolve, sep = require$$2.sep;
13643 var pathToFileURL = require$$2.pathToFileURL;
13644 var Input$3 = input;
13645 var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
13646 var pathAvailable = Boolean(dirname && resolve$3 && relative && sep);
13647 var MapGenerator$2 = /*#__PURE__*/ function() {
13648 function MapGenerator2(stringify2, root2, opts, cssString) {
13649 this.stringify = stringify2;
13650 this.mapOpts = opts.map || {};
13651 this.root = root2;
13652 this.opts = opts;
13653 this.css = cssString;
13654 this.originalCSS = cssString;
13655 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
13656 this.memoizedFileURLs = /* @__PURE__ */ new Map();
13657 this.memoizedPaths = /* @__PURE__ */ new Map();
13658 this.memoizedURLs = /* @__PURE__ */ new Map();
13659 }
13660 var _proto = MapGenerator2.prototype;
13661 _proto.addAnnotation = function addAnnotation() {
13662 var content;
13663 if (this.isInline()) {
13664 content = "data:application/json;base64," + this.toBase64(this.map.toString());
13665 } else if (typeof this.mapOpts.annotation === "string") {
13666 content = this.mapOpts.annotation;
13667 } else if (typeof this.mapOpts.annotation === "function") {
13668 content = this.mapOpts.annotation(this.opts.to, this.root);
13669 } else {
13670 content = this.outputFile() + ".map";
13671 }
13672 var eol = "\n";
13673 if (this.css.includes("\r\n")) eol = "\r\n";
13674 this.css += eol + "/*# sourceMappingURL=" + content + " */";
13675 };
13676 _proto.applyPrevMaps = function applyPrevMaps() {
13677 for(var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;){
13678 var prev = _step.value;
13679 var from = this.toUrl(this.path(prev.file));
13680 var root2 = prev.root || dirname(prev.file);
13681 var map = void 0;
13682 if (this.mapOpts.sourcesContent === false) {
13683 map = new SourceMapConsumer(prev.text);
13684 if (map.sourcesContent) {
13685 map.sourcesContent = null;
13686 }
13687 } else {
13688 map = prev.consumer();
13689 }
13690 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
13691 }
13692 };
13693 _proto.clearAnnotation = function clearAnnotation() {
13694 if (this.mapOpts.annotation === false) return;
13695 if (this.root) {
13696 var node2;
13697 for(var i2 = this.root.nodes.length - 1; i2 >= 0; i2--){
13698 node2 = this.root.nodes[i2];
13699 if (node2.type !== "comment") continue;
13700 if (node2.text.indexOf("# sourceMappingURL=") === 0) {
13701 this.root.removeChild(i2);
13702 }
13703 }
13704 } else if (this.css) {
13705 this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
13706 }
13707 };
13708 _proto.generate = function generate() {
13709 this.clearAnnotation();
13710 if (pathAvailable && sourceMapAvailable && this.isMap()) {
13711 return this.generateMap();
13712 } else {
13713 var result2 = "";
13714 this.stringify(this.root, function(i2) {
13715 result2 += i2;
13716 });
13717 return [
13718 result2
13719 ];
13720 }
13721 };
13722 _proto.generateMap = function generateMap() {
13723 if (this.root) {
13724 this.generateString();
13725 } else if (this.previous().length === 1) {
13726 var prev = this.previous()[0].consumer();
13727 prev.file = this.outputFile();
13728 this.map = SourceMapGenerator.fromSourceMap(prev, {
13729 ignoreInvalidMapping: true
13730 });
13731 } else {
13732 this.map = new SourceMapGenerator({
13733 file: this.outputFile(),
13734 ignoreInvalidMapping: true
13735 });
13736 this.map.addMapping({
13737 generated: {
13738 column: 0,
13739 line: 1
13740 },
13741 original: {
13742 column: 0,
13743 line: 1
13744 },
13745 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
13746 });
13747 }
13748 if (this.isSourcesContent()) this.setSourcesContent();
13749 if (this.root && this.previous().length > 0) this.applyPrevMaps();
13750 if (this.isAnnotation()) this.addAnnotation();
13751 if (this.isInline()) {
13752 return [
13753 this.css
13754 ];
13755 } else {
13756 return [
13757 this.css,
13758 this.map
13759 ];
13760 }
13761 };
13762 _proto.generateString = function generateString() {
13763 var _this = this;
13764 this.css = "";
13765 this.map = new SourceMapGenerator({
13766 file: this.outputFile(),
13767 ignoreInvalidMapping: true
13768 });
13769 var line = 1;
13770 var column = 1;
13771 var noSource = "<no source>";
13772 var mapping = {
13773 generated: {
13774 column: 0,
13775 line: 0
13776 },
13777 original: {
13778 column: 0,
13779 line: 0
13780 },
13781 source: ""
13782 };
13783 var lines, last;
13784 this.stringify(this.root, function(str, node2, type) {
13785 _this.css += str;
13786 if (node2 && type !== "end") {
13787 mapping.generated.line = line;
13788 mapping.generated.column = column - 1;
13789 if (node2.source && node2.source.start) {
13790 mapping.source = _this.sourcePath(node2);
13791 mapping.original.line = node2.source.start.line;
13792 mapping.original.column = node2.source.start.column - 1;
13793 _this.map.addMapping(mapping);
13794 } else {
13795 mapping.source = noSource;
13796 mapping.original.line = 1;
13797 mapping.original.column = 0;
13798 _this.map.addMapping(mapping);
13799 }
13800 }
13801 lines = str.match(/\n/g);
13802 if (lines) {
13803 line += lines.length;
13804 last = str.lastIndexOf("\n");
13805 column = str.length - last;
13806 } else {
13807 column += str.length;
13808 }
13809 if (node2 && type !== "start") {
13810 var p = node2.parent || {
13811 raws: {}
13812 };
13813 var childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
13814 if (!childless || node2 !== p.last || p.raws.semicolon) {
13815 if (node2.source && node2.source.end) {
13816 mapping.source = _this.sourcePath(node2);
13817 mapping.original.line = node2.source.end.line;
13818 mapping.original.column = node2.source.end.column - 1;
13819 mapping.generated.line = line;
13820 mapping.generated.column = column - 2;
13821 _this.map.addMapping(mapping);
13822 } else {
13823 mapping.source = noSource;
13824 mapping.original.line = 1;
13825 mapping.original.column = 0;
13826 mapping.generated.line = line;
13827 mapping.generated.column = column - 1;
13828 _this.map.addMapping(mapping);
13829 }
13830 }
13831 }
13832 });
13833 };
13834 _proto.isAnnotation = function isAnnotation() {
13835 if (this.isInline()) {
13836 return true;
13837 }
13838 if (typeof this.mapOpts.annotation !== "undefined") {
13839 return this.mapOpts.annotation;
13840 }
13841 if (this.previous().length) {
13842 return this.previous().some(function(i2) {
13843 return i2.annotation;
13844 });
13845 }
13846 return true;
13847 };
13848 _proto.isInline = function isInline() {
13849 if (typeof this.mapOpts.inline !== "undefined") {
13850 return this.mapOpts.inline;
13851 }
13852 var annotation = this.mapOpts.annotation;
13853 if (typeof annotation !== "undefined" && annotation !== true) {
13854 return false;
13855 }
13856 if (this.previous().length) {
13857 return this.previous().some(function(i2) {
13858 return i2.inline;
13859 });
13860 }
13861 return true;
13862 };
13863 _proto.isMap = function isMap() {
13864 if (typeof this.opts.map !== "undefined") {
13865 return !!this.opts.map;
13866 }
13867 return this.previous().length > 0;
13868 };
13869 _proto.isSourcesContent = function isSourcesContent() {
13870 if (typeof this.mapOpts.sourcesContent !== "undefined") {
13871 return this.mapOpts.sourcesContent;
13872 }
13873 if (this.previous().length) {
13874 return this.previous().some(function(i2) {
13875 return i2.withContent();
13876 });
13877 }
13878 return true;
13879 };
13880 _proto.outputFile = function outputFile() {
13881 if (this.opts.to) {
13882 return this.path(this.opts.to);
13883 } else if (this.opts.from) {
13884 return this.path(this.opts.from);
13885 } else {
13886 return "to.css";
13887 }
13888 };
13889 _proto.path = function path(file) {
13890 if (this.mapOpts.absolute) return file;
13891 if (file.charCodeAt(0) === 60) return file;
13892 if (/^\w+:\/\//.test(file)) return file;
13893 var cached = this.memoizedPaths.get(file);
13894 if (cached) return cached;
13895 var from = this.opts.to ? dirname(this.opts.to) : ".";
13896 if (typeof this.mapOpts.annotation === "string") {
13897 from = dirname(resolve$3(from, this.mapOpts.annotation));
13898 }
13899 var path = relative(from, file);
13900 this.memoizedPaths.set(file, path);
13901 return path;
13902 };
13903 _proto.previous = function previous() {
13904 var _this = this;
13905 if (!this.previousMaps) {
13906 this.previousMaps = [];
13907 if (this.root) {
13908 this.root.walk(function(node2) {
13909 if (node2.source && node2.source.input.map) {
13910 var map = node2.source.input.map;
13911 if (!_this.previousMaps.includes(map)) {
13912 _this.previousMaps.push(map);
13913 }
13914 }
13915 });
13916 } else {
13917 var input2 = new Input$3(this.originalCSS, this.opts);
13918 if (input2.map) this.previousMaps.push(input2.map);
13919 }
13920 }
13921 return this.previousMaps;
13922 };
13923 _proto.setSourcesContent = function setSourcesContent() {
13924 var _this = this;
13925 var already = {};
13926 if (this.root) {
13927 this.root.walk(function(node2) {
13928 if (node2.source) {
13929 var from = node2.source.input.from;
13930 if (from && !already[from]) {
13931 already[from] = true;
13932 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
13933 _this.map.setSourceContent(fromUrl, node2.source.input.css);
13934 }
13935 }
13936 });
13937 } else if (this.css) {
13938 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
13939 this.map.setSourceContent(from, this.css);
13940 }
13941 };
13942 _proto.sourcePath = function sourcePath(node2) {
13943 if (this.mapOpts.from) {
13944 return this.toUrl(this.mapOpts.from);
13945 } else if (this.usesFileUrls) {
13946 return this.toFileUrl(node2.source.input.from);
13947 } else {
13948 return this.toUrl(this.path(node2.source.input.from));
13949 }
13950 };
13951 _proto.toBase64 = function toBase64(str) {
13952 if (Buffer) {
13953 return Buffer.from(str).toString("base64");
13954 } else {
13955 return window.btoa(unescape(encodeURIComponent(str)));
13956 }
13957 };
13958 _proto.toFileUrl = function toFileUrl(path) {
13959 var cached = this.memoizedFileURLs.get(path);
13960 if (cached) return cached;
13961 if (pathToFileURL) {
13962 var fileURL = pathToFileURL(path).toString();
13963 this.memoizedFileURLs.set(path, fileURL);
13964 return fileURL;
13965 } else {
13966 throw new Error("`map.absolute` option is not available in this PostCSS build");
13967 }
13968 };
13969 _proto.toUrl = function toUrl(path) {
13970 var cached = this.memoizedURLs.get(path);
13971 if (cached) return cached;
13972 if (sep === "\\") {
13973 path = path.replace(/\\/g, "/");
13974 }
13975 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
13976 this.memoizedURLs.set(path, url);
13977 return url;
13978 };
13979 return MapGenerator2;
13980 }();
13981 var mapGenerator = MapGenerator$2;
13982 var Node$2 = node;
13983 var Comment$4 = /*#__PURE__*/ function(Node$2) {
13984 _inherits(Comment2, Node$2);
13985 function Comment2(defaults) {
13986 var _this;
13987 _this = Node$2.call(this, defaults) || this;
13988 _this.type = "comment";
13989 return _this;
13990 }
13991 return Comment2;
13992 }(Node$2);
13993 var comment = Comment$4;
13994 Comment$4.default = Comment$4;
13995 var isClean$1 = symbols.isClean, my$1 = symbols.my;
13996 var Declaration$3 = declaration;
13997 var Comment$3 = comment;
13998 var Node$1 = node;
13999 var parse$4, Rule$4, AtRule$4, Root$6;
14000 function cleanSource(nodes) {
14001 return nodes.map(function(i2) {
14002 if (i2.nodes) i2.nodes = cleanSource(i2.nodes);
14003 delete i2.source;
14004 return i2;
14005 });
14006 }
14007 function markDirtyUp(node2) {
14008 node2[isClean$1] = false;
14009 if (node2.proxyOf.nodes) {
14010 for(var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;){
14011 var i2 = _step.value;
14012 markDirtyUp(i2);
14013 }
14014 }
14015 }
14016 var Container$7 = /*#__PURE__*/ function(Node$1) {
14017 _inherits(Container2, Node$1);
14018 function Container2() {
14019 return Node$1.apply(this, arguments) || this;
14020 }
14021 var _proto = Container2.prototype;
14022 _proto.append = function append() {
14023 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
14024 children[_key] = arguments[_key];
14025 }
14026 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
14027 var child = _step.value;
14028 var nodes = this.normalize(child, this.last);
14029 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
14030 var node2 = _step1.value;
14031 this.proxyOf.nodes.push(node2);
14032 }
14033 }
14034 this.markDirty();
14035 return this;
14036 };
14037 _proto.cleanRaws = function cleanRaws(keepBetween) {
14038 Node$1.prototype.cleanRaws.call(this, keepBetween);
14039 if (this.nodes) {
14040 for(var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;){
14041 var node2 = _step.value;
14042 node2.cleanRaws(keepBetween);
14043 }
14044 }
14045 };
14046 _proto.each = function each(callback) {
14047 if (!this.proxyOf.nodes) return void 0;
14048 var iterator = this.getIterator();
14049 var index2, result2;
14050 while(this.indexes[iterator] < this.proxyOf.nodes.length){
14051 index2 = this.indexes[iterator];
14052 result2 = callback(this.proxyOf.nodes[index2], index2);
14053 if (result2 === false) break;
14054 this.indexes[iterator] += 1;
14055 }
14056 delete this.indexes[iterator];
14057 return result2;
14058 };
14059 _proto.every = function every(condition) {
14060 return this.nodes.every(condition);
14061 };
14062 _proto.getIterator = function getIterator() {
14063 if (!this.lastEach) this.lastEach = 0;
14064 if (!this.indexes) this.indexes = {};
14065 this.lastEach += 1;
14066 var iterator = this.lastEach;
14067 this.indexes[iterator] = 0;
14068 return iterator;
14069 };
14070 _proto.getProxyProcessor = function getProxyProcessor() {
14071 return {
14072 get: function get(node2, prop) {
14073 if (prop === "proxyOf") {
14074 return node2;
14075 } else if (!node2[prop]) {
14076 return node2[prop];
14077 } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
14078 return function() {
14079 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
14080 args[_key] = arguments[_key];
14081 }
14082 var _node2;
14083 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
14084 if (typeof i2 === "function") {
14085 return function(child, index2) {
14086 return i2(child.toProxy(), index2);
14087 };
14088 } else {
14089 return i2;
14090 }
14091 })));
14092 };
14093 } else if (prop === "every" || prop === "some") {
14094 return function(cb) {
14095 return node2[prop](function(child) {
14096 for(var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
14097 other[_key - 1] = arguments[_key];
14098 }
14099 return cb.apply(void 0, [].concat([
14100 child.toProxy()
14101 ], other));
14102 });
14103 };
14104 } else if (prop === "root") {
14105 return function() {
14106 return node2.root().toProxy();
14107 };
14108 } else if (prop === "nodes") {
14109 return node2.nodes.map(function(i2) {
14110 return i2.toProxy();
14111 });
14112 } else if (prop === "first" || prop === "last") {
14113 return node2[prop].toProxy();
14114 } else {
14115 return node2[prop];
14116 }
14117 },
14118 set: function set(node2, prop, value) {
14119 if (node2[prop] === value) return true;
14120 node2[prop] = value;
14121 if (prop === "name" || prop === "params" || prop === "selector") {
14122 node2.markDirty();
14123 }
14124 return true;
14125 }
14126 };
14127 };
14128 _proto.index = function index(child) {
14129 if (typeof child === "number") return child;
14130 if (child.proxyOf) child = child.proxyOf;
14131 return this.proxyOf.nodes.indexOf(child);
14132 };
14133 _proto.insertAfter = function insertAfter(exist, add) {
14134 var existIndex = this.index(exist);
14135 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
14136 existIndex = this.index(exist);
14137 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
14138 var node2 = _step.value;
14139 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
14140 }
14141 var index2;
14142 for(var id in this.indexes){
14143 index2 = this.indexes[id];
14144 if (existIndex < index2) {
14145 this.indexes[id] = index2 + nodes.length;
14146 }
14147 }
14148 this.markDirty();
14149 return this;
14150 };
14151 _proto.insertBefore = function insertBefore(exist, add) {
14152 var existIndex = this.index(exist);
14153 var type = existIndex === 0 ? "prepend" : false;
14154 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
14155 existIndex = this.index(exist);
14156 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
14157 var node2 = _step.value;
14158 this.proxyOf.nodes.splice(existIndex, 0, node2);
14159 }
14160 var index2;
14161 for(var id in this.indexes){
14162 index2 = this.indexes[id];
14163 if (existIndex <= index2) {
14164 this.indexes[id] = index2 + nodes.length;
14165 }
14166 }
14167 this.markDirty();
14168 return this;
14169 };
14170 _proto.normalize = function normalize(nodes, sample) {
14171 var _this = this;
14172 if (typeof nodes === "string") {
14173 nodes = cleanSource(parse$4(nodes).nodes);
14174 } else if (typeof nodes === "undefined") {
14175 nodes = [];
14176 } else if (Array.isArray(nodes)) {
14177 nodes = nodes.slice(0);
14178 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
14179 var i2 = _step.value;
14180 if (i2.parent) i2.parent.removeChild(i2, "ignore");
14181 }
14182 } else if (nodes.type === "root" && this.type !== "document") {
14183 nodes = nodes.nodes.slice(0);
14184 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
14185 var i21 = _step1.value;
14186 if (i21.parent) i21.parent.removeChild(i21, "ignore");
14187 }
14188 } else if (nodes.type) {
14189 nodes = [
14190 nodes
14191 ];
14192 } else if (nodes.prop) {
14193 if (typeof nodes.value === "undefined") {
14194 throw new Error("Value field is missed in node creation");
14195 } else if (typeof nodes.value !== "string") {
14196 nodes.value = String(nodes.value);
14197 }
14198 nodes = [
14199 new Declaration$3(nodes)
14200 ];
14201 } else if (nodes.selector) {
14202 nodes = [
14203 new Rule$4(nodes)
14204 ];
14205 } else if (nodes.name) {
14206 nodes = [
14207 new AtRule$4(nodes)
14208 ];
14209 } else if (nodes.text) {
14210 nodes = [
14211 new Comment$3(nodes)
14212 ];
14213 } else {
14214 throw new Error("Unknown node type in node creation");
14215 }
14216 var processed = nodes.map(function(i2) {
14217 if (!i2[my$1]) Container2.rebuild(i2);
14218 i2 = i2.proxyOf;
14219 if (i2.parent) i2.parent.removeChild(i2);
14220 if (i2[isClean$1]) markDirtyUp(i2);
14221 if (typeof i2.raws.before === "undefined") {
14222 if (sample && typeof sample.raws.before !== "undefined") {
14223 i2.raws.before = sample.raws.before.replace(/\S/g, "");
14224 }
14225 }
14226 i2.parent = _this.proxyOf;
14227 return i2;
14228 });
14229 return processed;
14230 };
14231 _proto.prepend = function prepend() {
14232 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
14233 children[_key] = arguments[_key];
14234 }
14235 children = children.reverse();
14236 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
14237 var child = _step.value;
14238 var nodes = this.normalize(child, this.first, "prepend").reverse();
14239 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
14240 var node2 = _step1.value;
14241 this.proxyOf.nodes.unshift(node2);
14242 }
14243 for(var id in this.indexes){
14244 this.indexes[id] = this.indexes[id] + nodes.length;
14245 }
14246 }
14247 this.markDirty();
14248 return this;
14249 };
14250 _proto.push = function push(child) {
14251 child.parent = this;
14252 this.proxyOf.nodes.push(child);
14253 return this;
14254 };
14255 _proto.removeAll = function removeAll() {
14256 for(var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;){
14257 var node2 = _step.value;
14258 node2.parent = void 0;
14259 }
14260 this.proxyOf.nodes = [];
14261 this.markDirty();
14262 return this;
14263 };
14264 _proto.removeChild = function removeChild(child) {
14265 child = this.index(child);
14266 this.proxyOf.nodes[child].parent = void 0;
14267 this.proxyOf.nodes.splice(child, 1);
14268 var index2;
14269 for(var id in this.indexes){
14270 index2 = this.indexes[id];
14271 if (index2 >= child) {
14272 this.indexes[id] = index2 - 1;
14273 }
14274 }
14275 this.markDirty();
14276 return this;
14277 };
14278 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
14279 if (!callback) {
14280 callback = opts;
14281 opts = {};
14282 }
14283 this.walkDecls(function(decl) {
14284 if (opts.props && !opts.props.includes(decl.prop)) return;
14285 if (opts.fast && !decl.value.includes(opts.fast)) return;
14286 decl.value = decl.value.replace(pattern, callback);
14287 });
14288 this.markDirty();
14289 return this;
14290 };
14291 _proto.some = function some(condition) {
14292 return this.nodes.some(condition);
14293 };
14294 _proto.walk = function walk(callback) {
14295 return this.each(function(child, i2) {
14296 var result2;
14297 try {
14298 result2 = callback(child, i2);
14299 } catch (e2) {
14300 throw child.addToError(e2);
14301 }
14302 if (result2 !== false && child.walk) {
14303 result2 = child.walk(callback);
14304 }
14305 return result2;
14306 });
14307 };
14308 _proto.walkAtRules = function walkAtRules(name, callback) {
14309 if (!callback) {
14310 callback = name;
14311 return this.walk(function(child, i2) {
14312 if (child.type === "atrule") {
14313 return callback(child, i2);
14314 }
14315 });
14316 }
14317 if (_instanceof(name, RegExp)) {
14318 return this.walk(function(child, i2) {
14319 if (child.type === "atrule" && name.test(child.name)) {
14320 return callback(child, i2);
14321 }
14322 });
14323 }
14324 return this.walk(function(child, i2) {
14325 if (child.type === "atrule" && child.name === name) {
14326 return callback(child, i2);
14327 }
14328 });
14329 };
14330 _proto.walkComments = function walkComments(callback) {
14331 return this.walk(function(child, i2) {
14332 if (child.type === "comment") {
14333 return callback(child, i2);
14334 }
14335 });
14336 };
14337 _proto.walkDecls = function walkDecls(prop, callback) {
14338 if (!callback) {
14339 callback = prop;
14340 return this.walk(function(child, i2) {
14341 if (child.type === "decl") {
14342 return callback(child, i2);
14343 }
14344 });
14345 }
14346 if (_instanceof(prop, RegExp)) {
14347 return this.walk(function(child, i2) {
14348 if (child.type === "decl" && prop.test(child.prop)) {
14349 return callback(child, i2);
14350 }
14351 });
14352 }
14353 return this.walk(function(child, i2) {
14354 if (child.type === "decl" && child.prop === prop) {
14355 return callback(child, i2);
14356 }
14357 });
14358 };
14359 _proto.walkRules = function walkRules(selector, callback) {
14360 if (!callback) {
14361 callback = selector;
14362 return this.walk(function(child, i2) {
14363 if (child.type === "rule") {
14364 return callback(child, i2);
14365 }
14366 });
14367 }
14368 if (_instanceof(selector, RegExp)) {
14369 return this.walk(function(child, i2) {
14370 if (child.type === "rule" && selector.test(child.selector)) {
14371 return callback(child, i2);
14372 }
14373 });
14374 }
14375 return this.walk(function(child, i2) {
14376 if (child.type === "rule" && child.selector === selector) {
14377 return callback(child, i2);
14378 }
14379 });
14380 };
14381 _create_class(Container2, [
14382 {
14383 key: "first",
14384 get: function get() {
14385 if (!this.proxyOf.nodes) return void 0;
14386 return this.proxyOf.nodes[0];
14387 }
14388 },
14389 {
14390 key: "last",
14391 get: function get() {
14392 if (!this.proxyOf.nodes) return void 0;
14393 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
14394 }
14395 }
14396 ]);
14397 return Container2;
14398 }(Node$1);
14399 Container$7.registerParse = function(dependant) {
14400 parse$4 = dependant;
14401 };
14402 Container$7.registerRule = function(dependant) {
14403 Rule$4 = dependant;
14404 };
14405 Container$7.registerAtRule = function(dependant) {
14406 AtRule$4 = dependant;
14407 };
14408 Container$7.registerRoot = function(dependant) {
14409 Root$6 = dependant;
14410 };
14411 var container = Container$7;
14412 Container$7.default = Container$7;
14413 Container$7.rebuild = function(node2) {
14414 if (node2.type === "atrule") {
14415 Object.setPrototypeOf(node2, AtRule$4.prototype);
14416 } else if (node2.type === "rule") {
14417 Object.setPrototypeOf(node2, Rule$4.prototype);
14418 } else if (node2.type === "decl") {
14419 Object.setPrototypeOf(node2, Declaration$3.prototype);
14420 } else if (node2.type === "comment") {
14421 Object.setPrototypeOf(node2, Comment$3.prototype);
14422 } else if (node2.type === "root") {
14423 Object.setPrototypeOf(node2, Root$6.prototype);
14424 }
14425 node2[my$1] = true;
14426 if (node2.nodes) {
14427 node2.nodes.forEach(function(child) {
14428 Container$7.rebuild(child);
14429 });
14430 }
14431 };
14432 var Container$6 = container;
14433 var LazyResult$4, Processor$3;
14434 var Document$3 = /*#__PURE__*/ function(Container$6) {
14435 _inherits(Document23, Container$6);
14436 function Document23(defaults) {
14437 var _this;
14438 _this = Container$6.call(this, _extends({
14439 type: "document"
14440 }, defaults)) || this;
14441 if (!_this.nodes) {
14442 _this.nodes = [];
14443 }
14444 return _this;
14445 }
14446 var _proto = Document23.prototype;
14447 _proto.toResult = function toResult(opts) {
14448 if (opts === void 0) opts = {};
14449 var lazy = new LazyResult$4(new Processor$3(), this, opts);
14450 return lazy.stringify();
14451 };
14452 return Document23;
14453 }(Container$6);
14454 Document$3.registerLazyResult = function(dependant) {
14455 LazyResult$4 = dependant;
14456 };
14457 Document$3.registerProcessor = function(dependant) {
14458 Processor$3 = dependant;
14459 };
14460 var document$1$2 = Document$3;
14461 Document$3.default = Document$3;
14462 var printed = {};
14463 var warnOnce$2 = function warnOnce2(message) {
14464 if (printed[message]) return;
14465 printed[message] = true;
14466 if (typeof console !== "undefined" && console.warn) {
14467 console.warn(message);
14468 }
14469 };
14470 var Warning$2 = /*#__PURE__*/ function() {
14471 function Warning2(text, opts) {
14472 if (opts === void 0) opts = {};
14473 this.type = "warning";
14474 this.text = text;
14475 if (opts.node && opts.node.source) {
14476 var range = opts.node.rangeBy(opts);
14477 this.line = range.start.line;
14478 this.column = range.start.column;
14479 this.endLine = range.end.line;
14480 this.endColumn = range.end.column;
14481 }
14482 for(var opt in opts)this[opt] = opts[opt];
14483 }
14484 var _proto = Warning2.prototype;
14485 _proto.toString = function toString() {
14486 if (this.node) {
14487 return this.node.error(this.text, {
14488 index: this.index,
14489 plugin: this.plugin,
14490 word: this.word
14491 }).message;
14492 }
14493 if (this.plugin) {
14494 return this.plugin + ": " + this.text;
14495 }
14496 return this.text;
14497 };
14498 return Warning2;
14499 }();
14500 var warning = Warning$2;
14501 Warning$2.default = Warning$2;
14502 var Warning$1 = warning;
14503 var Result$3 = /*#__PURE__*/ function() {
14504 function Result2(processor2, root2, opts) {
14505 this.processor = processor2;
14506 this.messages = [];
14507 this.root = root2;
14508 this.opts = opts;
14509 this.css = void 0;
14510 this.map = void 0;
14511 }
14512 var _proto = Result2.prototype;
14513 _proto.toString = function toString() {
14514 return this.css;
14515 };
14516 _proto.warn = function warn(text, opts) {
14517 if (opts === void 0) opts = {};
14518 if (!opts.plugin) {
14519 if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
14520 opts.plugin = this.lastPlugin.postcssPlugin;
14521 }
14522 }
14523 var warning2 = new Warning$1(text, opts);
14524 this.messages.push(warning2);
14525 return warning2;
14526 };
14527 _proto.warnings = function warnings() {
14528 return this.messages.filter(function(i2) {
14529 return i2.type === "warning";
14530 });
14531 };
14532 _create_class(Result2, [
14533 {
14534 key: "content",
14535 get: function get() {
14536 return this.css;
14537 }
14538 }
14539 ]);
14540 return Result2;
14541 }();
14542 var result = Result$3;
14543 Result$3.default = Result$3;
14544 var SINGLE_QUOTE = "'".charCodeAt(0);
14545 var DOUBLE_QUOTE = '"'.charCodeAt(0);
14546 var BACKSLASH = "\\".charCodeAt(0);
14547 var SLASH = "/".charCodeAt(0);
14548 var NEWLINE = "\n".charCodeAt(0);
14549 var SPACE = " ".charCodeAt(0);
14550 var FEED = "\f".charCodeAt(0);
14551 var TAB = " ".charCodeAt(0);
14552 var CR = "\r".charCodeAt(0);
14553 var OPEN_SQUARE = "[".charCodeAt(0);
14554 var CLOSE_SQUARE = "]".charCodeAt(0);
14555 var OPEN_PARENTHESES = "(".charCodeAt(0);
14556 var CLOSE_PARENTHESES = ")".charCodeAt(0);
14557 var OPEN_CURLY = "{".charCodeAt(0);
14558 var CLOSE_CURLY = "}".charCodeAt(0);
14559 var SEMICOLON = ";".charCodeAt(0);
14560 var ASTERISK = "*".charCodeAt(0);
14561 var COLON = ":".charCodeAt(0);
14562 var AT = "@".charCodeAt(0);
14563 var RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
14564 var RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
14565 var RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
14566 var RE_HEX_ESCAPE = /[\da-f]/i;
14567 var tokenize = function tokenizer2(input2, options) {
14568 if (options === void 0) options = {};
14569 var css = input2.css.valueOf();
14570 var ignore = options.ignoreErrors;
14571 var code, next, quote, content, escape;
14572 var escaped, escapePos, prev, n2, currentToken;
14573 var length = css.length;
14574 var pos = 0;
14575 var buffer = [];
14576 var returned = [];
14577 function position() {
14578 return pos;
14579 }
14580 function unclosed(what) {
14581 throw input2.error("Unclosed " + what, pos);
14582 }
14583 function endOfFile() {
14584 return returned.length === 0 && pos >= length;
14585 }
14586 function nextToken(opts) {
14587 if (returned.length) return returned.pop();
14588 if (pos >= length) return;
14589 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
14590 code = css.charCodeAt(pos);
14591 switch(code){
14592 case NEWLINE:
14593 case SPACE:
14594 case TAB:
14595 case CR:
14596 case FEED:
14597 {
14598 next = pos;
14599 do {
14600 next += 1;
14601 code = css.charCodeAt(next);
14602 }while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
14603 currentToken = [
14604 "space",
14605 css.slice(pos, next)
14606 ];
14607 pos = next - 1;
14608 break;
14609 }
14610 case OPEN_SQUARE:
14611 case CLOSE_SQUARE:
14612 case OPEN_CURLY:
14613 case CLOSE_CURLY:
14614 case COLON:
14615 case SEMICOLON:
14616 case CLOSE_PARENTHESES:
14617 {
14618 var controlChar = String.fromCharCode(code);
14619 currentToken = [
14620 controlChar,
14621 controlChar,
14622 pos
14623 ];
14624 break;
14625 }
14626 case OPEN_PARENTHESES:
14627 {
14628 prev = buffer.length ? buffer.pop()[1] : "";
14629 n2 = css.charCodeAt(pos + 1);
14630 if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE && n2 !== NEWLINE && n2 !== TAB && n2 !== FEED && n2 !== CR) {
14631 next = pos;
14632 do {
14633 escaped = false;
14634 next = css.indexOf(")", next + 1);
14635 if (next === -1) {
14636 if (ignore || ignoreUnclosed) {
14637 next = pos;
14638 break;
14639 } else {
14640 unclosed("bracket");
14641 }
14642 }
14643 escapePos = next;
14644 while(css.charCodeAt(escapePos - 1) === BACKSLASH){
14645 escapePos -= 1;
14646 escaped = !escaped;
14647 }
14648 }while (escaped);
14649 currentToken = [
14650 "brackets",
14651 css.slice(pos, next + 1),
14652 pos,
14653 next
14654 ];
14655 pos = next;
14656 } else {
14657 next = css.indexOf(")", pos + 1);
14658 content = css.slice(pos, next + 1);
14659 if (next === -1 || RE_BAD_BRACKET.test(content)) {
14660 currentToken = [
14661 "(",
14662 "(",
14663 pos
14664 ];
14665 } else {
14666 currentToken = [
14667 "brackets",
14668 content,
14669 pos,
14670 next
14671 ];
14672 pos = next;
14673 }
14674 }
14675 break;
14676 }
14677 case SINGLE_QUOTE:
14678 case DOUBLE_QUOTE:
14679 {
14680 quote = code === SINGLE_QUOTE ? "'" : '"';
14681 next = pos;
14682 do {
14683 escaped = false;
14684 next = css.indexOf(quote, next + 1);
14685 if (next === -1) {
14686 if (ignore || ignoreUnclosed) {
14687 next = pos + 1;
14688 break;
14689 } else {
14690 unclosed("string");
14691 }
14692 }
14693 escapePos = next;
14694 while(css.charCodeAt(escapePos - 1) === BACKSLASH){
14695 escapePos -= 1;
14696 escaped = !escaped;
14697 }
14698 }while (escaped);
14699 currentToken = [
14700 "string",
14701 css.slice(pos, next + 1),
14702 pos,
14703 next
14704 ];
14705 pos = next;
14706 break;
14707 }
14708 case AT:
14709 {
14710 RE_AT_END.lastIndex = pos + 1;
14711 RE_AT_END.test(css);
14712 if (RE_AT_END.lastIndex === 0) {
14713 next = css.length - 1;
14714 } else {
14715 next = RE_AT_END.lastIndex - 2;
14716 }
14717 currentToken = [
14718 "at-word",
14719 css.slice(pos, next + 1),
14720 pos,
14721 next
14722 ];
14723 pos = next;
14724 break;
14725 }
14726 case BACKSLASH:
14727 {
14728 next = pos;
14729 escape = true;
14730 while(css.charCodeAt(next + 1) === BACKSLASH){
14731 next += 1;
14732 escape = !escape;
14733 }
14734 code = css.charCodeAt(next + 1);
14735 if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
14736 next += 1;
14737 if (RE_HEX_ESCAPE.test(css.charAt(next))) {
14738 while(RE_HEX_ESCAPE.test(css.charAt(next + 1))){
14739 next += 1;
14740 }
14741 if (css.charCodeAt(next + 1) === SPACE) {
14742 next += 1;
14743 }
14744 }
14745 }
14746 currentToken = [
14747 "word",
14748 css.slice(pos, next + 1),
14749 pos,
14750 next
14751 ];
14752 pos = next;
14753 break;
14754 }
14755 default:
14756 {
14757 if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
14758 next = css.indexOf("*/", pos + 2) + 1;
14759 if (next === 0) {
14760 if (ignore || ignoreUnclosed) {
14761 next = css.length;
14762 } else {
14763 unclosed("comment");
14764 }
14765 }
14766 currentToken = [
14767 "comment",
14768 css.slice(pos, next + 1),
14769 pos,
14770 next
14771 ];
14772 pos = next;
14773 } else {
14774 RE_WORD_END.lastIndex = pos + 1;
14775 RE_WORD_END.test(css);
14776 if (RE_WORD_END.lastIndex === 0) {
14777 next = css.length - 1;
14778 } else {
14779 next = RE_WORD_END.lastIndex - 2;
14780 }
14781 currentToken = [
14782 "word",
14783 css.slice(pos, next + 1),
14784 pos,
14785 next
14786 ];
14787 buffer.push(currentToken);
14788 pos = next;
14789 }
14790 break;
14791 }
14792 }
14793 pos++;
14794 return currentToken;
14795 }
14796 function back(token) {
14797 returned.push(token);
14798 }
14799 return {
14800 back: back,
14801 endOfFile: endOfFile,
14802 nextToken: nextToken,
14803 position: position
14804 };
14805 };
14806 var Container$5 = container;
14807 var AtRule$3 = /*#__PURE__*/ function(Container$5) {
14808 _inherits(AtRule2, Container$5);
14809 function AtRule2(defaults) {
14810 var _this;
14811 _this = Container$5.call(this, defaults) || this;
14812 _this.type = "atrule";
14813 return _this;
14814 }
14815 var _proto = AtRule2.prototype;
14816 _proto.append = function append() {
14817 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
14818 children[_key] = arguments[_key];
14819 }
14820 var _Container$5_prototype_append;
14821 if (!this.proxyOf.nodes) this.nodes = [];
14822 return (_Container$5_prototype_append = Container$5.prototype.append).call.apply(_Container$5_prototype_append, [].concat([
14823 this
14824 ], children));
14825 };
14826 _proto.prepend = function prepend() {
14827 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
14828 children[_key] = arguments[_key];
14829 }
14830 var _Container$5_prototype_prepend;
14831 if (!this.proxyOf.nodes) this.nodes = [];
14832 return (_Container$5_prototype_prepend = Container$5.prototype.prepend).call.apply(_Container$5_prototype_prepend, [].concat([
14833 this
14834 ], children));
14835 };
14836 return AtRule2;
14837 }(Container$5);
14838 var atRule = AtRule$3;
14839 AtRule$3.default = AtRule$3;
14840 Container$5.registerAtRule(AtRule$3);
14841 var Container$4 = container;
14842 var LazyResult$3, Processor$2;
14843 var Root$5 = /*#__PURE__*/ function(Container$4) {
14844 _inherits(Root2, Container$4);
14845 function Root2(defaults) {
14846 var _this;
14847 _this = Container$4.call(this, defaults) || this;
14848 _this.type = "root";
14849 if (!_this.nodes) _this.nodes = [];
14850 return _this;
14851 }
14852 var _proto = Root2.prototype;
14853 _proto.normalize = function normalize(child, sample, type) {
14854 var nodes = Container$4.prototype.normalize.call(this, child);
14855 if (sample) {
14856 if (type === "prepend") {
14857 if (this.nodes.length > 1) {
14858 sample.raws.before = this.nodes[1].raws.before;
14859 } else {
14860 delete sample.raws.before;
14861 }
14862 } else if (this.first !== sample) {
14863 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
14864 var node2 = _step.value;
14865 node2.raws.before = sample.raws.before;
14866 }
14867 }
14868 }
14869 return nodes;
14870 };
14871 _proto.removeChild = function removeChild(child, ignore) {
14872 var index2 = this.index(child);
14873 if (!ignore && index2 === 0 && this.nodes.length > 1) {
14874 this.nodes[1].raws.before = this.nodes[index2].raws.before;
14875 }
14876 return Container$4.prototype.removeChild.call(this, child);
14877 };
14878 _proto.toResult = function toResult(opts) {
14879 if (opts === void 0) opts = {};
14880 var lazy = new LazyResult$3(new Processor$2(), this, opts);
14881 return lazy.stringify();
14882 };
14883 return Root2;
14884 }(Container$4);
14885 Root$5.registerLazyResult = function(dependant) {
14886 LazyResult$3 = dependant;
14887 };
14888 Root$5.registerProcessor = function(dependant) {
14889 Processor$2 = dependant;
14890 };
14891 var root = Root$5;
14892 Root$5.default = Root$5;
14893 Container$4.registerRoot(Root$5);
14894 var list$2 = {
14895 comma: function comma(string) {
14896 return list$2.split(string, [
14897 ","
14898 ], true);
14899 },
14900 space: function space(string) {
14901 var spaces = [
14902 " ",
14903 "\n",
14904 " "
14905 ];
14906 return list$2.split(string, spaces);
14907 },
14908 split: function split(string, separators, last) {
14909 var array = [];
14910 var current = "";
14911 var split = false;
14912 var func = 0;
14913 var inQuote = false;
14914 var prevQuote = "";
14915 var escape = false;
14916 for(var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;){
14917 var letter = _step.value;
14918 if (escape) {
14919 escape = false;
14920 } else if (letter === "\\") {
14921 escape = true;
14922 } else if (inQuote) {
14923 if (letter === prevQuote) {
14924 inQuote = false;
14925 }
14926 } else if (letter === '"' || letter === "'") {
14927 inQuote = true;
14928 prevQuote = letter;
14929 } else if (letter === "(") {
14930 func += 1;
14931 } else if (letter === ")") {
14932 if (func > 0) func -= 1;
14933 } else if (func === 0) {
14934 if (separators.includes(letter)) split = true;
14935 }
14936 if (split) {
14937 if (current !== "") array.push(current.trim());
14938 current = "";
14939 split = false;
14940 } else {
14941 current += letter;
14942 }
14943 }
14944 if (last || current !== "") array.push(current.trim());
14945 return array;
14946 }
14947 };
14948 var list_1 = list$2;
14949 list$2.default = list$2;
14950 var Container$3 = container;
14951 var list$1 = list_1;
14952 var Rule$3 = /*#__PURE__*/ function(Container$3) {
14953 _inherits(Rule2, Container$3);
14954 function Rule2(defaults) {
14955 var _this;
14956 _this = Container$3.call(this, defaults) || this;
14957 _this.type = "rule";
14958 if (!_this.nodes) _this.nodes = [];
14959 return _this;
14960 }
14961 _create_class(Rule2, [
14962 {
14963 key: "selectors",
14964 get: function get() {
14965 return list$1.comma(this.selector);
14966 },
14967 set: function set(values) {
14968 var match = this.selector ? this.selector.match(/,\s*/) : null;
14969 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
14970 this.selector = values.join(sep2);
14971 }
14972 }
14973 ]);
14974 return Rule2;
14975 }(Container$3);
14976 var rule = Rule$3;
14977 Rule$3.default = Rule$3;
14978 Container$3.registerRule(Rule$3);
14979 var Declaration$2 = declaration;
14980 var tokenizer22 = tokenize;
14981 var Comment$2 = comment;
14982 var AtRule$2 = atRule;
14983 var Root$4 = root;
14984 var Rule$2 = rule;
14985 var SAFE_COMMENT_NEIGHBOR = {
14986 empty: true,
14987 space: true
14988 };
14989 function findLastWithPosition(tokens) {
14990 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
14991 var token = tokens[i2];
14992 var pos = token[3] || token[2];
14993 if (pos) return pos;
14994 }
14995 }
14996 var Parser$1 = /*#__PURE__*/ function() {
14997 function Parser2(input2) {
14998 this.input = input2;
14999 this.root = new Root$4();
15000 this.current = this.root;
15001 this.spaces = "";
15002 this.semicolon = false;
15003 this.createTokenizer();
15004 this.root.source = {
15005 input: input2,
15006 start: {
15007 column: 1,
15008 line: 1,
15009 offset: 0
15010 }
15011 };
15012 }
15013 var _proto = Parser2.prototype;
15014 _proto.atrule = function atrule(token) {
15015 var node2 = new AtRule$2();
15016 node2.name = token[1].slice(1);
15017 if (node2.name === "") {
15018 this.unnamedAtrule(node2, token);
15019 }
15020 this.init(node2, token[2]);
15021 var type;
15022 var prev;
15023 var shift;
15024 var last = false;
15025 var open = false;
15026 var params = [];
15027 var brackets = [];
15028 while(!this.tokenizer.endOfFile()){
15029 token = this.tokenizer.nextToken();
15030 type = token[0];
15031 if (type === "(" || type === "[") {
15032 brackets.push(type === "(" ? ")" : "]");
15033 } else if (type === "{" && brackets.length > 0) {
15034 brackets.push("}");
15035 } else if (type === brackets[brackets.length - 1]) {
15036 brackets.pop();
15037 }
15038 if (brackets.length === 0) {
15039 if (type === ";") {
15040 node2.source.end = this.getPosition(token[2]);
15041 node2.source.end.offset++;
15042 this.semicolon = true;
15043 break;
15044 } else if (type === "{") {
15045 open = true;
15046 break;
15047 } else if (type === "}") {
15048 if (params.length > 0) {
15049 shift = params.length - 1;
15050 prev = params[shift];
15051 while(prev && prev[0] === "space"){
15052 prev = params[--shift];
15053 }
15054 if (prev) {
15055 node2.source.end = this.getPosition(prev[3] || prev[2]);
15056 node2.source.end.offset++;
15057 }
15058 }
15059 this.end(token);
15060 break;
15061 } else {
15062 params.push(token);
15063 }
15064 } else {
15065 params.push(token);
15066 }
15067 if (this.tokenizer.endOfFile()) {
15068 last = true;
15069 break;
15070 }
15071 }
15072 node2.raws.between = this.spacesAndCommentsFromEnd(params);
15073 if (params.length) {
15074 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
15075 this.raw(node2, "params", params);
15076 if (last) {
15077 token = params[params.length - 1];
15078 node2.source.end = this.getPosition(token[3] || token[2]);
15079 node2.source.end.offset++;
15080 this.spaces = node2.raws.between;
15081 node2.raws.between = "";
15082 }
15083 } else {
15084 node2.raws.afterName = "";
15085 node2.params = "";
15086 }
15087 if (open) {
15088 node2.nodes = [];
15089 this.current = node2;
15090 }
15091 };
15092 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
15093 var colon = this.colon(tokens);
15094 if (colon === false) return;
15095 var founded = 0;
15096 var token;
15097 for(var j = colon - 1; j >= 0; j--){
15098 token = tokens[j];
15099 if (token[0] !== "space") {
15100 founded += 1;
15101 if (founded === 2) break;
15102 }
15103 }
15104 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
15105 };
15106 _proto.colon = function colon(tokens) {
15107 var brackets = 0;
15108 var token, type, prev;
15109 for(var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;){
15110 var _step_value = _step.value, i2 = _step_value[0], element = _step_value[1];
15111 token = element;
15112 type = token[0];
15113 if (type === "(") {
15114 brackets += 1;
15115 }
15116 if (type === ")") {
15117 brackets -= 1;
15118 }
15119 if (brackets === 0 && type === ":") {
15120 if (!prev) {
15121 this.doubleColon(token);
15122 } else if (prev[0] === "word" && prev[1] === "progid") {
15123 continue;
15124 } else {
15125 return i2;
15126 }
15127 }
15128 prev = token;
15129 }
15130 return false;
15131 };
15132 _proto.comment = function comment(token) {
15133 var node2 = new Comment$2();
15134 this.init(node2, token[2]);
15135 node2.source.end = this.getPosition(token[3] || token[2]);
15136 node2.source.end.offset++;
15137 var text = token[1].slice(2, -2);
15138 if (/^\s*$/.test(text)) {
15139 node2.text = "";
15140 node2.raws.left = text;
15141 node2.raws.right = "";
15142 } else {
15143 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
15144 node2.text = match[2];
15145 node2.raws.left = match[1];
15146 node2.raws.right = match[3];
15147 }
15148 };
15149 _proto.createTokenizer = function createTokenizer() {
15150 this.tokenizer = tokenizer22(this.input);
15151 };
15152 _proto.decl = function decl(tokens, customProperty) {
15153 var node2 = new Declaration$2();
15154 this.init(node2, tokens[0][2]);
15155 var last = tokens[tokens.length - 1];
15156 if (last[0] === ";") {
15157 this.semicolon = true;
15158 tokens.pop();
15159 }
15160 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition(tokens));
15161 node2.source.end.offset++;
15162 while(tokens[0][0] !== "word"){
15163 if (tokens.length === 1) this.unknownWord(tokens);
15164 node2.raws.before += tokens.shift()[1];
15165 }
15166 node2.source.start = this.getPosition(tokens[0][2]);
15167 node2.prop = "";
15168 while(tokens.length){
15169 var type = tokens[0][0];
15170 if (type === ":" || type === "space" || type === "comment") {
15171 break;
15172 }
15173 node2.prop += tokens.shift()[1];
15174 }
15175 node2.raws.between = "";
15176 var token;
15177 while(tokens.length){
15178 token = tokens.shift();
15179 if (token[0] === ":") {
15180 node2.raws.between += token[1];
15181 break;
15182 } else {
15183 if (token[0] === "word" && /\w/.test(token[1])) {
15184 this.unknownWord([
15185 token
15186 ]);
15187 }
15188 node2.raws.between += token[1];
15189 }
15190 }
15191 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
15192 node2.raws.before += node2.prop[0];
15193 node2.prop = node2.prop.slice(1);
15194 }
15195 var firstSpaces = [];
15196 var next;
15197 while(tokens.length){
15198 next = tokens[0][0];
15199 if (next !== "space" && next !== "comment") break;
15200 firstSpaces.push(tokens.shift());
15201 }
15202 this.precheckMissedSemicolon(tokens);
15203 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
15204 token = tokens[i2];
15205 if (token[1].toLowerCase() === "!important") {
15206 node2.important = true;
15207 var string = this.stringFrom(tokens, i2);
15208 string = this.spacesFromEnd(tokens) + string;
15209 if (string !== " !important") node2.raws.important = string;
15210 break;
15211 } else if (token[1].toLowerCase() === "important") {
15212 var cache = tokens.slice(0);
15213 var str = "";
15214 for(var j = i2; j > 0; j--){
15215 var type1 = cache[j][0];
15216 if (str.trim().indexOf("!") === 0 && type1 !== "space") {
15217 break;
15218 }
15219 str = cache.pop()[1] + str;
15220 }
15221 if (str.trim().indexOf("!") === 0) {
15222 node2.important = true;
15223 node2.raws.important = str;
15224 tokens = cache;
15225 }
15226 }
15227 if (token[0] !== "space" && token[0] !== "comment") {
15228 break;
15229 }
15230 }
15231 var hasWord = tokens.some(function(i2) {
15232 return i2[0] !== "space" && i2[0] !== "comment";
15233 });
15234 if (hasWord) {
15235 node2.raws.between += firstSpaces.map(function(i2) {
15236 return i2[1];
15237 }).join("");
15238 firstSpaces = [];
15239 }
15240 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
15241 if (node2.value.includes(":") && !customProperty) {
15242 this.checkMissedSemicolon(tokens);
15243 }
15244 };
15245 _proto.doubleColon = function doubleColon(token) {
15246 throw this.input.error("Double colon", {
15247 offset: token[2]
15248 }, {
15249 offset: token[2] + token[1].length
15250 });
15251 };
15252 _proto.emptyRule = function emptyRule(token) {
15253 var node2 = new Rule$2();
15254 this.init(node2, token[2]);
15255 node2.selector = "";
15256 node2.raws.between = "";
15257 this.current = node2;
15258 };
15259 _proto.end = function end(token) {
15260 if (this.current.nodes && this.current.nodes.length) {
15261 this.current.raws.semicolon = this.semicolon;
15262 }
15263 this.semicolon = false;
15264 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
15265 this.spaces = "";
15266 if (this.current.parent) {
15267 this.current.source.end = this.getPosition(token[2]);
15268 this.current.source.end.offset++;
15269 this.current = this.current.parent;
15270 } else {
15271 this.unexpectedClose(token);
15272 }
15273 };
15274 _proto.endFile = function endFile() {
15275 if (this.current.parent) this.unclosedBlock();
15276 if (this.current.nodes && this.current.nodes.length) {
15277 this.current.raws.semicolon = this.semicolon;
15278 }
15279 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
15280 this.root.source.end = this.getPosition(this.tokenizer.position());
15281 };
15282 _proto.freeSemicolon = function freeSemicolon(token) {
15283 this.spaces += token[1];
15284 if (this.current.nodes) {
15285 var prev = this.current.nodes[this.current.nodes.length - 1];
15286 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
15287 prev.raws.ownSemicolon = this.spaces;
15288 this.spaces = "";
15289 }
15290 }
15291 };
15292 // Helpers
15293 _proto.getPosition = function getPosition(offset) {
15294 var pos = this.input.fromOffset(offset);
15295 return {
15296 column: pos.col,
15297 line: pos.line,
15298 offset: offset
15299 };
15300 };
15301 _proto.init = function init(node2, offset) {
15302 this.current.push(node2);
15303 node2.source = {
15304 input: this.input,
15305 start: this.getPosition(offset)
15306 };
15307 node2.raws.before = this.spaces;
15308 this.spaces = "";
15309 if (node2.type !== "comment") this.semicolon = false;
15310 };
15311 _proto.other = function other(start) {
15312 var end = false;
15313 var type = null;
15314 var colon = false;
15315 var bracket = null;
15316 var brackets = [];
15317 var customProperty = start[1].startsWith("--");
15318 var tokens = [];
15319 var token = start;
15320 while(token){
15321 type = token[0];
15322 tokens.push(token);
15323 if (type === "(" || type === "[") {
15324 if (!bracket) bracket = token;
15325 brackets.push(type === "(" ? ")" : "]");
15326 } else if (customProperty && colon && type === "{") {
15327 if (!bracket) bracket = token;
15328 brackets.push("}");
15329 } else if (brackets.length === 0) {
15330 if (type === ";") {
15331 if (colon) {
15332 this.decl(tokens, customProperty);
15333 return;
15334 } else {
15335 break;
15336 }
15337 } else if (type === "{") {
15338 this.rule(tokens);
15339 return;
15340 } else if (type === "}") {
15341 this.tokenizer.back(tokens.pop());
15342 end = true;
15343 break;
15344 } else if (type === ":") {
15345 colon = true;
15346 }
15347 } else if (type === brackets[brackets.length - 1]) {
15348 brackets.pop();
15349 if (brackets.length === 0) bracket = null;
15350 }
15351 token = this.tokenizer.nextToken();
15352 }
15353 if (this.tokenizer.endOfFile()) end = true;
15354 if (brackets.length > 0) this.unclosedBracket(bracket);
15355 if (end && colon) {
15356 if (!customProperty) {
15357 while(tokens.length){
15358 token = tokens[tokens.length - 1][0];
15359 if (token !== "space" && token !== "comment") break;
15360 this.tokenizer.back(tokens.pop());
15361 }
15362 }
15363 this.decl(tokens, customProperty);
15364 } else {
15365 this.unknownWord(tokens);
15366 }
15367 };
15368 _proto.parse = function parse() {
15369 var token;
15370 while(!this.tokenizer.endOfFile()){
15371 token = this.tokenizer.nextToken();
15372 switch(token[0]){
15373 case "space":
15374 this.spaces += token[1];
15375 break;
15376 case ";":
15377 this.freeSemicolon(token);
15378 break;
15379 case "}":
15380 this.end(token);
15381 break;
15382 case "comment":
15383 this.comment(token);
15384 break;
15385 case "at-word":
15386 this.atrule(token);
15387 break;
15388 case "{":
15389 this.emptyRule(token);
15390 break;
15391 default:
15392 this.other(token);
15393 break;
15394 }
15395 }
15396 this.endFile();
15397 };
15398 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
15399 _proto.raw = function raw(node2, prop, tokens, customProperty) {
15400 var token, type;
15401 var length = tokens.length;
15402 var value = "";
15403 var clean = true;
15404 var next, prev;
15405 for(var i2 = 0; i2 < length; i2 += 1){
15406 token = tokens[i2];
15407 type = token[0];
15408 if (type === "space" && i2 === length - 1 && !customProperty) {
15409 clean = false;
15410 } else if (type === "comment") {
15411 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
15412 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
15413 if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
15414 if (value.slice(-1) === ",") {
15415 clean = false;
15416 } else {
15417 value += token[1];
15418 }
15419 } else {
15420 clean = false;
15421 }
15422 } else {
15423 value += token[1];
15424 }
15425 }
15426 if (!clean) {
15427 var raw = tokens.reduce(function(all, i2) {
15428 return all + i2[1];
15429 }, "");
15430 node2.raws[prop] = {
15431 raw: raw,
15432 value: value
15433 };
15434 }
15435 node2[prop] = value;
15436 };
15437 _proto.rule = function rule(tokens) {
15438 tokens.pop();
15439 var node2 = new Rule$2();
15440 this.init(node2, tokens[0][2]);
15441 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
15442 this.raw(node2, "selector", tokens);
15443 this.current = node2;
15444 };
15445 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
15446 var lastTokenType;
15447 var spaces = "";
15448 while(tokens.length){
15449 lastTokenType = tokens[tokens.length - 1][0];
15450 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
15451 spaces = tokens.pop()[1] + spaces;
15452 }
15453 return spaces;
15454 };
15455 // Errors
15456 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
15457 var next;
15458 var spaces = "";
15459 while(tokens.length){
15460 next = tokens[0][0];
15461 if (next !== "space" && next !== "comment") break;
15462 spaces += tokens.shift()[1];
15463 }
15464 return spaces;
15465 };
15466 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
15467 var lastTokenType;
15468 var spaces = "";
15469 while(tokens.length){
15470 lastTokenType = tokens[tokens.length - 1][0];
15471 if (lastTokenType !== "space") break;
15472 spaces = tokens.pop()[1] + spaces;
15473 }
15474 return spaces;
15475 };
15476 _proto.stringFrom = function stringFrom(tokens, from) {
15477 var result2 = "";
15478 for(var i2 = from; i2 < tokens.length; i2++){
15479 result2 += tokens[i2][1];
15480 }
15481 tokens.splice(from, tokens.length - from);
15482 return result2;
15483 };
15484 _proto.unclosedBlock = function unclosedBlock() {
15485 var pos = this.current.source.start;
15486 throw this.input.error("Unclosed block", pos.line, pos.column);
15487 };
15488 _proto.unclosedBracket = function unclosedBracket(bracket) {
15489 throw this.input.error("Unclosed bracket", {
15490 offset: bracket[2]
15491 }, {
15492 offset: bracket[2] + 1
15493 });
15494 };
15495 _proto.unexpectedClose = function unexpectedClose(token) {
15496 throw this.input.error("Unexpected }", {
15497 offset: token[2]
15498 }, {
15499 offset: token[2] + 1
15500 });
15501 };
15502 _proto.unknownWord = function unknownWord(tokens) {
15503 throw this.input.error("Unknown word", {
15504 offset: tokens[0][2]
15505 }, {
15506 offset: tokens[0][2] + tokens[0][1].length
15507 });
15508 };
15509 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
15510 throw this.input.error("At-rule without name", {
15511 offset: token[2]
15512 }, {
15513 offset: token[2] + token[1].length
15514 });
15515 };
15516 return Parser2;
15517 }();
15518 var parser = Parser$1;
15519 var Container$2 = container;
15520 var Parser22 = parser;
15521 var Input$2 = input;
15522 function parse$3(css, opts) {
15523 var input2 = new Input$2(css, opts);
15524 var parser2 = new Parser22(input2);
15525 try {
15526 parser2.parse();
15527 } catch (e2) {
15528 if (true) {
15529 if (e2.name === "CssSyntaxError" && opts && opts.from) {
15530 if (/\.scss$/i.test(opts.from)) {
15531 e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
15532 } else if (/\.sass/i.test(opts.from)) {
15533 e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
15534 } else if (/\.less$/i.test(opts.from)) {
15535 e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
15536 }
15537 }
15538 }
15539 throw e2;
15540 }
15541 return parser2.root;
15542 }
15543 var parse_1 = parse$3;
15544 parse$3.default = parse$3;
15545 Container$2.registerParse(parse$3);
15546 var isClean = symbols.isClean, my = symbols.my;
15547 var MapGenerator$1 = mapGenerator;
15548 var stringify$2 = stringify_1;
15549 var Container$1 = container;
15550 var Document$2 = document$1$2;
15551 var warnOnce$1 = warnOnce$2;
15552 var Result$2 = result;
15553 var parse$2 = parse_1;
15554 var Root$3 = root;
15555 var TYPE_TO_CLASS_NAME = {
15556 atrule: "AtRule",
15557 comment: "Comment",
15558 decl: "Declaration",
15559 document: "Document",
15560 root: "Root",
15561 rule: "Rule"
15562 };
15563 var PLUGIN_PROPS = {
15564 AtRule: true,
15565 AtRuleExit: true,
15566 Comment: true,
15567 CommentExit: true,
15568 Declaration: true,
15569 DeclarationExit: true,
15570 Document: true,
15571 DocumentExit: true,
15572 Once: true,
15573 OnceExit: true,
15574 postcssPlugin: true,
15575 prepare: true,
15576 Root: true,
15577 RootExit: true,
15578 Rule: true,
15579 RuleExit: true
15580 };
15581 var NOT_VISITORS = {
15582 Once: true,
15583 postcssPlugin: true,
15584 prepare: true
15585 };
15586 var CHILDREN = 0;
15587 function isPromise(obj) {
15588 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
15589 }
15590 function getEvents(node2) {
15591 var key = false;
15592 var type = TYPE_TO_CLASS_NAME[node2.type];
15593 if (node2.type === "decl") {
15594 key = node2.prop.toLowerCase();
15595 } else if (node2.type === "atrule") {
15596 key = node2.name.toLowerCase();
15597 }
15598 if (key && node2.append) {
15599 return [
15600 type,
15601 type + "-" + key,
15602 CHILDREN,
15603 type + "Exit",
15604 type + "Exit-" + key
15605 ];
15606 } else if (key) {
15607 return [
15608 type,
15609 type + "-" + key,
15610 type + "Exit",
15611 type + "Exit-" + key
15612 ];
15613 } else if (node2.append) {
15614 return [
15615 type,
15616 CHILDREN,
15617 type + "Exit"
15618 ];
15619 } else {
15620 return [
15621 type,
15622 type + "Exit"
15623 ];
15624 }
15625 }
15626 function toStack(node2) {
15627 var events;
15628 if (node2.type === "document") {
15629 events = [
15630 "Document",
15631 CHILDREN,
15632 "DocumentExit"
15633 ];
15634 } else if (node2.type === "root") {
15635 events = [
15636 "Root",
15637 CHILDREN,
15638 "RootExit"
15639 ];
15640 } else {
15641 events = getEvents(node2);
15642 }
15643 return {
15644 eventIndex: 0,
15645 events: events,
15646 iterator: 0,
15647 node: node2,
15648 visitorIndex: 0,
15649 visitors: []
15650 };
15651 }
15652 function cleanMarks(node2) {
15653 node2[isClean] = false;
15654 if (node2.nodes) node2.nodes.forEach(function(i2) {
15655 return cleanMarks(i2);
15656 });
15657 return node2;
15658 }
15659 var postcss$2 = {};
15660 var LazyResult$2 = /*#__PURE__*/ function() {
15661 function LazyResult2(processor2, css, opts) {
15662 var _this = this;
15663 this.stringified = false;
15664 this.processed = false;
15665 var root2;
15666 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) {
15667 root2 = cleanMarks(css);
15668 } else if (_instanceof(css, LazyResult2) || _instanceof(css, Result$2)) {
15669 root2 = cleanMarks(css.root);
15670 if (css.map) {
15671 if (typeof opts.map === "undefined") opts.map = {};
15672 if (!opts.map.inline) opts.map.inline = false;
15673 opts.map.prev = css.map;
15674 }
15675 } else {
15676 var parser2 = parse$2;
15677 if (opts.syntax) parser2 = opts.syntax.parse;
15678 if (opts.parser) parser2 = opts.parser;
15679 if (parser2.parse) parser2 = parser2.parse;
15680 try {
15681 root2 = parser2(css, opts);
15682 } catch (error) {
15683 this.processed = true;
15684 this.error = error;
15685 }
15686 if (root2 && !root2[my]) {
15687 Container$1.rebuild(root2);
15688 }
15689 }
15690 this.result = new Result$2(processor2, root2, opts);
15691 this.helpers = _extends({}, postcss$2, {
15692 postcss: postcss$2,
15693 result: this.result
15694 });
15695 this.plugins = this.processor.plugins.map(function(plugin22) {
15696 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) {
15697 return _extends({}, plugin22, plugin22.prepare(_this.result));
15698 } else {
15699 return plugin22;
15700 }
15701 });
15702 }
15703 var _proto = LazyResult2.prototype;
15704 _proto.async = function async() {
15705 if (this.error) return Promise.reject(this.error);
15706 if (this.processed) return Promise.resolve(this.result);
15707 if (!this.processing) {
15708 this.processing = this.runAsync();
15709 }
15710 return this.processing;
15711 };
15712 _proto.catch = function _catch(onRejected) {
15713 return this.async().catch(onRejected);
15714 };
15715 _proto.finally = function _finally(onFinally) {
15716 return this.async().then(onFinally, onFinally);
15717 };
15718 _proto.getAsyncError = function getAsyncError() {
15719 throw new Error("Use process(css).then(cb) to work with async plugins");
15720 };
15721 _proto.handleError = function handleError(error, node2) {
15722 var plugin22 = this.result.lastPlugin;
15723 try {
15724 if (node2) node2.addToError(error);
15725 this.error = error;
15726 if (error.name === "CssSyntaxError" && !error.plugin) {
15727 error.plugin = plugin22.postcssPlugin;
15728 error.setMessage();
15729 } else if (plugin22.postcssVersion) {
15730 if (true) {
15731 var pluginName = plugin22.postcssPlugin;
15732 var pluginVer = plugin22.postcssVersion;
15733 var runtimeVer = this.result.processor.version;
15734 var a2 = pluginVer.split(".");
15735 var b = runtimeVer.split(".");
15736 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) {
15737 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.");
15738 }
15739 }
15740 }
15741 } catch (err) {
15742 if (console && console.error) console.error(err);
15743 }
15744 return error;
15745 };
15746 _proto.prepareVisitors = function prepareVisitors() {
15747 var _this = this;
15748 this.listeners = {};
15749 var add = function(plugin22, type, cb) {
15750 if (!_this.listeners[type]) _this.listeners[type] = [];
15751 _this.listeners[type].push([
15752 plugin22,
15753 cb
15754 ]);
15755 };
15756 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
15757 var plugin22 = _step.value;
15758 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") {
15759 for(var event in plugin22){
15760 if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
15761 throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
15762 }
15763 if (!NOT_VISITORS[event]) {
15764 if (_type_of(plugin22[event]) === "object") {
15765 for(var filter in plugin22[event]){
15766 if (filter === "*") {
15767 add(plugin22, event, plugin22[event][filter]);
15768 } else {
15769 add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
15770 }
15771 }
15772 } else if (typeof plugin22[event] === "function") {
15773 add(plugin22, event, plugin22[event]);
15774 }
15775 }
15776 }
15777 }
15778 }
15779 this.hasListener = Object.keys(this.listeners).length > 0;
15780 };
15781 _proto.runAsync = function runAsync() {
15782 var _this = this;
15783 return _async_to_generator(function() {
15784 var i2, plugin22, promise, error, root2, stack, promise1, e2, node2, _loop, _iterator, _step;
15785 return _ts_generator(this, function(_state) {
15786 switch(_state.label){
15787 case 0:
15788 _this.plugin = 0;
15789 i2 = 0;
15790 _state.label = 1;
15791 case 1:
15792 if (!(i2 < _this.plugins.length)) return [
15793 3,
15794 6
15795 ];
15796 plugin22 = _this.plugins[i2];
15797 promise = _this.runOnRoot(plugin22);
15798 if (!isPromise(promise)) return [
15799 3,
15800 5
15801 ];
15802 _state.label = 2;
15803 case 2:
15804 _state.trys.push([
15805 2,
15806 4,
15807 ,
15808 5
15809 ]);
15810 return [
15811 4,
15812 promise
15813 ];
15814 case 3:
15815 _state.sent();
15816 return [
15817 3,
15818 5
15819 ];
15820 case 4:
15821 error = _state.sent();
15822 throw _this.handleError(error);
15823 case 5:
15824 i2++;
15825 return [
15826 3,
15827 1
15828 ];
15829 case 6:
15830 _this.prepareVisitors();
15831 if (!_this.hasListener) return [
15832 3,
15833 18
15834 ];
15835 root2 = _this.result.root;
15836 _state.label = 7;
15837 case 7:
15838 if (!!root2[isClean]) return [
15839 3,
15840 14
15841 ];
15842 root2[isClean] = true;
15843 stack = [
15844 toStack(root2)
15845 ];
15846 _state.label = 8;
15847 case 8:
15848 if (!(stack.length > 0)) return [
15849 3,
15850 13
15851 ];
15852 promise1 = _this.visitTick(stack);
15853 if (!isPromise(promise1)) return [
15854 3,
15855 12
15856 ];
15857 _state.label = 9;
15858 case 9:
15859 _state.trys.push([
15860 9,
15861 11,
15862 ,
15863 12
15864 ]);
15865 return [
15866 4,
15867 promise1
15868 ];
15869 case 10:
15870 _state.sent();
15871 return [
15872 3,
15873 12
15874 ];
15875 case 11:
15876 e2 = _state.sent();
15877 node2 = stack[stack.length - 1].node;
15878 throw _this.handleError(e2, node2);
15879 case 12:
15880 return [
15881 3,
15882 8
15883 ];
15884 case 13:
15885 return [
15886 3,
15887 7
15888 ];
15889 case 14:
15890 if (!_this.listeners.OnceExit) return [
15891 3,
15892 18
15893 ];
15894 _loop = function() {
15895 var _step_value, plugin22, visitor, roots, e2;
15896 return _ts_generator(this, function(_state) {
15897 switch(_state.label){
15898 case 0:
15899 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
15900 _this.result.lastPlugin = plugin22;
15901 _state.label = 1;
15902 case 1:
15903 _state.trys.push([
15904 1,
15905 6,
15906 ,
15907 7
15908 ]);
15909 if (!(root2.type === "document")) return [
15910 3,
15911 3
15912 ];
15913 roots = root2.nodes.map(function(subRoot) {
15914 return visitor(subRoot, _this.helpers);
15915 });
15916 return [
15917 4,
15918 Promise.all(roots)
15919 ];
15920 case 2:
15921 _state.sent();
15922 return [
15923 3,
15924 5
15925 ];
15926 case 3:
15927 return [
15928 4,
15929 visitor(root2, _this.helpers)
15930 ];
15931 case 4:
15932 _state.sent();
15933 _state.label = 5;
15934 case 5:
15935 return [
15936 3,
15937 7
15938 ];
15939 case 6:
15940 e2 = _state.sent();
15941 throw _this.handleError(e2);
15942 case 7:
15943 return [
15944 2
15945 ];
15946 }
15947 });
15948 };
15949 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
15950 _state.label = 15;
15951 case 15:
15952 if (!!(_step = _iterator()).done) return [
15953 3,
15954 18
15955 ];
15956 return [
15957 5,
15958 _ts_values(_loop())
15959 ];
15960 case 16:
15961 _state.sent();
15962 _state.label = 17;
15963 case 17:
15964 return [
15965 3,
15966 15
15967 ];
15968 case 18:
15969 _this.processed = true;
15970 return [
15971 2,
15972 _this.stringify()
15973 ];
15974 }
15975 });
15976 })();
15977 };
15978 _proto.runOnRoot = function runOnRoot(plugin22) {
15979 var _this = this;
15980 this.result.lastPlugin = plugin22;
15981 try {
15982 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
15983 if (this.result.root.type === "document") {
15984 var roots = this.result.root.nodes.map(function(root2) {
15985 return plugin22.Once(root2, _this.helpers);
15986 });
15987 if (isPromise(roots[0])) {
15988 return Promise.all(roots);
15989 }
15990 return roots;
15991 }
15992 return plugin22.Once(this.result.root, this.helpers);
15993 } else if (typeof plugin22 === "function") {
15994 return plugin22(this.result.root, this.result);
15995 }
15996 } catch (error) {
15997 throw this.handleError(error);
15998 }
15999 };
16000 _proto.stringify = function stringify() {
16001 if (this.error) throw this.error;
16002 if (this.stringified) return this.result;
16003 this.stringified = true;
16004 this.sync();
16005 var opts = this.result.opts;
16006 var str = stringify$2;
16007 if (opts.syntax) str = opts.syntax.stringify;
16008 if (opts.stringifier) str = opts.stringifier;
16009 if (str.stringify) str = str.stringify;
16010 var map = new MapGenerator$1(str, this.result.root, this.result.opts);
16011 var data = map.generate();
16012 this.result.css = data[0];
16013 this.result.map = data[1];
16014 return this.result;
16015 };
16016 _proto.sync = function sync() {
16017 if (this.error) throw this.error;
16018 if (this.processed) return this.result;
16019 this.processed = true;
16020 if (this.processing) {
16021 throw this.getAsyncError();
16022 }
16023 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
16024 var plugin22 = _step.value;
16025 var promise = this.runOnRoot(plugin22);
16026 if (isPromise(promise)) {
16027 throw this.getAsyncError();
16028 }
16029 }
16030 this.prepareVisitors();
16031 if (this.hasListener) {
16032 var root2 = this.result.root;
16033 while(!root2[isClean]){
16034 root2[isClean] = true;
16035 this.walkSync(root2);
16036 }
16037 if (this.listeners.OnceExit) {
16038 if (root2.type === "document") {
16039 for(var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;){
16040 var subRoot = _step1.value;
16041 this.visitSync(this.listeners.OnceExit, subRoot);
16042 }
16043 } else {
16044 this.visitSync(this.listeners.OnceExit, root2);
16045 }
16046 }
16047 }
16048 return this.result;
16049 };
16050 _proto.then = function then(onFulfilled, onRejected) {
16051 if (true) {
16052 if (!("from" in this.opts)) {
16053 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.");
16054 }
16055 }
16056 return this.async().then(onFulfilled, onRejected);
16057 };
16058 _proto.toString = function toString() {
16059 return this.css;
16060 };
16061 _proto.visitSync = function visitSync(visitors, node2) {
16062 for(var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;){
16063 var _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
16064 this.result.lastPlugin = plugin22;
16065 var promise = void 0;
16066 try {
16067 promise = visitor(node2, this.helpers);
16068 } catch (e2) {
16069 throw this.handleError(e2, node2.proxyOf);
16070 }
16071 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
16072 return true;
16073 }
16074 if (isPromise(promise)) {
16075 throw this.getAsyncError();
16076 }
16077 }
16078 };
16079 _proto.visitTick = function visitTick(stack) {
16080 var visit2 = stack[stack.length - 1];
16081 var node2 = visit2.node, visitors = visit2.visitors;
16082 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
16083 stack.pop();
16084 return;
16085 }
16086 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
16087 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex], plugin22 = _visitors_visit2_visitorIndex[0], visitor = _visitors_visit2_visitorIndex[1];
16088 visit2.visitorIndex += 1;
16089 if (visit2.visitorIndex === visitors.length) {
16090 visit2.visitors = [];
16091 visit2.visitorIndex = 0;
16092 }
16093 this.result.lastPlugin = plugin22;
16094 try {
16095 return visitor(node2.toProxy(), this.helpers);
16096 } catch (e2) {
16097 throw this.handleError(e2, node2);
16098 }
16099 }
16100 if (visit2.iterator !== 0) {
16101 var iterator = visit2.iterator;
16102 var child;
16103 while(child = node2.nodes[node2.indexes[iterator]]){
16104 node2.indexes[iterator] += 1;
16105 if (!child[isClean]) {
16106 child[isClean] = true;
16107 stack.push(toStack(child));
16108 return;
16109 }
16110 }
16111 visit2.iterator = 0;
16112 delete node2.indexes[iterator];
16113 }
16114 var events = visit2.events;
16115 while(visit2.eventIndex < events.length){
16116 var event = events[visit2.eventIndex];
16117 visit2.eventIndex += 1;
16118 if (event === CHILDREN) {
16119 if (node2.nodes && node2.nodes.length) {
16120 node2[isClean] = true;
16121 visit2.iterator = node2.getIterator();
16122 }
16123 return;
16124 } else if (this.listeners[event]) {
16125 visit2.visitors = this.listeners[event];
16126 return;
16127 }
16128 }
16129 stack.pop();
16130 };
16131 _proto.walkSync = function walkSync(node2) {
16132 var _this = this;
16133 node2[isClean] = true;
16134 var events = getEvents(node2);
16135 for(var _iterator = _create_for_of_iterator_helper_loose(events), _step; !(_step = _iterator()).done;){
16136 var event = _step.value;
16137 if (event === CHILDREN) {
16138 if (node2.nodes) {
16139 node2.each(function(child) {
16140 if (!child[isClean]) _this.walkSync(child);
16141 });
16142 }
16143 } else {
16144 var visitors = this.listeners[event];
16145 if (visitors) {
16146 if (this.visitSync(visitors, node2.toProxy())) return;
16147 }
16148 }
16149 }
16150 };
16151 _proto.warnings = function warnings() {
16152 return this.sync().warnings();
16153 };
16154 _create_class(LazyResult2, [
16155 {
16156 key: "content",
16157 get: function get() {
16158 return this.stringify().content;
16159 }
16160 },
16161 {
16162 key: "css",
16163 get: function get() {
16164 return this.stringify().css;
16165 }
16166 },
16167 {
16168 key: "map",
16169 get: function get() {
16170 return this.stringify().map;
16171 }
16172 },
16173 {
16174 key: "messages",
16175 get: function get() {
16176 return this.sync().messages;
16177 }
16178 },
16179 {
16180 key: "opts",
16181 get: function get() {
16182 return this.result.opts;
16183 }
16184 },
16185 {
16186 key: "processor",
16187 get: function get() {
16188 return this.result.processor;
16189 }
16190 },
16191 {
16192 key: "root",
16193 get: function get() {
16194 return this.sync().root;
16195 }
16196 },
16197 {
16198 key: Symbol.toStringTag,
16199 get: function get() {
16200 return "LazyResult";
16201 }
16202 }
16203 ]);
16204 return LazyResult2;
16205 }();
16206 LazyResult$2.registerPostcss = function(dependant) {
16207 postcss$2 = dependant;
16208 };
16209 var lazyResult = LazyResult$2;
16210 LazyResult$2.default = LazyResult$2;
16211 Root$3.registerLazyResult(LazyResult$2);
16212 Document$2.registerLazyResult(LazyResult$2);
16213 var MapGenerator22 = mapGenerator;
16214 var stringify$1 = stringify_1;
16215 var warnOnce22 = warnOnce$2;
16216 var parse$1 = parse_1;
16217 var Result$1 = result;
16218 var NoWorkResult$1 = /*#__PURE__*/ function() {
16219 function NoWorkResult2(processor2, css, opts) {
16220 css = css.toString();
16221 this.stringified = false;
16222 this._processor = processor2;
16223 this._css = css;
16224 this._opts = opts;
16225 this._map = void 0;
16226 var root2;
16227 var str = stringify$1;
16228 this.result = new Result$1(this._processor, root2, this._opts);
16229 this.result.css = css;
16230 var self = this;
16231 Object.defineProperty(this.result, "root", {
16232 get: function get() {
16233 return self.root;
16234 }
16235 });
16236 var map = new MapGenerator22(str, root2, this._opts, css);
16237 if (map.isMap()) {
16238 var _map_generate = map.generate(), generatedCSS = _map_generate[0], generatedMap = _map_generate[1];
16239 if (generatedCSS) {
16240 this.result.css = generatedCSS;
16241 }
16242 if (generatedMap) {
16243 this.result.map = generatedMap;
16244 }
16245 } else {
16246 map.clearAnnotation();
16247 this.result.css = map.css;
16248 }
16249 }
16250 var _proto = NoWorkResult2.prototype;
16251 _proto.async = function async() {
16252 if (this.error) return Promise.reject(this.error);
16253 return Promise.resolve(this.result);
16254 };
16255 _proto.catch = function _catch(onRejected) {
16256 return this.async().catch(onRejected);
16257 };
16258 _proto.finally = function _finally(onFinally) {
16259 return this.async().then(onFinally, onFinally);
16260 };
16261 _proto.sync = function sync() {
16262 if (this.error) throw this.error;
16263 return this.result;
16264 };
16265 _proto.then = function then(onFulfilled, onRejected) {
16266 if (true) {
16267 if (!("from" in this._opts)) {
16268 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.");
16269 }
16270 }
16271 return this.async().then(onFulfilled, onRejected);
16272 };
16273 _proto.toString = function toString() {
16274 return this._css;
16275 };
16276 _proto.warnings = function warnings() {
16277 return [];
16278 };
16279 _create_class(NoWorkResult2, [
16280 {
16281 key: "content",
16282 get: function get() {
16283 return this.result.css;
16284 }
16285 },
16286 {
16287 key: "css",
16288 get: function get() {
16289 return this.result.css;
16290 }
16291 },
16292 {
16293 key: "map",
16294 get: function get() {
16295 return this.result.map;
16296 }
16297 },
16298 {
16299 key: "messages",
16300 get: function get() {
16301 return [];
16302 }
16303 },
16304 {
16305 key: "opts",
16306 get: function get() {
16307 return this.result.opts;
16308 }
16309 },
16310 {
16311 key: "processor",
16312 get: function get() {
16313 return this.result.processor;
16314 }
16315 },
16316 {
16317 key: "root",
16318 get: function get() {
16319 if (this._root) {
16320 return this._root;
16321 }
16322 var root2;
16323 var parser2 = parse$1;
16324 try {
16325 root2 = parser2(this._css, this._opts);
16326 } catch (error) {
16327 this.error = error;
16328 }
16329 if (this.error) {
16330 throw this.error;
16331 } else {
16332 this._root = root2;
16333 return root2;
16334 }
16335 }
16336 },
16337 {
16338 key: Symbol.toStringTag,
16339 get: function get() {
16340 return "NoWorkResult";
16341 }
16342 }
16343 ]);
16344 return NoWorkResult2;
16345 }();
16346 var noWorkResult = NoWorkResult$1;
16347 NoWorkResult$1.default = NoWorkResult$1;
16348 var NoWorkResult22 = noWorkResult;
16349 var LazyResult$1 = lazyResult;
16350 var Document$1 = document$1$2;
16351 var Root$2 = root;
16352 var Processor$1 = /*#__PURE__*/ function() {
16353 function Processor2(plugins) {
16354 if (plugins === void 0) plugins = [];
16355 this.version = "8.4.38";
16356 this.plugins = this.normalize(plugins);
16357 }
16358 var _proto = Processor2.prototype;
16359 _proto.normalize = function normalize(plugins) {
16360 var normalized = [];
16361 for(var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;){
16362 var i2 = _step.value;
16363 if (i2.postcss === true) {
16364 i2 = i2();
16365 } else if (i2.postcss) {
16366 i2 = i2.postcss;
16367 }
16368 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) {
16369 normalized = normalized.concat(i2.plugins);
16370 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) {
16371 normalized.push(i2);
16372 } else if (typeof i2 === "function") {
16373 normalized.push(i2);
16374 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) {
16375 if (true) {
16376 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.");
16377 }
16378 } else {
16379 throw new Error(i2 + " is not a PostCSS plugin");
16380 }
16381 }
16382 return normalized;
16383 };
16384 _proto.process = function process1(css, opts) {
16385 if (opts === void 0) opts = {};
16386 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
16387 return new NoWorkResult22(this, css, opts);
16388 } else {
16389 return new LazyResult$1(this, css, opts);
16390 }
16391 };
16392 _proto.use = function use(plugin22) {
16393 this.plugins = this.plugins.concat(this.normalize([
16394 plugin22
16395 ]));
16396 return this;
16397 };
16398 return Processor2;
16399 }();
16400 var processor = Processor$1;
16401 Processor$1.default = Processor$1;
16402 Root$2.registerProcessor(Processor$1);
16403 Document$1.registerProcessor(Processor$1);
16404 var Declaration$1 = declaration;
16405 var PreviousMap22 = previousMap;
16406 var Comment$1 = comment;
16407 var AtRule$1 = atRule;
16408 var Input$1 = input;
16409 var Root$1 = root;
16410 var Rule$1 = rule;
16411 function fromJSON$1(json, inputs) {
16412 if (Array.isArray(json)) return json.map(function(n2) {
16413 return fromJSON$1(n2);
16414 });
16415 var ownInputs = json.inputs, defaults = _object_without_properties_loose(json, [
16416 "inputs"
16417 ]);
16418 if (ownInputs) {
16419 inputs = [];
16420 for(var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;){
16421 var input2 = _step.value;
16422 var inputHydrated = _extends({}, input2, {
16423 __proto__: Input$1.prototype
16424 });
16425 if (inputHydrated.map) {
16426 inputHydrated.map = _extends({}, inputHydrated.map, {
16427 __proto__: PreviousMap22.prototype
16428 });
16429 }
16430 inputs.push(inputHydrated);
16431 }
16432 }
16433 if (defaults.nodes) {
16434 defaults.nodes = json.nodes.map(function(n2) {
16435 return fromJSON$1(n2, inputs);
16436 });
16437 }
16438 if (defaults.source) {
16439 var _defaults_source = defaults.source, inputId = _defaults_source.inputId, source = _object_without_properties_loose(_defaults_source, [
16440 "inputId"
16441 ]);
16442 defaults.source = source;
16443 if (inputId != null) {
16444 defaults.source.input = inputs[inputId];
16445 }
16446 }
16447 if (defaults.type === "root") {
16448 return new Root$1(defaults);
16449 } else if (defaults.type === "decl") {
16450 return new Declaration$1(defaults);
16451 } else if (defaults.type === "rule") {
16452 return new Rule$1(defaults);
16453 } else if (defaults.type === "comment") {
16454 return new Comment$1(defaults);
16455 } else if (defaults.type === "atrule") {
16456 return new AtRule$1(defaults);
16457 } else {
16458 throw new Error("Unknown node type: " + json.type);
16459 }
16460 }
16461 var fromJSON_1 = fromJSON$1;
16462 fromJSON$1.default = fromJSON$1;
16463 var CssSyntaxError22 = cssSyntaxError;
16464 var Declaration22 = declaration;
16465 var LazyResult22 = lazyResult;
16466 var Container22 = container;
16467 var Processor22 = processor;
16468 var stringify = stringify_1;
16469 var fromJSON = fromJSON_1;
16470 var Document222 = document$1$2;
16471 var Warning22 = warning;
16472 var Comment22 = comment;
16473 var AtRule22 = atRule;
16474 var Result22 = result;
16475 var Input22 = input;
16476 var parse = parse_1;
16477 var list = list_1;
16478 var Rule22 = rule;
16479 var Root22 = root;
16480 var Node22 = node;
16481 function postcss() {
16482 for(var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++){
16483 plugins[_key] = arguments[_key];
16484 }
16485 if (plugins.length === 1 && Array.isArray(plugins[0])) {
16486 plugins = plugins[0];
16487 }
16488 return new Processor22(plugins);
16489 }
16490 postcss.plugin = function plugin2(name, initializer) {
16491 var warningPrinted = false;
16492 function creator() {
16493 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
16494 args[_key] = arguments[_key];
16495 }
16496 if (console && console.warn && !warningPrinted) {
16497 warningPrinted = true;
16498 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
16499 if (process.env.LANG && process.env.LANG.startsWith("cn")) {
16500 console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
16501 }
16502 }
16503 var transformer = initializer.apply(void 0, [].concat(args));
16504 transformer.postcssPlugin = name;
16505 transformer.postcssVersion = new Processor22().version;
16506 return transformer;
16507 }
16508 var cache;
16509 Object.defineProperty(creator, "postcss", {
16510 get: function get() {
16511 if (!cache) cache = creator();
16512 return cache;
16513 }
16514 });
16515 creator.process = function(css, processOpts, pluginOpts) {
16516 return postcss([
16517 creator(pluginOpts)
16518 ]).process(css, processOpts);
16519 };
16520 return creator;
16521 };
16522 postcss.stringify = stringify;
16523 postcss.parse = parse;
16524 postcss.fromJSON = fromJSON;
16525 postcss.list = list;
16526 postcss.comment = function(defaults) {
16527 return new Comment22(defaults);
16528 };
16529 postcss.atRule = function(defaults) {
16530 return new AtRule22(defaults);
16531 };
16532 postcss.decl = function(defaults) {
16533 return new Declaration22(defaults);
16534 };
16535 postcss.rule = function(defaults) {
16536 return new Rule22(defaults);
16537 };
16538 postcss.root = function(defaults) {
16539 return new Root22(defaults);
16540 };
16541 postcss.document = function(defaults) {
16542 return new Document222(defaults);
16543 };
16544 postcss.CssSyntaxError = CssSyntaxError22;
16545 postcss.Declaration = Declaration22;
16546 postcss.Container = Container22;
16547 postcss.Processor = Processor22;
16548 postcss.Document = Document222;
16549 postcss.Comment = Comment22;
16550 postcss.Warning = Warning22;
16551 postcss.AtRule = AtRule22;
16552 postcss.Result = Result22;
16553 postcss.Input = Input22;
16554 postcss.Rule = Rule22;
16555 postcss.Root = Root22;
16556 postcss.Node = Node22;
16557 LazyResult22.registerPostcss(postcss);
16558 var postcss_1 = postcss;
16559 postcss.default = postcss;
16560 var postcss$1 = /* @__PURE__ */ getDefaultExportFromCjs(postcss_1);
16561 postcss$1.stringify;
16562 postcss$1.fromJSON;
16563 postcss$1.plugin;
16564 postcss$1.parse;
16565 postcss$1.list;
16566 postcss$1.document;
16567 postcss$1.comment;
16568 postcss$1.atRule;
16569 postcss$1.rule;
16570 postcss$1.decl;
16571 postcss$1.root;
16572 postcss$1.CssSyntaxError;
16573 postcss$1.Declaration;
16574 postcss$1.Container;
16575 postcss$1.Processor;
16576 postcss$1.Document;
16577 postcss$1.Comment;
16578 postcss$1.Warning;
16579 postcss$1.AtRule;
16580 postcss$1.Result;
16581 postcss$1.Input;
16582 postcss$1.Rule;
16583 postcss$1.Root;
16584 postcss$1.Node;
16585 var BaseRRNode = /*#__PURE__*/ function() {
16586 function BaseRRNode() {
16587 for(var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++){
16588 _args[_key] = arguments[_key];
16589 }
16590 __publicField2(this, "parentElement", null);
16591 __publicField2(this, "parentNode", null);
16592 __publicField2(this, "ownerDocument");
16593 __publicField2(this, "firstChild", null);
16594 __publicField2(this, "lastChild", null);
16595 __publicField2(this, "previousSibling", null);
16596 __publicField2(this, "nextSibling", null);
16597 __publicField2(this, "ELEMENT_NODE", 1);
16598 __publicField2(this, "TEXT_NODE", 3);
16599 __publicField2(this, "nodeType");
16600 __publicField2(this, "nodeName");
16601 __publicField2(this, "RRNodeType");
16602 }
16603 var _proto = BaseRRNode.prototype;
16604 _proto.contains = function contains(node2) {
16605 if (!_instanceof(node2, BaseRRNode)) return false;
16606 else if (node2.ownerDocument !== this.ownerDocument) return false;
16607 else if (node2 === this) return true;
16608 while(node2.parentNode){
16609 if (node2.parentNode === this) return true;
16610 node2 = node2.parentNode;
16611 }
16612 return false;
16613 };
16614 // eslint-disable-next-line @typescript-eslint/no-unused-vars
16615 _proto.appendChild = function appendChild(_newChild) {
16616 throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.");
16617 };
16618 // eslint-disable-next-line @typescript-eslint/no-unused-vars
16619 _proto.insertBefore = function insertBefore(_newChild, _refChild) {
16620 throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.");
16621 };
16622 // eslint-disable-next-line @typescript-eslint/no-unused-vars
16623 _proto.removeChild = function removeChild(_node) {
16624 throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.");
16625 };
16626 _proto.toString = function toString() {
16627 return "RRNode";
16628 };
16629 _create_class(BaseRRNode, [
16630 {
16631 key: "childNodes",
16632 get: function get() {
16633 var childNodes2 = [];
16634 var childIterator = this.firstChild;
16635 while(childIterator){
16636 childNodes2.push(childIterator);
16637 childIterator = childIterator.nextSibling;
16638 }
16639 return childNodes2;
16640 }
16641 }
16642 ]);
16643 return BaseRRNode;
16644 }();
16645 var testableAccessors = {
16646 Node: [
16647 "childNodes",
16648 "parentNode",
16649 "parentElement",
16650 "textContent"
16651 ],
16652 ShadowRoot: [
16653 "host",
16654 "styleSheets"
16655 ],
16656 Element: [
16657 "shadowRoot",
16658 "querySelector",
16659 "querySelectorAll"
16660 ],
16661 MutationObserver: []
16662 };
16663 var testableMethods = {
16664 Node: [
16665 "contains",
16666 "getRootNode"
16667 ],
16668 ShadowRoot: [
16669 "getSelection"
16670 ],
16671 Element: [],
16672 MutationObserver: [
16673 "constructor"
16674 ]
16675 };
16676 var untaintedBasePrototype = {};
16677 var isAngularZonePresent = function() {
16678 return !!globalThis.Zone;
16679 };
16680 function getUntaintedPrototype(key) {
16681 if (untaintedBasePrototype[key]) return untaintedBasePrototype[key];
16682 var defaultObj = globalThis[key];
16683 var defaultPrototype = defaultObj.prototype;
16684 var accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;
16685 var isUntaintedAccessors = Boolean(accessorNames && // @ts-expect-error 2345
16686 accessorNames.every(function(accessor) {
16687 var _a2, _b;
16688 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
16689 }));
16690 var methodNames = key in testableMethods ? testableMethods[key] : void 0;
16691 var isUntaintedMethods = Boolean(methodNames && methodNames.every(// @ts-expect-error 2345
16692 function(method) {
16693 var _a2;
16694 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
16695 }));
16696 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent()) {
16697 untaintedBasePrototype[key] = defaultObj.prototype;
16698 return defaultObj.prototype;
16699 }
16700 try {
16701 var iframeEl = document.createElement("iframe");
16702 document.body.appendChild(iframeEl);
16703 var win = iframeEl.contentWindow;
16704 if (!win) return defaultObj.prototype;
16705 var untaintedObject = win[key].prototype;
16706 document.body.removeChild(iframeEl);
16707 if (!untaintedObject) return defaultPrototype;
16708 return untaintedBasePrototype[key] = untaintedObject;
16709 } catch (e) {
16710 return defaultPrototype;
16711 }
16712 }
16713 var untaintedAccessorCache = {};
16714 function getUntaintedAccessor(key, instance, accessor) {
16715 var _a2;
16716 var cacheKey = key + "." + String(accessor);
16717 if (untaintedAccessorCache[cacheKey]) return untaintedAccessorCache[cacheKey].call(instance);
16718 var untaintedPrototype = getUntaintedPrototype(key);
16719 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
16720 if (!untaintedAccessor) return instance[accessor];
16721 untaintedAccessorCache[cacheKey] = untaintedAccessor;
16722 return untaintedAccessor.call(instance);
16723 }
16724 var untaintedMethodCache = {};
16725 function getUntaintedMethod(key, instance, method) {
16726 var cacheKey = key + "." + String(method);
16727 if (untaintedMethodCache[cacheKey]) return untaintedMethodCache[cacheKey].bind(instance);
16728 var untaintedPrototype = getUntaintedPrototype(key);
16729 var untaintedMethod = untaintedPrototype[method];
16730 if (typeof untaintedMethod !== "function") return instance[method];
16731 untaintedMethodCache[cacheKey] = untaintedMethod;
16732 return untaintedMethod.bind(instance);
16733 }
16734 function childNodes(n2) {
16735 return getUntaintedAccessor("Node", n2, "childNodes");
16736 }
16737 function parentNode(n2) {
16738 return getUntaintedAccessor("Node", n2, "parentNode");
16739 }
16740 function parentElement(n2) {
16741 return getUntaintedAccessor("Node", n2, "parentElement");
16742 }
16743 function textContent(n2) {
16744 return getUntaintedAccessor("Node", n2, "textContent");
16745 }
16746 function contains(n2, other) {
16747 return getUntaintedMethod("Node", n2, "contains")(other);
16748 }
16749 function getRootNode(n2) {
16750 return getUntaintedMethod("Node", n2, "getRootNode")();
16751 }
16752 function host(n2) {
16753 if (!n2 || !("host" in n2)) return null;
16754 return getUntaintedAccessor("ShadowRoot", n2, "host");
16755 }
16756 function styleSheets(n2) {
16757 return n2.styleSheets;
16758 }
16759 function shadowRoot(n2) {
16760 if (!n2 || !("shadowRoot" in n2)) return null;
16761 return getUntaintedAccessor("Element", n2, "shadowRoot");
16762 }
16763 function querySelector(n2, selectors) {
16764 return getUntaintedAccessor("Element", n2, "querySelector")(selectors);
16765 }
16766 function querySelectorAll(n2, selectors) {
16767 return getUntaintedAccessor("Element", n2, "querySelectorAll")(selectors);
16768 }
16769 function mutationObserverCtor() {
16770 return getUntaintedPrototype("MutationObserver").constructor;
16771 }
16772 function patch(source, name, replacement) {
16773 try {
16774 if (!(name in source)) {
16775 return function() {};
16776 }
16777 var original = source[name];
16778 var wrapped = replacement(original);
16779 if (typeof wrapped === "function") {
16780 wrapped.prototype = wrapped.prototype || {};
16781 Object.defineProperties(wrapped, {
16782 __rrweb_original__: {
16783 enumerable: false,
16784 value: original
16785 }
16786 });
16787 }
16788 source[name] = wrapped;
16789 return function() {
16790 source[name] = original;
16791 };
16792 } catch (e) {
16793 return function() {};
16794 }
16795 }
16796 var index = {
16797 childNodes: childNodes,
16798 parentNode: parentNode,
16799 parentElement: parentElement,
16800 textContent: textContent,
16801 contains: contains,
16802 getRootNode: getRootNode,
16803 host: host,
16804 styleSheets: styleSheets,
16805 shadowRoot: shadowRoot,
16806 querySelector: querySelector,
16807 querySelectorAll: querySelectorAll,
16808 mutationObserver: mutationObserverCtor,
16809 patch: patch
16810 };
16811 function on(type, fn, target) {
16812 if (target === void 0) target = document;
16813 var options = {
16814 capture: true,
16815 passive: true
16816 };
16817 target.addEventListener(type, fn, options);
16818 return function() {
16819 return target.removeEventListener(type, fn, options);
16820 };
16821 }
16822 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.";
16823 var _mirror = {
16824 map: {},
16825 getId: function getId() {
16826 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16827 return -1;
16828 },
16829 getNode: function getNode() {
16830 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16831 return null;
16832 },
16833 removeNodeFromMap: function removeNodeFromMap() {
16834 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16835 },
16836 has: function has() {
16837 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16838 return false;
16839 },
16840 reset: function reset() {
16841 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16842 }
16843 };
16844 if (typeof window !== "undefined" && window.Proxy && window.Reflect) {
16845 _mirror = new Proxy(_mirror, {
16846 get: function get(target, prop, receiver) {
16847 if (prop === "map") {
16848 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16849 }
16850 return Reflect.get(target, prop, receiver);
16851 }
16852 });
16853 }
16854 function throttle(func, wait, options) {
16855 if (options === void 0) options = {};
16856 var timeout = null;
16857 var previous = 0;
16858 return function() {
16859 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
16860 args[_key] = arguments[_key];
16861 }
16862 var now = Date.now();
16863 if (!previous && options.leading === false) {
16864 previous = now;
16865 }
16866 var remaining = wait - (now - previous);
16867 var context = this;
16868 if (remaining <= 0 || remaining > wait) {
16869 if (timeout) {
16870 clearTimeout(timeout);
16871 timeout = null;
16872 }
16873 previous = now;
16874 func.apply(context, args);
16875 } else if (!timeout && options.trailing !== false) {
16876 timeout = setTimeout(function() {
16877 previous = options.leading === false ? 0 : Date.now();
16878 timeout = null;
16879 func.apply(context, args);
16880 }, remaining);
16881 }
16882 };
16883 }
16884 function hookSetter(target, key, d, isRevoked, win) {
16885 if (win === void 0) win = window;
16886 var original = win.Object.getOwnPropertyDescriptor(target, key);
16887 win.Object.defineProperty(target, key, isRevoked ? d : {
16888 set: function set(value) {
16889 var _this = this;
16890 setTimeout(function() {
16891 d.set.call(_this, value);
16892 }, 0);
16893 if (original && original.set) {
16894 original.set.call(this, value);
16895 }
16896 }
16897 });
16898 return function() {
16899 return hookSetter(target, key, original || {}, true);
16900 };
16901 }
16902 var nowTimestamp = Date.now;
16903 if (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {
16904 nowTimestamp = function() {
16905 return /* @__PURE__ */ new Date().getTime();
16906 };
16907 }
16908 function getWindowScroll(win) {
16909 var _a2, _b, _c, _d;
16910 var doc = win.document;
16911 return {
16912 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,
16913 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
16914 };
16915 }
16916 function getWindowHeight() {
16917 return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
16918 }
16919 function getWindowWidth() {
16920 return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
16921 }
16922 function closestElementOfNode(node2) {
16923 if (!node2) {
16924 return null;
16925 }
16926 var el = node2.nodeType === node2.ELEMENT_NODE ? node2 : index.parentElement(node2);
16927 return el;
16928 }
16929 function isBlocked(node2, blockClass, blockSelector, checkAncestors) {
16930 if (!node2) {
16931 return false;
16932 }
16933 var el = closestElementOfNode(node2);
16934 if (!el) {
16935 return false;
16936 }
16937 try {
16938 if (typeof blockClass === "string") {
16939 if (el.classList.contains(blockClass)) return true;
16940 if (checkAncestors && el.closest("." + blockClass) !== null) return true;
16941 } else {
16942 if (classMatchesRegex(el, blockClass, checkAncestors)) return true;
16943 }
16944 } catch (e2) {}
16945 if (blockSelector) {
16946 if (el.matches(blockSelector)) return true;
16947 if (checkAncestors && el.closest(blockSelector) !== null) return true;
16948 }
16949 return false;
16950 }
16951 function isSerialized(n2, mirror2) {
16952 return mirror2.getId(n2) !== -1;
16953 }
16954 function isIgnored(n2, mirror2, slimDOMOptions) {
16955 if (n2.tagName === "TITLE" && slimDOMOptions.headTitleMutations) {
16956 return true;
16957 }
16958 return mirror2.getId(n2) === IGNORED_NODE;
16959 }
16960 function isAncestorRemoved(target, mirror2) {
16961 if (isShadowRoot(target)) {
16962 return false;
16963 }
16964 var id = mirror2.getId(target);
16965 if (!mirror2.has(id)) {
16966 return true;
16967 }
16968 var parent = index.parentNode(target);
16969 if (parent && parent.nodeType === target.DOCUMENT_NODE) {
16970 return false;
16971 }
16972 if (!parent) {
16973 return true;
16974 }
16975 return isAncestorRemoved(parent, mirror2);
16976 }
16977 function legacy_isTouchEvent(event) {
16978 return Boolean(event.changedTouches);
16979 }
16980 function polyfill$1(win) {
16981 if (win === void 0) win = window;
16982 if ("NodeList" in win && !win.NodeList.prototype.forEach) {
16983 win.NodeList.prototype.forEach = Array.prototype.forEach;
16984 }
16985 if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) {
16986 win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
16987 }
16988 }
16989 function isSerializedIframe(n2, mirror2) {
16990 return Boolean(n2.nodeName === "IFRAME" && mirror2.getMeta(n2));
16991 }
16992 function isSerializedStylesheet(n2, mirror2) {
16993 return Boolean(n2.nodeName === "LINK" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute("rel") === "stylesheet" && mirror2.getMeta(n2));
16994 }
16995 function hasShadowRoot(n2) {
16996 if (!n2) return false;
16997 if (_instanceof(n2, BaseRRNode) && "shadowRoot" in n2) {
16998 return Boolean(n2.shadowRoot);
16999 }
17000 return Boolean(index.shadowRoot(n2));
17001 }
17002 var StyleSheetMirror = /*#__PURE__*/ function() {
17003 function StyleSheetMirror() {
17004 __publicField(this, "id", 1);
17005 __publicField(this, "styleIDMap", /* @__PURE__ */ new WeakMap());
17006 __publicField(this, "idStyleMap", /* @__PURE__ */ new Map());
17007 }
17008 var _proto = StyleSheetMirror.prototype;
17009 _proto.getId = function getId(stylesheet) {
17010 var _this_styleIDMap_get;
17011 return (_this_styleIDMap_get = this.styleIDMap.get(stylesheet)) != null ? _this_styleIDMap_get : -1;
17012 };
17013 _proto.has = function has(stylesheet) {
17014 return this.styleIDMap.has(stylesheet);
17015 };
17016 /**
17017 * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.
17018 */ _proto.add = function add(stylesheet, id) {
17019 if (this.has(stylesheet)) return this.getId(stylesheet);
17020 var newId;
17021 if (id === void 0) {
17022 newId = this.id++;
17023 } else newId = id;
17024 this.styleIDMap.set(stylesheet, newId);
17025 this.idStyleMap.set(newId, stylesheet);
17026 return newId;
17027 };
17028 _proto.getStyle = function getStyle(id) {
17029 return this.idStyleMap.get(id) || null;
17030 };
17031 _proto.reset = function reset() {
17032 this.styleIDMap = /* @__PURE__ */ new WeakMap();
17033 this.idStyleMap = /* @__PURE__ */ new Map();
17034 this.id = 1;
17035 };
17036 _proto.generateId = function generateId() {
17037 return this.id++;
17038 };
17039 return StyleSheetMirror;
17040 }();
17041 function getShadowHost(n2) {
17042 var _a2;
17043 var shadowHost = null;
17044 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));
17045 return shadowHost;
17046 }
17047 function getRootShadowHost(n2) {
17048 var rootShadowHost = n2;
17049 var shadowHost;
17050 while(shadowHost = getShadowHost(rootShadowHost))rootShadowHost = shadowHost;
17051 return rootShadowHost;
17052 }
17053 function shadowHostInDom(n2) {
17054 var doc = n2.ownerDocument;
17055 if (!doc) return false;
17056 var shadowHost = getRootShadowHost(n2);
17057 return index.contains(doc, shadowHost);
17058 }
17059 function inDom(n2) {
17060 var doc = n2.ownerDocument;
17061 if (!doc) return false;
17062 return index.contains(doc, n2) || shadowHostInDom(n2);
17063 }
17064 var EventType = /* @__PURE__ */ function(EventType2) {
17065 EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
17066 EventType2[EventType2["Load"] = 1] = "Load";
17067 EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
17068 EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
17069 EventType2[EventType2["Meta"] = 4] = "Meta";
17070 EventType2[EventType2["Custom"] = 5] = "Custom";
17071 EventType2[EventType2["Plugin"] = 6] = "Plugin";
17072 return EventType2;
17073 }(EventType || {});
17074 var IncrementalSource = /* @__PURE__ */ function(IncrementalSource2) {
17075 IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
17076 IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
17077 IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
17078 IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
17079 IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
17080 IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
17081 IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
17082 IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
17083 IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
17084 IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
17085 IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
17086 IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
17087 IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
17088 IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
17089 IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
17090 IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
17091 IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement";
17092 return IncrementalSource2;
17093 }(IncrementalSource || {});
17094 var MouseInteractions = /* @__PURE__ */ function(MouseInteractions2) {
17095 MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
17096 MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
17097 MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
17098 MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
17099 MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
17100 MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
17101 MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
17102 MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
17103 MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
17104 MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
17105 MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
17106 return MouseInteractions2;
17107 }(MouseInteractions || {});
17108 var PointerTypes = /* @__PURE__ */ function(PointerTypes2) {
17109 PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse";
17110 PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen";
17111 PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch";
17112 return PointerTypes2;
17113 }(PointerTypes || {});
17114 var CanvasContext = /* @__PURE__ */ function(CanvasContext2) {
17115 CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
17116 CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
17117 CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
17118 return CanvasContext2;
17119 }(CanvasContext || {});
17120 var MediaInteractions = /* @__PURE__ */ function(MediaInteractions2) {
17121 MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play";
17122 MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause";
17123 MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked";
17124 MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange";
17125 MediaInteractions2[MediaInteractions2["RateChange"] = 4] = "RateChange";
17126 return MediaInteractions2;
17127 }(MediaInteractions || {});
17128 var NodeType = /* @__PURE__ */ function(NodeType2) {
17129 NodeType2[NodeType2["Document"] = 0] = "Document";
17130 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
17131 NodeType2[NodeType2["Element"] = 2] = "Element";
17132 NodeType2[NodeType2["Text"] = 3] = "Text";
17133 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
17134 NodeType2[NodeType2["Comment"] = 5] = "Comment";
17135 return NodeType2;
17136 }(NodeType || {});
17137 function isNodeInLinkedList(n2) {
17138 return "__ln" in n2;
17139 }
17140 var DoubleLinkedList = /*#__PURE__*/ function() {
17141 function DoubleLinkedList() {
17142 __publicField(this, "length", 0);
17143 __publicField(this, "head", null);
17144 __publicField(this, "tail", null);
17145 }
17146 var _proto = DoubleLinkedList.prototype;
17147 _proto.get = function get(position) {
17148 if (position >= this.length) {
17149 throw new Error("Position outside of list range");
17150 }
17151 var current = this.head;
17152 for(var index2 = 0; index2 < position; index2++){
17153 current = (current == null ? void 0 : current.next) || null;
17154 }
17155 return current;
17156 };
17157 _proto.addNode = function addNode(n2) {
17158 var node2 = {
17159 value: n2,
17160 previous: null,
17161 next: null
17162 };
17163 n2.__ln = node2;
17164 if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {
17165 var current = n2.previousSibling.__ln.next;
17166 node2.next = current;
17167 node2.previous = n2.previousSibling.__ln;
17168 n2.previousSibling.__ln.next = node2;
17169 if (current) {
17170 current.previous = node2;
17171 }
17172 } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {
17173 var current1 = n2.nextSibling.__ln.previous;
17174 node2.previous = current1;
17175 node2.next = n2.nextSibling.__ln;
17176 n2.nextSibling.__ln.previous = node2;
17177 if (current1) {
17178 current1.next = node2;
17179 }
17180 } else {
17181 if (this.head) {
17182 this.head.previous = node2;
17183 }
17184 node2.next = this.head;
17185 this.head = node2;
17186 }
17187 if (node2.next === null) {
17188 this.tail = node2;
17189 }
17190 this.length++;
17191 };
17192 _proto.removeNode = function removeNode(n2) {
17193 var current = n2.__ln;
17194 if (!this.head) {
17195 return;
17196 }
17197 if (!current.previous) {
17198 this.head = current.next;
17199 if (this.head) {
17200 this.head.previous = null;
17201 } else {
17202 this.tail = null;
17203 }
17204 } else {
17205 current.previous.next = current.next;
17206 if (current.next) {
17207 current.next.previous = current.previous;
17208 } else {
17209 this.tail = current.previous;
17210 }
17211 }
17212 if (n2.__ln) {
17213 delete n2.__ln;
17214 }
17215 this.length--;
17216 };
17217 return DoubleLinkedList;
17218 }();
17219 var moveKey = function(id, parentId) {
17220 return id + "@" + parentId;
17221 };
17222 var MutationBuffer = /*#__PURE__*/ function() {
17223 function MutationBuffer() {
17224 var _this = this;
17225 __publicField(this, "frozen", false);
17226 __publicField(this, "locked", false);
17227 __publicField(this, "texts", []);
17228 __publicField(this, "attributes", []);
17229 __publicField(this, "attributeMap", /* @__PURE__ */ new WeakMap());
17230 __publicField(this, "removes", []);
17231 __publicField(this, "mapRemoves", []);
17232 __publicField(this, "movedMap", {});
17233 /**
17234 * the browser MutationObserver emits multiple mutations after
17235 * a delay for performance reasons, making tracing added nodes hard
17236 * in our `processMutations` callback function.
17237 * For example, if we append an element el_1 into body, and then append
17238 * another element el_2 into el_1, these two mutations may be passed to the
17239 * callback function together when the two operations were done.
17240 * Generally we need to trace child nodes of newly added nodes, but in this
17241 * case if we count el_2 as el_1's child node in the first mutation record,
17242 * then we will count el_2 again in the second mutation record which was
17243 * duplicated.
17244 * To avoid of duplicate counting added nodes, we use a Set to store
17245 * added nodes and its child nodes during iterate mutation records. Then
17246 * collect added nodes from the Set which have no duplicate copy. But
17247 * this also causes newly added nodes will not be serialized with id ASAP,
17248 * which means all the id related calculation should be lazy too.
17249 */ __publicField(this, "addedSet", /* @__PURE__ */ new Set());
17250 __publicField(this, "movedSet", /* @__PURE__ */ new Set());
17251 __publicField(this, "droppedSet", /* @__PURE__ */ new Set());
17252 __publicField(this, "removesSubTreeCache", /* @__PURE__ */ new Set());
17253 __publicField(this, "mutationCb");
17254 __publicField(this, "blockClass");
17255 __publicField(this, "blockSelector");
17256 __publicField(this, "maskTextClass");
17257 __publicField(this, "maskTextSelector");
17258 __publicField(this, "inlineStylesheet");
17259 __publicField(this, "maskInputOptions");
17260 __publicField(this, "maskTextFn");
17261 __publicField(this, "maskInputFn");
17262 __publicField(this, "keepIframeSrcFn");
17263 __publicField(this, "recordCanvas");
17264 __publicField(this, "inlineImages");
17265 __publicField(this, "slimDOMOptions");
17266 __publicField(this, "dataURLOptions");
17267 __publicField(this, "doc");
17268 __publicField(this, "mirror");
17269 __publicField(this, "iframeManager");
17270 __publicField(this, "stylesheetManager");
17271 __publicField(this, "shadowDomManager");
17272 __publicField(this, "canvasManager");
17273 __publicField(this, "processedNodeManager");
17274 __publicField(this, "unattachedDoc");
17275 __publicField(this, "processMutations", function(mutations) {
17276 mutations.forEach(_this.processMutation);
17277 _this.emit();
17278 });
17279 __publicField(this, "emit", function() {
17280 if (_this.frozen || _this.locked) {
17281 return;
17282 }
17283 var adds = [];
17284 var addedIds = /* @__PURE__ */ new Set();
17285 var addList = new DoubleLinkedList();
17286 var getNextId = function(n2) {
17287 var ns = n2;
17288 var nextId = IGNORED_NODE;
17289 while(nextId === IGNORED_NODE){
17290 ns = ns && ns.nextSibling;
17291 nextId = ns && _this.mirror.getId(ns);
17292 }
17293 return nextId;
17294 };
17295 var pushAdd = function(n2) {
17296 var parent = index.parentNode(n2);
17297 if (!parent || !inDom(n2)) {
17298 return;
17299 }
17300 var cssCaptured = false;
17301 if (n2.nodeType === Node.TEXT_NODE) {
17302 var parentTag = parent.tagName;
17303 if (parentTag === "TEXTAREA") {
17304 return;
17305 } else if (parentTag === "STYLE" && _this.addedSet.has(parent)) {
17306 cssCaptured = true;
17307 }
17308 }
17309 var parentId = isShadowRoot(parent) ? _this.mirror.getId(getShadowHost(n2)) : _this.mirror.getId(parent);
17310 var nextId = getNextId(n2);
17311 if (parentId === -1 || nextId === -1) {
17312 return addList.addNode(n2);
17313 }
17314 var sn = serializeNodeWithId(n2, {
17315 doc: _this.doc,
17316 mirror: _this.mirror,
17317 blockClass: _this.blockClass,
17318 blockSelector: _this.blockSelector,
17319 maskTextClass: _this.maskTextClass,
17320 maskTextSelector: _this.maskTextSelector,
17321 skipChild: true,
17322 newlyAddedElement: true,
17323 inlineStylesheet: _this.inlineStylesheet,
17324 maskInputOptions: _this.maskInputOptions,
17325 maskTextFn: _this.maskTextFn,
17326 maskInputFn: _this.maskInputFn,
17327 slimDOMOptions: _this.slimDOMOptions,
17328 dataURLOptions: _this.dataURLOptions,
17329 recordCanvas: _this.recordCanvas,
17330 inlineImages: _this.inlineImages,
17331 onSerialize: function(currentN) {
17332 if (isSerializedIframe(currentN, _this.mirror)) {
17333 _this.iframeManager.addIframe(currentN);
17334 }
17335 if (isSerializedStylesheet(currentN, _this.mirror)) {
17336 _this.stylesheetManager.trackLinkElement(currentN);
17337 }
17338 if (hasShadowRoot(n2)) {
17339 _this.shadowDomManager.addShadowRoot(index.shadowRoot(n2), _this.doc);
17340 }
17341 },
17342 onIframeLoad: function(iframe, childSn) {
17343 _this.iframeManager.attachIframe(iframe, childSn);
17344 _this.shadowDomManager.observeAttachShadow(iframe);
17345 },
17346 onStylesheetLoad: function(link, childSn) {
17347 _this.stylesheetManager.attachLinkElement(link, childSn);
17348 },
17349 cssCaptured: cssCaptured
17350 });
17351 if (sn) {
17352 adds.push({
17353 parentId: parentId,
17354 nextId: nextId,
17355 node: sn
17356 });
17357 addedIds.add(sn.id);
17358 }
17359 };
17360 while(_this.mapRemoves.length){
17361 _this.mirror.removeNodeFromMap(_this.mapRemoves.shift());
17362 }
17363 for(var _iterator = _create_for_of_iterator_helper_loose(_this.movedSet), _step; !(_step = _iterator()).done;){
17364 var n2 = _step.value;
17365 if (isParentRemoved(_this.removesSubTreeCache, n2, _this.mirror) && !_this.movedSet.has(index.parentNode(n2))) {
17366 continue;
17367 }
17368 pushAdd(n2);
17369 }
17370 for(var _iterator1 = _create_for_of_iterator_helper_loose(_this.addedSet), _step1; !(_step1 = _iterator1()).done;){
17371 var n21 = _step1.value;
17372 if (!isAncestorInSet(_this.droppedSet, n21) && !isParentRemoved(_this.removesSubTreeCache, n21, _this.mirror)) {
17373 pushAdd(n21);
17374 } else if (isAncestorInSet(_this.movedSet, n21)) {
17375 pushAdd(n21);
17376 } else {
17377 _this.droppedSet.add(n21);
17378 }
17379 }
17380 var candidate = null;
17381 while(addList.length){
17382 var node2 = null;
17383 if (candidate) {
17384 var parentId = _this.mirror.getId(index.parentNode(candidate.value));
17385 var nextId = getNextId(candidate.value);
17386 if (parentId !== -1 && nextId !== -1) {
17387 node2 = candidate;
17388 }
17389 }
17390 if (!node2) {
17391 var tailNode = addList.tail;
17392 while(tailNode){
17393 var _node = tailNode;
17394 tailNode = tailNode.previous;
17395 if (_node) {
17396 var parentId1 = _this.mirror.getId(index.parentNode(_node.value));
17397 var nextId1 = getNextId(_node.value);
17398 if (nextId1 === -1) continue;
17399 else if (parentId1 !== -1) {
17400 node2 = _node;
17401 break;
17402 } else {
17403 var unhandledNode = _node.value;
17404 var parent = index.parentNode(unhandledNode);
17405 if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
17406 var shadowHost = index.host(parent);
17407 var parentId2 = _this.mirror.getId(shadowHost);
17408 if (parentId2 !== -1) {
17409 node2 = _node;
17410 break;
17411 }
17412 }
17413 }
17414 }
17415 }
17416 }
17417 if (!node2) {
17418 while(addList.head){
17419 addList.removeNode(addList.head.value);
17420 }
17421 break;
17422 }
17423 candidate = node2.previous;
17424 addList.removeNode(node2.value);
17425 pushAdd(node2.value);
17426 }
17427 var payload = {
17428 texts: _this.texts.map(function(text) {
17429 var n2 = text.node;
17430 var parent = index.parentNode(n2);
17431 if (parent && parent.tagName === "TEXTAREA") {
17432 _this.genTextAreaValueMutation(parent);
17433 }
17434 return {
17435 id: _this.mirror.getId(n2),
17436 value: text.value
17437 };
17438 }).filter(function(text) {
17439 return !addedIds.has(text.id);
17440 }).filter(function(text) {
17441 return _this.mirror.has(text.id);
17442 }),
17443 attributes: _this.attributes.map(function(attribute) {
17444 var attributes = attribute.attributes;
17445 if (typeof attributes.style === "string") {
17446 var diffAsStr = JSON.stringify(attribute.styleDiff);
17447 var unchangedAsStr = JSON.stringify(attribute._unchangedStyles);
17448 if (diffAsStr.length < attributes.style.length) {
17449 if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) {
17450 attributes.style = attribute.styleDiff;
17451 }
17452 }
17453 }
17454 return {
17455 id: _this.mirror.getId(attribute.node),
17456 attributes: attributes
17457 };
17458 }).filter(function(attribute) {
17459 return !addedIds.has(attribute.id);
17460 }).filter(function(attribute) {
17461 return _this.mirror.has(attribute.id);
17462 }),
17463 removes: _this.removes,
17464 adds: adds
17465 };
17466 if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {
17467 return;
17468 }
17469 _this.texts = [];
17470 _this.attributes = [];
17471 _this.attributeMap = /* @__PURE__ */ new WeakMap();
17472 _this.removes = [];
17473 _this.addedSet = /* @__PURE__ */ new Set();
17474 _this.movedSet = /* @__PURE__ */ new Set();
17475 _this.droppedSet = /* @__PURE__ */ new Set();
17476 _this.removesSubTreeCache = /* @__PURE__ */ new Set();
17477 _this.movedMap = {};
17478 _this.mutationCb(payload);
17479 });
17480 __publicField(this, "genTextAreaValueMutation", function(textarea) {
17481 var item = _this.attributeMap.get(textarea);
17482 if (!item) {
17483 item = {
17484 node: textarea,
17485 attributes: {},
17486 styleDiff: {},
17487 _unchangedStyles: {}
17488 };
17489 _this.attributes.push(item);
17490 _this.attributeMap.set(textarea, item);
17491 }
17492 var value = Array.from(index.childNodes(textarea), function(cn) {
17493 return index.textContent(cn) || "";
17494 }).join("");
17495 item.attributes.value = maskInputValue({
17496 element: textarea,
17497 maskInputOptions: _this.maskInputOptions,
17498 tagName: textarea.tagName,
17499 type: getInputType(textarea),
17500 value: value,
17501 maskInputFn: _this.maskInputFn
17502 });
17503 });
17504 __publicField(this, "processMutation", function(m) {
17505 if (isIgnored(m.target, _this.mirror, _this.slimDOMOptions)) {
17506 return;
17507 }
17508 switch(m.type){
17509 case "characterData":
17510 {
17511 var value = index.textContent(m.target);
17512 if (!isBlocked(m.target, _this.blockClass, _this.blockSelector, false) && value !== m.oldValue) {
17513 _this.texts.push({
17514 value: needMaskingText(m.target, _this.maskTextClass, _this.maskTextSelector, true) && value ? _this.maskTextFn ? _this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\S]/g, "*") : value,
17515 node: m.target
17516 });
17517 }
17518 break;
17519 }
17520 case "attributes":
17521 {
17522 var target = m.target;
17523 var attributeName = m.attributeName;
17524 var value1 = m.target.getAttribute(attributeName);
17525 if (attributeName === "value") {
17526 var type = getInputType(target);
17527 value1 = maskInputValue({
17528 element: target,
17529 maskInputOptions: _this.maskInputOptions,
17530 tagName: target.tagName,
17531 type: type,
17532 value: value1,
17533 maskInputFn: _this.maskInputFn
17534 });
17535 }
17536 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || value1 === m.oldValue) {
17537 return;
17538 }
17539 var item = _this.attributeMap.get(m.target);
17540 if (target.tagName === "IFRAME" && attributeName === "src" && !_this.keepIframeSrcFn(value1)) {
17541 if (!target.contentDocument) {
17542 attributeName = "rr_src";
17543 } else {
17544 return;
17545 }
17546 }
17547 if (!item) {
17548 item = {
17549 node: m.target,
17550 attributes: {},
17551 styleDiff: {},
17552 _unchangedStyles: {}
17553 };
17554 _this.attributes.push(item);
17555 _this.attributeMap.set(m.target, item);
17556 }
17557 if (attributeName === "type" && target.tagName === "INPUT" && (m.oldValue || "").toLowerCase() === "password") {
17558 target.setAttribute("data-rr-is-password", "true");
17559 }
17560 if (!ignoreAttribute(target.tagName, attributeName)) {
17561 item.attributes[attributeName] = transformAttribute(_this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value1);
17562 if (attributeName === "style") {
17563 if (!_this.unattachedDoc) {
17564 try {
17565 _this.unattachedDoc = document.implementation.createHTMLDocument();
17566 } catch (e2) {
17567 _this.unattachedDoc = _this.doc;
17568 }
17569 }
17570 var old = _this.unattachedDoc.createElement("span");
17571 if (m.oldValue) {
17572 old.setAttribute("style", m.oldValue);
17573 }
17574 for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(target.style)), _step; !(_step = _iterator()).done;){
17575 var pname = _step.value;
17576 var newValue = target.style.getPropertyValue(pname);
17577 var newPriority = target.style.getPropertyPriority(pname);
17578 if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {
17579 if (newPriority === "") {
17580 item.styleDiff[pname] = newValue;
17581 } else {
17582 item.styleDiff[pname] = [
17583 newValue,
17584 newPriority
17585 ];
17586 }
17587 } else {
17588 item._unchangedStyles[pname] = [
17589 newValue,
17590 newPriority
17591 ];
17592 }
17593 }
17594 for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(old.style)), _step1; !(_step1 = _iterator1()).done;){
17595 var pname1 = _step1.value;
17596 if (target.style.getPropertyValue(pname1) === "") {
17597 item.styleDiff[pname1] = false;
17598 }
17599 }
17600 } else if (attributeName === "open" && target.tagName === "DIALOG") {
17601 if (target.matches("dialog:modal")) {
17602 item.attributes["rr_open_mode"] = "modal";
17603 } else {
17604 item.attributes["rr_open_mode"] = "non-modal";
17605 }
17606 }
17607 }
17608 break;
17609 }
17610 case "childList":
17611 {
17612 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, true)) return;
17613 if (m.target.tagName === "TEXTAREA") {
17614 _this.genTextAreaValueMutation(m.target);
17615 return;
17616 }
17617 m.addedNodes.forEach(function(n2) {
17618 return _this.genAdds(n2, m.target);
17619 });
17620 m.removedNodes.forEach(function(n2) {
17621 var nodeId = _this.mirror.getId(n2);
17622 var parentId = isShadowRoot(m.target) ? _this.mirror.getId(index.host(m.target)) : _this.mirror.getId(m.target);
17623 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || isIgnored(n2, _this.mirror, _this.slimDOMOptions) || !isSerialized(n2, _this.mirror)) {
17624 return;
17625 }
17626 if (_this.addedSet.has(n2)) {
17627 deepDelete(_this.addedSet, n2);
17628 _this.droppedSet.add(n2);
17629 } else if (_this.addedSet.has(m.target) && nodeId === -1) ;
17630 else if (isAncestorRemoved(m.target, _this.mirror)) ;
17631 else if (_this.movedSet.has(n2) && _this.movedMap[moveKey(nodeId, parentId)]) {
17632 deepDelete(_this.movedSet, n2);
17633 } else {
17634 _this.removes.push({
17635 parentId: parentId,
17636 id: nodeId,
17637 isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0
17638 });
17639 processRemoves(n2, _this.removesSubTreeCache);
17640 }
17641 _this.mapRemoves.push(n2);
17642 });
17643 break;
17644 }
17645 }
17646 });
17647 /**
17648 * Make sure you check if `n`'s parent is blocked before calling this function
17649 * */ __publicField(this, "genAdds", function(n2, target) {
17650 if (_this.processedNodeManager.inOtherBuffer(n2, _this)) return;
17651 if (_this.addedSet.has(n2) || _this.movedSet.has(n2)) return;
17652 if (_this.mirror.hasNode(n2)) {
17653 if (isIgnored(n2, _this.mirror, _this.slimDOMOptions)) {
17654 return;
17655 }
17656 _this.movedSet.add(n2);
17657 var targetId = null;
17658 if (target && _this.mirror.hasNode(target)) {
17659 targetId = _this.mirror.getId(target);
17660 }
17661 if (targetId && targetId !== -1) {
17662 _this.movedMap[moveKey(_this.mirror.getId(n2), targetId)] = true;
17663 }
17664 } else {
17665 _this.addedSet.add(n2);
17666 _this.droppedSet.delete(n2);
17667 }
17668 if (!isBlocked(n2, _this.blockClass, _this.blockSelector, false)) {
17669 index.childNodes(n2).forEach(function(childN) {
17670 return _this.genAdds(childN);
17671 });
17672 if (hasShadowRoot(n2)) {
17673 index.childNodes(index.shadowRoot(n2)).forEach(function(childN) {
17674 _this.processedNodeManager.add(childN, _this);
17675 _this.genAdds(childN, n2);
17676 });
17677 }
17678 }
17679 });
17680 }
17681 var _proto = MutationBuffer.prototype;
17682 _proto.init = function init(options) {
17683 var _this = this;
17684 [
17685 "mutationCb",
17686 "blockClass",
17687 "blockSelector",
17688 "maskTextClass",
17689 "maskTextSelector",
17690 "inlineStylesheet",
17691 "maskInputOptions",
17692 "maskTextFn",
17693 "maskInputFn",
17694 "keepIframeSrcFn",
17695 "recordCanvas",
17696 "inlineImages",
17697 "slimDOMOptions",
17698 "dataURLOptions",
17699 "doc",
17700 "mirror",
17701 "iframeManager",
17702 "stylesheetManager",
17703 "shadowDomManager",
17704 "canvasManager",
17705 "processedNodeManager"
17706 ].forEach(function(key) {
17707 _this[key] = options[key];
17708 });
17709 };
17710 _proto.freeze = function freeze() {
17711 this.frozen = true;
17712 this.canvasManager.freeze();
17713 };
17714 _proto.unfreeze = function unfreeze() {
17715 this.frozen = false;
17716 this.canvasManager.unfreeze();
17717 this.emit();
17718 };
17719 _proto.isFrozen = function isFrozen() {
17720 return this.frozen;
17721 };
17722 _proto.lock = function lock() {
17723 this.locked = true;
17724 this.canvasManager.lock();
17725 };
17726 _proto.unlock = function unlock() {
17727 this.locked = false;
17728 this.canvasManager.unlock();
17729 this.emit();
17730 };
17731 _proto.reset = function reset() {
17732 this.shadowDomManager.reset();
17733 this.canvasManager.reset();
17734 };
17735 return MutationBuffer;
17736 }();
17737 function deepDelete(addsSet, n2) {
17738 addsSet.delete(n2);
17739 index.childNodes(n2).forEach(function(childN) {
17740 return deepDelete(addsSet, childN);
17741 });
17742 }
17743 function processRemoves(n2, cache) {
17744 var queue = [
17745 n2
17746 ];
17747 while(queue.length){
17748 var next = queue.pop();
17749 if (cache.has(next)) continue;
17750 cache.add(next);
17751 index.childNodes(next).forEach(function(n22) {
17752 return queue.push(n22);
17753 });
17754 }
17755 return;
17756 }
17757 function isParentRemoved(removes, n2, mirror2) {
17758 if (removes.size === 0) return false;
17759 return _isParentRemoved(removes, n2);
17760 }
17761 function _isParentRemoved(removes, n2, _mirror2) {
17762 var node2 = index.parentNode(n2);
17763 if (!node2) return false;
17764 return removes.has(node2);
17765 }
17766 function isAncestorInSet(set, n2) {
17767 if (set.size === 0) return false;
17768 return _isAncestorInSet(set, n2);
17769 }
17770 function _isAncestorInSet(set, n2) {
17771 var parent = index.parentNode(n2);
17772 if (!parent) {
17773 return false;
17774 }
17775 if (set.has(parent)) {
17776 return true;
17777 }
17778 return _isAncestorInSet(set, parent);
17779 }
17780 var errorHandler;
17781 function registerErrorHandler(handler) {
17782 errorHandler = handler;
17783 }
17784 function unregisterErrorHandler() {
17785 errorHandler = void 0;
17786 }
17787 var callbackWrapper = function(cb) {
17788 if (!errorHandler) {
17789 return cb;
17790 }
17791 var rrwebWrapped = function() {
17792 for(var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++){
17793 rest[_key] = arguments[_key];
17794 }
17795 try {
17796 return cb.apply(void 0, [].concat(rest));
17797 } catch (error) {
17798 if (errorHandler && errorHandler(error) === true) {
17799 return;
17800 }
17801 throw error;
17802 }
17803 };
17804 return rrwebWrapped;
17805 };
17806 var mutationBuffers = [];
17807 function getEventTarget(event) {
17808 try {
17809 if ("composedPath" in event) {
17810 var path = event.composedPath();
17811 if (path.length) {
17812 return path[0];
17813 }
17814 } else if ("path" in event && event.path.length) {
17815 return event.path[0];
17816 }
17817 } catch (e) {}
17818 return event && event.target;
17819 }
17820 function initMutationObserver(options, rootEl) {
17821 var mutationBuffer = new MutationBuffer();
17822 mutationBuffers.push(mutationBuffer);
17823 mutationBuffer.init(options);
17824 var observer = new (mutationObserverCtor())(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));
17825 observer.observe(rootEl, {
17826 attributes: true,
17827 attributeOldValue: true,
17828 characterData: true,
17829 characterDataOldValue: true,
17830 childList: true,
17831 subtree: true
17832 });
17833 return observer;
17834 }
17835 function initMoveObserver(param) {
17836 var mousemoveCb = param.mousemoveCb, sampling = param.sampling, doc = param.doc, mirror2 = param.mirror;
17837 if (sampling.mousemove === false) {
17838 return function() {};
17839 }
17840 var threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50;
17841 var callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500;
17842 var positions = [];
17843 var timeBaseline;
17844 var wrappedCb = throttle(callbackWrapper(function(source) {
17845 var totalOffset = Date.now() - timeBaseline;
17846 mousemoveCb(positions.map(function(p) {
17847 p.timeOffset -= totalOffset;
17848 return p;
17849 }), source);
17850 positions = [];
17851 timeBaseline = null;
17852 }), callbackThreshold);
17853 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
17854 var target = getEventTarget(evt);
17855 var _ref = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt, clientX = _ref.clientX, clientY = _ref.clientY;
17856 if (!timeBaseline) {
17857 timeBaseline = nowTimestamp();
17858 }
17859 positions.push({
17860 x: clientX,
17861 y: clientY,
17862 id: mirror2.getId(target),
17863 timeOffset: nowTimestamp() - timeBaseline
17864 });
17865 wrappedCb(typeof DragEvent !== "undefined" && _instanceof(evt, DragEvent) ? IncrementalSource.Drag : _instanceof(evt, MouseEvent) ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
17866 }), threshold, {
17867 trailing: false
17868 }));
17869 var handlers = [
17870 on("mousemove", updatePosition, doc),
17871 on("touchmove", updatePosition, doc),
17872 on("drag", updatePosition, doc)
17873 ];
17874 return callbackWrapper(function() {
17875 handlers.forEach(function(h) {
17876 return h();
17877 });
17878 });
17879 }
17880 function initMouseInteractionObserver(param) {
17881 var mouseInteractionCb = param.mouseInteractionCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, sampling = param.sampling;
17882 if (sampling.mouseInteraction === false) {
17883 return function() {};
17884 }
17885 var disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;
17886 var handlers = [];
17887 var currentPointerType = null;
17888 var getHandler = function(eventKey) {
17889 return function(event) {
17890 var target = getEventTarget(event);
17891 if (isBlocked(target, blockClass, blockSelector, true)) {
17892 return;
17893 }
17894 var pointerType = null;
17895 var thisEventKey = eventKey;
17896 if ("pointerType" in event) {
17897 switch(event.pointerType){
17898 case "mouse":
17899 pointerType = PointerTypes.Mouse;
17900 break;
17901 case "touch":
17902 pointerType = PointerTypes.Touch;
17903 break;
17904 case "pen":
17905 pointerType = PointerTypes.Pen;
17906 break;
17907 }
17908 if (pointerType === PointerTypes.Touch) {
17909 if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {
17910 thisEventKey = "TouchStart";
17911 } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {
17912 thisEventKey = "TouchEnd";
17913 }
17914 } else if (pointerType === PointerTypes.Pen) ;
17915 } else if (legacy_isTouchEvent(event)) {
17916 pointerType = PointerTypes.Touch;
17917 }
17918 if (pointerType !== null) {
17919 currentPointerType = pointerType;
17920 if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) {
17921 pointerType = null;
17922 }
17923 } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {
17924 pointerType = currentPointerType;
17925 currentPointerType = null;
17926 }
17927 var e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;
17928 if (!e2) {
17929 return;
17930 }
17931 var id = mirror2.getId(target);
17932 var clientX = e2.clientX, clientY = e2.clientY;
17933 callbackWrapper(mouseInteractionCb)(_extends({
17934 type: MouseInteractions[thisEventKey],
17935 id: id,
17936 x: clientX,
17937 y: clientY
17938 }, pointerType !== null && {
17939 pointerType: pointerType
17940 }));
17941 };
17942 };
17943 Object.keys(MouseInteractions).filter(function(key) {
17944 return Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false;
17945 }).forEach(function(eventKey) {
17946 var eventName = toLowerCase(eventKey);
17947 var handler = getHandler(eventKey);
17948 if (window.PointerEvent) {
17949 switch(MouseInteractions[eventKey]){
17950 case MouseInteractions.MouseDown:
17951 case MouseInteractions.MouseUp:
17952 eventName = eventName.replace("mouse", "pointer");
17953 break;
17954 case MouseInteractions.TouchStart:
17955 case MouseInteractions.TouchEnd:
17956 return;
17957 }
17958 }
17959 handlers.push(on(eventName, handler, doc));
17960 });
17961 return callbackWrapper(function() {
17962 handlers.forEach(function(h) {
17963 return h();
17964 });
17965 });
17966 }
17967 function initScrollObserver(param) {
17968 var scrollCb = param.scrollCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, sampling = param.sampling;
17969 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
17970 var target = getEventTarget(evt);
17971 if (!target || isBlocked(target, blockClass, blockSelector, true)) {
17972 return;
17973 }
17974 var id = mirror2.getId(target);
17975 if (target === doc && doc.defaultView) {
17976 var scrollLeftTop = getWindowScroll(doc.defaultView);
17977 scrollCb({
17978 id: id,
17979 x: scrollLeftTop.left,
17980 y: scrollLeftTop.top
17981 });
17982 } else {
17983 scrollCb({
17984 id: id,
17985 x: target.scrollLeft,
17986 y: target.scrollTop
17987 });
17988 }
17989 }), sampling.scroll || 100));
17990 return on("scroll", updatePosition, doc);
17991 }
17992 function initViewportResizeObserver(param, param1) {
17993 var viewportResizeCb = param.viewportResizeCb;
17994 var win = param1.win;
17995 var lastH = -1;
17996 var lastW = -1;
17997 var updateDimension = callbackWrapper(throttle(callbackWrapper(function() {
17998 var height = getWindowHeight();
17999 var width = getWindowWidth();
18000 if (lastH !== height || lastW !== width) {
18001 viewportResizeCb({
18002 width: Number(width),
18003 height: Number(height)
18004 });
18005 lastH = height;
18006 lastW = width;
18007 }
18008 }), 200));
18009 return on("resize", updateDimension, win);
18010 }
18011 var INPUT_TAGS = [
18012 "INPUT",
18013 "TEXTAREA",
18014 "SELECT"
18015 ];
18016 var lastInputValueMap = /* @__PURE__ */ new WeakMap();
18017 function initInputObserver(param) {
18018 var inputCb = param.inputCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, ignoreClass = param.ignoreClass, ignoreSelector = param.ignoreSelector, maskInputOptions = param.maskInputOptions, maskInputFn = param.maskInputFn, sampling = param.sampling, userTriggeredOnInput = param.userTriggeredOnInput;
18019 function eventHandler(event) {
18020 var target = getEventTarget(event);
18021 var userTriggered = event.isTrusted;
18022 var tagName = target && target.tagName;
18023 if (target && tagName === "OPTION") {
18024 target = index.parentElement(target);
18025 }
18026 if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {
18027 return;
18028 }
18029 if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) {
18030 return;
18031 }
18032 var text = target.value;
18033 var isChecked = false;
18034 var type = getInputType(target) || "";
18035 if (type === "radio" || type === "checkbox") {
18036 isChecked = target.checked;
18037 } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {
18038 text = maskInputValue({
18039 element: target,
18040 maskInputOptions: maskInputOptions,
18041 tagName: tagName,
18042 type: type,
18043 value: text,
18044 maskInputFn: maskInputFn
18045 });
18046 }
18047 cbWithDedup(target, userTriggeredOnInput ? {
18048 text: text,
18049 isChecked: isChecked,
18050 userTriggered: userTriggered
18051 } : {
18052 text: text,
18053 isChecked: isChecked
18054 });
18055 var name = target.name;
18056 if (type === "radio" && name && isChecked) {
18057 doc.querySelectorAll('input[type="radio"][name="' + name + '"]').forEach(function(el) {
18058 if (el !== target) {
18059 var text2 = el.value;
18060 cbWithDedup(el, userTriggeredOnInput ? {
18061 text: text2,
18062 isChecked: !isChecked,
18063 userTriggered: false
18064 } : {
18065 text: text2,
18066 isChecked: !isChecked
18067 });
18068 }
18069 });
18070 }
18071 }
18072 function cbWithDedup(target, v2) {
18073 var lastInputValue = lastInputValueMap.get(target);
18074 if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {
18075 lastInputValueMap.set(target, v2);
18076 var id = mirror2.getId(target);
18077 callbackWrapper(inputCb)(_extends({}, v2, {
18078 id: id
18079 }));
18080 }
18081 }
18082 var events = sampling.input === "last" ? [
18083 "change"
18084 ] : [
18085 "input",
18086 "change"
18087 ];
18088 var handlers = events.map(function(eventName) {
18089 return on(eventName, callbackWrapper(eventHandler), doc);
18090 });
18091 var currentWindow = doc.defaultView;
18092 if (!currentWindow) {
18093 return function() {
18094 handlers.forEach(function(h) {
18095 return h();
18096 });
18097 };
18098 }
18099 var propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value");
18100 var hookProperties = [
18101 [
18102 currentWindow.HTMLInputElement.prototype,
18103 "value"
18104 ],
18105 [
18106 currentWindow.HTMLInputElement.prototype,
18107 "checked"
18108 ],
18109 [
18110 currentWindow.HTMLSelectElement.prototype,
18111 "value"
18112 ],
18113 [
18114 currentWindow.HTMLTextAreaElement.prototype,
18115 "value"
18116 ],
18117 // Some UI library use selectedIndex to set select value
18118 [
18119 currentWindow.HTMLSelectElement.prototype,
18120 "selectedIndex"
18121 ],
18122 [
18123 currentWindow.HTMLOptionElement.prototype,
18124 "selected"
18125 ]
18126 ];
18127 if (propertyDescriptor && propertyDescriptor.set) {
18128 var _handlers;
18129 (_handlers = handlers).push.apply(_handlers, [].concat(hookProperties.map(function(p) {
18130 return hookSetter(p[0], p[1], {
18131 set: function set() {
18132 callbackWrapper(eventHandler)({
18133 target: this,
18134 isTrusted: false
18135 });
18136 }
18137 }, false, currentWindow);
18138 })));
18139 }
18140 return callbackWrapper(function() {
18141 handlers.forEach(function(h) {
18142 return h();
18143 });
18144 });
18145 }
18146 function getNestedCSSRulePositions(rule2) {
18147 var positions = [];
18148 function recurse(childRule, pos) {
18149 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)) {
18150 var rules2 = Array.from(childRule.parentRule.cssRules);
18151 var index2 = rules2.indexOf(childRule);
18152 pos.unshift(index2);
18153 } else if (childRule.parentStyleSheet) {
18154 var rules21 = Array.from(childRule.parentStyleSheet.cssRules);
18155 var index21 = rules21.indexOf(childRule);
18156 pos.unshift(index21);
18157 }
18158 return pos;
18159 }
18160 return recurse(rule2, positions);
18161 }
18162 function getIdAndStyleId(sheet, mirror2, styleMirror) {
18163 var id, styleId;
18164 if (!sheet) return {};
18165 if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);
18166 else styleId = styleMirror.getId(sheet);
18167 return {
18168 styleId: styleId,
18169 id: id
18170 };
18171 }
18172 function initStyleSheetObserver(param, param1) {
18173 var styleSheetRuleCb = param.styleSheetRuleCb, mirror2 = param.mirror, stylesheetManager = param.stylesheetManager;
18174 var win = param1.win;
18175 if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {
18176 return function() {};
18177 }
18178 var insertRule = win.CSSStyleSheet.prototype.insertRule;
18179 win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {
18180 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18181 var rule2 = argumentsList[0], index2 = argumentsList[1];
18182 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18183 if (id && id !== -1 || styleId && styleId !== -1) {
18184 styleSheetRuleCb({
18185 id: id,
18186 styleId: styleId,
18187 adds: [
18188 {
18189 rule: rule2,
18190 index: index2
18191 }
18192 ]
18193 });
18194 }
18195 return target.apply(thisArg, argumentsList);
18196 })
18197 });
18198 win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2) {
18199 if (index2 === void 0) index2 = this.cssRules.length;
18200 var rule2 = selector + " { " + styleBlock + " }";
18201 return win.CSSStyleSheet.prototype.insertRule.apply(this, [
18202 rule2,
18203 index2
18204 ]);
18205 };
18206 var deleteRule = win.CSSStyleSheet.prototype.deleteRule;
18207 win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {
18208 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18209 var index2 = argumentsList[0];
18210 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18211 if (id && id !== -1 || styleId && styleId !== -1) {
18212 styleSheetRuleCb({
18213 id: id,
18214 styleId: styleId,
18215 removes: [
18216 {
18217 index: index2
18218 }
18219 ]
18220 });
18221 }
18222 return target.apply(thisArg, argumentsList);
18223 })
18224 });
18225 win.CSSStyleSheet.prototype.removeRule = function(index2) {
18226 return win.CSSStyleSheet.prototype.deleteRule.apply(this, [
18227 index2
18228 ]);
18229 };
18230 var replace;
18231 if (win.CSSStyleSheet.prototype.replace) {
18232 replace = win.CSSStyleSheet.prototype.replace;
18233 win.CSSStyleSheet.prototype.replace = new Proxy(replace, {
18234 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18235 var text = argumentsList[0];
18236 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18237 if (id && id !== -1 || styleId && styleId !== -1) {
18238 styleSheetRuleCb({
18239 id: id,
18240 styleId: styleId,
18241 replace: text
18242 });
18243 }
18244 return target.apply(thisArg, argumentsList);
18245 })
18246 });
18247 }
18248 var replaceSync;
18249 if (win.CSSStyleSheet.prototype.replaceSync) {
18250 replaceSync = win.CSSStyleSheet.prototype.replaceSync;
18251 win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {
18252 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18253 var text = argumentsList[0];
18254 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18255 if (id && id !== -1 || styleId && styleId !== -1) {
18256 styleSheetRuleCb({
18257 id: id,
18258 styleId: styleId,
18259 replaceSync: text
18260 });
18261 }
18262 return target.apply(thisArg, argumentsList);
18263 })
18264 });
18265 }
18266 var supportedNestedCSSRuleTypes = {};
18267 if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) {
18268 supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
18269 } else {
18270 if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) {
18271 supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
18272 }
18273 if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) {
18274 supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
18275 }
18276 if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) {
18277 supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
18278 }
18279 }
18280 var unmodifiedFunctions = {};
18281 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
18282 var typeKey = param[0], type = param[1];
18283 unmodifiedFunctions[typeKey] = {
18284 // eslint-disable-next-line @typescript-eslint/unbound-method
18285 insertRule: type.prototype.insertRule,
18286 // eslint-disable-next-line @typescript-eslint/unbound-method
18287 deleteRule: type.prototype.deleteRule
18288 };
18289 type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {
18290 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18291 var rule2 = argumentsList[0], index2 = argumentsList[1];
18292 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18293 if (id && id !== -1 || styleId && styleId !== -1) {
18294 styleSheetRuleCb({
18295 id: id,
18296 styleId: styleId,
18297 adds: [
18298 {
18299 rule: rule2,
18300 index: [].concat(getNestedCSSRulePositions(thisArg), [
18301 index2 || 0
18302 ])
18303 }
18304 ]
18305 });
18306 }
18307 return target.apply(thisArg, argumentsList);
18308 })
18309 });
18310 type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {
18311 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18312 var index2 = argumentsList[0];
18313 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18314 if (id && id !== -1 || styleId && styleId !== -1) {
18315 styleSheetRuleCb({
18316 id: id,
18317 styleId: styleId,
18318 removes: [
18319 {
18320 index: [].concat(getNestedCSSRulePositions(thisArg), [
18321 index2
18322 ])
18323 }
18324 ]
18325 });
18326 }
18327 return target.apply(thisArg, argumentsList);
18328 })
18329 });
18330 });
18331 return callbackWrapper(function() {
18332 win.CSSStyleSheet.prototype.insertRule = insertRule;
18333 win.CSSStyleSheet.prototype.deleteRule = deleteRule;
18334 replace && (win.CSSStyleSheet.prototype.replace = replace);
18335 replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
18336 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
18337 var typeKey = param[0], type = param[1];
18338 type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
18339 type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
18340 });
18341 });
18342 }
18343 function initAdoptedStyleSheetObserver(param, host2) {
18344 var mirror2 = param.mirror, stylesheetManager = param.stylesheetManager;
18345 var _a2, _b, _c;
18346 var hostId = null;
18347 if (host2.nodeName === "#document") hostId = mirror2.getId(host2);
18348 else hostId = mirror2.getId(index.host(host2));
18349 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;
18350 var originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(patchTarget == null ? void 0 : patchTarget.prototype, "adoptedStyleSheets") : void 0;
18351 if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return function() {};
18352 Object.defineProperty(host2, "adoptedStyleSheets", {
18353 configurable: originalPropertyDescriptor.configurable,
18354 enumerable: originalPropertyDescriptor.enumerable,
18355 get: function get() {
18356 var _a3;
18357 return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);
18358 },
18359 set: function set(sheets) {
18360 var _a3;
18361 var result2 = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);
18362 if (hostId !== null && hostId !== -1) {
18363 try {
18364 stylesheetManager.adoptStyleSheets(sheets, hostId);
18365 } catch (e2) {}
18366 }
18367 return result2;
18368 }
18369 });
18370 return callbackWrapper(function() {
18371 Object.defineProperty(host2, "adoptedStyleSheets", {
18372 configurable: originalPropertyDescriptor.configurable,
18373 enumerable: originalPropertyDescriptor.enumerable,
18374 // eslint-disable-next-line @typescript-eslint/unbound-method
18375 get: originalPropertyDescriptor.get,
18376 // eslint-disable-next-line @typescript-eslint/unbound-method
18377 set: originalPropertyDescriptor.set
18378 });
18379 });
18380 }
18381 function initStyleDeclarationObserver(param, param1) {
18382 var styleDeclarationCb = param.styleDeclarationCb, mirror2 = param.mirror, ignoreCSSAttributes = param.ignoreCSSAttributes, stylesheetManager = param.stylesheetManager;
18383 var win = param1.win;
18384 var setProperty = win.CSSStyleDeclaration.prototype.setProperty;
18385 win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {
18386 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18387 var _a2;
18388 var property = argumentsList[0], value = argumentsList[1], priority = argumentsList[2];
18389 if (ignoreCSSAttributes.has(property)) {
18390 return setProperty.apply(thisArg, [
18391 property,
18392 value,
18393 priority
18394 ]);
18395 }
18396 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18397 if (id && id !== -1 || styleId && styleId !== -1) {
18398 styleDeclarationCb({
18399 id: id,
18400 styleId: styleId,
18401 set: {
18402 property: property,
18403 value: value,
18404 priority: priority
18405 },
18406 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
18407 index: getNestedCSSRulePositions(thisArg.parentRule)
18408 });
18409 }
18410 return target.apply(thisArg, argumentsList);
18411 })
18412 });
18413 var removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
18414 win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {
18415 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18416 var _a2;
18417 var property = argumentsList[0];
18418 if (ignoreCSSAttributes.has(property)) {
18419 return removeProperty.apply(thisArg, [
18420 property
18421 ]);
18422 }
18423 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18424 if (id && id !== -1 || styleId && styleId !== -1) {
18425 styleDeclarationCb({
18426 id: id,
18427 styleId: styleId,
18428 remove: {
18429 property: property
18430 },
18431 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
18432 index: getNestedCSSRulePositions(thisArg.parentRule)
18433 });
18434 }
18435 return target.apply(thisArg, argumentsList);
18436 })
18437 });
18438 return callbackWrapper(function() {
18439 win.CSSStyleDeclaration.prototype.setProperty = setProperty;
18440 win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
18441 });
18442 }
18443 function initMediaInteractionObserver(param) {
18444 var mediaInteractionCb = param.mediaInteractionCb, blockClass = param.blockClass, blockSelector = param.blockSelector, mirror2 = param.mirror, sampling = param.sampling, doc = param.doc;
18445 var handler = callbackWrapper(function(type) {
18446 return throttle(callbackWrapper(function(event) {
18447 var target = getEventTarget(event);
18448 if (!target || isBlocked(target, blockClass, blockSelector, true)) {
18449 return;
18450 }
18451 var currentTime = target.currentTime, volume = target.volume, muted = target.muted, playbackRate = target.playbackRate, loop = target.loop;
18452 mediaInteractionCb({
18453 type: type,
18454 id: mirror2.getId(target),
18455 currentTime: currentTime,
18456 volume: volume,
18457 muted: muted,
18458 playbackRate: playbackRate,
18459 loop: loop
18460 });
18461 }), sampling.media || 500);
18462 });
18463 var handlers = [
18464 on("play", handler(MediaInteractions.Play), doc),
18465 on("pause", handler(MediaInteractions.Pause), doc),
18466 on("seeked", handler(MediaInteractions.Seeked), doc),
18467 on("volumechange", handler(MediaInteractions.VolumeChange), doc),
18468 on("ratechange", handler(MediaInteractions.RateChange), doc)
18469 ];
18470 return callbackWrapper(function() {
18471 handlers.forEach(function(h) {
18472 return h();
18473 });
18474 });
18475 }
18476 function initFontObserver(param) {
18477 var fontCb = param.fontCb, doc = param.doc;
18478 var win = doc.defaultView;
18479 if (!win) {
18480 return function() {};
18481 }
18482 var handlers = [];
18483 var fontMap = /* @__PURE__ */ new WeakMap();
18484 var originalFontFace = win.FontFace;
18485 win.FontFace = function FontFace2(family, source, descriptors) {
18486 var fontFace = new originalFontFace(family, source, descriptors);
18487 fontMap.set(fontFace, {
18488 family: family,
18489 buffer: typeof source !== "string",
18490 descriptors: descriptors,
18491 fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source)))
18492 });
18493 return fontFace;
18494 };
18495 var restoreHandler = patch(doc.fonts, "add", function(original) {
18496 return function(fontFace) {
18497 setTimeout(callbackWrapper(function() {
18498 var p = fontMap.get(fontFace);
18499 if (p) {
18500 fontCb(p);
18501 fontMap.delete(fontFace);
18502 }
18503 }), 0);
18504 return original.apply(this, [
18505 fontFace
18506 ]);
18507 };
18508 });
18509 handlers.push(function() {
18510 win.FontFace = originalFontFace;
18511 });
18512 handlers.push(restoreHandler);
18513 return callbackWrapper(function() {
18514 handlers.forEach(function(h) {
18515 return h();
18516 });
18517 });
18518 }
18519 function initSelectionObserver(param) {
18520 var doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, selectionCb = param.selectionCb;
18521 var collapsed = true;
18522 var updateSelection = callbackWrapper(function() {
18523 var selection = doc.getSelection();
18524 if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;
18525 collapsed = selection.isCollapsed || false;
18526 var ranges = [];
18527 var count = selection.rangeCount || 0;
18528 for(var i2 = 0; i2 < count; i2++){
18529 var range = selection.getRangeAt(i2);
18530 var startContainer = range.startContainer, startOffset = range.startOffset, endContainer = range.endContainer, endOffset = range.endOffset;
18531 var blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);
18532 if (blocked) continue;
18533 ranges.push({
18534 start: mirror2.getId(startContainer),
18535 startOffset: startOffset,
18536 end: mirror2.getId(endContainer),
18537 endOffset: endOffset
18538 });
18539 }
18540 selectionCb({
18541 ranges: ranges
18542 });
18543 });
18544 updateSelection();
18545 return on("selectionchange", updateSelection);
18546 }
18547 function initCustomElementObserver(param) {
18548 var doc = param.doc, customElementCb = param.customElementCb;
18549 var win = doc.defaultView;
18550 if (!win || !win.customElements) return function() {};
18551 var restoreHandler = patch(win.customElements, "define", function(original) {
18552 return function(name, constructor, options) {
18553 try {
18554 customElementCb({
18555 define: {
18556 name: name
18557 }
18558 });
18559 } catch (e2) {
18560 console.warn("Custom element callback failed for " + name);
18561 }
18562 return original.apply(this, [
18563 name,
18564 constructor,
18565 options
18566 ]);
18567 };
18568 });
18569 return restoreHandler;
18570 }
18571 function mergeHooks(o2, hooks) {
18572 var mutationCb = o2.mutationCb, mousemoveCb = o2.mousemoveCb, mouseInteractionCb = o2.mouseInteractionCb, scrollCb = o2.scrollCb, viewportResizeCb = o2.viewportResizeCb, inputCb = o2.inputCb, mediaInteractionCb = o2.mediaInteractionCb, styleSheetRuleCb = o2.styleSheetRuleCb, styleDeclarationCb = o2.styleDeclarationCb, canvasMutationCb = o2.canvasMutationCb, fontCb = o2.fontCb, selectionCb = o2.selectionCb, customElementCb = o2.customElementCb;
18573 o2.mutationCb = function() {
18574 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18575 p[_key] = arguments[_key];
18576 }
18577 if (hooks.mutation) {
18578 var _hooks;
18579 (_hooks = hooks).mutation.apply(_hooks, [].concat(p));
18580 }
18581 mutationCb.apply(void 0, [].concat(p));
18582 };
18583 o2.mousemoveCb = function() {
18584 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18585 p[_key] = arguments[_key];
18586 }
18587 if (hooks.mousemove) {
18588 var _hooks;
18589 (_hooks = hooks).mousemove.apply(_hooks, [].concat(p));
18590 }
18591 mousemoveCb.apply(void 0, [].concat(p));
18592 };
18593 o2.mouseInteractionCb = function() {
18594 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18595 p[_key] = arguments[_key];
18596 }
18597 if (hooks.mouseInteraction) {
18598 var _hooks;
18599 (_hooks = hooks).mouseInteraction.apply(_hooks, [].concat(p));
18600 }
18601 mouseInteractionCb.apply(void 0, [].concat(p));
18602 };
18603 o2.scrollCb = function() {
18604 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18605 p[_key] = arguments[_key];
18606 }
18607 if (hooks.scroll) {
18608 var _hooks;
18609 (_hooks = hooks).scroll.apply(_hooks, [].concat(p));
18610 }
18611 scrollCb.apply(void 0, [].concat(p));
18612 };
18613 o2.viewportResizeCb = function() {
18614 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18615 p[_key] = arguments[_key];
18616 }
18617 if (hooks.viewportResize) {
18618 var _hooks;
18619 (_hooks = hooks).viewportResize.apply(_hooks, [].concat(p));
18620 }
18621 viewportResizeCb.apply(void 0, [].concat(p));
18622 };
18623 o2.inputCb = function() {
18624 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18625 p[_key] = arguments[_key];
18626 }
18627 if (hooks.input) {
18628 var _hooks;
18629 (_hooks = hooks).input.apply(_hooks, [].concat(p));
18630 }
18631 inputCb.apply(void 0, [].concat(p));
18632 };
18633 o2.mediaInteractionCb = function() {
18634 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18635 p[_key] = arguments[_key];
18636 }
18637 if (hooks.mediaInteaction) {
18638 var _hooks;
18639 (_hooks = hooks).mediaInteaction.apply(_hooks, [].concat(p));
18640 }
18641 mediaInteractionCb.apply(void 0, [].concat(p));
18642 };
18643 o2.styleSheetRuleCb = function() {
18644 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18645 p[_key] = arguments[_key];
18646 }
18647 if (hooks.styleSheetRule) {
18648 var _hooks;
18649 (_hooks = hooks).styleSheetRule.apply(_hooks, [].concat(p));
18650 }
18651 styleSheetRuleCb.apply(void 0, [].concat(p));
18652 };
18653 o2.styleDeclarationCb = function() {
18654 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18655 p[_key] = arguments[_key];
18656 }
18657 if (hooks.styleDeclaration) {
18658 var _hooks;
18659 (_hooks = hooks).styleDeclaration.apply(_hooks, [].concat(p));
18660 }
18661 styleDeclarationCb.apply(void 0, [].concat(p));
18662 };
18663 o2.canvasMutationCb = function() {
18664 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18665 p[_key] = arguments[_key];
18666 }
18667 if (hooks.canvasMutation) {
18668 var _hooks;
18669 (_hooks = hooks).canvasMutation.apply(_hooks, [].concat(p));
18670 }
18671 canvasMutationCb.apply(void 0, [].concat(p));
18672 };
18673 o2.fontCb = function() {
18674 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18675 p[_key] = arguments[_key];
18676 }
18677 if (hooks.font) {
18678 var _hooks;
18679 (_hooks = hooks).font.apply(_hooks, [].concat(p));
18680 }
18681 fontCb.apply(void 0, [].concat(p));
18682 };
18683 o2.selectionCb = function() {
18684 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18685 p[_key] = arguments[_key];
18686 }
18687 if (hooks.selection) {
18688 var _hooks;
18689 (_hooks = hooks).selection.apply(_hooks, [].concat(p));
18690 }
18691 selectionCb.apply(void 0, [].concat(p));
18692 };
18693 o2.customElementCb = function() {
18694 for(var _len = arguments.length, c2 = new Array(_len), _key = 0; _key < _len; _key++){
18695 c2[_key] = arguments[_key];
18696 }
18697 if (hooks.customElement) {
18698 var _hooks;
18699 (_hooks = hooks).customElement.apply(_hooks, [].concat(c2));
18700 }
18701 customElementCb.apply(void 0, [].concat(c2));
18702 };
18703 }
18704 function initObservers(o2, hooks) {
18705 if (hooks === void 0) hooks = {};
18706 var currentWindow = o2.doc.defaultView;
18707 if (!currentWindow) {
18708 return function() {};
18709 }
18710 mergeHooks(o2, hooks);
18711 var mutationObserver;
18712 if (o2.recordDOM) {
18713 mutationObserver = initMutationObserver(o2, o2.doc);
18714 }
18715 var mousemoveHandler = initMoveObserver(o2);
18716 var mouseInteractionHandler = initMouseInteractionObserver(o2);
18717 var scrollHandler = initScrollObserver(o2);
18718 var viewportResizeHandler = initViewportResizeObserver(o2, {
18719 win: currentWindow
18720 });
18721 var inputHandler = initInputObserver(o2);
18722 var mediaInteractionHandler = initMediaInteractionObserver(o2);
18723 var styleSheetObserver = function() {};
18724 var adoptedStyleSheetObserver = function() {};
18725 var styleDeclarationObserver = function() {};
18726 var fontObserver = function() {};
18727 if (o2.recordDOM) {
18728 styleSheetObserver = initStyleSheetObserver(o2, {
18729 win: currentWindow
18730 });
18731 adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);
18732 styleDeclarationObserver = initStyleDeclarationObserver(o2, {
18733 win: currentWindow
18734 });
18735 if (o2.collectFonts) {
18736 fontObserver = initFontObserver(o2);
18737 }
18738 }
18739 var selectionObserver = initSelectionObserver(o2);
18740 var customElementObserver = initCustomElementObserver(o2);
18741 var pluginHandlers = [];
18742 for(var _iterator = _create_for_of_iterator_helper_loose(o2.plugins), _step; !(_step = _iterator()).done;){
18743 var plugin3 = _step.value;
18744 pluginHandlers.push(plugin3.observer(plugin3.callback, currentWindow, plugin3.options));
18745 }
18746 return callbackWrapper(function() {
18747 mutationBuffers.forEach(function(b) {
18748 return b.reset();
18749 });
18750 mutationObserver == null ? void 0 : mutationObserver.disconnect();
18751 mousemoveHandler();
18752 mouseInteractionHandler();
18753 scrollHandler();
18754 viewportResizeHandler();
18755 inputHandler();
18756 mediaInteractionHandler();
18757 styleSheetObserver();
18758 adoptedStyleSheetObserver();
18759 styleDeclarationObserver();
18760 fontObserver();
18761 selectionObserver();
18762 customElementObserver();
18763 pluginHandlers.forEach(function(h) {
18764 return h();
18765 });
18766 });
18767 }
18768 function hasNestedCSSRule(prop) {
18769 return typeof window[prop] !== "undefined";
18770 }
18771 function canMonkeyPatchNestedCSSRule(prop) {
18772 return Boolean(typeof window[prop] !== "undefined" && // Note: Generally, this check _shouldn't_ be necessary
18773 // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here
18774 window[prop].prototype && "insertRule" in window[prop].prototype && "deleteRule" in window[prop].prototype);
18775 }
18776 var CrossOriginIframeMirror = /*#__PURE__*/ function() {
18777 function CrossOriginIframeMirror(generateIdFn) {
18778 __publicField(this, "iframeIdToRemoteIdMap", /* @__PURE__ */ new WeakMap());
18779 __publicField(this, "iframeRemoteIdToIdMap", /* @__PURE__ */ new WeakMap());
18780 this.generateIdFn = generateIdFn;
18781 }
18782 var _proto = CrossOriginIframeMirror.prototype;
18783 _proto.getId = function getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
18784 var idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
18785 var remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
18786 var id = idToRemoteIdMap.get(remoteId);
18787 if (!id) {
18788 id = this.generateIdFn();
18789 idToRemoteIdMap.set(remoteId, id);
18790 remoteIdToIdMap.set(id, remoteId);
18791 }
18792 return id;
18793 };
18794 _proto.getIds = function getIds(iframe, remoteId) {
18795 var _this = this;
18796 var idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
18797 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
18798 return remoteId.map(function(id) {
18799 return _this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap);
18800 });
18801 };
18802 _proto.getRemoteId = function getRemoteId(iframe, id, map) {
18803 var remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
18804 if (typeof id !== "number") return id;
18805 var remoteId = remoteIdToIdMap.get(id);
18806 if (!remoteId) return -1;
18807 return remoteId;
18808 };
18809 _proto.getRemoteIds = function getRemoteIds(iframe, ids) {
18810 var _this = this;
18811 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
18812 return ids.map(function(id) {
18813 return _this.getRemoteId(iframe, id, remoteIdToIdMap);
18814 });
18815 };
18816 _proto.reset = function reset(iframe) {
18817 if (!iframe) {
18818 this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
18819 this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
18820 return;
18821 }
18822 this.iframeIdToRemoteIdMap.delete(iframe);
18823 this.iframeRemoteIdToIdMap.delete(iframe);
18824 };
18825 _proto.getIdToRemoteIdMap = function getIdToRemoteIdMap(iframe) {
18826 var idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
18827 if (!idToRemoteIdMap) {
18828 idToRemoteIdMap = /* @__PURE__ */ new Map();
18829 this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
18830 }
18831 return idToRemoteIdMap;
18832 };
18833 _proto.getRemoteIdToIdMap = function getRemoteIdToIdMap(iframe) {
18834 var remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
18835 if (!remoteIdToIdMap) {
18836 remoteIdToIdMap = /* @__PURE__ */ new Map();
18837 this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
18838 }
18839 return remoteIdToIdMap;
18840 };
18841 return CrossOriginIframeMirror;
18842 }();
18843 var IframeManager = /*#__PURE__*/ function() {
18844 function IframeManager(options) {
18845 __publicField(this, "iframes", /* @__PURE__ */ new WeakMap());
18846 __publicField(this, "crossOriginIframeMap", /* @__PURE__ */ new WeakMap());
18847 __publicField(this, "crossOriginIframeMirror", new CrossOriginIframeMirror(genId));
18848 __publicField(this, "crossOriginIframeStyleMirror");
18849 __publicField(this, "crossOriginIframeRootIdMap", /* @__PURE__ */ new WeakMap());
18850 __publicField(this, "mirror");
18851 __publicField(this, "mutationCb");
18852 __publicField(this, "wrappedEmit");
18853 __publicField(this, "loadListener");
18854 __publicField(this, "stylesheetManager");
18855 __publicField(this, "recordCrossOriginIframes");
18856 this.mutationCb = options.mutationCb;
18857 this.wrappedEmit = options.wrappedEmit;
18858 this.stylesheetManager = options.stylesheetManager;
18859 this.recordCrossOriginIframes = options.recordCrossOriginIframes;
18860 this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
18861 this.mirror = options.mirror;
18862 if (this.recordCrossOriginIframes) {
18863 window.addEventListener("message", this.handleMessage.bind(this));
18864 }
18865 }
18866 var _proto = IframeManager.prototype;
18867 _proto.addIframe = function addIframe(iframeEl) {
18868 this.iframes.set(iframeEl, true);
18869 if (iframeEl.contentWindow) this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
18870 };
18871 _proto.addLoadListener = function addLoadListener(cb) {
18872 this.loadListener = cb;
18873 };
18874 _proto.attachIframe = function attachIframe(iframeEl, childSn) {
18875 var _a2, _b;
18876 this.mutationCb({
18877 adds: [
18878 {
18879 parentId: this.mirror.getId(iframeEl),
18880 nextId: null,
18881 node: childSn
18882 }
18883 ],
18884 removes: [],
18885 texts: [],
18886 attributes: [],
18887 isAttachIframe: true
18888 });
18889 if (this.recordCrossOriginIframes) (_a2 = iframeEl.contentWindow) == null ? void 0 : _a2.addEventListener("message", this.handleMessage.bind(this));
18890 (_b = this.loadListener) == null ? void 0 : _b.call(this, iframeEl);
18891 if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
18892 };
18893 _proto.handleMessage = function handleMessage(message) {
18894 var crossOriginMessageEvent = message;
18895 if (crossOriginMessageEvent.data.type !== "rrweb" || // To filter out the rrweb messages which are forwarded by some sites.
18896 crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return;
18897 var iframeSourceWindow = message.source;
18898 if (!iframeSourceWindow) return;
18899 var iframeEl = this.crossOriginIframeMap.get(message.source);
18900 if (!iframeEl) return;
18901 var transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
18902 if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
18903 };
18904 _proto.transformCrossOriginEvent = function transformCrossOriginEvent(iframeEl, e2) {
18905 var _this = this;
18906 var _a2;
18907 switch(e2.type){
18908 case EventType.FullSnapshot:
18909 {
18910 this.crossOriginIframeMirror.reset(iframeEl);
18911 this.crossOriginIframeStyleMirror.reset(iframeEl);
18912 this.replaceIdOnNode(e2.data.node, iframeEl);
18913 var rootId = e2.data.node.id;
18914 this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
18915 this.patchRootIdOnNode(e2.data.node, rootId);
18916 return {
18917 timestamp: e2.timestamp,
18918 type: EventType.IncrementalSnapshot,
18919 data: {
18920 source: IncrementalSource.Mutation,
18921 adds: [
18922 {
18923 parentId: this.mirror.getId(iframeEl),
18924 nextId: null,
18925 node: e2.data.node
18926 }
18927 ],
18928 removes: [],
18929 texts: [],
18930 attributes: [],
18931 isAttachIframe: true
18932 }
18933 };
18934 }
18935 case EventType.Meta:
18936 case EventType.Load:
18937 case EventType.DomContentLoaded:
18938 {
18939 return false;
18940 }
18941 case EventType.Plugin:
18942 {
18943 return e2;
18944 }
18945 case EventType.Custom:
18946 {
18947 this.replaceIds(e2.data.payload, iframeEl, [
18948 "id",
18949 "parentId",
18950 "previousId",
18951 "nextId"
18952 ]);
18953 return e2;
18954 }
18955 case EventType.IncrementalSnapshot:
18956 {
18957 switch(e2.data.source){
18958 case IncrementalSource.Mutation:
18959 {
18960 e2.data.adds.forEach(function(n2) {
18961 _this.replaceIds(n2, iframeEl, [
18962 "parentId",
18963 "nextId",
18964 "previousId"
18965 ]);
18966 _this.replaceIdOnNode(n2.node, iframeEl);
18967 var rootId = _this.crossOriginIframeRootIdMap.get(iframeEl);
18968 rootId && _this.patchRootIdOnNode(n2.node, rootId);
18969 });
18970 e2.data.removes.forEach(function(n2) {
18971 _this.replaceIds(n2, iframeEl, [
18972 "parentId",
18973 "id"
18974 ]);
18975 });
18976 e2.data.attributes.forEach(function(n2) {
18977 _this.replaceIds(n2, iframeEl, [
18978 "id"
18979 ]);
18980 });
18981 e2.data.texts.forEach(function(n2) {
18982 _this.replaceIds(n2, iframeEl, [
18983 "id"
18984 ]);
18985 });
18986 return e2;
18987 }
18988 case IncrementalSource.Drag:
18989 case IncrementalSource.TouchMove:
18990 case IncrementalSource.MouseMove:
18991 {
18992 e2.data.positions.forEach(function(p) {
18993 _this.replaceIds(p, iframeEl, [
18994 "id"
18995 ]);
18996 });
18997 return e2;
18998 }
18999 case IncrementalSource.ViewportResize:
19000 {
19001 return false;
19002 }
19003 case IncrementalSource.MediaInteraction:
19004 case IncrementalSource.MouseInteraction:
19005 case IncrementalSource.Scroll:
19006 case IncrementalSource.CanvasMutation:
19007 case IncrementalSource.Input:
19008 {
19009 this.replaceIds(e2.data, iframeEl, [
19010 "id"
19011 ]);
19012 return e2;
19013 }
19014 case IncrementalSource.StyleSheetRule:
19015 case IncrementalSource.StyleDeclaration:
19016 {
19017 this.replaceIds(e2.data, iframeEl, [
19018 "id"
19019 ]);
19020 this.replaceStyleIds(e2.data, iframeEl, [
19021 "styleId"
19022 ]);
19023 return e2;
19024 }
19025 case IncrementalSource.Font:
19026 {
19027 return e2;
19028 }
19029 case IncrementalSource.Selection:
19030 {
19031 e2.data.ranges.forEach(function(range) {
19032 _this.replaceIds(range, iframeEl, [
19033 "start",
19034 "end"
19035 ]);
19036 });
19037 return e2;
19038 }
19039 case IncrementalSource.AdoptedStyleSheet:
19040 {
19041 this.replaceIds(e2.data, iframeEl, [
19042 "id"
19043 ]);
19044 this.replaceStyleIds(e2.data, iframeEl, [
19045 "styleIds"
19046 ]);
19047 (_a2 = e2.data.styles) == null ? void 0 : _a2.forEach(function(style) {
19048 _this.replaceStyleIds(style, iframeEl, [
19049 "styleId"
19050 ]);
19051 });
19052 return e2;
19053 }
19054 }
19055 }
19056 }
19057 return false;
19058 };
19059 _proto.replace = function replace(iframeMirror, obj, iframeEl, keys) {
19060 for(var _iterator = _create_for_of_iterator_helper_loose(keys), _step; !(_step = _iterator()).done;){
19061 var key = _step.value;
19062 if (!Array.isArray(obj[key]) && typeof obj[key] !== "number") continue;
19063 if (Array.isArray(obj[key])) {
19064 obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
19065 } else {
19066 obj[key] = iframeMirror.getId(iframeEl, obj[key]);
19067 }
19068 }
19069 return obj;
19070 };
19071 _proto.replaceIds = function replaceIds(obj, iframeEl, keys) {
19072 return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
19073 };
19074 _proto.replaceStyleIds = function replaceStyleIds(obj, iframeEl, keys) {
19075 return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
19076 };
19077 _proto.replaceIdOnNode = function replaceIdOnNode(node2, iframeEl) {
19078 var _this = this;
19079 this.replaceIds(node2, iframeEl, [
19080 "id",
19081 "rootId"
19082 ]);
19083 if ("childNodes" in node2) {
19084 node2.childNodes.forEach(function(child) {
19085 _this.replaceIdOnNode(child, iframeEl);
19086 });
19087 }
19088 };
19089 _proto.patchRootIdOnNode = function patchRootIdOnNode(node2, rootId) {
19090 var _this = this;
19091 if (node2.type !== NodeType.Document && !node2.rootId) node2.rootId = rootId;
19092 if ("childNodes" in node2) {
19093 node2.childNodes.forEach(function(child) {
19094 _this.patchRootIdOnNode(child, rootId);
19095 });
19096 }
19097 };
19098 return IframeManager;
19099 }();
19100 var ShadowDomManager = /*#__PURE__*/ function() {
19101 function ShadowDomManager(options) {
19102 __publicField(this, "shadowDoms", /* @__PURE__ */ new WeakSet());
19103 __publicField(this, "mutationCb");
19104 __publicField(this, "scrollCb");
19105 __publicField(this, "bypassOptions");
19106 __publicField(this, "mirror");
19107 __publicField(this, "restoreHandlers", []);
19108 this.mutationCb = options.mutationCb;
19109 this.scrollCb = options.scrollCb;
19110 this.bypassOptions = options.bypassOptions;
19111 this.mirror = options.mirror;
19112 this.init();
19113 }
19114 var _proto = ShadowDomManager.prototype;
19115 _proto.init = function init() {
19116 this.reset();
19117 this.patchAttachShadow(Element, document);
19118 };
19119 _proto.addShadowRoot = function addShadowRoot(shadowRoot2, doc) {
19120 var _this = this;
19121 if (!isNativeShadowDom(shadowRoot2)) return;
19122 if (this.shadowDoms.has(shadowRoot2)) return;
19123 this.shadowDoms.add(shadowRoot2);
19124 var observer = initMutationObserver(_extends({}, this.bypassOptions, {
19125 doc: doc,
19126 mutationCb: this.mutationCb,
19127 mirror: this.mirror,
19128 shadowDomManager: this
19129 }), shadowRoot2);
19130 this.restoreHandlers.push(function() {
19131 return observer.disconnect();
19132 });
19133 this.restoreHandlers.push(initScrollObserver(_extends({}, this.bypassOptions, {
19134 scrollCb: this.scrollCb,
19135 // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813
19136 // scroll is not allowed to pass the boundary, so we need to listen the shadow document
19137 doc: shadowRoot2,
19138 mirror: this.mirror
19139 })));
19140 setTimeout(function() {
19141 if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0) _this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot2.adoptedStyleSheets, _this.mirror.getId(index.host(shadowRoot2)));
19142 _this.restoreHandlers.push(initAdoptedStyleSheetObserver({
19143 mirror: _this.mirror,
19144 stylesheetManager: _this.bypassOptions.stylesheetManager
19145 }, shadowRoot2));
19146 }, 0);
19147 };
19148 /**
19149 * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.
19150 */ _proto.observeAttachShadow = function observeAttachShadow(iframeElement) {
19151 if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;
19152 this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);
19153 };
19154 /**
19155 * Patch 'attachShadow' to observe newly added shadow doms.
19156 */ _proto.patchAttachShadow = function patchAttachShadow(element, doc) {
19157 var manager = this;
19158 this.restoreHandlers.push(patch(element.prototype, "attachShadow", function(original) {
19159 return function(option) {
19160 var sRoot = original.call(this, option);
19161 var shadowRootEl = index.shadowRoot(this);
19162 if (shadowRootEl && inDom(this)) manager.addShadowRoot(shadowRootEl, doc);
19163 return sRoot;
19164 };
19165 }));
19166 };
19167 _proto.reset = function reset() {
19168 this.restoreHandlers.forEach(function(handler) {
19169 try {
19170 handler();
19171 } catch (e2) {}
19172 });
19173 this.restoreHandlers = [];
19174 this.shadowDoms = /* @__PURE__ */ new WeakSet();
19175 };
19176 return ShadowDomManager;
19177 }();
19178 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
19179 var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
19180 for(var i$1 = 0; i$1 < chars.length; i$1++){
19181 lookup[chars.charCodeAt(i$1)] = i$1;
19182 }
19183 var encode = function encode(arraybuffer) {
19184 var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";
19185 for(i2 = 0; i2 < len; i2 += 3){
19186 base64 += chars[bytes[i2] >> 2];
19187 base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
19188 base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
19189 base64 += chars[bytes[i2 + 2] & 63];
19190 }
19191 if (len % 3 === 2) {
19192 base64 = base64.substring(0, base64.length - 1) + "=";
19193 } else if (len % 3 === 1) {
19194 base64 = base64.substring(0, base64.length - 2) + "==";
19195 }
19196 return base64;
19197 };
19198 var canvasVarMap = /* @__PURE__ */ new Map();
19199 function variableListFor$1(ctx, ctor) {
19200 var contextMap = canvasVarMap.get(ctx);
19201 if (!contextMap) {
19202 contextMap = /* @__PURE__ */ new Map();
19203 canvasVarMap.set(ctx, contextMap);
19204 }
19205 if (!contextMap.has(ctor)) {
19206 contextMap.set(ctor, []);
19207 }
19208 return contextMap.get(ctor);
19209 }
19210 var saveWebGLVar = function(value, win, ctx) {
19211 if (!value || !(isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object")) return;
19212 var name = value.constructor.name;
19213 var list2 = variableListFor$1(ctx, name);
19214 var index2 = list2.indexOf(value);
19215 if (index2 === -1) {
19216 index2 = list2.length;
19217 list2.push(value);
19218 }
19219 return index2;
19220 };
19221 function serializeArg(value, win, ctx) {
19222 if (_instanceof(value, Array)) {
19223 return value.map(function(arg) {
19224 return serializeArg(arg, win, ctx);
19225 });
19226 } else if (value === null) {
19227 return value;
19228 } 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)) {
19229 var name = value.constructor.name;
19230 return {
19231 rr_type: name,
19232 args: [
19233 Object.values(value)
19234 ]
19235 };
19236 } else if (// SharedArrayBuffer disabled on most browsers due to spectre.
19237 // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer
19238 // value instanceof SharedArrayBuffer ||
19239 _instanceof(value, ArrayBuffer)) {
19240 var name1 = value.constructor.name;
19241 var base64 = encode(value);
19242 return {
19243 rr_type: name1,
19244 base64: base64
19245 };
19246 } else if (_instanceof(value, DataView)) {
19247 var name2 = value.constructor.name;
19248 return {
19249 rr_type: name2,
19250 args: [
19251 serializeArg(value.buffer, win, ctx),
19252 value.byteOffset,
19253 value.byteLength
19254 ]
19255 };
19256 } else if (_instanceof(value, HTMLImageElement)) {
19257 var name3 = value.constructor.name;
19258 var src = value.src;
19259 return {
19260 rr_type: name3,
19261 src: src
19262 };
19263 } else if (_instanceof(value, HTMLCanvasElement)) {
19264 var name4 = "HTMLImageElement";
19265 var src1 = value.toDataURL();
19266 return {
19267 rr_type: name4,
19268 src: src1
19269 };
19270 } else if (_instanceof(value, ImageData)) {
19271 var name5 = value.constructor.name;
19272 return {
19273 rr_type: name5,
19274 args: [
19275 serializeArg(value.data, win, ctx),
19276 value.width,
19277 value.height
19278 ]
19279 };
19280 } else if (isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") {
19281 var name6 = value.constructor.name;
19282 var index2 = saveWebGLVar(value, win, ctx);
19283 return {
19284 rr_type: name6,
19285 index: index2
19286 };
19287 }
19288 return value;
19289 }
19290 var serializeArgs = function(args, win, ctx) {
19291 return args.map(function(arg) {
19292 return serializeArg(arg, win, ctx);
19293 });
19294 };
19295 var isInstanceOfWebGLObject = function(value, win) {
19296 var webGLConstructorNames = [
19297 "WebGLActiveInfo",
19298 "WebGLBuffer",
19299 "WebGLFramebuffer",
19300 "WebGLProgram",
19301 "WebGLRenderbuffer",
19302 "WebGLShader",
19303 "WebGLShaderPrecisionFormat",
19304 "WebGLTexture",
19305 "WebGLUniformLocation",
19306 "WebGLVertexArrayObject",
19307 // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.
19308 "WebGLVertexArrayObjectOES"
19309 ];
19310 var supportedWebGLConstructorNames = webGLConstructorNames.filter(function(name) {
19311 return typeof win[name] === "function";
19312 });
19313 return Boolean(supportedWebGLConstructorNames.find(function(name) {
19314 return _instanceof(value, win[name]);
19315 }));
19316 };
19317 function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
19318 var _loop = function() {
19319 var prop = _step.value;
19320 try {
19321 if (typeof win.CanvasRenderingContext2D.prototype[prop] !== "function") {
19322 return "continue";
19323 }
19324 var restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function(original) {
19325 return function() {
19326 var _this = this;
19327 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
19328 args[_key] = arguments[_key];
19329 }
19330 if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
19331 setTimeout(function() {
19332 var recordArgs = serializeArgs(args, win, _this);
19333 cb(_this.canvas, {
19334 type: CanvasContext["2D"],
19335 property: prop,
19336 args: recordArgs
19337 });
19338 }, 0);
19339 }
19340 return original.apply(this, args);
19341 };
19342 });
19343 handlers.push(restoreHandler);
19344 } catch (e) {
19345 var hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
19346 set: function set(v2) {
19347 cb(this.canvas, {
19348 type: CanvasContext["2D"],
19349 property: prop,
19350 args: [
19351 v2
19352 ],
19353 setter: true
19354 });
19355 }
19356 });
19357 handlers.push(hookHandler);
19358 }
19359 };
19360 var handlers = [];
19361 var props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
19362 for(var _iterator = _create_for_of_iterator_helper_loose(props2D), _step; !(_step = _iterator()).done;)_loop();
19363 return function() {
19364 handlers.forEach(function(h) {
19365 return h();
19366 });
19367 };
19368 }
19369 function getNormalizedContextName(contextType) {
19370 return contextType === "experimental-webgl" ? "webgl" : contextType;
19371 }
19372 function initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {
19373 var handlers = [];
19374 try {
19375 var restoreHandler = patch(win.HTMLCanvasElement.prototype, "getContext", function(original) {
19376 return function(contextType) {
19377 for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
19378 args[_key - 1] = arguments[_key];
19379 }
19380 if (!isBlocked(this, blockClass, blockSelector, true)) {
19381 var ctxName = getNormalizedContextName(contextType);
19382 if (!("__context" in this)) this.__context = ctxName;
19383 if (setPreserveDrawingBufferToTrue && [
19384 "webgl",
19385 "webgl2"
19386 ].includes(ctxName)) {
19387 if (args[0] && _type_of(args[0]) === "object") {
19388 var contextAttributes = args[0];
19389 if (!contextAttributes.preserveDrawingBuffer) {
19390 contextAttributes.preserveDrawingBuffer = true;
19391 }
19392 } else {
19393 args.splice(0, 1, {
19394 preserveDrawingBuffer: true
19395 });
19396 }
19397 }
19398 }
19399 return original.apply(this, [].concat([
19400 contextType
19401 ], args));
19402 };
19403 });
19404 handlers.push(restoreHandler);
19405 } catch (e) {
19406 console.error("failed to patch HTMLCanvasElement.prototype.getContext");
19407 }
19408 return function() {
19409 handlers.forEach(function(h) {
19410 return h();
19411 });
19412 };
19413 }
19414 function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win) {
19415 var _loop = function() {
19416 var prop = _step.value;
19417 if (//prop.startsWith('get') || // e.g. getProgramParameter, but too risky
19418 [
19419 "isContextLost",
19420 "canvas",
19421 "drawingBufferWidth",
19422 "drawingBufferHeight"
19423 ].includes(prop)) {
19424 return "continue";
19425 }
19426 try {
19427 if (typeof prototype[prop] !== "function") {
19428 return "continue";
19429 }
19430 var restoreHandler = patch(prototype, prop, function(original) {
19431 return function() {
19432 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
19433 args[_key] = arguments[_key];
19434 }
19435 var result2 = original.apply(this, args);
19436 saveWebGLVar(result2, win, this);
19437 if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {
19438 var recordArgs = serializeArgs(args, win, this);
19439 var mutation = {
19440 type: type,
19441 property: prop,
19442 args: recordArgs
19443 };
19444 cb(this.canvas, mutation);
19445 }
19446 return result2;
19447 };
19448 });
19449 handlers.push(restoreHandler);
19450 } catch (e) {
19451 var hookHandler = hookSetter(prototype, prop, {
19452 set: function set(v2) {
19453 cb(this.canvas, {
19454 type: type,
19455 property: prop,
19456 args: [
19457 v2
19458 ],
19459 setter: true
19460 });
19461 }
19462 });
19463 handlers.push(hookHandler);
19464 }
19465 };
19466 var handlers = [];
19467 var props = Object.getOwnPropertyNames(prototype);
19468 for(var _iterator = _create_for_of_iterator_helper_loose(props), _step; !(_step = _iterator()).done;)_loop();
19469 return handlers;
19470 }
19471 function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector) {
19472 var _handlers;
19473 var handlers = [];
19474 (_handlers = handlers).push.apply(_handlers, [].concat(patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, win)));
19475 if (typeof win.WebGL2RenderingContext !== "undefined") {
19476 var _handlers1;
19477 (_handlers1 = handlers).push.apply(_handlers1, [].concat(patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, win)));
19478 }
19479 return function() {
19480 handlers.forEach(function(h) {
19481 return h();
19482 });
19483 };
19484 }
19485 var encodedJs = "KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=";
19486 var decodeBase64 = function(base64) {
19487 return Uint8Array.from(atob(base64), function(c2) {
19488 return c2.charCodeAt(0);
19489 });
19490 };
19491 var blob = typeof window !== "undefined" && window.Blob && new Blob([
19492 decodeBase64(encodedJs)
19493 ], {
19494 type: "text/javascript;charset=utf-8"
19495 });
19496 function WorkerWrapper(options) {
19497 var objURL;
19498 try {
19499 objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
19500 if (!objURL) throw "";
19501 var worker = new Worker(objURL, {
19502 name: options == null ? void 0 : options.name
19503 });
19504 worker.addEventListener("error", function() {
19505 (window.URL || window.webkitURL).revokeObjectURL(objURL);
19506 });
19507 return worker;
19508 } catch (e2) {
19509 return new Worker("data:text/javascript;base64," + encodedJs, {
19510 name: options == null ? void 0 : options.name
19511 });
19512 } finally{
19513 objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
19514 }
19515 }
19516 var CanvasManager = /*#__PURE__*/ function() {
19517 function CanvasManager(options) {
19518 var _this = this;
19519 __publicField(this, "pendingCanvasMutations", /* @__PURE__ */ new Map());
19520 __publicField(this, "rafStamps", {
19521 latestId: 0,
19522 invokeId: null
19523 });
19524 __publicField(this, "mirror");
19525 __publicField(this, "mutationCb");
19526 __publicField(this, "resetObservers");
19527 __publicField(this, "frozen", false);
19528 __publicField(this, "locked", false);
19529 __publicField(this, "processMutation", function(target, mutation) {
19530 var newFrame = _this.rafStamps.invokeId && _this.rafStamps.latestId !== _this.rafStamps.invokeId;
19531 if (newFrame || !_this.rafStamps.invokeId) _this.rafStamps.invokeId = _this.rafStamps.latestId;
19532 if (!_this.pendingCanvasMutations.has(target)) {
19533 _this.pendingCanvasMutations.set(target, []);
19534 }
19535 _this.pendingCanvasMutations.get(target).push(mutation);
19536 });
19537 var _options_sampling = options.sampling, sampling = _options_sampling === void 0 ? "all" : _options_sampling, win = options.win, blockClass = options.blockClass, blockSelector = options.blockSelector, recordCanvas = options.recordCanvas, dataURLOptions = options.dataURLOptions;
19538 this.mutationCb = options.mutationCb;
19539 this.mirror = options.mirror;
19540 if (recordCanvas && sampling === "all") this.initCanvasMutationObserver(win, blockClass, blockSelector);
19541 if (recordCanvas && typeof sampling === "number") this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
19542 dataURLOptions: dataURLOptions
19543 });
19544 }
19545 var _proto = CanvasManager.prototype;
19546 _proto.reset = function reset() {
19547 this.pendingCanvasMutations.clear();
19548 this.resetObservers && this.resetObservers();
19549 };
19550 _proto.freeze = function freeze() {
19551 this.frozen = true;
19552 };
19553 _proto.unfreeze = function unfreeze() {
19554 this.frozen = false;
19555 };
19556 _proto.lock = function lock() {
19557 this.locked = true;
19558 };
19559 _proto.unlock = function unlock() {
19560 this.locked = false;
19561 };
19562 _proto.initCanvasFPSObserver = function initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
19563 var _this = this;
19564 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, true);
19565 var snapshotInProgressMap = /* @__PURE__ */ new Map();
19566 var worker = new WorkerWrapper();
19567 worker.onmessage = function(e2) {
19568 var id = e2.data.id;
19569 snapshotInProgressMap.set(id, false);
19570 if (!("base64" in e2.data)) return;
19571 var _e2_data = e2.data, base64 = _e2_data.base64, type = _e2_data.type, width = _e2_data.width, height = _e2_data.height;
19572 _this.mutationCb({
19573 id: id,
19574 type: CanvasContext["2D"],
19575 commands: [
19576 {
19577 property: "clearRect",
19578 // wipe canvas
19579 args: [
19580 0,
19581 0,
19582 width,
19583 height
19584 ]
19585 },
19586 {
19587 property: "drawImage",
19588 // draws (semi-transparent) image
19589 args: [
19590 {
19591 rr_type: "ImageBitmap",
19592 args: [
19593 {
19594 rr_type: "Blob",
19595 data: [
19596 {
19597 rr_type: "ArrayBuffer",
19598 base64: base64
19599 }
19600 ],
19601 type: type
19602 }
19603 ]
19604 },
19605 0,
19606 0
19607 ]
19608 }
19609 ]
19610 });
19611 };
19612 var timeBetweenSnapshots = 1e3 / fps;
19613 var lastSnapshotTime = 0;
19614 var rafId;
19615 var getCanvas = function() {
19616 var matchedCanvas = [];
19617 win.document.querySelectorAll("canvas").forEach(function(canvas) {
19618 if (!isBlocked(canvas, blockClass, blockSelector, true)) {
19619 matchedCanvas.push(canvas);
19620 }
19621 });
19622 return matchedCanvas;
19623 };
19624 var takeCanvasSnapshots = function(timestamp) {
19625 if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {
19626 rafId = requestAnimationFrame(takeCanvasSnapshots);
19627 return;
19628 }
19629 lastSnapshotTime = timestamp;
19630 var _this1 = _this;
19631 getCanvas().forEach(/*#__PURE__*/ _async_to_generator(function(canvas) {
19632 var _a2, id, context, bitmap;
19633 return _ts_generator(this, function(_state) {
19634 switch(_state.label){
19635 case 0:
19636 id = _this1.mirror.getId(canvas);
19637 if (snapshotInProgressMap.get(id)) return [
19638 2
19639 ];
19640 if (canvas.width === 0 || canvas.height === 0) return [
19641 2
19642 ];
19643 snapshotInProgressMap.set(id, true);
19644 if ([
19645 "webgl",
19646 "webgl2"
19647 ].includes(canvas.__context)) {
19648 context = canvas.getContext(canvas.__context);
19649 if (((_a2 = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _a2.preserveDrawingBuffer) === false) {
19650 context.clear(context.COLOR_BUFFER_BIT);
19651 }
19652 }
19653 return [
19654 4,
19655 createImageBitmap(canvas)
19656 ];
19657 case 1:
19658 bitmap = _state.sent();
19659 worker.postMessage({
19660 id: id,
19661 bitmap: bitmap,
19662 width: canvas.width,
19663 height: canvas.height,
19664 dataURLOptions: options.dataURLOptions
19665 }, [
19666 bitmap
19667 ]);
19668 return [
19669 2
19670 ];
19671 }
19672 });
19673 }));
19674 rafId = requestAnimationFrame(takeCanvasSnapshots);
19675 };
19676 rafId = requestAnimationFrame(takeCanvasSnapshots);
19677 this.resetObservers = function() {
19678 canvasContextReset();
19679 cancelAnimationFrame(rafId);
19680 };
19681 };
19682 _proto.initCanvasMutationObserver = function initCanvasMutationObserver(win, blockClass, blockSelector) {
19683 this.startRAFTimestamping();
19684 this.startPendingCanvasMutationFlusher();
19685 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, false);
19686 var canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
19687 var canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
19688 this.resetObservers = function() {
19689 canvasContextReset();
19690 canvas2DReset();
19691 canvasWebGL1and2Reset();
19692 };
19693 };
19694 _proto.startPendingCanvasMutationFlusher = function startPendingCanvasMutationFlusher() {
19695 var _this = this;
19696 requestAnimationFrame(function() {
19697 return _this.flushPendingCanvasMutations();
19698 });
19699 };
19700 _proto.startRAFTimestamping = function startRAFTimestamping() {
19701 var _this = this;
19702 var setLatestRAFTimestamp = function(timestamp) {
19703 _this.rafStamps.latestId = timestamp;
19704 requestAnimationFrame(setLatestRAFTimestamp);
19705 };
19706 requestAnimationFrame(setLatestRAFTimestamp);
19707 };
19708 _proto.flushPendingCanvasMutations = function flushPendingCanvasMutations() {
19709 var _this = this;
19710 this.pendingCanvasMutations.forEach(function(_values, canvas) {
19711 var id = _this.mirror.getId(canvas);
19712 _this.flushPendingCanvasMutationFor(canvas, id);
19713 });
19714 requestAnimationFrame(function() {
19715 return _this.flushPendingCanvasMutations();
19716 });
19717 };
19718 _proto.flushPendingCanvasMutationFor = function flushPendingCanvasMutationFor(canvas, id) {
19719 if (this.frozen || this.locked) {
19720 return;
19721 }
19722 var valuesWithType = this.pendingCanvasMutations.get(canvas);
19723 if (!valuesWithType || id === -1) return;
19724 var values = valuesWithType.map(function(value) {
19725 value.type; var rest = _object_without_properties_loose(value, [
19726 "type"
19727 ]);
19728 return rest;
19729 });
19730 var type = valuesWithType[0].type;
19731 this.mutationCb({
19732 id: id,
19733 type: type,
19734 commands: values
19735 });
19736 this.pendingCanvasMutations.delete(canvas);
19737 };
19738 return CanvasManager;
19739 }();
19740 var StylesheetManager = /*#__PURE__*/ function() {
19741 function StylesheetManager(options) {
19742 __publicField(this, "trackedLinkElements", /* @__PURE__ */ new WeakSet());
19743 __publicField(this, "mutationCb");
19744 __publicField(this, "adoptedStyleSheetCb");
19745 __publicField(this, "styleMirror", new StyleSheetMirror());
19746 this.mutationCb = options.mutationCb;
19747 this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
19748 }
19749 var _proto = StylesheetManager.prototype;
19750 _proto.attachLinkElement = function attachLinkElement(linkEl, childSn) {
19751 if ("_cssText" in childSn.attributes) this.mutationCb({
19752 adds: [],
19753 removes: [],
19754 texts: [],
19755 attributes: [
19756 {
19757 id: childSn.id,
19758 attributes: childSn.attributes
19759 }
19760 ]
19761 });
19762 this.trackLinkElement(linkEl);
19763 };
19764 _proto.trackLinkElement = function trackLinkElement(linkEl) {
19765 if (this.trackedLinkElements.has(linkEl)) return;
19766 this.trackedLinkElements.add(linkEl);
19767 this.trackStylesheetInLinkElement(linkEl);
19768 };
19769 _proto.adoptStyleSheets = function adoptStyleSheets(sheets, hostId) {
19770 var _this, _loop = function() {
19771 var sheet = _step.value;
19772 var styleId = void 0;
19773 if (!_this.styleMirror.has(sheet)) {
19774 styleId = _this.styleMirror.add(sheet);
19775 styles.push({
19776 styleId: styleId,
19777 rules: Array.from(sheet.rules || CSSRule, function(r2, index2) {
19778 return {
19779 rule: stringifyRule(r2, sheet.href),
19780 index: index2
19781 };
19782 })
19783 });
19784 } else styleId = _this.styleMirror.getId(sheet);
19785 adoptedStyleSheetData.styleIds.push(styleId);
19786 };
19787 if (sheets.length === 0) return;
19788 var adoptedStyleSheetData = {
19789 id: hostId,
19790 styleIds: []
19791 };
19792 var styles = [];
19793 for(var _iterator = _create_for_of_iterator_helper_loose(sheets), _step; !(_step = _iterator()).done;)_this = this, _loop();
19794 if (styles.length > 0) adoptedStyleSheetData.styles = styles;
19795 this.adoptedStyleSheetCb(adoptedStyleSheetData);
19796 };
19797 _proto.reset = function reset() {
19798 this.styleMirror.reset();
19799 this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
19800 };
19801 // TODO: take snapshot on stylesheet reload by applying event listener
19802 _proto.trackStylesheetInLinkElement = function trackStylesheetInLinkElement(_linkEl) {};
19803 return StylesheetManager;
19804 }();
19805 var ProcessedNodeManager = /*#__PURE__*/ function() {
19806 function ProcessedNodeManager() {
19807 __publicField(this, "nodeMap", /* @__PURE__ */ new WeakMap());
19808 __publicField(this, "active", false);
19809 }
19810 var _proto = ProcessedNodeManager.prototype;
19811 _proto.inOtherBuffer = function inOtherBuffer(node2, thisBuffer) {
19812 var buffers = this.nodeMap.get(node2);
19813 return buffers && Array.from(buffers).some(function(buffer) {
19814 return buffer !== thisBuffer;
19815 });
19816 };
19817 _proto.add = function add(node2, buffer) {
19818 var _this = this;
19819 if (!this.active) {
19820 this.active = true;
19821 requestAnimationFrame(function() {
19822 _this.nodeMap = /* @__PURE__ */ new WeakMap();
19823 _this.active = false;
19824 });
19825 }
19826 this.nodeMap.set(node2, (this.nodeMap.get(node2) || /* @__PURE__ */ new Set()).add(buffer));
19827 };
19828 _proto.destroy = function destroy() {};
19829 return ProcessedNodeManager;
19830 }();
19831 var wrappedEmit;
19832 var takeFullSnapshot$1;
19833 var canvasManager;
19834 var recording = false;
19835 try {
19836 if (Array.from([
19837 1
19838 ], function(x2) {
19839 return x2 * 2;
19840 })[0] !== 2) {
19841 var cleanFrame = document.createElement("iframe");
19842 document.body.appendChild(cleanFrame);
19843 Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;
19844 document.body.removeChild(cleanFrame);
19845 }
19846 } catch (err) {
19847 console.debug("Unable to override Array.from", err);
19848 }
19849 var mirror = createMirror$2();
19850 function record(options) {
19851 if (options === void 0) options = {};
19852 var emit = options.emit, checkoutEveryNms = options.checkoutEveryNms, checkoutEveryNth = options.checkoutEveryNth, _options_blockClass = options.blockClass, blockClass = _options_blockClass === void 0 ? "rr-block" : _options_blockClass, _options_blockSelector = options.blockSelector, blockSelector = _options_blockSelector === void 0 ? null : _options_blockSelector, _options_ignoreClass = options.ignoreClass, ignoreClass = _options_ignoreClass === void 0 ? "rr-ignore" : _options_ignoreClass, _options_ignoreSelector = options.ignoreSelector, ignoreSelector = _options_ignoreSelector === void 0 ? null : _options_ignoreSelector, _options_maskTextClass = options.maskTextClass, maskTextClass = _options_maskTextClass === void 0 ? "rr-mask" : _options_maskTextClass, _options_maskTextSelector = options.maskTextSelector, maskTextSelector = _options_maskTextSelector === void 0 ? null : _options_maskTextSelector, _options_inlineStylesheet = options.inlineStylesheet, inlineStylesheet = _options_inlineStylesheet === void 0 ? true : _options_inlineStylesheet, maskAllInputs = options.maskAllInputs, _maskInputOptions = options.maskInputOptions, _slimDOMOptions = options.slimDOMOptions, maskInputFn = options.maskInputFn, maskTextFn = options.maskTextFn, hooks = options.hooks, packFn = options.packFn, _options_sampling = options.sampling, sampling = _options_sampling === void 0 ? {} : _options_sampling, _options_dataURLOptions = options.dataURLOptions, dataURLOptions = _options_dataURLOptions === void 0 ? {} : _options_dataURLOptions, mousemoveWait = options.mousemoveWait, _options_recordDOM = options.recordDOM, recordDOM = _options_recordDOM === void 0 ? true : _options_recordDOM, _options_recordCanvas = options.recordCanvas, recordCanvas = _options_recordCanvas === void 0 ? false : _options_recordCanvas, _options_recordCrossOriginIframes = options.recordCrossOriginIframes, recordCrossOriginIframes = _options_recordCrossOriginIframes === void 0 ? false : _options_recordCrossOriginIframes, _options_recordAfter = options.recordAfter, recordAfter = _options_recordAfter === void 0 ? options.recordAfter === "DOMContentLoaded" ? options.recordAfter : "load" : _options_recordAfter, _options_userTriggeredOnInput = options.userTriggeredOnInput, userTriggeredOnInput = _options_userTriggeredOnInput === void 0 ? false : _options_userTriggeredOnInput, _options_collectFonts = options.collectFonts, collectFonts = _options_collectFonts === void 0 ? false : _options_collectFonts, _options_inlineImages = options.inlineImages, inlineImages = _options_inlineImages === void 0 ? false : _options_inlineImages, plugins = options.plugins, _options_keepIframeSrcFn = options.keepIframeSrcFn, keepIframeSrcFn = _options_keepIframeSrcFn === void 0 ? function() {
19853 return false;
19854 } : _options_keepIframeSrcFn, _options_ignoreCSSAttributes = options.ignoreCSSAttributes, ignoreCSSAttributes = _options_ignoreCSSAttributes === void 0 ? /* @__PURE__ */ new Set([]) : _options_ignoreCSSAttributes, errorHandler2 = options.errorHandler;
19855 registerErrorHandler(errorHandler2);
19856 var inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
19857 var passEmitsToParent = false;
19858 if (!inEmittingFrame) {
19859 try {
19860 if (window.parent.document) {
19861 passEmitsToParent = false;
19862 }
19863 } catch (e2) {
19864 passEmitsToParent = true;
19865 }
19866 }
19867 if (inEmittingFrame && !emit) {
19868 throw new Error("emit function is required");
19869 }
19870 if (!inEmittingFrame && !passEmitsToParent) {
19871 return function() {};
19872 }
19873 if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {
19874 sampling.mousemove = mousemoveWait;
19875 }
19876 mirror.reset();
19877 var maskInputOptions = maskAllInputs === true ? {
19878 color: true,
19879 date: true,
19880 "datetime-local": true,
19881 email: true,
19882 month: true,
19883 number: true,
19884 range: true,
19885 search: true,
19886 tel: true,
19887 text: true,
19888 time: true,
19889 url: true,
19890 week: true,
19891 textarea: true,
19892 select: true,
19893 password: true,
19894 hidden: true
19895 } : _maskInputOptions !== void 0 ? _maskInputOptions : {
19896 password: true
19897 };
19898 var slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? {
19899 script: true,
19900 comment: true,
19901 headFavicon: true,
19902 headWhitespace: true,
19903 headMetaSocial: true,
19904 headMetaRobots: true,
19905 headMetaHttpEquiv: true,
19906 headMetaVerification: true,
19907 // the following are off for slimDOMOptions === true,
19908 // as they destroy some (hidden) info:
19909 headMetaAuthorship: _slimDOMOptions === "all",
19910 headMetaDescKeywords: _slimDOMOptions === "all",
19911 headTitleMutations: _slimDOMOptions === "all"
19912 } : _slimDOMOptions ? _slimDOMOptions : {};
19913 polyfill$1();
19914 var lastFullSnapshotEvent;
19915 var incrementalSnapshotCount = 0;
19916 var eventProcessor = function(e2) {
19917 for(var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;){
19918 var plugin3 = _step.value;
19919 if (plugin3.eventProcessor) {
19920 e2 = plugin3.eventProcessor(e2);
19921 }
19922 }
19923 if (packFn && // Disable packing events which will be emitted to parent frames.
19924 !passEmitsToParent) {
19925 e2 = packFn(e2);
19926 }
19927 return e2;
19928 };
19929 wrappedEmit = function(r2, isCheckout) {
19930 var _a2;
19931 var e2 = r2;
19932 e2.timestamp = nowTimestamp();
19933 if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) {
19934 mutationBuffers.forEach(function(buf) {
19935 return buf.unfreeze();
19936 });
19937 }
19938 if (inEmittingFrame) {
19939 emit == null ? void 0 : emit(eventProcessor(e2), isCheckout);
19940 } else if (passEmitsToParent) {
19941 var message = {
19942 type: "rrweb",
19943 event: eventProcessor(e2),
19944 origin: window.location.origin,
19945 isCheckout: isCheckout
19946 };
19947 window.parent.postMessage(message, "*");
19948 }
19949 if (e2.type === EventType.FullSnapshot) {
19950 lastFullSnapshotEvent = e2;
19951 incrementalSnapshotCount = 0;
19952 } else if (e2.type === EventType.IncrementalSnapshot) {
19953 if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) {
19954 return;
19955 }
19956 incrementalSnapshotCount++;
19957 var exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
19958 var exceedTime = checkoutEveryNms && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
19959 if (exceedCount || exceedTime) {
19960 takeFullSnapshot$1(true);
19961 }
19962 }
19963 };
19964 var wrappedMutationEmit = function(m) {
19965 wrappedEmit({
19966 type: EventType.IncrementalSnapshot,
19967 data: _extends({
19968 source: IncrementalSource.Mutation
19969 }, m)
19970 });
19971 };
19972 var wrappedScrollEmit = function(p) {
19973 return wrappedEmit({
19974 type: EventType.IncrementalSnapshot,
19975 data: _extends({
19976 source: IncrementalSource.Scroll
19977 }, p)
19978 });
19979 };
19980 var wrappedCanvasMutationEmit = function(p) {
19981 return wrappedEmit({
19982 type: EventType.IncrementalSnapshot,
19983 data: _extends({
19984 source: IncrementalSource.CanvasMutation
19985 }, p)
19986 });
19987 };
19988 var wrappedAdoptedStyleSheetEmit = function(a2) {
19989 return wrappedEmit({
19990 type: EventType.IncrementalSnapshot,
19991 data: _extends({
19992 source: IncrementalSource.AdoptedStyleSheet
19993 }, a2)
19994 });
19995 };
19996 var stylesheetManager = new StylesheetManager({
19997 mutationCb: wrappedMutationEmit,
19998 adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
19999 });
20000 var iframeManager = new IframeManager({
20001 mirror: mirror,
20002 mutationCb: wrappedMutationEmit,
20003 stylesheetManager: stylesheetManager,
20004 recordCrossOriginIframes: recordCrossOriginIframes,
20005 wrappedEmit: wrappedEmit
20006 });
20007 for(var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;){
20008 var plugin3 = _step.value;
20009 if (plugin3.getMirror) plugin3.getMirror({
20010 nodeMirror: mirror,
20011 crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
20012 crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
20013 });
20014 }
20015 var processedNodeManager = new ProcessedNodeManager();
20016 canvasManager = new CanvasManager({
20017 recordCanvas: recordCanvas,
20018 mutationCb: wrappedCanvasMutationEmit,
20019 win: window,
20020 blockClass: blockClass,
20021 blockSelector: blockSelector,
20022 mirror: mirror,
20023 sampling: sampling.canvas,
20024 dataURLOptions: dataURLOptions
20025 });
20026 var shadowDomManager = new ShadowDomManager({
20027 mutationCb: wrappedMutationEmit,
20028 scrollCb: wrappedScrollEmit,
20029 bypassOptions: {
20030 blockClass: blockClass,
20031 blockSelector: blockSelector,
20032 maskTextClass: maskTextClass,
20033 maskTextSelector: maskTextSelector,
20034 inlineStylesheet: inlineStylesheet,
20035 maskInputOptions: maskInputOptions,
20036 dataURLOptions: dataURLOptions,
20037 maskTextFn: maskTextFn,
20038 maskInputFn: maskInputFn,
20039 recordCanvas: recordCanvas,
20040 inlineImages: inlineImages,
20041 sampling: sampling,
20042 slimDOMOptions: slimDOMOptions,
20043 iframeManager: iframeManager,
20044 stylesheetManager: stylesheetManager,
20045 canvasManager: canvasManager,
20046 keepIframeSrcFn: keepIframeSrcFn,
20047 processedNodeManager: processedNodeManager
20048 },
20049 mirror: mirror
20050 });
20051 takeFullSnapshot$1 = function(isCheckout) {
20052 if (isCheckout === void 0) isCheckout = false;
20053 if (!recordDOM) {
20054 return;
20055 }
20056 wrappedEmit({
20057 type: EventType.Meta,
20058 data: {
20059 href: window.location.href,
20060 width: getWindowWidth(),
20061 height: getWindowHeight()
20062 }
20063 }, isCheckout);
20064 stylesheetManager.reset();
20065 shadowDomManager.init();
20066 mutationBuffers.forEach(function(buf) {
20067 return buf.lock();
20068 });
20069 var node2 = snapshot(document, {
20070 mirror: mirror,
20071 blockClass: blockClass,
20072 blockSelector: blockSelector,
20073 maskTextClass: maskTextClass,
20074 maskTextSelector: maskTextSelector,
20075 inlineStylesheet: inlineStylesheet,
20076 maskAllInputs: maskInputOptions,
20077 maskTextFn: maskTextFn,
20078 maskInputFn: maskInputFn,
20079 slimDOM: slimDOMOptions,
20080 dataURLOptions: dataURLOptions,
20081 recordCanvas: recordCanvas,
20082 inlineImages: inlineImages,
20083 onSerialize: function(n2) {
20084 if (isSerializedIframe(n2, mirror)) {
20085 iframeManager.addIframe(n2);
20086 }
20087 if (isSerializedStylesheet(n2, mirror)) {
20088 stylesheetManager.trackLinkElement(n2);
20089 }
20090 if (hasShadowRoot(n2)) {
20091 shadowDomManager.addShadowRoot(index.shadowRoot(n2), document);
20092 }
20093 },
20094 onIframeLoad: function(iframe, childSn) {
20095 iframeManager.attachIframe(iframe, childSn);
20096 shadowDomManager.observeAttachShadow(iframe);
20097 },
20098 onStylesheetLoad: function(linkEl, childSn) {
20099 stylesheetManager.attachLinkElement(linkEl, childSn);
20100 },
20101 keepIframeSrcFn: keepIframeSrcFn
20102 });
20103 if (!node2) {
20104 return console.warn("Failed to snapshot the document");
20105 }
20106 wrappedEmit({
20107 type: EventType.FullSnapshot,
20108 data: {
20109 node: node2,
20110 initialOffset: getWindowScroll(window)
20111 }
20112 }, isCheckout);
20113 mutationBuffers.forEach(function(buf) {
20114 return buf.unlock();
20115 });
20116 if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
20117 };
20118 try {
20119 var handlers = [];
20120 var observe = function(doc) {
20121 var _a2;
20122 return callbackWrapper(initObservers)({
20123 mutationCb: wrappedMutationEmit,
20124 mousemoveCb: function(positions, source) {
20125 return wrappedEmit({
20126 type: EventType.IncrementalSnapshot,
20127 data: {
20128 source: source,
20129 positions: positions
20130 }
20131 });
20132 },
20133 mouseInteractionCb: function(d) {
20134 return wrappedEmit({
20135 type: EventType.IncrementalSnapshot,
20136 data: _extends({
20137 source: IncrementalSource.MouseInteraction
20138 }, d)
20139 });
20140 },
20141 scrollCb: wrappedScrollEmit,
20142 viewportResizeCb: function(d) {
20143 return wrappedEmit({
20144 type: EventType.IncrementalSnapshot,
20145 data: _extends({
20146 source: IncrementalSource.ViewportResize
20147 }, d)
20148 });
20149 },
20150 inputCb: function(v2) {
20151 return wrappedEmit({
20152 type: EventType.IncrementalSnapshot,
20153 data: _extends({
20154 source: IncrementalSource.Input
20155 }, v2)
20156 });
20157 },
20158 mediaInteractionCb: function(p) {
20159 return wrappedEmit({
20160 type: EventType.IncrementalSnapshot,
20161 data: _extends({
20162 source: IncrementalSource.MediaInteraction
20163 }, p)
20164 });
20165 },
20166 styleSheetRuleCb: function(r2) {
20167 return wrappedEmit({
20168 type: EventType.IncrementalSnapshot,
20169 data: _extends({
20170 source: IncrementalSource.StyleSheetRule
20171 }, r2)
20172 });
20173 },
20174 styleDeclarationCb: function(r2) {
20175 return wrappedEmit({
20176 type: EventType.IncrementalSnapshot,
20177 data: _extends({
20178 source: IncrementalSource.StyleDeclaration
20179 }, r2)
20180 });
20181 },
20182 canvasMutationCb: wrappedCanvasMutationEmit,
20183 fontCb: function(p) {
20184 return wrappedEmit({
20185 type: EventType.IncrementalSnapshot,
20186 data: _extends({
20187 source: IncrementalSource.Font
20188 }, p)
20189 });
20190 },
20191 selectionCb: function(p) {
20192 wrappedEmit({
20193 type: EventType.IncrementalSnapshot,
20194 data: _extends({
20195 source: IncrementalSource.Selection
20196 }, p)
20197 });
20198 },
20199 customElementCb: function(c2) {
20200 wrappedEmit({
20201 type: EventType.IncrementalSnapshot,
20202 data: _extends({
20203 source: IncrementalSource.CustomElement
20204 }, c2)
20205 });
20206 },
20207 blockClass: blockClass,
20208 ignoreClass: ignoreClass,
20209 ignoreSelector: ignoreSelector,
20210 maskTextClass: maskTextClass,
20211 maskTextSelector: maskTextSelector,
20212 maskInputOptions: maskInputOptions,
20213 inlineStylesheet: inlineStylesheet,
20214 sampling: sampling,
20215 recordDOM: recordDOM,
20216 recordCanvas: recordCanvas,
20217 inlineImages: inlineImages,
20218 userTriggeredOnInput: userTriggeredOnInput,
20219 collectFonts: collectFonts,
20220 doc: doc,
20221 maskInputFn: maskInputFn,
20222 maskTextFn: maskTextFn,
20223 keepIframeSrcFn: keepIframeSrcFn,
20224 blockSelector: blockSelector,
20225 slimDOMOptions: slimDOMOptions,
20226 dataURLOptions: dataURLOptions,
20227 mirror: mirror,
20228 iframeManager: iframeManager,
20229 stylesheetManager: stylesheetManager,
20230 shadowDomManager: shadowDomManager,
20231 processedNodeManager: processedNodeManager,
20232 canvasManager: canvasManager,
20233 ignoreCSSAttributes: ignoreCSSAttributes,
20234 plugins: ((_a2 = plugins == null ? void 0 : plugins.filter(function(p) {
20235 return p.observer;
20236 })) == null ? void 0 : _a2.map(function(p) {
20237 return {
20238 observer: p.observer,
20239 options: p.options,
20240 callback: function(payload) {
20241 return wrappedEmit({
20242 type: EventType.Plugin,
20243 data: {
20244 plugin: p.name,
20245 payload: payload
20246 }
20247 });
20248 }
20249 };
20250 })) || []
20251 }, hooks);
20252 };
20253 iframeManager.addLoadListener(function(iframeEl) {
20254 try {
20255 handlers.push(observe(iframeEl.contentDocument));
20256 } catch (error) {
20257 console.warn(error);
20258 }
20259 });
20260 var init = function() {
20261 takeFullSnapshot$1();
20262 handlers.push(observe(document));
20263 recording = true;
20264 };
20265 if (document.readyState === "interactive" || document.readyState === "complete") {
20266 init();
20267 } else {
20268 handlers.push(on("DOMContentLoaded", function() {
20269 wrappedEmit({
20270 type: EventType.DomContentLoaded,
20271 data: {}
20272 });
20273 if (recordAfter === "DOMContentLoaded") init();
20274 }));
20275 handlers.push(on("load", function() {
20276 wrappedEmit({
20277 type: EventType.Load,
20278 data: {}
20279 });
20280 if (recordAfter === "load") init();
20281 }, window));
20282 }
20283 return function() {
20284 handlers.forEach(function(handler) {
20285 try {
20286 handler();
20287 } catch (error) {
20288 var msg = String(error).toLowerCase();
20289 if (!msg.includes("cross-origin")) {
20290 console.warn(error);
20291 }
20292 }
20293 });
20294 processedNodeManager.destroy();
20295 recording = false;
20296 unregisterErrorHandler();
20297 };
20298 } catch (error) {
20299 console.warn(error);
20300 }
20301 }
20302 record.addCustomEvent = function(tag, payload) {
20303 if (!recording) {
20304 throw new Error("please add custom event after start recording");
20305 }
20306 wrappedEmit({
20307 type: EventType.Custom,
20308 data: {
20309 tag: tag,
20310 payload: payload
20311 }
20312 });
20313 };
20314 record.freezePage = function() {
20315 mutationBuffers.forEach(function(buf) {
20316 return buf.freeze();
20317 });
20318 };
20319 record.takeFullSnapshot = function(isCheckout) {
20320 if (!recording) {
20321 throw new Error("please take full snapshot after start recording");
20322 }
20323 takeFullSnapshot$1(isCheckout);
20324 };
20325 record.mirror = mirror;
20326 var n;
20327 !function(t2) {
20328 t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped";
20329 }(n || (n = {}));
20330 record.addCustomEvent;
20331 record.freezePage;
20332 record.takeFullSnapshot;
20333
20334 var setImmediate = win['setImmediate'];
20335 var builtInProp, cycle, schedulingQueue,
20336 ToString = Object.prototype.toString,
20337 timer = (typeof setImmediate !== 'undefined') ?
20338 function timer(fn) { return setImmediate(fn); } :
20339 setTimeout;
20340
20341 // dammit, IE8.
20342 try {
20343 Object.defineProperty({},'x',{});
20344 builtInProp = function builtInProp(obj,name,val,config) {
20345 return Object.defineProperty(obj,name,{
20346 value: val,
20347 writable: true,
20348 configurable: config !== false
20349 });
20350 };
20351 }
20352 catch (err) {
20353 builtInProp = function builtInProp(obj,name,val) {
20354 obj[name] = val;
20355 return obj;
20356 };
20357 }
20358
20359 // Note: using a queue instead of array for efficiency
20360 schedulingQueue = (function Queue() {
20361 var first, last, item;
20362
20363 function Item(fn,self) {
20364 this.fn = fn;
20365 this.self = self;
20366 this.next = void 0;
20367 }
20368
20369 return {
20370 add: function add(fn,self) {
20371 item = new Item(fn,self);
20372 if (last) {
20373 last.next = item;
20374 }
20375 else {
20376 first = item;
20377 }
20378 last = item;
20379 item = void 0;
20380 },
20381 drain: function drain() {
20382 var f = first;
20383 first = last = cycle = void 0;
20384
20385 while (f) {
20386 f.fn.call(f.self);
20387 f = f.next;
20388 }
20389 }
20390 };
20391 })();
20392
20393 function schedule(fn,self) {
20394 schedulingQueue.add(fn,self);
20395 if (!cycle) {
20396 cycle = timer(schedulingQueue.drain);
20397 }
20398 }
20399
20400 // promise duck typing
20401 function isThenable(o) {
20402 var _then, oType = typeof o;
20403
20404 if (o !== null && (oType === 'object' || oType === 'function')) {
20405 _then = o.then;
20406 }
20407 return typeof _then === 'function' ? _then : false;
20408 }
20409
20410 function notify() {
20411 for (var i=0; i<this.chain.length; i++) {
20412 notifyIsolated(
20413 this,
20414 (this.state === 1) ? this.chain[i].success : this.chain[i].failure,
20415 this.chain[i]
20416 );
20417 }
20418 this.chain.length = 0;
20419 }
20420
20421 // NOTE: This is a separate function to isolate
20422 // the `try..catch` so that other code can be
20423 // optimized better
20424 function notifyIsolated(self,cb,chain) {
20425 var ret, _then;
20426 try {
20427 if (cb === false) {
20428 chain.reject(self.msg);
20429 }
20430 else {
20431 if (cb === true) {
20432 ret = self.msg;
20433 }
20434 else {
20435 ret = cb.call(void 0,self.msg);
20436 }
20437
20438 if (ret === chain.promise) {
20439 chain.reject(TypeError('Promise-chain cycle'));
20440 }
20441 // eslint-disable-next-line no-cond-assign
20442 else if (_then = isThenable(ret)) {
20443 _then.call(ret,chain.resolve,chain.reject);
20444 }
20445 else {
20446 chain.resolve(ret);
20447 }
20448 }
20449 }
20450 catch (err) {
20451 chain.reject(err);
20452 }
20453 }
20454
20455 function resolve(msg) {
20456 var _then, self = this;
20457
20458 // already triggered?
20459 if (self.triggered) { return; }
20460
20461 self.triggered = true;
20462
20463 // unwrap
20464 if (self.def) {
20465 self = self.def;
20466 }
20467
20468 try {
20469 // eslint-disable-next-line no-cond-assign
20470 if (_then = isThenable(msg)) {
20471 schedule(function(){
20472 var defWrapper = new MakeDefWrapper(self);
20473 try {
20474 _then.call(msg,
20475 function $resolve$(){ resolve.apply(defWrapper,arguments); },
20476 function $reject$(){ reject.apply(defWrapper,arguments); }
20477 );
20478 }
20479 catch (err) {
20480 reject.call(defWrapper,err);
20481 }
20482 });
20483 }
20484 else {
20485 self.msg = msg;
20486 self.state = 1;
20487 if (self.chain.length > 0) {
20488 schedule(notify,self);
20489 }
20490 }
20491 }
20492 catch (err) {
20493 reject.call(new MakeDefWrapper(self),err);
20494 }
20495 }
20496
20497 function reject(msg) {
20498 var self = this;
20499
20500 // already triggered?
20501 if (self.triggered) { return; }
20502
20503 self.triggered = true;
20504
20505 // unwrap
20506 if (self.def) {
20507 self = self.def;
20508 }
20509
20510 self.msg = msg;
20511 self.state = 2;
20512 if (self.chain.length > 0) {
20513 schedule(notify,self);
20514 }
20515 }
20516
20517 function iteratePromises(Constructor,arr,resolver,rejecter) {
20518 for (var idx=0; idx<arr.length; idx++) {
20519 (function IIFE(idx){
20520 Constructor.resolve(arr[idx])
20521 .then(
20522 function $resolver$(msg){
20523 resolver(idx,msg);
20524 },
20525 rejecter
20526 );
20527 })(idx);
20528 }
20529 }
20530
20531 function MakeDefWrapper(self) {
20532 this.def = self;
20533 this.triggered = false;
20534 }
20535
20536 function MakeDef(self) {
20537 this.promise = self;
20538 this.state = 0;
20539 this.triggered = false;
20540 this.chain = [];
20541 this.msg = void 0;
20542 }
20543
20544 function NpoPromise(executor) {
20545 if (typeof executor !== 'function') {
20546 throw TypeError('Not a function');
20547 }
20548
20549 if (this['__NPO__'] !== 0) {
20550 throw TypeError('Not a promise');
20551 }
20552
20553 // instance shadowing the inherited "brand"
20554 // to signal an already "initialized" promise
20555 this['__NPO__'] = 1;
20556
20557 var def = new MakeDef(this);
20558
20559 this['then'] = function then(success,failure) {
20560 var o = {
20561 success: typeof success === 'function' ? success : true,
20562 failure: typeof failure === 'function' ? failure : false
20563 };
20564 // Note: `then(..)` itself can be borrowed to be used against
20565 // a different promise constructor for making the chained promise,
20566 // by substituting a different `this` binding.
20567 o.promise = new this.constructor(function extractChain(resolve,reject) {
20568 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20569 throw TypeError('Not a function');
20570 }
20571
20572 o.resolve = resolve;
20573 o.reject = reject;
20574 });
20575 def.chain.push(o);
20576
20577 if (def.state !== 0) {
20578 schedule(notify,def);
20579 }
20580
20581 return o.promise;
20582 };
20583 this['catch'] = function $catch$(failure) {
20584 return this.then(void 0,failure);
20585 };
20586
20587 try {
20588 executor.call(
20589 void 0,
20590 function publicResolve(msg){
20591 resolve.call(def,msg);
20592 },
20593 function publicReject(msg) {
20594 reject.call(def,msg);
20595 }
20596 );
20597 }
20598 catch (err) {
20599 reject.call(def,err);
20600 }
20601 }
20602
20603 var PromisePrototype = builtInProp({},'constructor',NpoPromise,
20604 /*configurable=*/false
20605 );
20606
20607 // Note: Android 4 cannot use `Object.defineProperty(..)` here
20608 NpoPromise.prototype = PromisePrototype;
20609
20610 // built-in "brand" to signal an "uninitialized" promise
20611 builtInProp(PromisePrototype,'__NPO__',0,
20612 /*configurable=*/false
20613 );
20614
20615 builtInProp(NpoPromise,'resolve',function Promise$resolve(msg) {
20616 var Constructor = this;
20617
20618 // spec mandated checks
20619 // note: best "isPromise" check that's practical for now
20620 if (msg && typeof msg === 'object' && msg['__NPO__'] === 1) {
20621 return msg;
20622 }
20623
20624 return new Constructor(function executor(resolve,reject){
20625 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20626 throw TypeError('Not a function');
20627 }
20628
20629 resolve(msg);
20630 });
20631 });
20632
20633 builtInProp(NpoPromise,'reject',function Promise$reject(msg) {
20634 return new this(function executor(resolve,reject){
20635 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20636 throw TypeError('Not a function');
20637 }
20638
20639 reject(msg);
20640 });
20641 });
20642
20643 builtInProp(NpoPromise,'all',function Promise$all(arr) {
20644 var Constructor = this;
20645
20646 // spec mandated checks
20647 if (ToString.call(arr) !== '[object Array]') {
20648 return Constructor.reject(TypeError('Not an array'));
20649 }
20650 if (arr.length === 0) {
20651 return Constructor.resolve([]);
20652 }
20653
20654 return new Constructor(function executor(resolve,reject){
20655 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20656 throw TypeError('Not a function');
20657 }
20658
20659 var len = arr.length, msgs = Array(len), count = 0;
20660
20661 iteratePromises(Constructor,arr,function resolver(idx,msg) {
20662 msgs[idx] = msg;
20663 if (++count === len) {
20664 resolve(msgs);
20665 }
20666 },reject);
20667 });
20668 });
20669
20670 builtInProp(NpoPromise,'race',function Promise$race(arr) {
20671 var Constructor = this;
20672
20673 // spec mandated checks
20674 if (ToString.call(arr) !== '[object Array]') {
20675 return Constructor.reject(TypeError('Not an array'));
20676 }
20677
20678 return new Constructor(function executor(resolve,reject){
20679 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20680 throw TypeError('Not a function');
20681 }
20682
20683 iteratePromises(Constructor,arr,function resolver(idx,msg){
20684 resolve(msg);
20685 },reject);
20686 });
20687 });
20688
20689 var PromisePolyfill;
20690 if (typeof Promise !== 'undefined' && Promise.toString().indexOf('[native code]') !== -1) {
20691 PromisePolyfill = Promise;
20692 } else {
20693 PromisePolyfill = NpoPromise;
20694 }
20695
20696 var Config = {
20697 DEBUG: false,
20698 LIB_VERSION: '2.71.1'
20699 };
20700
20701 /* eslint camelcase: "off", eqeqeq: "off" */
20702
20703 // Maximum allowed session recording length
20704 var MAX_RECORDING_MS = 24 * 60 * 60 * 1000; // 24 hours
20705 // Maximum allowed value for minimum session recording length
20706 var MAX_VALUE_FOR_MIN_RECORDING_MS = 8 * 1000; // 8 seconds
20707
20708 /*
20709 * Saved references to long variable names, so that closure compiler can
20710 * minimize file size.
20711 */
20712
20713 var ArrayProto = Array.prototype,
20714 FuncProto = Function.prototype,
20715 ObjProto = Object.prototype,
20716 slice = ArrayProto.slice,
20717 toString = ObjProto.toString,
20718 hasOwnProperty = ObjProto.hasOwnProperty,
20719 windowConsole = win.console,
20720 navigator = win.navigator,
20721 document$1 = win.document,
20722 windowOpera = win.opera,
20723 screen = win.screen,
20724 userAgent = navigator.userAgent;
20725
20726 var nativeBind = FuncProto.bind,
20727 nativeForEach = ArrayProto.forEach,
20728 nativeIndexOf = ArrayProto.indexOf,
20729 nativeMap = ArrayProto.map,
20730 nativeIsArray = Array.isArray,
20731 breaker = {};
20732
20733 var _ = {
20734 trim: function(str) {
20735 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
20736 return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
20737 }
20738 };
20739
20740 // Console override
20741 var console$1 = {
20742 /** @type {function(...*)} */
20743 log: function() {
20744 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
20745 try {
20746 windowConsole.log.apply(windowConsole, arguments);
20747 } catch (err) {
20748 _.each(arguments, function(arg) {
20749 windowConsole.log(arg);
20750 });
20751 }
20752 }
20753 },
20754 /** @type {function(...*)} */
20755 warn: function() {
20756 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
20757 var args = ['Mixpanel warning:'].concat(_.toArray(arguments));
20758 try {
20759 windowConsole.warn.apply(windowConsole, args);
20760 } catch (err) {
20761 _.each(args, function(arg) {
20762 windowConsole.warn(arg);
20763 });
20764 }
20765 }
20766 },
20767 /** @type {function(...*)} */
20768 error: function() {
20769 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
20770 var args = ['Mixpanel error:'].concat(_.toArray(arguments));
20771 try {
20772 windowConsole.error.apply(windowConsole, args);
20773 } catch (err) {
20774 _.each(args, function(arg) {
20775 windowConsole.error(arg);
20776 });
20777 }
20778 }
20779 },
20780 /** @type {function(...*)} */
20781 critical: function() {
20782 if (!_.isUndefined(windowConsole) && windowConsole) {
20783 var args = ['Mixpanel error:'].concat(_.toArray(arguments));
20784 try {
20785 windowConsole.error.apply(windowConsole, args);
20786 } catch (err) {
20787 _.each(args, function(arg) {
20788 windowConsole.error(arg);
20789 });
20790 }
20791 }
20792 }
20793 };
20794
20795 var log_func_with_prefix = function(func, prefix) {
20796 return function() {
20797 arguments[0] = '[' + prefix + '] ' + arguments[0];
20798 return func.apply(console$1, arguments);
20799 };
20800 };
20801 var console_with_prefix = function(prefix) {
20802 return {
20803 log: log_func_with_prefix(console$1.log, prefix),
20804 error: log_func_with_prefix(console$1.error, prefix),
20805 critical: log_func_with_prefix(console$1.critical, prefix)
20806 };
20807 };
20808
20809
20810 var safewrap = function(f) {
20811 return function() {
20812 try {
20813 return f.apply(this, arguments);
20814 } catch (e) {
20815 console$1.critical('Implementation error. Please turn on debug and contact [email protected].');
20816 if (Config.DEBUG){
20817 console$1.critical(e);
20818 }
20819 }
20820 };
20821 };
20822
20823 var safewrapClass = function(klass) {
20824 var proto = klass.prototype;
20825 for (var func in proto) {
20826 if (typeof(proto[func]) === 'function') {
20827 proto[func] = safewrap(proto[func]);
20828 }
20829 }
20830 };
20831
20832
20833 // UNDERSCORE
20834 // Embed part of the Underscore Library
20835 _.bind = function(func, context) {
20836 var args, bound;
20837 if (nativeBind && func.bind === nativeBind) {
20838 return nativeBind.apply(func, slice.call(arguments, 1));
20839 }
20840 if (!_.isFunction(func)) {
20841 throw new TypeError();
20842 }
20843 args = slice.call(arguments, 2);
20844 bound = function() {
20845 if (!(this instanceof bound)) {
20846 return func.apply(context, args.concat(slice.call(arguments)));
20847 }
20848 var ctor = {};
20849 ctor.prototype = func.prototype;
20850 var self = new ctor();
20851 ctor.prototype = null;
20852 var result = func.apply(self, args.concat(slice.call(arguments)));
20853 if (Object(result) === result) {
20854 return result;
20855 }
20856 return self;
20857 };
20858 return bound;
20859 };
20860
20861 /**
20862 * @param {*=} obj
20863 * @param {function(...*)=} iterator
20864 * @param {Object=} context
20865 */
20866 _.each = function(obj, iterator, context) {
20867 if (obj === null || obj === undefined) {
20868 return;
20869 }
20870 if (nativeForEach && obj.forEach === nativeForEach) {
20871 obj.forEach(iterator, context);
20872 } else if (obj.length === +obj.length) {
20873 for (var i = 0, l = obj.length; i < l; i++) {
20874 if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {
20875 return;
20876 }
20877 }
20878 } else {
20879 for (var key in obj) {
20880 if (hasOwnProperty.call(obj, key)) {
20881 if (iterator.call(context, obj[key], key, obj) === breaker) {
20882 return;
20883 }
20884 }
20885 }
20886 }
20887 };
20888
20889 _.extend = function(obj) {
20890 _.each(slice.call(arguments, 1), function(source) {
20891 for (var prop in source) {
20892 if (source[prop] !== void 0) {
20893 obj[prop] = source[prop];
20894 }
20895 }
20896 });
20897 return obj;
20898 };
20899
20900 _.isArray = nativeIsArray || function(obj) {
20901 return toString.call(obj) === '[object Array]';
20902 };
20903
20904 // from a comment on http://dbj.org/dbj/?p=286
20905 // fails on only one very rare and deliberate custom object:
20906 // var bomb = { toString : undefined, valueOf: function(o) { return "function BOMBA!"; }};
20907 _.isFunction = function(f) {
20908 try {
20909 return /^\s*\bfunction\b/.test(f);
20910 } catch (x) {
20911 return false;
20912 }
20913 };
20914
20915 _.isArguments = function(obj) {
20916 return !!(obj && hasOwnProperty.call(obj, 'callee'));
20917 };
20918
20919 _.toArray = function(iterable) {
20920 if (!iterable) {
20921 return [];
20922 }
20923 if (iterable.toArray) {
20924 return iterable.toArray();
20925 }
20926 if (_.isArray(iterable)) {
20927 return slice.call(iterable);
20928 }
20929 if (_.isArguments(iterable)) {
20930 return slice.call(iterable);
20931 }
20932 return _.values(iterable);
20933 };
20934
20935 _.map = function(arr, callback, context) {
20936 if (nativeMap && arr.map === nativeMap) {
20937 return arr.map(callback, context);
20938 } else {
20939 var results = [];
20940 _.each(arr, function(item) {
20941 results.push(callback.call(context, item));
20942 });
20943 return results;
20944 }
20945 };
20946
20947 _.keys = function(obj) {
20948 var results = [];
20949 if (obj === null) {
20950 return results;
20951 }
20952 _.each(obj, function(value, key) {
20953 results[results.length] = key;
20954 });
20955 return results;
20956 };
20957
20958 _.values = function(obj) {
20959 var results = [];
20960 if (obj === null) {
20961 return results;
20962 }
20963 _.each(obj, function(value) {
20964 results[results.length] = value;
20965 });
20966 return results;
20967 };
20968
20969 _.include = function(obj, target) {
20970 var found = false;
20971 if (obj === null) {
20972 return found;
20973 }
20974 if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
20975 return obj.indexOf(target) != -1;
20976 }
20977 _.each(obj, function(value) {
20978 if (found || (found = (value === target))) {
20979 return breaker;
20980 }
20981 });
20982 return found;
20983 };
20984
20985 _.includes = function(str, needle) {
20986 return str.indexOf(needle) !== -1;
20987 };
20988
20989 // Underscore Addons
20990 _.inherit = function(subclass, superclass) {
20991 subclass.prototype = new superclass();
20992 subclass.prototype.constructor = subclass;
20993 subclass.superclass = superclass.prototype;
20994 return subclass;
20995 };
20996
20997 _.isObject = function(obj) {
20998 return (obj === Object(obj) && !_.isArray(obj));
20999 };
21000
21001 _.isEmptyObject = function(obj) {
21002 if (_.isObject(obj)) {
21003 for (var key in obj) {
21004 if (hasOwnProperty.call(obj, key)) {
21005 return false;
21006 }
21007 }
21008 return true;
21009 }
21010 return false;
21011 };
21012
21013 _.isUndefined = function(obj) {
21014 return obj === void 0;
21015 };
21016
21017 _.isString = function(obj) {
21018 return toString.call(obj) == '[object String]';
21019 };
21020
21021 _.isDate = function(obj) {
21022 return toString.call(obj) == '[object Date]';
21023 };
21024
21025 _.isNumber = function(obj) {
21026 return toString.call(obj) == '[object Number]';
21027 };
21028
21029 _.isElement = function(obj) {
21030 return !!(obj && obj.nodeType === 1);
21031 };
21032
21033 _.encodeDates = function(obj) {
21034 _.each(obj, function(v, k) {
21035 if (_.isDate(v)) {
21036 obj[k] = _.formatDate(v);
21037 } else if (_.isObject(v)) {
21038 obj[k] = _.encodeDates(v); // recurse
21039 }
21040 });
21041 return obj;
21042 };
21043
21044 _.timestamp = function() {
21045 Date.now = Date.now || function() {
21046 return +new Date;
21047 };
21048 return Date.now();
21049 };
21050
21051 _.formatDate = function(d) {
21052 // YYYY-MM-DDTHH:MM:SS in UTC
21053 function pad(n) {
21054 return n < 10 ? '0' + n : n;
21055 }
21056 return d.getUTCFullYear() + '-' +
21057 pad(d.getUTCMonth() + 1) + '-' +
21058 pad(d.getUTCDate()) + 'T' +
21059 pad(d.getUTCHours()) + ':' +
21060 pad(d.getUTCMinutes()) + ':' +
21061 pad(d.getUTCSeconds());
21062 };
21063
21064 _.strip_empty_properties = function(p) {
21065 var ret = {};
21066 _.each(p, function(v, k) {
21067 if (_.isString(v) && v.length > 0) {
21068 ret[k] = v;
21069 }
21070 });
21071 return ret;
21072 };
21073
21074 /*
21075 * this function returns a copy of object after truncating it. If
21076 * passed an Array or Object it will iterate through obj and
21077 * truncate all the values recursively.
21078 */
21079 _.truncate = function(obj, length) {
21080 var ret;
21081
21082 if (typeof(obj) === 'string') {
21083 ret = obj.slice(0, length);
21084 } else if (_.isArray(obj)) {
21085 ret = [];
21086 _.each(obj, function(val) {
21087 ret.push(_.truncate(val, length));
21088 });
21089 } else if (_.isObject(obj)) {
21090 ret = {};
21091 _.each(obj, function(val, key) {
21092 ret[key] = _.truncate(val, length);
21093 });
21094 } else {
21095 ret = obj;
21096 }
21097
21098 return ret;
21099 };
21100
21101 _.JSONEncode = (function() {
21102 return function(mixed_val) {
21103 var value = mixed_val;
21104 var quote = function(string) {
21105 var escapable = /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // eslint-disable-line no-control-regex
21106 var meta = { // table of character substitutions
21107 '\b': '\\b',
21108 '\t': '\\t',
21109 '\n': '\\n',
21110 '\f': '\\f',
21111 '\r': '\\r',
21112 '"': '\\"',
21113 '\\': '\\\\'
21114 };
21115
21116 escapable.lastIndex = 0;
21117 return escapable.test(string) ?
21118 '"' + string.replace(escapable, function(a) {
21119 var c = meta[a];
21120 return typeof c === 'string' ? c :
21121 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
21122 }) + '"' :
21123 '"' + string + '"';
21124 };
21125
21126 var str = function(key, holder) {
21127 var gap = '';
21128 var indent = ' ';
21129 var i = 0; // The loop counter.
21130 var k = ''; // The member key.
21131 var v = ''; // The member value.
21132 var length = 0;
21133 var mind = gap;
21134 var partial = [];
21135 var value = holder[key];
21136
21137 // If the value has a toJSON method, call it to obtain a replacement value.
21138 if (value && typeof value === 'object' &&
21139 typeof value.toJSON === 'function') {
21140 value = value.toJSON(key);
21141 }
21142
21143 // What happens next depends on the value's type.
21144 switch (typeof value) {
21145 case 'string':
21146 return quote(value);
21147
21148 case 'number':
21149 // JSON numbers must be finite. Encode non-finite numbers as null.
21150 return isFinite(value) ? String(value) : 'null';
21151
21152 case 'boolean':
21153 case 'null':
21154 // If the value is a boolean or null, convert it to a string. Note:
21155 // typeof null does not produce 'null'. The case is included here in
21156 // the remote chance that this gets fixed someday.
21157
21158 return String(value);
21159
21160 case 'object':
21161 // If the type is 'object', we might be dealing with an object or an array or
21162 // null.
21163 // Due to a specification blunder in ECMAScript, typeof null is 'object',
21164 // so watch out for that case.
21165 if (!value) {
21166 return 'null';
21167 }
21168
21169 // Make an array to hold the partial results of stringifying this object value.
21170 gap += indent;
21171 partial = [];
21172
21173 // Is the value an array?
21174 if (toString.apply(value) === '[object Array]') {
21175 // The value is an array. Stringify every element. Use null as a placeholder
21176 // for non-JSON values.
21177
21178 length = value.length;
21179 for (i = 0; i < length; i += 1) {
21180 partial[i] = str(i, value) || 'null';
21181 }
21182
21183 // Join all of the elements together, separated with commas, and wrap them in
21184 // brackets.
21185 v = partial.length === 0 ? '[]' :
21186 gap ? '[\n' + gap +
21187 partial.join(',\n' + gap) + '\n' +
21188 mind + ']' :
21189 '[' + partial.join(',') + ']';
21190 gap = mind;
21191 return v;
21192 }
21193
21194 // Iterate through all of the keys in the object.
21195 for (k in value) {
21196 if (hasOwnProperty.call(value, k)) {
21197 v = str(k, value);
21198 if (v) {
21199 partial.push(quote(k) + (gap ? ': ' : ':') + v);
21200 }
21201 }
21202 }
21203
21204 // Join all of the member texts together, separated with commas,
21205 // and wrap them in braces.
21206 v = partial.length === 0 ? '{}' :
21207 gap ? '{' + partial.join(',') + '' +
21208 mind + '}' : '{' + partial.join(',') + '}';
21209 gap = mind;
21210 return v;
21211 }
21212 };
21213
21214 // Make a fake root object containing our value under the key of ''.
21215 // Return the result of stringifying the value.
21216 return str('', {
21217 '': value
21218 });
21219 };
21220 })();
21221
21222 /**
21223 * From https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
21224 * Slightly modified to throw a real Error rather than a POJO
21225 */
21226 _.JSONDecode = (function() {
21227 var at, // The index of the current character
21228 ch, // The current character
21229 escapee = {
21230 '"': '"',
21231 '\\': '\\',
21232 '/': '/',
21233 'b': '\b',
21234 'f': '\f',
21235 'n': '\n',
21236 'r': '\r',
21237 't': '\t'
21238 },
21239 text,
21240 error = function(m) {
21241 var e = new SyntaxError(m);
21242 e.at = at;
21243 e.text = text;
21244 throw e;
21245 },
21246 next = function(c) {
21247 // If a c parameter is provided, verify that it matches the current character.
21248 if (c && c !== ch) {
21249 error('Expected \'' + c + '\' instead of \'' + ch + '\'');
21250 }
21251 // Get the next character. When there are no more characters,
21252 // return the empty string.
21253 ch = text.charAt(at);
21254 at += 1;
21255 return ch;
21256 },
21257 number = function() {
21258 // Parse a number value.
21259 var number,
21260 string = '';
21261
21262 if (ch === '-') {
21263 string = '-';
21264 next('-');
21265 }
21266 while (ch >= '0' && ch <= '9') {
21267 string += ch;
21268 next();
21269 }
21270 if (ch === '.') {
21271 string += '.';
21272 while (next() && ch >= '0' && ch <= '9') {
21273 string += ch;
21274 }
21275 }
21276 if (ch === 'e' || ch === 'E') {
21277 string += ch;
21278 next();
21279 if (ch === '-' || ch === '+') {
21280 string += ch;
21281 next();
21282 }
21283 while (ch >= '0' && ch <= '9') {
21284 string += ch;
21285 next();
21286 }
21287 }
21288 number = +string;
21289 if (!isFinite(number)) {
21290 error('Bad number');
21291 } else {
21292 return number;
21293 }
21294 },
21295
21296 string = function() {
21297 // Parse a string value.
21298 var hex,
21299 i,
21300 string = '',
21301 uffff;
21302 // When parsing for string values, we must look for " and \ characters.
21303 if (ch === '"') {
21304 while (next()) {
21305 if (ch === '"') {
21306 next();
21307 return string;
21308 }
21309 if (ch === '\\') {
21310 next();
21311 if (ch === 'u') {
21312 uffff = 0;
21313 for (i = 0; i < 4; i += 1) {
21314 hex = parseInt(next(), 16);
21315 if (!isFinite(hex)) {
21316 break;
21317 }
21318 uffff = uffff * 16 + hex;
21319 }
21320 string += String.fromCharCode(uffff);
21321 } else if (typeof escapee[ch] === 'string') {
21322 string += escapee[ch];
21323 } else {
21324 break;
21325 }
21326 } else {
21327 string += ch;
21328 }
21329 }
21330 }
21331 error('Bad string');
21332 },
21333 white = function() {
21334 // Skip whitespace.
21335 while (ch && ch <= ' ') {
21336 next();
21337 }
21338 },
21339 word = function() {
21340 // true, false, or null.
21341 switch (ch) {
21342 case 't':
21343 next('t');
21344 next('r');
21345 next('u');
21346 next('e');
21347 return true;
21348 case 'f':
21349 next('f');
21350 next('a');
21351 next('l');
21352 next('s');
21353 next('e');
21354 return false;
21355 case 'n':
21356 next('n');
21357 next('u');
21358 next('l');
21359 next('l');
21360 return null;
21361 }
21362 error('Unexpected "' + ch + '"');
21363 },
21364 value, // Placeholder for the value function.
21365 array = function() {
21366 // Parse an array value.
21367 var array = [];
21368
21369 if (ch === '[') {
21370 next('[');
21371 white();
21372 if (ch === ']') {
21373 next(']');
21374 return array; // empty array
21375 }
21376 while (ch) {
21377 array.push(value());
21378 white();
21379 if (ch === ']') {
21380 next(']');
21381 return array;
21382 }
21383 next(',');
21384 white();
21385 }
21386 }
21387 error('Bad array');
21388 },
21389 object = function() {
21390 // Parse an object value.
21391 var key,
21392 object = {};
21393
21394 if (ch === '{') {
21395 next('{');
21396 white();
21397 if (ch === '}') {
21398 next('}');
21399 return object; // empty object
21400 }
21401 while (ch) {
21402 key = string();
21403 white();
21404 next(':');
21405 if (Object.hasOwnProperty.call(object, key)) {
21406 error('Duplicate key "' + key + '"');
21407 }
21408 object[key] = value();
21409 white();
21410 if (ch === '}') {
21411 next('}');
21412 return object;
21413 }
21414 next(',');
21415 white();
21416 }
21417 }
21418 error('Bad object');
21419 };
21420
21421 value = function() {
21422 // Parse a JSON value. It could be an object, an array, a string,
21423 // a number, or a word.
21424 white();
21425 switch (ch) {
21426 case '{':
21427 return object();
21428 case '[':
21429 return array();
21430 case '"':
21431 return string();
21432 case '-':
21433 return number();
21434 default:
21435 return ch >= '0' && ch <= '9' ? number() : word();
21436 }
21437 };
21438
21439 // Return the json_parse function. It will have access to all of the
21440 // above functions and variables.
21441 return function(source) {
21442 var result;
21443
21444 text = source;
21445 at = 0;
21446 ch = ' ';
21447 result = value();
21448 white();
21449 if (ch) {
21450 error('Syntax error');
21451 }
21452
21453 return result;
21454 };
21455 })();
21456
21457 _.base64Encode = function(data) {
21458 var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
21459 var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
21460 ac = 0,
21461 enc = '',
21462 tmp_arr = [];
21463
21464 if (!data) {
21465 return data;
21466 }
21467
21468 data = _.utf8Encode(data);
21469
21470 do { // pack three octets into four hexets
21471 o1 = data.charCodeAt(i++);
21472 o2 = data.charCodeAt(i++);
21473 o3 = data.charCodeAt(i++);
21474
21475 bits = o1 << 16 | o2 << 8 | o3;
21476
21477 h1 = bits >> 18 & 0x3f;
21478 h2 = bits >> 12 & 0x3f;
21479 h3 = bits >> 6 & 0x3f;
21480 h4 = bits & 0x3f;
21481
21482 // use hexets to index into b64, and append result to encoded string
21483 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
21484 } while (i < data.length);
21485
21486 enc = tmp_arr.join('');
21487
21488 switch (data.length % 3) {
21489 case 1:
21490 enc = enc.slice(0, -2) + '==';
21491 break;
21492 case 2:
21493 enc = enc.slice(0, -1) + '=';
21494 break;
21495 }
21496
21497 return enc;
21498 };
21499
21500 _.utf8Encode = function(string) {
21501 string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
21502
21503 var utftext = '',
21504 start,
21505 end;
21506 var stringl = 0,
21507 n;
21508
21509 start = end = 0;
21510 stringl = string.length;
21511
21512 for (n = 0; n < stringl; n++) {
21513 var c1 = string.charCodeAt(n);
21514 var enc = null;
21515
21516 if (c1 < 128) {
21517 end++;
21518 } else if ((c1 > 127) && (c1 < 2048)) {
21519 enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
21520 } else {
21521 enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
21522 }
21523 if (enc !== null) {
21524 if (end > start) {
21525 utftext += string.substring(start, end);
21526 }
21527 utftext += enc;
21528 start = end = n + 1;
21529 }
21530 }
21531
21532 if (end > start) {
21533 utftext += string.substring(start, string.length);
21534 }
21535
21536 return utftext;
21537 };
21538
21539 _.UUID = function() {
21540 try {
21541 // use native Crypto API when available
21542 return win['crypto']['randomUUID']();
21543 } catch (err) {
21544 // fall back to generating our own UUID
21545 // based on https://gist.github.com/scwood/3bff42cc005cc20ab7ec98f0d8e1d59d
21546 var uuid = new Array(36);
21547 for (var i = 0; i < 36; i++) {
21548 uuid[i] = Math.floor(Math.random() * 16);
21549 }
21550 uuid[14] = 4; // set bits 12-15 of time-high-and-version to 0100
21551 uuid[19] = uuid[19] &= -5; // set bit 6 of clock-seq-and-reserved to zero
21552 uuid[19] = uuid[19] |= (1 << 3); // set bit 7 of clock-seq-and-reserved to one
21553 uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
21554
21555 return _.map(uuid, function(x) {
21556 return x.toString(16);
21557 }).join('');
21558 }
21559 };
21560
21561 // _.isBlockedUA()
21562 // This is to block various web spiders from executing our JS and
21563 // sending false tracking data
21564 var BLOCKED_UA_STRS = [
21565 'ahrefsbot',
21566 'ahrefssiteaudit',
21567 'amazonbot',
21568 'baiduspider',
21569 'bingbot',
21570 'bingpreview',
21571 'chrome-lighthouse',
21572 'facebookexternal',
21573 'petalbot',
21574 'pinterest',
21575 'screaming frog',
21576 'yahoo! slurp',
21577 'yandex',
21578
21579 // a whole bunch of goog-specific crawlers
21580 // https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
21581 'adsbot-google',
21582 'apis-google',
21583 'duplexweb-google',
21584 'feedfetcher-google',
21585 'google favicon',
21586 'google web preview',
21587 'google-read-aloud',
21588 'googlebot',
21589 'googleweblight',
21590 'mediapartners-google',
21591 'storebot-google'
21592 ];
21593 _.isBlockedUA = function(ua) {
21594 var i;
21595 ua = ua.toLowerCase();
21596 for (i = 0; i < BLOCKED_UA_STRS.length; i++) {
21597 if (ua.indexOf(BLOCKED_UA_STRS[i]) !== -1) {
21598 return true;
21599 }
21600 }
21601 return false;
21602 };
21603
21604 /**
21605 * @param {Object=} formdata
21606 * @param {string=} arg_separator
21607 */
21608 _.HTTPBuildQuery = function(formdata, arg_separator) {
21609 var use_val, use_key, tmp_arr = [];
21610
21611 if (_.isUndefined(arg_separator)) {
21612 arg_separator = '&';
21613 }
21614
21615 _.each(formdata, function(val, key) {
21616 use_val = encodeURIComponent(val.toString());
21617 use_key = encodeURIComponent(key);
21618 tmp_arr[tmp_arr.length] = use_key + '=' + use_val;
21619 });
21620
21621 return tmp_arr.join(arg_separator);
21622 };
21623
21624 _.getQueryParam = function(url, param) {
21625 // Expects a raw URL
21626
21627 param = param.replace(/[[]/g, '\\[').replace(/[\]]/g, '\\]');
21628 var regexS = '[\\?&]' + param + '=([^&#]*)',
21629 regex = new RegExp(regexS),
21630 results = regex.exec(url);
21631 if (results === null || (results && typeof(results[1]) !== 'string' && results[1].length)) {
21632 return '';
21633 } else {
21634 var result = results[1];
21635 try {
21636 result = decodeURIComponent(result);
21637 } catch(err) {
21638 console$1.error('Skipping decoding for malformed query param: ' + result);
21639 }
21640 return result.replace(/\+/g, ' ');
21641 }
21642 };
21643
21644
21645 // _.cookie
21646 // Methods partially borrowed from quirksmode.org/js/cookies.html
21647 _.cookie = {
21648 get: function(name) {
21649 var nameEQ = name + '=';
21650 var ca = document$1.cookie.split(';');
21651 for (var i = 0; i < ca.length; i++) {
21652 var c = ca[i];
21653 while (c.charAt(0) == ' ') {
21654 c = c.substring(1, c.length);
21655 }
21656 if (c.indexOf(nameEQ) === 0) {
21657 return decodeURIComponent(c.substring(nameEQ.length, c.length));
21658 }
21659 }
21660 return null;
21661 },
21662
21663 parse: function(name) {
21664 var cookie;
21665 try {
21666 cookie = _.JSONDecode(_.cookie.get(name)) || {};
21667 } catch (err) {
21668 // noop
21669 }
21670 return cookie;
21671 },
21672
21673 set_seconds: function(name, value, seconds, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
21674 var cdomain = '',
21675 expires = '',
21676 secure = '';
21677
21678 if (domain_override) {
21679 cdomain = '; domain=' + domain_override;
21680 } else if (is_cross_subdomain) {
21681 var domain = extract_domain(document$1.location.hostname);
21682 cdomain = domain ? '; domain=.' + domain : '';
21683 }
21684
21685 if (seconds) {
21686 var date = new Date();
21687 date.setTime(date.getTime() + (seconds * 1000));
21688 expires = '; expires=' + date.toGMTString();
21689 }
21690
21691 if (is_cross_site) {
21692 is_secure = true;
21693 secure = '; SameSite=None';
21694 }
21695 if (is_secure) {
21696 secure += '; secure';
21697 }
21698
21699 document$1.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
21700 },
21701
21702 set: function(name, value, days, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
21703 var cdomain = '', expires = '', secure = '';
21704
21705 if (domain_override) {
21706 cdomain = '; domain=' + domain_override;
21707 } else if (is_cross_subdomain) {
21708 var domain = extract_domain(document$1.location.hostname);
21709 cdomain = domain ? '; domain=.' + domain : '';
21710 }
21711
21712 if (days) {
21713 var date = new Date();
21714 date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
21715 expires = '; expires=' + date.toGMTString();
21716 }
21717
21718 if (is_cross_site) {
21719 is_secure = true;
21720 secure = '; SameSite=None';
21721 }
21722 if (is_secure) {
21723 secure += '; secure';
21724 }
21725
21726 var new_cookie_val = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
21727 document$1.cookie = new_cookie_val;
21728 return new_cookie_val;
21729 },
21730
21731 remove: function(name, is_cross_subdomain, domain_override) {
21732 _.cookie.set(name, '', -1, is_cross_subdomain, false, false, domain_override);
21733 }
21734 };
21735
21736 var _testStorageSupported = function (storage) {
21737 var supported = true;
21738 try {
21739 var key = '__mplss_' + cheap_guid(8),
21740 val = 'xyz';
21741 storage.setItem(key, val);
21742 if (storage.getItem(key) !== val) {
21743 supported = false;
21744 }
21745 storage.removeItem(key);
21746 } catch (err) {
21747 supported = false;
21748 }
21749 return supported;
21750 };
21751
21752 var _localStorageSupported = null;
21753 var localStorageSupported = function(storage, forceCheck) {
21754 if (_localStorageSupported !== null && !forceCheck) {
21755 return _localStorageSupported;
21756 }
21757 return _localStorageSupported = _testStorageSupported(storage || win.localStorage);
21758 };
21759
21760 var _sessionStorageSupported = null;
21761 var sessionStorageSupported = function(storage, forceCheck) {
21762 if (_sessionStorageSupported !== null && !forceCheck) {
21763 return _sessionStorageSupported;
21764 }
21765 return _sessionStorageSupported = _testStorageSupported(storage || win.sessionStorage);
21766 };
21767
21768 function _storageWrapper(storage, name, is_supported_fn) {
21769 var log_error = function(msg) {
21770 console$1.error(name + ' error: ' + msg);
21771 };
21772
21773 return {
21774 is_supported: function(forceCheck) {
21775 var supported = is_supported_fn(storage, forceCheck);
21776 if (!supported) {
21777 console$1.error(name + ' unsupported');
21778 }
21779 return supported;
21780 },
21781 error: log_error,
21782 get: function(key) {
21783 try {
21784 return storage.getItem(key);
21785 } catch (err) {
21786 log_error(err);
21787 }
21788 return null;
21789 },
21790 parse: function(key) {
21791 try {
21792 return _.JSONDecode(storage.getItem(key)) || {};
21793 } catch (err) {
21794 // noop
21795 }
21796 return null;
21797 },
21798 set: function(key, value) {
21799 try {
21800 storage.setItem(key, value);
21801 } catch (err) {
21802 log_error(err);
21803 }
21804 },
21805 remove: function(key) {
21806 try {
21807 storage.removeItem(key);
21808 } catch (err) {
21809 log_error(err);
21810 }
21811 }
21812 };
21813 }
21814
21815 _.localStorage = _storageWrapper(win.localStorage, 'localStorage', localStorageSupported);
21816 _.sessionStorage = _storageWrapper(win.sessionStorage, 'sessionStorage', sessionStorageSupported);
21817
21818 _.register_event = (function() {
21819 // written by Dean Edwards, 2005
21820 // with input from Tino Zijdel - [email protected]
21821 // with input from Carl Sverre - [email protected]
21822 // with input from Mixpanel
21823 // http://dean.edwards.name/weblog/2005/10/add-event/
21824 // https://gist.github.com/1930440
21825
21826 /**
21827 * @param {Object} element
21828 * @param {string} type
21829 * @param {function(...*)} handler
21830 * @param {boolean=} oldSchool
21831 * @param {boolean=} useCapture
21832 */
21833 var register_event = function(element, type, handler, oldSchool, useCapture) {
21834 if (!element) {
21835 console$1.error('No valid element provided to register_event');
21836 return;
21837 }
21838
21839 if (element.addEventListener && !oldSchool) {
21840 element.addEventListener(type, handler, !!useCapture);
21841 } else {
21842 var ontype = 'on' + type;
21843 var old_handler = element[ontype]; // can be undefined
21844 element[ontype] = makeHandler(element, handler, old_handler);
21845 }
21846 };
21847
21848 function makeHandler(element, new_handler, old_handlers) {
21849 var handler = function(event) {
21850 event = event || fixEvent(win.event);
21851
21852 // this basically happens in firefox whenever another script
21853 // overwrites the onload callback and doesn't pass the event
21854 // object to previously defined callbacks. All the browsers
21855 // that don't define window.event implement addEventListener
21856 // so the dom_loaded handler will still be fired as usual.
21857 if (!event) {
21858 return undefined;
21859 }
21860
21861 var ret = true;
21862 var old_result, new_result;
21863
21864 if (_.isFunction(old_handlers)) {
21865 old_result = old_handlers(event);
21866 }
21867 new_result = new_handler.call(element, event);
21868
21869 if ((false === old_result) || (false === new_result)) {
21870 ret = false;
21871 }
21872
21873 return ret;
21874 };
21875
21876 return handler;
21877 }
21878
21879 function fixEvent(event) {
21880 if (event) {
21881 event.preventDefault = fixEvent.preventDefault;
21882 event.stopPropagation = fixEvent.stopPropagation;
21883 }
21884 return event;
21885 }
21886 fixEvent.preventDefault = function() {
21887 this.returnValue = false;
21888 };
21889 fixEvent.stopPropagation = function() {
21890 this.cancelBubble = true;
21891 };
21892
21893 return register_event;
21894 })();
21895
21896
21897 var TOKEN_MATCH_REGEX = new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$');
21898
21899 _.dom_query = (function() {
21900 /* document.getElementsBySelector(selector)
21901 - returns an array of element objects from the current document
21902 matching the CSS selector. Selectors can contain element names,
21903 class names and ids and can be nested. For example:
21904
21905 elements = document.getElementsBySelector('div#main p a.external')
21906
21907 Will return an array of all 'a' elements with 'external' in their
21908 class attribute that are contained inside 'p' elements that are
21909 contained inside the 'div' element which has id="main"
21910
21911 New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
21912 See http://www.w3.org/TR/css3-selectors/#attribute-selectors
21913
21914 Version 0.4 - Simon Willison, March 25th 2003
21915 -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
21916 -- Opera 7 fails
21917
21918 Version 0.5 - Carl Sverre, Jan 7th 2013
21919 -- Now uses jQuery-esque `hasClass` for testing class name
21920 equality. This fixes a bug related to '-' characters being
21921 considered not part of a 'word' in regex.
21922 */
21923
21924 function getAllChildren(e) {
21925 // Returns all children of element. Workaround required for IE5/Windows. Ugh.
21926 return e.all ? e.all : e.getElementsByTagName('*');
21927 }
21928
21929 var bad_whitespace = /[\t\r\n]/g;
21930
21931 function hasClass(elem, selector) {
21932 var className = ' ' + selector + ' ';
21933 return ((' ' + elem.className + ' ').replace(bad_whitespace, ' ').indexOf(className) >= 0);
21934 }
21935
21936 function getElementsBySelector(selector) {
21937 // Attempt to fail gracefully in lesser browsers
21938 if (!document$1.getElementsByTagName) {
21939 return [];
21940 }
21941 // Split selector in to tokens
21942 var tokens = selector.split(' ');
21943 var token, bits, tagName, found, foundCount, i, j, k, elements, currentContextIndex;
21944 var currentContext = [document$1];
21945 for (i = 0; i < tokens.length; i++) {
21946 token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, '');
21947 if (token.indexOf('#') > -1) {
21948 // Token is an ID selector
21949 bits = token.split('#');
21950 tagName = bits[0];
21951 var id = bits[1];
21952 var element = document$1.getElementById(id);
21953 if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) {
21954 // element not found or tag with that ID not found, return false
21955 return [];
21956 }
21957 // Set currentContext to contain just this element
21958 currentContext = [element];
21959 continue; // Skip to next token
21960 }
21961 if (token.indexOf('.') > -1) {
21962 // Token contains a class selector
21963 bits = token.split('.');
21964 tagName = bits[0];
21965 var className = bits[1];
21966 if (!tagName) {
21967 tagName = '*';
21968 }
21969 // Get elements matching tag, filter them for class selector
21970 found = [];
21971 foundCount = 0;
21972 for (j = 0; j < currentContext.length; j++) {
21973 if (tagName == '*') {
21974 elements = getAllChildren(currentContext[j]);
21975 } else {
21976 elements = currentContext[j].getElementsByTagName(tagName);
21977 }
21978 for (k = 0; k < elements.length; k++) {
21979 found[foundCount++] = elements[k];
21980 }
21981 }
21982 currentContext = [];
21983 currentContextIndex = 0;
21984 for (j = 0; j < found.length; j++) {
21985 if (found[j].className &&
21986 _.isString(found[j].className) && // some SVG elements have classNames which are not strings
21987 hasClass(found[j], className)
21988 ) {
21989 currentContext[currentContextIndex++] = found[j];
21990 }
21991 }
21992 continue; // Skip to next token
21993 }
21994 // Code to deal with attribute selectors
21995 var token_match = token.match(TOKEN_MATCH_REGEX);
21996 if (token_match) {
21997 tagName = token_match[1];
21998 var attrName = token_match[2];
21999 var attrOperator = token_match[3];
22000 var attrValue = token_match[4];
22001 if (!tagName) {
22002 tagName = '*';
22003 }
22004 // Grab all of the tagName elements within current context
22005 found = [];
22006 foundCount = 0;
22007 for (j = 0; j < currentContext.length; j++) {
22008 if (tagName == '*') {
22009 elements = getAllChildren(currentContext[j]);
22010 } else {
22011 elements = currentContext[j].getElementsByTagName(tagName);
22012 }
22013 for (k = 0; k < elements.length; k++) {
22014 found[foundCount++] = elements[k];
22015 }
22016 }
22017 currentContext = [];
22018 currentContextIndex = 0;
22019 var checkFunction; // This function will be used to filter the elements
22020 switch (attrOperator) {
22021 case '=': // Equality
22022 checkFunction = function(e) {
22023 return (e.getAttribute(attrName) == attrValue);
22024 };
22025 break;
22026 case '~': // Match one of space seperated words
22027 checkFunction = function(e) {
22028 return (e.getAttribute(attrName).match(new RegExp('\\b' + attrValue + '\\b')));
22029 };
22030 break;
22031 case '|': // Match start with value followed by optional hyphen
22032 checkFunction = function(e) {
22033 return (e.getAttribute(attrName).match(new RegExp('^' + attrValue + '-?')));
22034 };
22035 break;
22036 case '^': // Match starts with value
22037 checkFunction = function(e) {
22038 return (e.getAttribute(attrName).indexOf(attrValue) === 0);
22039 };
22040 break;
22041 case '$': // Match ends with value - fails with "Warning" in Opera 7
22042 checkFunction = function(e) {
22043 return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length);
22044 };
22045 break;
22046 case '*': // Match ends with value
22047 checkFunction = function(e) {
22048 return (e.getAttribute(attrName).indexOf(attrValue) > -1);
22049 };
22050 break;
22051 default:
22052 // Just test for existence of attribute
22053 checkFunction = function(e) {
22054 return e.getAttribute(attrName);
22055 };
22056 }
22057 currentContext = [];
22058 currentContextIndex = 0;
22059 for (j = 0; j < found.length; j++) {
22060 if (checkFunction(found[j])) {
22061 currentContext[currentContextIndex++] = found[j];
22062 }
22063 }
22064 // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
22065 continue; // Skip to next token
22066 }
22067 // If we get here, token is JUST an element (not a class or ID selector)
22068 tagName = token;
22069 found = [];
22070 foundCount = 0;
22071 for (j = 0; j < currentContext.length; j++) {
22072 elements = currentContext[j].getElementsByTagName(tagName);
22073 for (k = 0; k < elements.length; k++) {
22074 found[foundCount++] = elements[k];
22075 }
22076 }
22077 currentContext = found;
22078 }
22079 return currentContext;
22080 }
22081
22082 return function(query) {
22083 if (_.isElement(query)) {
22084 return [query];
22085 } else if (_.isObject(query) && !_.isUndefined(query.length)) {
22086 return query;
22087 } else {
22088 return getElementsBySelector.call(this, query);
22089 }
22090 };
22091 })();
22092
22093 var CAMPAIGN_KEYWORDS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'utm_id', 'utm_source_platform','utm_campaign_id', 'utm_creative_format', 'utm_marketing_tactic'];
22094 var CLICK_IDS = ['dclid', 'fbclid', 'gclid', 'ko_click_id', 'li_fat_id', 'msclkid', 'sccid', 'ttclid', 'twclid', 'wbraid'];
22095
22096 _.info = {
22097 campaignParams: function(default_value) {
22098 var kw = '',
22099 params = {};
22100 _.each(CAMPAIGN_KEYWORDS, function(kwkey) {
22101 kw = _.getQueryParam(document$1.URL, kwkey);
22102 if (kw.length) {
22103 params[kwkey] = kw;
22104 } else if (default_value !== undefined) {
22105 params[kwkey] = default_value;
22106 }
22107 });
22108
22109 return params;
22110 },
22111
22112 clickParams: function() {
22113 var id = '',
22114 params = {};
22115 _.each(CLICK_IDS, function(idkey) {
22116 id = _.getQueryParam(document$1.URL, idkey);
22117 if (id.length) {
22118 params[idkey] = id;
22119 }
22120 });
22121
22122 return params;
22123 },
22124
22125 marketingParams: function() {
22126 return _.extend(_.info.campaignParams(), _.info.clickParams());
22127 },
22128
22129 searchEngine: function(referrer) {
22130 if (referrer.search('https?://(.*)google.([^/?]*)') === 0) {
22131 return 'google';
22132 } else if (referrer.search('https?://(.*)bing.com') === 0) {
22133 return 'bing';
22134 } else if (referrer.search('https?://(.*)yahoo.com') === 0) {
22135 return 'yahoo';
22136 } else if (referrer.search('https?://(.*)duckduckgo.com') === 0) {
22137 return 'duckduckgo';
22138 } else {
22139 return null;
22140 }
22141 },
22142
22143 searchInfo: function(referrer) {
22144 var search = _.info.searchEngine(referrer),
22145 param = (search != 'yahoo') ? 'q' : 'p',
22146 ret = {};
22147
22148 if (search !== null) {
22149 ret['$search_engine'] = search;
22150
22151 var keyword = _.getQueryParam(referrer, param);
22152 if (keyword.length) {
22153 ret['mp_keyword'] = keyword;
22154 }
22155 }
22156
22157 return ret;
22158 },
22159
22160 /**
22161 * This function detects which browser is running this script.
22162 * The order of the checks are important since many user agents
22163 * include key words used in later checks.
22164 */
22165 browser: function(user_agent, vendor, opera) {
22166 vendor = vendor || ''; // vendor is undefined for at least IE9
22167 if (opera || _.includes(user_agent, ' OPR/')) {
22168 if (_.includes(user_agent, 'Mini')) {
22169 return 'Opera Mini';
22170 }
22171 return 'Opera';
22172 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
22173 return 'BlackBerry';
22174 } else if (_.includes(user_agent, 'IEMobile') || _.includes(user_agent, 'WPDesktop')) {
22175 return 'Internet Explorer Mobile';
22176 } else if (_.includes(user_agent, 'SamsungBrowser/')) {
22177 // https://developer.samsung.com/internet/user-agent-string-format
22178 return 'Samsung Internet';
22179 } else if (_.includes(user_agent, 'Edge') || _.includes(user_agent, 'Edg/')) {
22180 return 'Microsoft Edge';
22181 } else if (_.includes(user_agent, 'FBIOS')) {
22182 return 'Facebook Mobile';
22183 } else if (_.includes(user_agent, 'Whale/')) {
22184 // https://user-agents.net/browsers/whale-browser
22185 return 'Whale Browser';
22186 } else if (_.includes(user_agent, 'Chrome')) {
22187 return 'Chrome';
22188 } else if (_.includes(user_agent, 'CriOS')) {
22189 return 'Chrome iOS';
22190 } else if (_.includes(user_agent, 'UCWEB') || _.includes(user_agent, 'UCBrowser')) {
22191 return 'UC Browser';
22192 } else if (_.includes(user_agent, 'FxiOS')) {
22193 return 'Firefox iOS';
22194 } else if (_.includes(vendor, 'Apple')) {
22195 if (_.includes(user_agent, 'Mobile')) {
22196 return 'Mobile Safari';
22197 }
22198 return 'Safari';
22199 } else if (_.includes(user_agent, 'Android')) {
22200 return 'Android Mobile';
22201 } else if (_.includes(user_agent, 'Konqueror')) {
22202 return 'Konqueror';
22203 } else if (_.includes(user_agent, 'Firefox')) {
22204 return 'Firefox';
22205 } else if (_.includes(user_agent, 'MSIE') || _.includes(user_agent, 'Trident/')) {
22206 return 'Internet Explorer';
22207 } else if (_.includes(user_agent, 'Gecko')) {
22208 return 'Mozilla';
22209 } else {
22210 return '';
22211 }
22212 },
22213
22214 /**
22215 * This function detects which browser version is running this script,
22216 * parsing major and minor version (e.g., 42.1). User agent strings from:
22217 * http://www.useragentstring.com/pages/useragentstring.php
22218 */
22219 browserVersion: function(userAgent, vendor, opera) {
22220 var browser = _.info.browser(userAgent, vendor, opera);
22221 var versionRegexs = {
22222 'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
22223 'Microsoft Edge': /Edge?\/(\d+(\.\d+)?)/,
22224 'Chrome': /Chrome\/(\d+(\.\d+)?)/,
22225 'Chrome iOS': /CriOS\/(\d+(\.\d+)?)/,
22226 'UC Browser' : /(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,
22227 'Safari': /Version\/(\d+(\.\d+)?)/,
22228 'Mobile Safari': /Version\/(\d+(\.\d+)?)/,
22229 'Opera': /(Opera|OPR)\/(\d+(\.\d+)?)/,
22230 'Firefox': /Firefox\/(\d+(\.\d+)?)/,
22231 'Firefox iOS': /FxiOS\/(\d+(\.\d+)?)/,
22232 'Konqueror': /Konqueror:(\d+(\.\d+)?)/,
22233 'BlackBerry': /BlackBerry (\d+(\.\d+)?)/,
22234 'Android Mobile': /android\s(\d+(\.\d+)?)/,
22235 'Samsung Internet': /SamsungBrowser\/(\d+(\.\d+)?)/,
22236 'Internet Explorer': /(rv:|MSIE )(\d+(\.\d+)?)/,
22237 'Mozilla': /rv:(\d+(\.\d+)?)/,
22238 'Whale Browser': /Whale\/(\d+(\.\d+)?)/
22239 };
22240 var regex = versionRegexs[browser];
22241 if (regex === undefined) {
22242 return null;
22243 }
22244 var matches = userAgent.match(regex);
22245 if (!matches) {
22246 return null;
22247 }
22248 return parseFloat(matches[matches.length - 2]);
22249 },
22250
22251 os: function() {
22252 var a = userAgent;
22253 if (/Windows/i.test(a)) {
22254 if (/Phone/.test(a) || /WPDesktop/.test(a)) {
22255 return 'Windows Phone';
22256 }
22257 return 'Windows';
22258 } else if (/(iPhone|iPad|iPod)/.test(a)) {
22259 return 'iOS';
22260 } else if (/Android/.test(a)) {
22261 return 'Android';
22262 } else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) {
22263 return 'BlackBerry';
22264 } else if (/Mac/i.test(a)) {
22265 return 'Mac OS X';
22266 } else if (/Linux/.test(a)) {
22267 return 'Linux';
22268 } else if (/CrOS/.test(a)) {
22269 return 'Chrome OS';
22270 } else {
22271 return '';
22272 }
22273 },
22274
22275 device: function(user_agent) {
22276 if (/Windows Phone/i.test(user_agent) || /WPDesktop/.test(user_agent)) {
22277 return 'Windows Phone';
22278 } else if (/iPad/.test(user_agent)) {
22279 return 'iPad';
22280 } else if (/iPod/.test(user_agent)) {
22281 return 'iPod Touch';
22282 } else if (/iPhone/.test(user_agent)) {
22283 return 'iPhone';
22284 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
22285 return 'BlackBerry';
22286 } else if (/Android/.test(user_agent)) {
22287 return 'Android';
22288 } else {
22289 return '';
22290 }
22291 },
22292
22293 referringDomain: function(referrer) {
22294 var split = referrer.split('/');
22295 if (split.length >= 3) {
22296 return split[2];
22297 }
22298 return '';
22299 },
22300
22301 currentUrl: function() {
22302 return win.location.href;
22303 },
22304
22305 properties: function(extra_props) {
22306 if (typeof extra_props !== 'object') {
22307 extra_props = {};
22308 }
22309 return _.extend(_.strip_empty_properties({
22310 '$os': _.info.os(),
22311 '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera),
22312 '$referrer': document$1.referrer,
22313 '$referring_domain': _.info.referringDomain(document$1.referrer),
22314 '$device': _.info.device(userAgent)
22315 }), {
22316 '$current_url': _.info.currentUrl(),
22317 '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera),
22318 '$screen_height': screen.height,
22319 '$screen_width': screen.width,
22320 'mp_lib': 'web',
22321 '$lib_version': Config.LIB_VERSION,
22322 '$insert_id': cheap_guid(),
22323 'time': _.timestamp() / 1000 // epoch time in seconds
22324 }, _.strip_empty_properties(extra_props));
22325 },
22326
22327 people_properties: function() {
22328 return _.extend(_.strip_empty_properties({
22329 '$os': _.info.os(),
22330 '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera)
22331 }), {
22332 '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera)
22333 });
22334 },
22335
22336 mpPageViewProperties: function() {
22337 return _.strip_empty_properties({
22338 'current_page_title': document$1.title,
22339 'current_domain': win.location.hostname,
22340 'current_url_path': win.location.pathname,
22341 'current_url_protocol': win.location.protocol,
22342 'current_url_search': win.location.search
22343 });
22344 }
22345 };
22346
22347 /**
22348 * Returns a throttled function that will only run at most every `waitMs` and returns a promise that resolves with the next invocation.
22349 * Throttled calls will build up a batch of args and invoke the callback with all args since the last invocation.
22350 */
22351 var batchedThrottle = function (fn, waitMs) {
22352 var timeoutPromise = null;
22353 var throttledItems = [];
22354 return function (item) {
22355 var self = this;
22356 throttledItems.push(item);
22357
22358 if (!timeoutPromise) {
22359 timeoutPromise = new PromisePolyfill(function (resolve) {
22360 setTimeout(function () {
22361 var returnValue = fn.apply(self, [throttledItems]);
22362 timeoutPromise = null;
22363 throttledItems = [];
22364 resolve(returnValue);
22365 }, waitMs);
22366 });
22367 }
22368 return timeoutPromise;
22369 };
22370 };
22371
22372 var cheap_guid = function(maxlen) {
22373 var guid = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
22374 return maxlen ? guid.substring(0, maxlen) : guid;
22375 };
22376
22377 /**
22378 * Generates a W3C traceparent header for easy interop with distributed tracing systems i.e Open Telemetry
22379 * https://www.w3.org/TR/trace-context/#traceparent-header
22380 */
22381 var generateTraceparent = function() {
22382 var traceID = _.UUID().replace(/-/g, '');
22383 var parentID = _.UUID().replace(/-/g, '').substring(0, 16);
22384
22385 // Sampled trace
22386 var traceFlags = '01';
22387
22388 return '00-' + traceID + '-' + parentID + '-' + traceFlags;
22389 };
22390
22391 // naive way to extract domain name (example.com) from full hostname (my.sub.example.com)
22392 var SIMPLE_DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]*\.[a-z]+$/i;
22393 // this next one attempts to account for some ccSLDs, e.g. extracting oxford.ac.uk from www.oxford.ac.uk
22394 var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
22395 /**
22396 * Attempts to extract main domain name from full hostname, using a few blunt heuristics. For
22397 * common TLDs like .com/.org that always have a simple SLD.TLD structure (example.com), we
22398 * simply extract the last two .-separated parts of the hostname (SIMPLE_DOMAIN_MATCH_REGEX).
22399 * For others, we attempt to account for short ccSLD+TLD combos (.ac.uk) with the legacy
22400 * DOMAIN_MATCH_REGEX (kept to maintain backwards compatibility with existing Mixpanel
22401 * integrations). The only _reliable_ way to extract domain from hostname is with an up-to-date
22402 * list like at https://publicsuffix.org/ so for cases that this helper fails at, the SDK
22403 * offers the 'cookie_domain' config option to set it explicitly.
22404 * @example
22405 * extract_domain('my.sub.example.com')
22406 * // 'example.com'
22407 */
22408 var extract_domain = function(hostname) {
22409 var domain_regex = DOMAIN_MATCH_REGEX;
22410 var parts = hostname.split('.');
22411 var tld = parts[parts.length - 1];
22412 if (tld.length > 4 || tld === 'com' || tld === 'org') {
22413 domain_regex = SIMPLE_DOMAIN_MATCH_REGEX;
22414 }
22415 var matches = hostname.match(domain_regex);
22416 return matches ? matches[0] : '';
22417 };
22418
22419 /**
22420 * Check whether we have network connection. default to true for browsers that don't support navigator.onLine (IE)
22421 * @returns {boolean}
22422 */
22423 var isOnline = function() {
22424 var onLine = win.navigator['onLine'];
22425 return _.isUndefined(onLine) || onLine;
22426 };
22427
22428 var NOOP_FUNC = function () {};
22429
22430 var JSONStringify = null, JSONParse = null;
22431 if (typeof JSON !== 'undefined') {
22432 JSONStringify = JSON.stringify;
22433 JSONParse = JSON.parse;
22434 }
22435 JSONStringify = JSONStringify || _.JSONEncode;
22436 JSONParse = JSONParse || _.JSONDecode;
22437
22438 // UNMINIFIED EXPORTS (for closure compiler)
22439 _['info'] = _.info;
22440 _['info']['browser'] = _.info.browser;
22441 _['info']['browserVersion'] = _.info.browserVersion;
22442 _['info']['device'] = _.info.device;
22443 _['info']['properties'] = _.info.properties;
22444 _['isBlockedUA'] = _.isBlockedUA;
22445 _['isEmptyObject'] = _.isEmptyObject;
22446 _['isObject'] = _.isObject;
22447 _['JSONDecode'] = _.JSONDecode;
22448 _['JSONEncode'] = _.JSONEncode;
22449 _['toArray'] = _.toArray;
22450 _['NPO'] = NpoPromise;
22451
22452 var MIXPANEL_DB_NAME = 'mixpanelBrowserDb';
22453
22454 var RECORDING_EVENTS_STORE_NAME = 'mixpanelRecordingEvents';
22455 var RECORDING_REGISTRY_STORE_NAME = 'mixpanelRecordingRegistry';
22456
22457 // note: increment the version number when adding new object stores
22458 var DB_VERSION = 1;
22459 var OBJECT_STORES = [RECORDING_EVENTS_STORE_NAME, RECORDING_REGISTRY_STORE_NAME];
22460
22461 /**
22462 * @type {import('./wrapper').StorageWrapper}
22463 */
22464 var IDBStorageWrapper = function (storeName) {
22465 /**
22466 * @type {Promise<IDBDatabase>|null}
22467 */
22468 this.dbPromise = null;
22469 this.storeName = storeName;
22470 };
22471
22472 IDBStorageWrapper.prototype._openDb = function () {
22473 return new PromisePolyfill(function (resolve, reject) {
22474 var openRequest = win.indexedDB.open(MIXPANEL_DB_NAME, DB_VERSION);
22475 openRequest['onerror'] = function () {
22476 reject(openRequest.error);
22477 };
22478
22479 openRequest['onsuccess'] = function () {
22480 resolve(openRequest.result);
22481 };
22482
22483 openRequest['onupgradeneeded'] = function (ev) {
22484 var db = ev.target.result;
22485
22486 OBJECT_STORES.forEach(function (storeName) {
22487 db.createObjectStore(storeName);
22488 });
22489 };
22490 });
22491 };
22492
22493 IDBStorageWrapper.prototype.init = function () {
22494 if (!win.indexedDB) {
22495 return PromisePolyfill.reject('indexedDB is not supported in this browser');
22496 }
22497
22498 if (!this.dbPromise) {
22499 this.dbPromise = this._openDb();
22500 }
22501
22502 return this.dbPromise
22503 .then(function (dbOrError) {
22504 if (dbOrError instanceof win['IDBDatabase']) {
22505 return PromisePolyfill.resolve();
22506 } else {
22507 return PromisePolyfill.reject(dbOrError);
22508 }
22509 });
22510 };
22511
22512 IDBStorageWrapper.prototype.isInitialized = function () {
22513 return !!this.dbPromise;
22514 };
22515
22516 /**
22517 * @param {IDBTransactionMode} mode
22518 * @param {function(IDBObjectStore): void} storeCb
22519 */
22520 IDBStorageWrapper.prototype.makeTransaction = function (mode, storeCb) {
22521 var storeName = this.storeName;
22522 var doTransaction = function (db) {
22523 return new PromisePolyfill(function (resolve, reject) {
22524 var transaction = db.transaction(storeName, mode);
22525 transaction.oncomplete = function () {
22526 resolve(transaction);
22527 };
22528 transaction.onabort = transaction.onerror = function () {
22529 reject(transaction.error);
22530 };
22531
22532 storeCb(transaction.objectStore(storeName));
22533 });
22534 };
22535
22536 return this.dbPromise
22537 .then(doTransaction)
22538 .catch(function (err) {
22539 if (err && err['name'] === 'InvalidStateError') {
22540 // try reopening the DB if the connection is closed
22541 this.dbPromise = this._openDb();
22542 return this.dbPromise.then(doTransaction);
22543 } else {
22544 return PromisePolyfill.reject(err);
22545 }
22546 }.bind(this));
22547 };
22548
22549 IDBStorageWrapper.prototype.setItem = function (key, value) {
22550 return this.makeTransaction('readwrite', function (objectStore) {
22551 objectStore.put(value, key);
22552 });
22553 };
22554
22555 IDBStorageWrapper.prototype.getItem = function (key) {
22556 var req;
22557 return this.makeTransaction('readonly', function (objectStore) {
22558 req = objectStore.get(key);
22559 }).then(function () {
22560 return req.result;
22561 });
22562 };
22563
22564 IDBStorageWrapper.prototype.removeItem = function (key) {
22565 return this.makeTransaction('readwrite', function (objectStore) {
22566 objectStore.delete(key);
22567 });
22568 };
22569
22570 IDBStorageWrapper.prototype.getAll = function () {
22571 var req;
22572 return this.makeTransaction('readonly', function (objectStore) {
22573 req = objectStore.getAll();
22574 }).then(function () {
22575 return req.result;
22576 });
22577 };
22578
22579 /**
22580 * GDPR utils
22581 *
22582 * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection
22583 * and privacy for all individuals within the European Union. It addresses the export of personal
22584 * data outside the EU. The GDPR aims primarily to give control back to citizens and residents
22585 * over their personal data and to simplify the regulatory environment for international business
22586 * by unifying the regulation within the EU.
22587 *
22588 * This set of utilities is intended to enable opt in/out functionality in the Mixpanel JS SDK.
22589 * These functions are used internally by the SDK and are not intended to be publicly exposed.
22590 */
22591
22592
22593 /**
22594 * A function used to track a Mixpanel event (e.g. MixpanelLib.track)
22595 * @callback trackFunction
22596 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
22597 * @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.
22598 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
22599 */
22600
22601 /** Public **/
22602
22603 var GDPR_DEFAULT_PERSISTENCE_PREFIX = '__mp_opt_in_out_';
22604
22605 /**
22606 * Opt the user in to data tracking and cookies/localstorage for the given token
22607 * @param {string} token - Mixpanel project tracking token
22608 * @param {Object} [options]
22609 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
22610 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
22611 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
22612 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22613 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22614 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
22615 * @param {string} [options.cookieDomain] - custom cookie domain
22616 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
22617 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
22618 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
22619 */
22620 function optIn(token, options) {
22621 _optInOut(true, token, options);
22622 }
22623
22624 /**
22625 * Opt the user out of data tracking and cookies/localstorage for the given token
22626 * @param {string} token - Mixpanel project tracking token
22627 * @param {Object} [options]
22628 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22629 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22630 * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires
22631 * @param {string} [options.cookieDomain] - custom cookie domain
22632 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
22633 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not
22634 * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not
22635 */
22636 function optOut(token, options) {
22637 _optInOut(false, token, options);
22638 }
22639
22640 /**
22641 * Check whether the user has opted in to data tracking and cookies/localstorage for the given token
22642 * @param {string} token - Mixpanel project tracking token
22643 * @param {Object} [options]
22644 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22645 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22646 * @returns {boolean} whether the user has opted in to the given opt type
22647 */
22648 function hasOptedIn(token, options) {
22649 return _getStorageValue(token, options) === '1';
22650 }
22651
22652 /**
22653 * Check whether the user has opted out of data tracking and cookies/localstorage for the given token
22654 * @param {string} token - Mixpanel project tracking token
22655 * @param {Object} [options]
22656 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22657 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22658 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
22659 * @returns {boolean} whether the user has opted out of the given opt type
22660 */
22661 function hasOptedOut(token, options) {
22662 if (_hasDoNotTrackFlagOn(options)) {
22663 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"');
22664 return true;
22665 }
22666 var optedOut = _getStorageValue(token, options) === '0';
22667 if (optedOut) {
22668 console$1.warn('You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data.');
22669 }
22670 return optedOut;
22671 }
22672
22673 /**
22674 * Wrap a MixpanelLib method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
22675 * If the user has opted out, return early instead of executing the method.
22676 * If a callback argument was provided, execute it passing the 0 error code.
22677 * @param {function} method - wrapped method to be executed if the user has not opted out
22678 * @returns {*} the result of executing method OR undefined if the user has opted out
22679 */
22680 function addOptOutCheckMixpanelLib(method) {
22681 return _addOptOutCheck(method, function(name) {
22682 return this.get_config(name);
22683 });
22684 }
22685
22686 /**
22687 * Wrap a MixpanelPeople method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
22688 * If the user has opted out, return early instead of executing the method.
22689 * If a callback argument was provided, execute it passing the 0 error code.
22690 * @param {function} method - wrapped method to be executed if the user has not opted out
22691 * @returns {*} the result of executing method OR undefined if the user has opted out
22692 */
22693 function addOptOutCheckMixpanelPeople(method) {
22694 return _addOptOutCheck(method, function(name) {
22695 return this._get_config(name);
22696 });
22697 }
22698
22699 /**
22700 * Wrap a MixpanelGroup method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
22701 * If the user has opted out, return early instead of executing the method.
22702 * If a callback argument was provided, execute it passing the 0 error code.
22703 * @param {function} method - wrapped method to be executed if the user has not opted out
22704 * @returns {*} the result of executing method OR undefined if the user has opted out
22705 */
22706 function addOptOutCheckMixpanelGroup(method) {
22707 return _addOptOutCheck(method, function(name) {
22708 return this._get_config(name);
22709 });
22710 }
22711
22712 /**
22713 * Clear the user's opt in/out status of data tracking and cookies/localstorage for the given token
22714 * @param {string} token - Mixpanel project tracking token
22715 * @param {Object} [options]
22716 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22717 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22718 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
22719 * @param {string} [options.cookieDomain] - custom cookie domain
22720 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
22721 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
22722 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
22723 */
22724 function clearOptInOut(token, options) {
22725 options = options || {};
22726 _getStorage(options).remove(
22727 _getStorageKey(token, options), !!options.crossSubdomainCookie, options.cookieDomain
22728 );
22729 }
22730
22731 /** Private **/
22732
22733 /**
22734 * Get storage util
22735 * @param {Object} [options]
22736 * @param {string} [options.persistenceType]
22737 * @returns {object} either _.cookie or _.localstorage
22738 */
22739 function _getStorage(options) {
22740 options = options || {};
22741 return options.persistenceType === 'localStorage' ? _.localStorage : _.cookie;
22742 }
22743
22744 /**
22745 * Get the name of the cookie that is used for the given opt type (tracking, cookie, etc.)
22746 * @param {string} token - Mixpanel project tracking token
22747 * @param {Object} [options]
22748 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22749 * @returns {string} the name of the cookie for the given opt type
22750 */
22751 function _getStorageKey(token, options) {
22752 options = options || {};
22753 return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token;
22754 }
22755
22756 /**
22757 * Get the value of the cookie that is used for the given opt type (tracking, cookie, etc.)
22758 * @param {string} token - Mixpanel project tracking token
22759 * @param {Object} [options]
22760 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22761 * @returns {string} the value of the cookie for the given opt type
22762 */
22763 function _getStorageValue(token, options) {
22764 return _getStorage(options).get(_getStorageKey(token, options));
22765 }
22766
22767 /**
22768 * Check whether the user has set the DNT/doNotTrack setting to true in their browser
22769 * @param {Object} [options]
22770 * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests
22771 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
22772 * @returns {boolean} whether the DNT setting is true
22773 */
22774 function _hasDoNotTrackFlagOn(options) {
22775 if (options && options.ignoreDnt) {
22776 return false;
22777 }
22778 var win$1 = (options && options.window) || win;
22779 var nav = win$1['navigator'] || {};
22780 var hasDntOn = false;
22781
22782 _.each([
22783 nav['doNotTrack'], // standard
22784 nav['msDoNotTrack'],
22785 win$1['doNotTrack']
22786 ], function(dntValue) {
22787 if (_.includes([true, 1, '1', 'yes'], dntValue)) {
22788 hasDntOn = true;
22789 }
22790 });
22791
22792 return hasDntOn;
22793 }
22794
22795 /**
22796 * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type
22797 * @param {boolean} optValue - whether to opt the user in or out for the given opt type
22798 * @param {string} token - Mixpanel project tracking token
22799 * @param {Object} [options]
22800 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
22801 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
22802 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
22803 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22804 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
22805 * @param {string} [options.cookieDomain] - custom cookie domain
22806 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
22807 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
22808 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
22809 */
22810 function _optInOut(optValue, token, options) {
22811 if (!_.isString(token) || !token.length) {
22812 console$1.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token');
22813 return;
22814 }
22815
22816 options = options || {};
22817
22818 _getStorage(options).set(
22819 _getStorageKey(token, options),
22820 optValue ? 1 : 0,
22821 _.isNumber(options.cookieExpiration) ? options.cookieExpiration : null,
22822 !!options.crossSubdomainCookie,
22823 !!options.secureCookie,
22824 !!options.crossSiteCookie,
22825 options.cookieDomain
22826 );
22827
22828 if (options.track && optValue) { // only track event if opting in (optValue=true)
22829 options.track(options.trackEventName || '$opt_in', options.trackProperties, {
22830 'send_immediately': true
22831 });
22832 }
22833 }
22834
22835 /**
22836 * Wrap a method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
22837 * If the user has opted out, return early instead of executing the method.
22838 * If a callback argument was provided, execute it passing the 0 error code.
22839 * @param {function} method - wrapped method to be executed if the user has not opted out
22840 * @param {function} getConfigValue - getter function for the Mixpanel API token and other options to be used with opt-out check
22841 * @returns {*} the result of executing method OR undefined if the user has opted out
22842 */
22843 function _addOptOutCheck(method, getConfigValue) {
22844 return function() {
22845 var optedOut = false;
22846
22847 try {
22848 var token = getConfigValue.call(this, 'token');
22849 var ignoreDnt = getConfigValue.call(this, 'ignore_dnt');
22850 var persistenceType = getConfigValue.call(this, 'opt_out_tracking_persistence_type');
22851 var persistencePrefix = getConfigValue.call(this, 'opt_out_tracking_cookie_prefix');
22852 var win = getConfigValue.call(this, 'window'); // used to override window during browser tests
22853
22854 if (token) { // if there was an issue getting the token, continue method execution as normal
22855 optedOut = hasOptedOut(token, {
22856 ignoreDnt: ignoreDnt,
22857 persistenceType: persistenceType,
22858 persistencePrefix: persistencePrefix,
22859 window: win
22860 });
22861 }
22862 } catch(err) {
22863 console$1.error('Unexpected error when checking tracking opt-out status: ' + err);
22864 }
22865
22866 if (!optedOut) {
22867 return method.apply(this, arguments);
22868 }
22869
22870 var callback = arguments[arguments.length - 1];
22871 if (typeof(callback) === 'function') {
22872 callback(0);
22873 }
22874
22875 return;
22876 };
22877 }
22878
22879 var logger$6 = console_with_prefix('lock');
22880
22881 /**
22882 * SharedLock: a mutex built on HTML5 localStorage, to ensure that only one browser
22883 * window/tab at a time will be able to access shared resources.
22884 *
22885 * Based on the Alur and Taubenfeld fast lock
22886 * (http://www.cs.rochester.edu/research/synchronization/pseudocode/fastlock.html)
22887 * with an added timeout to ensure there will be eventual progress in the event
22888 * that a window is closed in the middle of the callback.
22889 *
22890 * Implementation based on the original version by David Wolever (https://github.com/wolever)
22891 * at https://gist.github.com/wolever/5fd7573d1ef6166e8f8c4af286a69432.
22892 *
22893 * @example
22894 * const myLock = new SharedLock('some-key');
22895 * myLock.withLock(function() {
22896 * console.log('I hold the mutex!');
22897 * });
22898 *
22899 * @constructor
22900 */
22901 var SharedLock = function(key, options) {
22902 options = options || {};
22903
22904 this.storageKey = key;
22905 this.storage = options.storage || win.localStorage;
22906 this.pollIntervalMS = options.pollIntervalMS || 100;
22907 this.timeoutMS = options.timeoutMS || 2000;
22908
22909 // dependency-inject promise implementation for testing purposes
22910 this.promiseImpl = options.promiseImpl || PromisePolyfill;
22911 };
22912
22913 // pass in a specific pid to test contention scenarios; otherwise
22914 // it is chosen randomly for each acquisition attempt
22915 SharedLock.prototype.withLock = function(lockedCB, pid) {
22916 var Promise = this.promiseImpl;
22917 return new Promise(_.bind(function (resolve, reject) {
22918 var i = pid || (new Date().getTime() + '|' + Math.random());
22919 var startTime = new Date().getTime();
22920 var key = this.storageKey;
22921 var pollIntervalMS = this.pollIntervalMS;
22922 var timeoutMS = this.timeoutMS;
22923 var storage = this.storage;
22924
22925 var keyX = key + ':X';
22926 var keyY = key + ':Y';
22927 var keyZ = key + ':Z';
22928
22929 var delay = function(cb) {
22930 if (new Date().getTime() - startTime > timeoutMS) {
22931 logger$6.error('Timeout waiting for mutex on ' + key + '; clearing lock. [' + i + ']');
22932 storage.removeItem(keyZ);
22933 storage.removeItem(keyY);
22934 loop();
22935 return;
22936 }
22937 setTimeout(function() {
22938 try {
22939 cb();
22940 } catch(err) {
22941 reject(err);
22942 }
22943 }, pollIntervalMS * (Math.random() + 0.1));
22944 };
22945
22946 var waitFor = function(predicate, cb) {
22947 if (predicate()) {
22948 cb();
22949 } else {
22950 delay(function() {
22951 waitFor(predicate, cb);
22952 });
22953 }
22954 };
22955
22956 var getSetY = function() {
22957 var valY = storage.getItem(keyY);
22958 if (valY && valY !== i) { // if Y == i then this process already has the lock (useful for test cases)
22959 return false;
22960 } else {
22961 storage.setItem(keyY, i);
22962 if (storage.getItem(keyY) === i) {
22963 return true;
22964 } else {
22965 if (!localStorageSupported(storage, true)) {
22966 reject(new Error('localStorage support dropped while acquiring lock'));
22967 }
22968 return false;
22969 }
22970 }
22971 };
22972
22973 var loop = function() {
22974 storage.setItem(keyX, i);
22975
22976 waitFor(getSetY, function() {
22977 if (storage.getItem(keyX) === i) {
22978 criticalSection();
22979 return;
22980 }
22981
22982 delay(function() {
22983 if (storage.getItem(keyY) !== i) {
22984 loop();
22985 return;
22986 }
22987 waitFor(function() {
22988 return !storage.getItem(keyZ);
22989 }, criticalSection);
22990 });
22991 });
22992 };
22993
22994 var criticalSection = function() {
22995 storage.setItem(keyZ, '1');
22996 var removeLock = function () {
22997 storage.removeItem(keyZ);
22998 if (storage.getItem(keyY) === i) {
22999 storage.removeItem(keyY);
23000 }
23001 if (storage.getItem(keyX) === i) {
23002 storage.removeItem(keyX);
23003 }
23004 };
23005
23006 lockedCB()
23007 .then(function (ret) {
23008 removeLock();
23009 resolve(ret);
23010 })
23011 .catch(function (err) {
23012 removeLock();
23013 reject(err);
23014 });
23015 };
23016
23017 try {
23018 if (localStorageSupported(storage, true)) {
23019 loop();
23020 } else {
23021 throw new Error('localStorage support check failed');
23022 }
23023 } catch(err) {
23024 reject(err);
23025 }
23026 }, this));
23027 };
23028
23029 /**
23030 * @type {import('./wrapper').StorageWrapper}
23031 */
23032 var LocalStorageWrapper = function (storageOverride) {
23033 this.storage = storageOverride || win.localStorage;
23034 };
23035
23036 LocalStorageWrapper.prototype.init = function () {
23037 return PromisePolyfill.resolve();
23038 };
23039
23040 LocalStorageWrapper.prototype.isInitialized = function () {
23041 return true;
23042 };
23043
23044 LocalStorageWrapper.prototype.setItem = function (key, value) {
23045 return new PromisePolyfill(_.bind(function (resolve, reject) {
23046 try {
23047 this.storage.setItem(key, JSONStringify(value));
23048 } catch (e) {
23049 reject(e);
23050 }
23051 resolve();
23052 }, this));
23053 };
23054
23055 LocalStorageWrapper.prototype.getItem = function (key) {
23056 return new PromisePolyfill(_.bind(function (resolve, reject) {
23057 var item;
23058 try {
23059 item = JSONParse(this.storage.getItem(key));
23060 } catch (e) {
23061 reject(e);
23062 }
23063 resolve(item);
23064 }, this));
23065 };
23066
23067 LocalStorageWrapper.prototype.removeItem = function (key) {
23068 return new PromisePolyfill(_.bind(function (resolve, reject) {
23069 try {
23070 this.storage.removeItem(key);
23071 } catch (e) {
23072 reject(e);
23073 }
23074 resolve();
23075 }, this));
23076 };
23077
23078 var logger$5 = console_with_prefix('batch');
23079
23080 /**
23081 * RequestQueue: queue for batching API requests with localStorage backup for retries.
23082 * Maintains an in-memory queue which represents the source of truth for the current
23083 * page, but also writes all items out to a copy in the browser's localStorage, which
23084 * can be read on subsequent pageloads and retried. For batchability, all the request
23085 * items in the queue should be of the same type (events, people updates, group updates)
23086 * so they can be sent in a single request to the same API endpoint.
23087 *
23088 * LocalStorage keying and locking: In order for reloads and subsequent pageloads of
23089 * the same site to access the same persisted data, they must share the same localStorage
23090 * key (for instance based on project token and queue type). Therefore access to the
23091 * localStorage entry is guarded by an asynchronous mutex (SharedLock) to prevent
23092 * simultaneously open windows/tabs from overwriting each other's data (which would lead
23093 * to data loss in some situations).
23094 * @constructor
23095 */
23096 var RequestQueue = function (storageKey, options) {
23097 options = options || {};
23098 this.storageKey = storageKey;
23099 this.usePersistence = options.usePersistence;
23100 if (this.usePersistence) {
23101 this.queueStorage = options.queueStorage || new LocalStorageWrapper();
23102 this.lock = new SharedLock(storageKey, {
23103 storage: options.sharedLockStorage || win.localStorage,
23104 timeoutMS: options.sharedLockTimeoutMS,
23105 });
23106 }
23107 this.reportError = options.errorReporter || _.bind(logger$5.error, logger$5);
23108
23109 this.pid = options.pid || null; // pass pid to test out storage lock contention scenarios
23110
23111 this.memQueue = [];
23112 this.initialized = false;
23113
23114 if (options.enqueueThrottleMs) {
23115 this.enqueuePersisted = batchedThrottle(_.bind(this._enqueuePersisted, this), options.enqueueThrottleMs);
23116 } else {
23117 this.enqueuePersisted = _.bind(function (queueEntry) {
23118 return this._enqueuePersisted([queueEntry]);
23119 }, this);
23120 }
23121 };
23122
23123 RequestQueue.prototype.ensureInit = function () {
23124 if (this.initialized || !this.usePersistence) {
23125 return PromisePolyfill.resolve();
23126 }
23127
23128 return this.queueStorage
23129 .init()
23130 .then(_.bind(function () {
23131 this.initialized = true;
23132 }, this))
23133 .catch(_.bind(function (err) {
23134 this.reportError('Error initializing queue persistence. Disabling persistence', err);
23135 this.initialized = true;
23136 this.usePersistence = false;
23137 }, this));
23138 };
23139
23140 /**
23141 * Add one item to queues (memory and localStorage). The queued entry includes
23142 * the given item along with an auto-generated ID and a "flush-after" timestamp.
23143 * It is expected that the item will be sent over the network and dequeued
23144 * before the flush-after time; if this doesn't happen it is considered orphaned
23145 * (e.g., the original tab where it was enqueued got closed before it could be
23146 * sent) and the item can be sent by any tab that finds it in localStorage.
23147 *
23148 * The final callback param is called with a param indicating success or
23149 * failure of the enqueue operation; it is asynchronous because the localStorage
23150 * lock is asynchronous.
23151 */
23152 RequestQueue.prototype.enqueue = function (item, flushInterval) {
23153 var queueEntry = {
23154 'id': cheap_guid(),
23155 'flushAfter': new Date().getTime() + flushInterval * 2,
23156 'payload': item
23157 };
23158
23159 if (!this.usePersistence) {
23160 this.memQueue.push(queueEntry);
23161 return PromisePolyfill.resolve(true);
23162 } else {
23163 return this.enqueuePersisted(queueEntry);
23164 }
23165 };
23166
23167 RequestQueue.prototype._enqueuePersisted = function (queueEntries) {
23168 var enqueueItem = _.bind(function () {
23169 return this.ensureInit()
23170 .then(_.bind(function () {
23171 return this.readFromStorage();
23172 }, this))
23173 .then(_.bind(function (storedQueue) {
23174 return this.saveToStorage(storedQueue.concat(queueEntries));
23175 }, this))
23176 .then(_.bind(function (succeeded) {
23177 // only add to in-memory queue when storage succeeds
23178 if (succeeded) {
23179 this.memQueue = this.memQueue.concat(queueEntries);
23180 }
23181
23182 return succeeded;
23183 }, this))
23184 .catch(_.bind(function (err) {
23185 this.reportError('Error enqueueing items', err, queueEntries);
23186 return false;
23187 }, this));
23188 }, this);
23189
23190 return this.lock
23191 .withLock(enqueueItem, this.pid)
23192 .catch(_.bind(function (err) {
23193 this.reportError('Error acquiring storage lock', err);
23194 return false;
23195 }, this));
23196 };
23197
23198 /**
23199 * Read out the given number of queue entries. If this.memQueue
23200 * has fewer than batchSize items, then look for "orphaned" items
23201 * in the persisted queue (items where the 'flushAfter' time has
23202 * already passed).
23203 */
23204 RequestQueue.prototype.fillBatch = function (batchSize) {
23205 var batch = this.memQueue.slice(0, batchSize);
23206 if (this.usePersistence && batch.length < batchSize) {
23207 // don't need lock just to read events; localStorage is thread-safe
23208 // and the worst that could happen is a duplicate send of some
23209 // orphaned events, which will be deduplicated on the server side
23210 return this.ensureInit()
23211 .then(_.bind(function () {
23212 return this.readFromStorage();
23213 }, this))
23214 .then(_.bind(function (storedQueue) {
23215 if (storedQueue.length) {
23216 // item IDs already in batch; don't duplicate out of storage
23217 var idsInBatch = {}; // poor man's Set
23218 _.each(batch, function (item) {
23219 idsInBatch[item['id']] = true;
23220 });
23221
23222 for (var i = 0; i < storedQueue.length; i++) {
23223 var item = storedQueue[i];
23224 if (new Date().getTime() > item['flushAfter'] && !idsInBatch[item['id']]) {
23225 item.orphaned = true;
23226 batch.push(item);
23227 if (batch.length >= batchSize) {
23228 break;
23229 }
23230 }
23231 }
23232 }
23233
23234 return batch;
23235 }, this));
23236 } else {
23237 return PromisePolyfill.resolve(batch);
23238 }
23239 };
23240
23241 /**
23242 * Remove items with matching 'id' from array (immutably)
23243 * also remove any item without a valid id (e.g., malformed
23244 * storage entries).
23245 */
23246 var filterOutIDsAndInvalid = function (items, idSet) {
23247 var filteredItems = [];
23248 _.each(items, function (item) {
23249 if (item['id'] && !idSet[item['id']]) {
23250 filteredItems.push(item);
23251 }
23252 });
23253 return filteredItems;
23254 };
23255
23256 /**
23257 * Remove items with matching IDs from both in-memory queue
23258 * and persisted queue
23259 */
23260 RequestQueue.prototype.removeItemsByID = function (ids) {
23261 var idSet = {}; // poor man's Set
23262 _.each(ids, function (id) {
23263 idSet[id] = true;
23264 });
23265
23266 this.memQueue = filterOutIDsAndInvalid(this.memQueue, idSet);
23267 if (!this.usePersistence) {
23268 return PromisePolyfill.resolve(true);
23269 } else {
23270 var removeFromStorage = _.bind(function () {
23271 return this.ensureInit()
23272 .then(_.bind(function () {
23273 return this.readFromStorage();
23274 }, this))
23275 .then(_.bind(function (storedQueue) {
23276 storedQueue = filterOutIDsAndInvalid(storedQueue, idSet);
23277 return this.saveToStorage(storedQueue);
23278 }, this))
23279 .then(_.bind(function () {
23280 return this.readFromStorage();
23281 }, this))
23282 .then(_.bind(function (storedQueue) {
23283 // an extra check: did storage report success but somehow
23284 // the items are still there?
23285 for (var i = 0; i < storedQueue.length; i++) {
23286 var item = storedQueue[i];
23287 if (item['id'] && !!idSet[item['id']]) {
23288 throw new Error('Item not removed from storage');
23289 }
23290 }
23291 return true;
23292 }, this))
23293 .catch(_.bind(function (err) {
23294 this.reportError('Error removing items', err, ids);
23295 return false;
23296 }, this));
23297 }, this);
23298
23299 return this.lock
23300 .withLock(removeFromStorage, this.pid)
23301 .catch(_.bind(function (err) {
23302 this.reportError('Error acquiring storage lock', err);
23303 if (!localStorageSupported(this.lock.storage, true)) {
23304 // Looks like localStorage writes have stopped working sometime after
23305 // initialization (probably full), and so nobody can acquire locks
23306 // anymore. Consider it temporarily safe to remove items without the
23307 // lock, since nobody's writing successfully anyway.
23308 return removeFromStorage()
23309 .then(_.bind(function (success) {
23310 if (!success) {
23311 // OK, we couldn't even write out the smaller queue. Try clearing it
23312 // entirely.
23313 return this.queueStorage.removeItem(this.storageKey).then(function () {
23314 return success;
23315 });
23316 }
23317 return success;
23318 }, this))
23319 .catch(_.bind(function (err) {
23320 this.reportError('Error clearing queue', err);
23321 return false;
23322 }, this));
23323 } else {
23324 return false;
23325 }
23326 }, this));
23327 }
23328 };
23329
23330 // internal helper for RequestQueue.updatePayloads
23331 var updatePayloads = function (existingItems, itemsToUpdate) {
23332 var newItems = [];
23333 _.each(existingItems, function (item) {
23334 var id = item['id'];
23335 if (id in itemsToUpdate) {
23336 var newPayload = itemsToUpdate[id];
23337 if (newPayload !== null) {
23338 item['payload'] = newPayload;
23339 newItems.push(item);
23340 }
23341 } else {
23342 // no update
23343 newItems.push(item);
23344 }
23345 });
23346 return newItems;
23347 };
23348
23349 /**
23350 * Update payloads of given items in both in-memory queue and
23351 * persisted queue. Items set to null are removed from queues.
23352 */
23353 RequestQueue.prototype.updatePayloads = function (itemsToUpdate) {
23354 this.memQueue = updatePayloads(this.memQueue, itemsToUpdate);
23355 if (!this.usePersistence) {
23356 return PromisePolyfill.resolve(true);
23357 } else {
23358 return this.lock
23359 .withLock(_.bind(function lockAcquired() {
23360 return this.ensureInit()
23361 .then(_.bind(function () {
23362 return this.readFromStorage();
23363 }, this))
23364 .then(_.bind(function (storedQueue) {
23365 storedQueue = updatePayloads(storedQueue, itemsToUpdate);
23366 return this.saveToStorage(storedQueue);
23367 }, this))
23368 .catch(_.bind(function (err) {
23369 this.reportError('Error updating items', itemsToUpdate, err);
23370 return false;
23371 }, this));
23372 }, this), this.pid)
23373 .catch(_.bind(function (err) {
23374 this.reportError('Error acquiring storage lock', err);
23375 return false;
23376 }, this));
23377 }
23378 };
23379
23380 /**
23381 * Read and parse items array from localStorage entry, handling
23382 * malformed/missing data if necessary.
23383 */
23384 RequestQueue.prototype.readFromStorage = function () {
23385 return this.ensureInit()
23386 .then(_.bind(function () {
23387 return this.queueStorage.getItem(this.storageKey);
23388 }, this))
23389 .then(_.bind(function (storageEntry) {
23390 if (storageEntry) {
23391 if (!_.isArray(storageEntry)) {
23392 this.reportError('Invalid storage entry:', storageEntry);
23393 storageEntry = null;
23394 }
23395 }
23396 return storageEntry || [];
23397 }, this))
23398 .catch(_.bind(function (err) {
23399 this.reportError('Error retrieving queue', err);
23400 return [];
23401 }, this));
23402 };
23403
23404 /**
23405 * Serialize the given items array to localStorage.
23406 */
23407 RequestQueue.prototype.saveToStorage = function (queue) {
23408 return this.ensureInit()
23409 .then(_.bind(function () {
23410 return this.queueStorage.setItem(this.storageKey, queue);
23411 }, this))
23412 .then(function () {
23413 return true;
23414 })
23415 .catch(_.bind(function (err) {
23416 this.reportError('Error saving queue', err);
23417 return false;
23418 }, this));
23419 };
23420
23421 /**
23422 * Clear out queues (memory and localStorage).
23423 */
23424 RequestQueue.prototype.clear = function () {
23425 this.memQueue = [];
23426
23427 if (this.usePersistence) {
23428 return this.ensureInit()
23429 .then(_.bind(function () {
23430 return this.queueStorage.removeItem(this.storageKey);
23431 }, this));
23432 } else {
23433 return PromisePolyfill.resolve();
23434 }
23435 };
23436
23437 // maximum interval between request retries after exponential backoff
23438 var MAX_RETRY_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
23439
23440 var logger$4 = console_with_prefix('batch');
23441
23442 /**
23443 * RequestBatcher: manages the queueing, flushing, retry etc of requests of one
23444 * type (events, people, groups).
23445 * Uses RequestQueue to manage the backing store.
23446 * @constructor
23447 */
23448 var RequestBatcher = function(storageKey, options) {
23449 this.errorReporter = options.errorReporter;
23450 this.queue = new RequestQueue(storageKey, {
23451 errorReporter: _.bind(this.reportError, this),
23452 queueStorage: options.queueStorage,
23453 sharedLockStorage: options.sharedLockStorage,
23454 sharedLockTimeoutMS: options.sharedLockTimeoutMS,
23455 usePersistence: options.usePersistence,
23456 enqueueThrottleMs: options.enqueueThrottleMs
23457 });
23458
23459 this.libConfig = options.libConfig;
23460 this.sendRequest = options.sendRequestFunc;
23461 this.beforeSendHook = options.beforeSendHook;
23462 this.stopAllBatching = options.stopAllBatchingFunc;
23463
23464 // seed variable batch size + flush interval with configured values
23465 this.batchSize = this.libConfig['batch_size'];
23466 this.flushInterval = this.libConfig['batch_flush_interval_ms'];
23467
23468 this.stopped = !this.libConfig['batch_autostart'];
23469 this.consecutiveRemovalFailures = 0;
23470
23471 // extra client-side dedupe
23472 this.itemIdsSentSuccessfully = {};
23473
23474 // Make the flush occur at the interval specified by flushIntervalMs, default behavior will attempt consecutive flushes
23475 // as long as the queue is not empty. This is useful for high-frequency events like Session Replay where we might end up
23476 // in a request loop and get ratelimited by the server.
23477 this.flushOnlyOnInterval = options.flushOnlyOnInterval || false;
23478
23479 this._flushPromise = null;
23480 };
23481
23482 /**
23483 * Add one item to queue.
23484 */
23485 RequestBatcher.prototype.enqueue = function(item) {
23486 return this.queue.enqueue(item, this.flushInterval);
23487 };
23488
23489 /**
23490 * Start flushing batches at the configured time interval. Must call
23491 * this method upon SDK init in order to send anything over the network.
23492 */
23493 RequestBatcher.prototype.start = function() {
23494 this.stopped = false;
23495 this.consecutiveRemovalFailures = 0;
23496 return this.flush();
23497 };
23498
23499 /**
23500 * Stop flushing batches. Can be restarted by calling start().
23501 */
23502 RequestBatcher.prototype.stop = function() {
23503 this.stopped = true;
23504 if (this.timeoutID) {
23505 clearTimeout(this.timeoutID);
23506 this.timeoutID = null;
23507 }
23508 };
23509
23510 /**
23511 * Clear out queue.
23512 */
23513 RequestBatcher.prototype.clear = function() {
23514 return this.queue.clear();
23515 };
23516
23517 /**
23518 * Restore batch size configuration to whatever is set in the main SDK.
23519 */
23520 RequestBatcher.prototype.resetBatchSize = function() {
23521 this.batchSize = this.libConfig['batch_size'];
23522 };
23523
23524 /**
23525 * Restore flush interval time configuration to whatever is set in the main SDK.
23526 */
23527 RequestBatcher.prototype.resetFlush = function() {
23528 this.scheduleFlush(this.libConfig['batch_flush_interval_ms']);
23529 };
23530
23531 /**
23532 * Schedule the next flush in the given number of milliseconds.
23533 */
23534 RequestBatcher.prototype.scheduleFlush = function(flushMS) {
23535 this.flushInterval = flushMS;
23536 if (!this.stopped) { // don't schedule anymore if batching has been stopped
23537 this.timeoutID = setTimeout(_.bind(function() {
23538 if (!this.stopped) {
23539 this._flushPromise = this.flush();
23540 }
23541 }, this), this.flushInterval);
23542 }
23543 };
23544
23545 /**
23546 * Send a request using the sendRequest callback, but promisified.
23547 * TODO: sendRequest should be promisified in the first place.
23548 */
23549 RequestBatcher.prototype.sendRequestPromise = function(data, options) {
23550 return new PromisePolyfill(_.bind(function(resolve) {
23551 this.sendRequest(data, options, resolve);
23552 }, this));
23553 };
23554
23555
23556 /**
23557 * Flush one batch to network. Depending on success/failure modes, it will either
23558 * remove the batch from the queue or leave it in for retry, and schedule the next
23559 * flush. In cases of most network or API failures, it will back off exponentially
23560 * when retrying.
23561 * @param {Object} [options]
23562 * @param {boolean} [options.sendBeacon] - whether to send batch with
23563 * navigator.sendBeacon (only useful for sending batches before page unloads, as
23564 * sendBeacon offers no callbacks or status indications)
23565 */
23566 RequestBatcher.prototype.flush = function(options) {
23567 if (this.requestInProgress) {
23568 logger$4.log('Flush: Request already in progress');
23569 return PromisePolyfill.resolve();
23570 }
23571
23572 this.requestInProgress = true;
23573
23574 options = options || {};
23575 var timeoutMS = this.libConfig['batch_request_timeout_ms'];
23576 var startTime = new Date().getTime();
23577 var currentBatchSize = this.batchSize;
23578
23579 return this.queue.fillBatch(currentBatchSize)
23580 .then(_.bind(function(batch) {
23581
23582 // if there's more items in the queue than the batch size, attempt
23583 // to flush again after the current batch is done.
23584 var attemptSecondaryFlush = batch.length === currentBatchSize;
23585 var dataForRequest = [];
23586 var transformedItems = {};
23587 _.each(batch, function(item) {
23588 var payload = item['payload'];
23589 if (this.beforeSendHook && !item.orphaned) {
23590 payload = this.beforeSendHook(payload);
23591 }
23592 if (payload) {
23593 // mp_sent_by_lib_version prop captures which lib version actually
23594 // sends each event (regardless of which version originally queued
23595 // it for sending)
23596 if (payload['event'] && payload['properties']) {
23597 payload['properties'] = _.extend(
23598 {},
23599 payload['properties'],
23600 {'mp_sent_by_lib_version': Config.LIB_VERSION}
23601 );
23602 }
23603 var addPayload = true;
23604 var itemId = item['id'];
23605 if (itemId) {
23606 if ((this.itemIdsSentSuccessfully[itemId] || 0) > 5) {
23607 this.reportError('[dupe] item ID sent too many times, not sending', {
23608 item: item,
23609 batchSize: batch.length,
23610 timesSent: this.itemIdsSentSuccessfully[itemId]
23611 });
23612 addPayload = false;
23613 }
23614 } else {
23615 this.reportError('[dupe] found item with no ID', {item: item});
23616 }
23617
23618 if (addPayload) {
23619 dataForRequest.push(payload);
23620 }
23621 }
23622 transformedItems[item['id']] = payload;
23623 }, this);
23624
23625 if (dataForRequest.length < 1) {
23626 this.requestInProgress = false;
23627 this.resetFlush();
23628 return PromisePolyfill.resolve(); // nothing to do
23629 }
23630
23631 var removeItemsFromQueue = _.bind(function () {
23632 return this.queue
23633 .removeItemsByID(
23634 _.map(batch, function (item) {
23635 return item['id'];
23636 })
23637 )
23638 .then(_.bind(function (succeeded) {
23639 // client-side dedupe
23640 _.each(batch, _.bind(function(item) {
23641 var itemId = item['id'];
23642 if (itemId) {
23643 this.itemIdsSentSuccessfully[itemId] = this.itemIdsSentSuccessfully[itemId] || 0;
23644 this.itemIdsSentSuccessfully[itemId]++;
23645 if (this.itemIdsSentSuccessfully[itemId] > 5) {
23646 this.reportError('[dupe] item ID sent too many times', {
23647 item: item,
23648 batchSize: batch.length,
23649 timesSent: this.itemIdsSentSuccessfully[itemId]
23650 });
23651 }
23652 } else {
23653 this.reportError('[dupe] found item with no ID while removing', {item: item});
23654 }
23655 }, this));
23656
23657 if (succeeded) {
23658 this.consecutiveRemovalFailures = 0;
23659 if (this.flushOnlyOnInterval && !attemptSecondaryFlush) {
23660 this.resetFlush(); // schedule next batch with a delay
23661 return PromisePolyfill.resolve();
23662 } else {
23663 return this.flush(); // handle next batch if the queue isn't empty
23664 }
23665 } else {
23666 if (++this.consecutiveRemovalFailures > 5) {
23667 this.reportError('Too many queue failures; disabling batching system.');
23668 this.stopAllBatching();
23669 } else {
23670 this.resetFlush();
23671 }
23672 return PromisePolyfill.resolve();
23673 }
23674 }, this));
23675 }, this);
23676
23677 var batchSendCallback = _.bind(function(res) {
23678 this.requestInProgress = false;
23679
23680 try {
23681
23682 // handle API response in a try-catch to make sure we can reset the
23683 // flush operation if something goes wrong
23684
23685 if (options.unloading) {
23686 // update persisted data to include hook transformations
23687 return this.queue.updatePayloads(transformedItems);
23688 } else if (
23689 _.isObject(res) &&
23690 res.error === 'timeout' &&
23691 new Date().getTime() - startTime >= timeoutMS
23692 ) {
23693 this.reportError('Network timeout; retrying');
23694 return this.flush();
23695 } else if (
23696 _.isObject(res) &&
23697 (
23698 res.httpStatusCode >= 500
23699 || res.httpStatusCode === 429
23700 || (res.httpStatusCode <= 0 && !isOnline())
23701 || res.error === 'timeout'
23702 )
23703 ) {
23704 // network or API error, or 429 Too Many Requests, retry
23705 var retryMS = this.flushInterval * 2;
23706 if (res.retryAfter) {
23707 retryMS = (parseInt(res.retryAfter, 10) * 1000) || retryMS;
23708 }
23709 retryMS = Math.min(MAX_RETRY_INTERVAL_MS, retryMS);
23710 this.reportError('Error; retry in ' + retryMS + ' ms');
23711 this.scheduleFlush(retryMS);
23712 return PromisePolyfill.resolve();
23713 } else if (_.isObject(res) && res.httpStatusCode === 413) {
23714 // 413 Payload Too Large
23715 if (batch.length > 1) {
23716 var halvedBatchSize = Math.max(1, Math.floor(currentBatchSize / 2));
23717 this.batchSize = Math.min(this.batchSize, halvedBatchSize, batch.length - 1);
23718 this.reportError('413 response; reducing batch size to ' + this.batchSize);
23719 this.resetFlush();
23720 return PromisePolyfill.resolve();
23721 } else {
23722 this.reportError('Single-event request too large; dropping', batch);
23723 this.resetBatchSize();
23724 return removeItemsFromQueue();
23725 }
23726 } else {
23727 // successful network request+response; remove each item in batch from queue
23728 // (even if it was e.g. a 400, in which case retrying won't help)
23729 return removeItemsFromQueue();
23730 }
23731 } catch(err) {
23732 this.reportError('Error handling API response', err);
23733 this.resetFlush();
23734 }
23735 }, this);
23736 var requestOptions = {
23737 method: 'POST',
23738 verbose: true,
23739 ignore_json_errors: true, // eslint-disable-line camelcase
23740 timeout_ms: timeoutMS // eslint-disable-line camelcase
23741 };
23742 if (options.unloading) {
23743 requestOptions.transport = 'sendBeacon';
23744 }
23745 logger$4.log('MIXPANEL REQUEST:', dataForRequest);
23746 return this.sendRequestPromise(dataForRequest, requestOptions).then(batchSendCallback);
23747 }, this))
23748 .catch(_.bind(function(err) {
23749 this.reportError('Error flushing request queue', err);
23750 this.resetFlush();
23751 }, this));
23752 };
23753
23754 /**
23755 * Log error to global logger and optional user-defined logger.
23756 */
23757 RequestBatcher.prototype.reportError = function(msg, err) {
23758 logger$4.error.apply(logger$4.error, arguments);
23759 if (this.errorReporter) {
23760 try {
23761 if (!(err instanceof Error)) {
23762 err = new Error(msg);
23763 }
23764 this.errorReporter(msg, err);
23765 } catch(err) {
23766 logger$4.error(err);
23767 }
23768 }
23769 };
23770
23771 /**
23772 * @param {import('./session-recording').SerializedRecording} serializedRecording
23773 * @returns {boolean}
23774 */
23775 var isRecordingExpired = function(serializedRecording) {
23776 var now = Date.now();
23777 return !serializedRecording || now > serializedRecording['maxExpires'] || now > serializedRecording['idleExpires'];
23778 };
23779
23780 var RECORD_ENQUEUE_THROTTLE_MS = 250;
23781
23782 var logger$3 = console_with_prefix('recorder');
23783 var CompressionStream = win['CompressionStream'];
23784
23785 var RECORDER_BATCHER_LIB_CONFIG = {
23786 'batch_size': 1000,
23787 'batch_flush_interval_ms': 10 * 1000,
23788 'batch_request_timeout_ms': 90 * 1000,
23789 'batch_autostart': true
23790 };
23791
23792 var ACTIVE_SOURCES = new Set([
23793 IncrementalSource.MouseMove,
23794 IncrementalSource.MouseInteraction,
23795 IncrementalSource.Scroll,
23796 IncrementalSource.ViewportResize,
23797 IncrementalSource.Input,
23798 IncrementalSource.TouchMove,
23799 IncrementalSource.MediaInteraction,
23800 IncrementalSource.Drag,
23801 IncrementalSource.Selection,
23802 ]);
23803
23804 function isUserEvent(ev) {
23805 return ev.type === EventType.IncrementalSnapshot && ACTIVE_SOURCES.has(ev.data.source);
23806 }
23807
23808 /**
23809 * @typedef {Object} SerializedRecording
23810 * @property {number} idleExpires
23811 * @property {number} maxExpires
23812 * @property {number} replayStartTime
23813 * @property {number} seqNo
23814 * @property {string} batchStartUrl
23815 * @property {string} replayId
23816 * @property {string} tabId
23817 * @property {string} replayStartUrl
23818 */
23819
23820 /**
23821 * @typedef {Object} SessionRecordingOptions
23822 * @property {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
23823 * @property {String} [options.replayId] - unique uuid for a single replay
23824 * @property {Function} [options.onIdleTimeout] - callback when a recording reaches idle timeout
23825 * @property {Function} [options.onMaxLengthReached] - callback when a recording reaches its maximum length
23826 * @property {Function} [options.rrwebRecord] - rrweb's `record` function
23827 * @property {Function} [options.onBatchSent] - callback when a batch of events is sent to the server
23828 * @property {Storage} [options.sharedLockStorage] - optional storage for shared lock, used for test dependency injection
23829 * optional properties for deserialization:
23830 * @property {number} idleExpires
23831 * @property {number} maxExpires
23832 * @property {number} replayStartTime
23833 * @property {number} seqNo
23834 * @property {string} batchStartUrl
23835 * @property {string} replayStartUrl
23836 */
23837
23838 /**
23839 * @typedef {Object} UserIdInfo
23840 * @property {string} distinct_id
23841 * @property {string} user_id
23842 * @property {string} device_id
23843 */
23844
23845
23846 /**
23847 * This class encapsulates a single session recording and its lifecycle.
23848 * @param {SessionRecordingOptions} options
23849 */
23850 var SessionRecording = function(options) {
23851 this._mixpanel = options.mixpanelInstance;
23852 this._onIdleTimeout = options.onIdleTimeout || NOOP_FUNC;
23853 this._onMaxLengthReached = options.onMaxLengthReached || NOOP_FUNC;
23854 this._onBatchSent = options.onBatchSent || NOOP_FUNC;
23855 this._rrwebRecord = options.rrwebRecord || null;
23856
23857 // internal rrweb stopRecording function
23858 this._stopRecording = null;
23859 this.replayId = options.replayId;
23860
23861 this.batchStartUrl = options.batchStartUrl || null;
23862 this.replayStartUrl = options.replayStartUrl || null;
23863 this.idleExpires = options.idleExpires || null;
23864 this.maxExpires = options.maxExpires || null;
23865 this.replayStartTime = options.replayStartTime || null;
23866 this.seqNo = options.seqNo || 0;
23867
23868 this.idleTimeoutId = null;
23869 this.maxTimeoutId = null;
23870
23871 this.recordMaxMs = MAX_RECORDING_MS;
23872 this.recordMinMs = 0;
23873
23874 // disable persistence if localStorage is not supported
23875 // request-queue will automatically disable persistence if indexedDB fails to initialize
23876 var usePersistence = localStorageSupported(options.sharedLockStorage, true) && !this.getConfig('disable_persistence');
23877
23878 // each replay has its own batcher key to avoid conflicts between rrweb events of different recordings
23879 this.batcherKey = '__mprec_' + this.getConfig('name') + '_' + this.getConfig('token') + '_' + this.replayId;
23880 this.queueStorage = new IDBStorageWrapper(RECORDING_EVENTS_STORE_NAME);
23881 this.batcher = new RequestBatcher(this.batcherKey, {
23882 errorReporter: this.reportError.bind(this),
23883 flushOnlyOnInterval: true,
23884 libConfig: RECORDER_BATCHER_LIB_CONFIG,
23885 sendRequestFunc: this.flushEventsWithOptOut.bind(this),
23886 queueStorage: this.queueStorage,
23887 sharedLockStorage: options.sharedLockStorage,
23888 usePersistence: usePersistence,
23889 stopAllBatchingFunc: this.stopRecording.bind(this),
23890
23891 // increased throttle and shared lock timeout because recording events are very high frequency.
23892 // this will minimize the amount of lock contention between enqueued events.
23893 // for session recordings there is a lock for each tab anyway, so there's no risk of deadlock between tabs.
23894 enqueueThrottleMs: RECORD_ENQUEUE_THROTTLE_MS,
23895 sharedLockTimeoutMS: 10 * 1000,
23896 });
23897 };
23898
23899 /**
23900 * @returns {UserIdInfo}
23901 */
23902 SessionRecording.prototype.getUserIdInfo = function () {
23903 if (this.finalFlushUserIdInfo) {
23904 return this.finalFlushUserIdInfo;
23905 }
23906
23907 var userIdInfo = {
23908 'distinct_id': String(this._mixpanel.get_distinct_id()),
23909 };
23910
23911 // send ID management props if they exist
23912 var deviceId = this._mixpanel.get_property('$device_id');
23913 if (deviceId) {
23914 userIdInfo['$device_id'] = deviceId;
23915 }
23916 var userId = this._mixpanel.get_property('$user_id');
23917 if (userId) {
23918 userIdInfo['$user_id'] = userId;
23919 }
23920 return userIdInfo;
23921 };
23922
23923 SessionRecording.prototype.unloadPersistedData = function () {
23924 this.batcher.stop();
23925 return this.batcher.flush()
23926 .then(function () {
23927 return this.queueStorage.removeItem(this.batcherKey);
23928 }.bind(this));
23929 };
23930
23931 SessionRecording.prototype.getConfig = function(configVar) {
23932 return this._mixpanel.get_config(configVar);
23933 };
23934
23935 // Alias for getConfig, used by the common addOptOutCheckMixpanelLib function which
23936 // reaches into this class instance and expects the snake case version of the function.
23937 // eslint-disable-next-line camelcase
23938 SessionRecording.prototype.get_config = function(configVar) {
23939 return this.getConfig(configVar);
23940 };
23941
23942 SessionRecording.prototype.startRecording = function (shouldStopBatcher) {
23943 if (this._rrwebRecord === null) {
23944 this.reportError('rrweb record function not provided. ');
23945 return;
23946 }
23947
23948 if (this._stopRecording !== null) {
23949 logger$3.log('Recording already in progress, skipping startRecording.');
23950 return;
23951 }
23952
23953 this.recordMaxMs = this.getConfig('record_max_ms');
23954 if (this.recordMaxMs > MAX_RECORDING_MS) {
23955 this.recordMaxMs = MAX_RECORDING_MS;
23956 logger$3.critical('record_max_ms cannot be greater than ' + MAX_RECORDING_MS + 'ms. Capping value.');
23957 }
23958
23959 if (!this.maxExpires) {
23960 this.maxExpires = new Date().getTime() + this.recordMaxMs;
23961 }
23962
23963 this.recordMinMs = this.getConfig('record_min_ms');
23964 if (this.recordMinMs > MAX_VALUE_FOR_MIN_RECORDING_MS) {
23965 this.recordMinMs = MAX_VALUE_FOR_MIN_RECORDING_MS;
23966 logger$3.critical('record_min_ms cannot be greater than ' + MAX_VALUE_FOR_MIN_RECORDING_MS + 'ms. Capping value.');
23967 }
23968
23969 if (!this.replayStartTime) {
23970 this.replayStartTime = new Date().getTime();
23971 this.batchStartUrl = _.info.currentUrl();
23972 this.replayStartUrl = _.info.currentUrl();
23973 }
23974
23975 if (shouldStopBatcher || this.recordMinMs > 0) {
23976 // the primary case for shouldStopBatcher is when we're starting recording after a reset
23977 // and don't want to send anything over the network until there's
23978 // actual user activity
23979 // this also applies if the minimum recording length has not been hit yet
23980 // so that we don't send data until we know the recording will be long enough
23981 this.batcher.stop();
23982 } else {
23983 this.batcher.start();
23984 }
23985
23986 var resetIdleTimeout = function () {
23987 clearTimeout(this.idleTimeoutId);
23988 var idleTimeoutMs = this.getConfig('record_idle_timeout_ms');
23989 this.idleTimeoutId = setTimeout(this._onIdleTimeout, idleTimeoutMs);
23990 this.idleExpires = new Date().getTime() + idleTimeoutMs;
23991 }.bind(this);
23992 resetIdleTimeout();
23993
23994 var blockSelector = this.getConfig('record_block_selector');
23995 if (blockSelector === '' || blockSelector === null) {
23996 blockSelector = undefined;
23997 }
23998
23999 try {
24000 this._stopRecording = this._rrwebRecord({
24001 'emit': function (ev) {
24002 if (this.idleExpires && this.idleExpires < ev.timestamp) {
24003 this._onIdleTimeout();
24004 return;
24005 }
24006 if (isUserEvent(ev)) {
24007 if (this.batcher.stopped && new Date().getTime() - this.replayStartTime >= this.recordMinMs) {
24008 // start flushing again after user activity
24009 this.batcher.start();
24010 }
24011 resetIdleTimeout();
24012 }
24013 // promise only used to await during tests
24014 this.__enqueuePromise = this.batcher.enqueue(ev);
24015 }.bind(this),
24016 'blockClass': this.getConfig('record_block_class'),
24017 'blockSelector': blockSelector,
24018 'collectFonts': this.getConfig('record_collect_fonts'),
24019 'dataURLOptions': { // canvas image options (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL)
24020 'type': 'image/webp',
24021 'quality': 0.6
24022 },
24023 'maskAllInputs': true,
24024 'maskTextClass': this.getConfig('record_mask_text_class'),
24025 'maskTextSelector': this.getConfig('record_mask_text_selector'),
24026 'recordCanvas': this.getConfig('record_canvas'),
24027 'sampling': {
24028 'canvas': 15
24029 }
24030 });
24031 } catch (err) {
24032 this.reportError('Unexpected error when starting rrweb recording.', err);
24033 }
24034
24035 if (typeof this._stopRecording !== 'function') {
24036 this.reportError('rrweb failed to start, skipping this recording.');
24037 this._stopRecording = null;
24038 this.stopRecording(); // stop batcher looping and any timeouts
24039 return;
24040 }
24041
24042 var maxTimeoutMs = this.maxExpires - new Date().getTime();
24043 this.maxTimeoutId = setTimeout(this._onMaxLengthReached.bind(this), maxTimeoutMs);
24044 };
24045
24046 SessionRecording.prototype.stopRecording = function (skipFlush) {
24047 // store the user ID info in case this is getting called in mixpanel.reset()
24048 this.finalFlushUserIdInfo = this.getUserIdInfo();
24049
24050 if (!this.isRrwebStopped()) {
24051 try {
24052 this._stopRecording();
24053 } catch (err) {
24054 this.reportError('Error with rrweb stopRecording', err);
24055 }
24056 this._stopRecording = null;
24057 }
24058
24059 var flushPromise;
24060 if (this.batcher.stopped) {
24061 // never got user activity to flush after reset, so just clear the batcher
24062 flushPromise = this.batcher.clear();
24063 } else if (!skipFlush) {
24064 // flush any remaining events from running batcher
24065 flushPromise = this.batcher.flush();
24066 }
24067 this.batcher.stop();
24068
24069 clearTimeout(this.idleTimeoutId);
24070 clearTimeout(this.maxTimeoutId);
24071 return flushPromise;
24072 };
24073
24074 SessionRecording.prototype.isRrwebStopped = function () {
24075 return this._stopRecording === null;
24076 };
24077
24078
24079 /**
24080 * Flushes the current batch of events to the server, but passes an opt-out callback to make sure
24081 * we stop recording and dump any queued events if the user has opted out.
24082 */
24083 SessionRecording.prototype.flushEventsWithOptOut = function (data, options, cb) {
24084 var onOptOut = function (code) {
24085 // addOptOutCheckMixpanelLib invokes this function with code=0 when the user has opted out
24086 if (code === 0) {
24087 this.stopRecording();
24088 cb({error: 'Tracking has been opted out, stopping recording.'});
24089 }
24090 }.bind(this);
24091
24092 this._flushEvents(data, options, cb, onOptOut);
24093 };
24094
24095 /**
24096 * @returns {SerializedRecording}
24097 */
24098 SessionRecording.prototype.serialize = function () {
24099 // don't break if mixpanel instance was destroyed at some point
24100 var tabId;
24101 try {
24102 tabId = this._mixpanel.get_tab_id();
24103 } catch (e) {
24104 this.reportError('Error getting tab ID for serialization ', e);
24105 tabId = null;
24106 }
24107
24108 return {
24109 'replayId': this.replayId,
24110 'seqNo': this.seqNo,
24111 'replayStartTime': this.replayStartTime,
24112 'batchStartUrl': this.batchStartUrl,
24113 'replayStartUrl': this.replayStartUrl,
24114 'idleExpires': this.idleExpires,
24115 'maxExpires': this.maxExpires,
24116 'tabId': tabId,
24117 };
24118 };
24119
24120
24121 /**
24122 * @static
24123 * @param {SerializedRecording} serializedRecording
24124 * @param {SessionRecordingOptions} options
24125 * @returns {SessionRecording}
24126 */
24127 SessionRecording.deserialize = function (serializedRecording, options) {
24128 var recording = new SessionRecording(_.extend({}, options, {
24129 replayId: serializedRecording['replayId'],
24130 batchStartUrl: serializedRecording['batchStartUrl'],
24131 replayStartUrl: serializedRecording['replayStartUrl'],
24132 idleExpires: serializedRecording['idleExpires'],
24133 maxExpires: serializedRecording['maxExpires'],
24134 replayStartTime: serializedRecording['replayStartTime'],
24135 seqNo: serializedRecording['seqNo'],
24136 sharedLockStorage: options.sharedLockStorage,
24137 }));
24138
24139 return recording;
24140 };
24141
24142 SessionRecording.prototype._sendRequest = function(currentReplayId, reqParams, reqBody, callback) {
24143 var onSuccess = function (response, responseBody) {
24144 // Update batch specific props only if the request was successful to guarantee ordering.
24145 // RequestBatcher will always flush the next batch after the previous one succeeds.
24146 // extra check to see if the replay ID has changed so that we don't increment the seqNo on the wrong replay
24147 if (response.status === 200 && this.replayId === currentReplayId) {
24148 this.seqNo++;
24149 this.batchStartUrl = _.info.currentUrl();
24150 }
24151
24152 this._onBatchSent();
24153 callback({
24154 status: 0,
24155 httpStatusCode: response.status,
24156 responseBody: responseBody,
24157 retryAfter: response.headers.get('Retry-After')
24158 });
24159 }.bind(this);
24160 var apiHost = (this._mixpanel.get_api_host && this._mixpanel.get_api_host('record')) || this.getConfig('api_host');
24161 win['fetch'](apiHost + '/' + this.getConfig('api_routes')['record'] + '?' + new URLSearchParams(reqParams), {
24162 'method': 'POST',
24163 'headers': {
24164 'Authorization': 'Basic ' + btoa(this.getConfig('token') + ':'),
24165 'Content-Type': 'application/octet-stream'
24166 },
24167 'body': reqBody,
24168 }).then(function (response) {
24169 response.json().then(function (responseBody) {
24170 onSuccess(response, responseBody);
24171 }).catch(function (error) {
24172 callback({error: error});
24173 });
24174 }).catch(function (error) {
24175 callback({error: error, httpStatusCode: 0});
24176 });
24177 };
24178
24179 SessionRecording.prototype._flushEvents = addOptOutCheckMixpanelLib(function (data, options, callback) {
24180 var numEvents = data.length;
24181
24182 if (numEvents > 0) {
24183 var replayId = this.replayId;
24184
24185 // each rrweb event has a timestamp - leverage those to get time properties
24186 var batchStartTime = Infinity;
24187 var batchEndTime = -Infinity;
24188 var hasFullSnapshot = false;
24189 for (var i = 0; i < numEvents; i++) {
24190 batchStartTime = Math.min(batchStartTime, data[i].timestamp);
24191 batchEndTime = Math.max(batchEndTime, data[i].timestamp);
24192 if (data[i].type === EventType.FullSnapshot) {
24193 hasFullSnapshot = true;
24194 }
24195 }
24196
24197 if (this.seqNo === 0) {
24198 if (!hasFullSnapshot) {
24199 callback({error: 'First batch does not contain a full snapshot. Aborting recording.'});
24200 this.stopRecording(true);
24201 return;
24202 }
24203 this.replayStartTime = batchStartTime;
24204 } else if (!this.replayStartTime) {
24205 this.reportError('Replay start time not set but seqNo is not 0. Using current batch start time as a fallback.');
24206 this.replayStartTime = batchStartTime;
24207 }
24208
24209 var replayLengthMs = batchEndTime - this.replayStartTime;
24210
24211 var reqParams = {
24212 '$current_url': this.batchStartUrl,
24213 '$lib_version': Config.LIB_VERSION,
24214 'batch_start_time': batchStartTime / 1000,
24215 'mp_lib': 'web',
24216 'replay_id': replayId,
24217 'replay_length_ms': replayLengthMs,
24218 'replay_start_time': this.replayStartTime / 1000,
24219 'replay_start_url': this.replayStartUrl,
24220 'seq': this.seqNo
24221 };
24222 var eventsJson = JSON.stringify(data);
24223 Object.assign(reqParams, this.getUserIdInfo());
24224
24225 if (CompressionStream) {
24226 var jsonStream = new Blob([eventsJson], {type: 'application/json'}).stream();
24227 var gzipStream = jsonStream.pipeThrough(new CompressionStream('gzip'));
24228 new Response(gzipStream)
24229 .blob()
24230 .then(function(compressedBlob) {
24231 reqParams['format'] = 'gzip';
24232 this._sendRequest(replayId, reqParams, compressedBlob, callback);
24233 }.bind(this));
24234 } else {
24235 reqParams['format'] = 'body';
24236 this._sendRequest(replayId, reqParams, eventsJson, callback);
24237 }
24238 }
24239 });
24240
24241
24242 SessionRecording.prototype.reportError = function(msg, err) {
24243 logger$3.error.apply(logger$3.error, arguments);
24244 try {
24245 if (!err && !(msg instanceof Error)) {
24246 msg = new Error(msg);
24247 }
24248 this.getConfig('error_reporter')(msg, err);
24249 } catch(err) {
24250 logger$3.error(err);
24251 }
24252 };
24253
24254 /**
24255 * Module for handling the storage and retrieval of recording metadata as well as any active recordings.
24256 * Makes sure that only one tab can be recording at a time.
24257 */
24258 var RecordingRegistry = function (options) {
24259 /** @type {IDBStorageWrapper} */
24260 this.idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
24261 this.errorReporter = options.errorReporter;
24262 this.mixpanelInstance = options.mixpanelInstance;
24263 this.sharedLockStorage = options.sharedLockStorage;
24264 };
24265
24266 RecordingRegistry.prototype.isPersistenceEnabled = function() {
24267 return !this.mixpanelInstance.get_config('disable_persistence');
24268 };
24269
24270 RecordingRegistry.prototype.handleError = function (err) {
24271 this.errorReporter('IndexedDB error: ', err);
24272 };
24273
24274 /**
24275 * @param {import('./session-recording').SerializedRecording} serializedRecording
24276 */
24277 RecordingRegistry.prototype.setActiveRecording = function (serializedRecording) {
24278 if (!this.isPersistenceEnabled()) {
24279 return PromisePolyfill.resolve();
24280 }
24281
24282 var tabId = serializedRecording['tabId'];
24283 if (!tabId) {
24284 console.warn('No tab ID is set, cannot persist recording metadata.');
24285 return PromisePolyfill.resolve();
24286 }
24287
24288 return this.idb.init()
24289 .then(function () {
24290 return this.idb.setItem(tabId, serializedRecording);
24291 }.bind(this))
24292 .catch(this.handleError.bind(this));
24293 };
24294
24295 /**
24296 * @returns {Promise<import('./session-recording').SerializedRecording>}
24297 */
24298 RecordingRegistry.prototype.getActiveRecording = function () {
24299 if (!this.isPersistenceEnabled()) {
24300 return PromisePolyfill.resolve(null);
24301 }
24302
24303 return this.idb.init()
24304 .then(function () {
24305 return this.idb.getItem(this.mixpanelInstance.get_tab_id());
24306 }.bind(this))
24307 .then(function (serializedRecording) {
24308 return isRecordingExpired(serializedRecording) ? null : serializedRecording;
24309 }.bind(this))
24310 .catch(this.handleError.bind(this));
24311 };
24312
24313 RecordingRegistry.prototype.clearActiveRecording = function () {
24314 if (this.isPersistenceEnabled()) {
24315 // mark recording as expired instead of deleting it in case the page unloads mid-flush and doesn't make it to ingestion.
24316 // this will ensure the next pageload will flush the remaining events, but not try to continue the recording.
24317 return this.markActiveRecordingExpired();
24318 } else {
24319 return this.deleteActiveRecording();
24320 }
24321 };
24322
24323 RecordingRegistry.prototype.markActiveRecordingExpired = function () {
24324 return this.getActiveRecording()
24325 .then(function (serializedRecording) {
24326 if (serializedRecording) {
24327 serializedRecording['maxExpires'] = 0;
24328 return this.setActiveRecording(serializedRecording);
24329 }
24330 }.bind(this))
24331 .catch(this.handleError.bind(this));
24332 };
24333
24334 RecordingRegistry.prototype.deleteActiveRecording = function () {
24335 // avoid initializing IDB if this registry instance hasn't already written a recording
24336 if (this.idb.isInitialized()) {
24337 return this.idb.removeItem(this.mixpanelInstance.get_tab_id())
24338 .catch(this.handleError.bind(this));
24339 } else {
24340 return PromisePolyfill.resolve();
24341 }
24342 };
24343
24344 /**
24345 * Flush any inactive recordings from the registry to minimize data loss.
24346 * The main idea here is that we can flush remaining rrweb events on the next page load if a tab is closed mid-batch.
24347 */
24348 RecordingRegistry.prototype.flushInactiveRecordings = function () {
24349 if (!this.isPersistenceEnabled()) {
24350 return PromisePolyfill.resolve([]);
24351 }
24352
24353 return this.idb.init()
24354 .then(function() {
24355 return this.idb.getAll();
24356 }.bind(this))
24357 .then(function (serializedRecordings) {
24358 // clean up any expired recordings from the registry, non-expired ones may be active in other tabs
24359 var unloadPromises = serializedRecordings
24360 .filter(function (serializedRecording) {
24361 return isRecordingExpired(serializedRecording);
24362 })
24363 .map(function (serializedRecording) {
24364 var sessionRecording = SessionRecording.deserialize(serializedRecording, {
24365 mixpanelInstance: this.mixpanelInstance,
24366 sharedLockStorage: this.sharedLockStorage
24367 });
24368 return sessionRecording.unloadPersistedData()
24369 .then(function () {
24370 // expired recording was successfully flushed, we can clean it up from the registry
24371 return this.idb.removeItem(serializedRecording['tabId']);
24372 }.bind(this))
24373 .catch(this.handleError.bind(this));
24374 }.bind(this));
24375
24376 return PromisePolyfill.all(unloadPromises);
24377 }.bind(this))
24378 .catch(this.handleError.bind(this));
24379 };
24380
24381 var logger$2 = console_with_prefix('recorder');
24382
24383 /**
24384 * Recorder API: bundles rrweb and and exposes methods to start and stop recordings.
24385 * @param {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
24386 */
24387 var MixpanelRecorder = function(mixpanelInstance, rrwebRecord, sharedLockStorage) {
24388 this.mixpanelInstance = mixpanelInstance;
24389 this.rrwebRecord = rrwebRecord || record;
24390 this.sharedLockStorage = sharedLockStorage;
24391
24392 /**
24393 * @member {import('./registry').RecordingRegistry}
24394 */
24395 this.recordingRegistry = new RecordingRegistry({
24396 mixpanelInstance: this.mixpanelInstance,
24397 errorReporter: logger$2.error,
24398 sharedLockStorage: sharedLockStorage
24399 });
24400 this._flushInactivePromise = this.recordingRegistry.flushInactiveRecordings();
24401
24402 this.activeRecording = null;
24403 this.stopRecordingInProgress = false;
24404 };
24405
24406 MixpanelRecorder.prototype.startRecording = function(options) {
24407 options = options || {};
24408 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
24409 logger$2.log('Recording already in progress, skipping startRecording.');
24410 return;
24411 }
24412
24413 var onIdleTimeout = function () {
24414 logger$2.log('Idle timeout reached, restarting recording.');
24415 this.resetRecording();
24416 }.bind(this);
24417
24418 var onMaxLengthReached = function () {
24419 logger$2.log('Max recording length reached, stopping recording.');
24420 this.resetRecording();
24421 }.bind(this);
24422
24423 var onBatchSent = function () {
24424 this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
24425 this['__flushPromise'] = this.activeRecording.batcher._flushPromise;
24426 }.bind(this);
24427
24428 /**
24429 * @type {import('./session-recording').SessionRecordingOptions}
24430 */
24431 var sessionRecordingOptions = {
24432 mixpanelInstance: this.mixpanelInstance,
24433 onBatchSent: onBatchSent,
24434 onIdleTimeout: onIdleTimeout,
24435 onMaxLengthReached: onMaxLengthReached,
24436 replayId: _.UUID(),
24437 rrwebRecord: this.rrwebRecord,
24438 sharedLockStorage: this.sharedLockStorage
24439 };
24440
24441 if (options.activeSerializedRecording) {
24442 this.activeRecording = SessionRecording.deserialize(options.activeSerializedRecording, sessionRecordingOptions);
24443 } else {
24444 this.activeRecording = new SessionRecording(sessionRecordingOptions);
24445 }
24446
24447 this.activeRecording.startRecording(options.shouldStopBatcher);
24448 return this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
24449 };
24450
24451 MixpanelRecorder.prototype.stopRecording = function() {
24452 // Prevents activeSerializedRecording from being reused when stopping the recording.
24453 this.stopRecordingInProgress = true;
24454 return this._stopCurrentRecording(false, true).then(function() {
24455 return this.recordingRegistry.clearActiveRecording();
24456 }.bind(this)).then(function() {
24457 this.stopRecordingInProgress = false;
24458 }.bind(this));
24459 };
24460
24461 MixpanelRecorder.prototype.pauseRecording = function() {
24462 return this._stopCurrentRecording(false);
24463 };
24464
24465 MixpanelRecorder.prototype._stopCurrentRecording = function(skipFlush, disableActiveRecording) {
24466 if (this.activeRecording) {
24467 var stopRecordingPromise = this.activeRecording.stopRecording(skipFlush);
24468 if (disableActiveRecording) {
24469 this.activeRecording = null;
24470 }
24471 return stopRecordingPromise;
24472 }
24473 return PromisePolyfill.resolve();
24474 };
24475
24476 MixpanelRecorder.prototype.resumeRecording = function (startNewIfInactive) {
24477 if (this.activeRecording && this.activeRecording.isRrwebStopped()) {
24478 this.activeRecording.startRecording(false);
24479 return PromisePolyfill.resolve(null);
24480 }
24481
24482 return this.recordingRegistry.getActiveRecording()
24483 .then(function (activeSerializedRecording) {
24484 if (activeSerializedRecording && !this.stopRecordingInProgress) {
24485 return this.startRecording({activeSerializedRecording: activeSerializedRecording});
24486 } else if (startNewIfInactive) {
24487 return this.startRecording({shouldStopBatcher: false});
24488 } else {
24489 logger$2.log('No resumable recording found.');
24490 return null;
24491 }
24492 }.bind(this));
24493 };
24494
24495
24496 MixpanelRecorder.prototype.resetRecording = function () {
24497 this.stopRecording();
24498 this.startRecording({shouldStopBatcher: true});
24499 };
24500
24501 MixpanelRecorder.prototype.getActiveReplayId = function () {
24502 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
24503 return this.activeRecording.replayId;
24504 } else {
24505 return null;
24506 }
24507 };
24508
24509 // getter so that older mixpanel-core versions can still retrieve the replay ID
24510 // when pulling the latest recorder bundle from the CDN
24511 Object.defineProperty(MixpanelRecorder.prototype, 'replayId', {
24512 get: function () {
24513 return this.getActiveReplayId();
24514 }
24515 });
24516
24517 win['__mp_recorder'] = MixpanelRecorder;
24518
24519 // stateless utils
24520 // mostly from https://github.com/mixpanel/mixpanel-js/blob/989ada50f518edab47b9c4fd9535f9fbd5ec5fc0/src/autotrack-utils.js
24521
24522
24523 var EV_CHANGE = 'change';
24524 var EV_CLICK = 'click';
24525 var EV_HASHCHANGE = 'hashchange';
24526 var EV_INPUT = 'input';
24527 var EV_LOAD = 'load';
24528 var EV_MP_LOCATION_CHANGE = 'mp_locationchange';
24529 var EV_POPSTATE = 'popstate';
24530 // TODO scrollend isn't available in Safari: document or polyfill?
24531 var EV_SCROLLEND = 'scrollend';
24532 var EV_SCROLL = 'scroll';
24533 var EV_SELECT = 'select';
24534 var EV_SUBMIT = 'submit';
24535 var EV_TOGGLE = 'toggle';
24536 var EV_VISIBILITYCHANGE = 'visibilitychange';
24537
24538 var CLICK_EVENT_PROPS = [
24539 'clientX', 'clientY',
24540 'offsetX', 'offsetY',
24541 'pageX', 'pageY',
24542 'screenX', 'screenY',
24543 'x', 'y'
24544 ];
24545 var OPT_IN_CLASSES = ['mp-include'];
24546 var OPT_OUT_CLASSES = ['mp-no-track'];
24547 var SENSITIVE_DATA_CLASSES = OPT_OUT_CLASSES.concat(['mp-sensitive']);
24548 var TRACKED_ATTRS = [
24549 'aria-label', 'aria-labelledby', 'aria-describedby',
24550 'href', 'name', 'role', 'title', 'type'
24551 ];
24552
24553 var INTERACTIVE_ARIA_ROLES = {
24554 'button': true,
24555 'checkbox': true,
24556 'combobox': true,
24557 'grid': true,
24558 'link': true,
24559 'listbox': true,
24560 'menu': true,
24561 'menubar': true,
24562 'menuitem': true,
24563 'menuitemcheckbox': true,
24564 'menuitemradio': true,
24565 'navigation': true,
24566 'option': true,
24567 'radio': true,
24568 'radiogroup': true,
24569 'searchbox': true,
24570 'slider': true,
24571 'spinbutton': true,
24572 'switch': true,
24573 'tab': true,
24574 'tablist': true,
24575 'textbox': true,
24576 'tree': true,
24577 'treegrid': true,
24578 'treeitem': true
24579 };
24580
24581 var ALWAYS_NON_INTERACTIVE_TAGS = {
24582 // Document metadata
24583 'base': true,
24584 'head': true,
24585 'html': true,
24586 'link': true,
24587 'meta': true,
24588 'script': true,
24589 'style': true,
24590 'title': true,
24591 // Text formatting
24592 'br': true,
24593 'hr': true,
24594 'wbr': true,
24595 // Other
24596 'noscript': true,
24597 'picture': true,
24598 'source': true,
24599 'template': true,
24600 'track': true
24601 };
24602
24603 // Common container tags that need additional checks
24604 var TEXT_CONTAINER_TAGS = {
24605 'article': true,
24606 'div': true,
24607 'h1': true,
24608 'h2': true,
24609 'h3': true,
24610 'h4': true,
24611 'h5': true,
24612 'h6': true,
24613 'p': true,
24614 'section': true,
24615 'span': true
24616 };
24617
24618 var EVENT_HANDLER_ATTRIBUTES = [
24619 'onclick', 'onmousedown', 'onmouseup', 'onpointerdown', 'onpointerup', 'ontouchend', 'ontouchstart'
24620 ];
24621
24622 var MAX_DEPTH = 5;
24623
24624 var logger$1 = console_with_prefix('autocapture');
24625
24626
24627 function getClasses(el) {
24628 var classes = {};
24629 var classList = getClassName(el).split(' ');
24630 for (var i = 0; i < classList.length; i++) {
24631 var cls = classList[i];
24632 if (cls) {
24633 classes[cls] = true;
24634 }
24635 }
24636 return classes;
24637 }
24638
24639 /*
24640 * Get the className of an element, accounting for edge cases where element.className is an object
24641 * @param {Element} el - element to get the className of
24642 * @returns {string} the element's class
24643 */
24644 function getClassName(el) {
24645 switch(typeof el.className) {
24646 case 'string':
24647 return el.className;
24648 case 'object': // handle cases where className might be SVGAnimatedString or some other type
24649 return el.className.baseVal || el.getAttribute('class') || '';
24650 default: // future proof
24651 return '';
24652 }
24653 }
24654
24655 function getPreviousElementSibling(el) {
24656 if (el.previousElementSibling) {
24657 return el.previousElementSibling;
24658 } else {
24659 do {
24660 el = el.previousSibling;
24661 } while (el && !isElementNode(el));
24662 return el;
24663 }
24664 }
24665
24666 function getPropertiesFromElement(el, ev, blockAttrsSet, extraAttrs, allowElementCallback, allowSelectors) {
24667 var props = {
24668 '$classes': getClassName(el).split(' '),
24669 '$tag_name': el.tagName.toLowerCase()
24670 };
24671 var elId = el.id;
24672 if (elId) {
24673 props['$id'] = elId;
24674 }
24675
24676 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors)) {
24677 _.each(TRACKED_ATTRS.concat(extraAttrs), function(attr) {
24678 if (el.hasAttribute(attr) && !blockAttrsSet[attr]) {
24679 var attrVal = el.getAttribute(attr);
24680 if (shouldTrackValue(attrVal)) {
24681 props['$attr-' + attr] = attrVal;
24682 }
24683 }
24684 });
24685 }
24686
24687 var nthChild = 1;
24688 var nthOfType = 1;
24689 var currentElem = el;
24690 while (currentElem = getPreviousElementSibling(currentElem)) { // eslint-disable-line no-cond-assign
24691 nthChild++;
24692 if (currentElem.tagName === el.tagName) {
24693 nthOfType++;
24694 }
24695 }
24696 props['$nth_child'] = nthChild;
24697 props['$nth_of_type'] = nthOfType;
24698
24699 return props;
24700 }
24701
24702 function getPropsForDOMEvent(ev, config) {
24703 var allowElementCallback = config.allowElementCallback;
24704 var allowSelectors = config.allowSelectors || [];
24705 var blockAttrs = config.blockAttrs || [];
24706 var blockElementCallback = config.blockElementCallback;
24707 var blockSelectors = config.blockSelectors || [];
24708 var captureTextContent = config.captureTextContent || false;
24709 var captureExtraAttrs = config.captureExtraAttrs || [];
24710 var capturedForHeatMap = config.capturedForHeatMap || false;
24711
24712 // convert array to set every time, as the config may have changed
24713 var blockAttrsSet = {};
24714 _.each(blockAttrs, function(attr) {
24715 blockAttrsSet[attr] = true;
24716 });
24717
24718 var props = null;
24719
24720 var target = typeof ev.target === 'undefined' ? ev.srcElement : ev.target;
24721 if (isTextNode(target)) { // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
24722 target = target.parentNode;
24723 }
24724
24725 if (
24726 shouldTrackDomEvent(target, ev) &&
24727 isElementAllowed(target, ev, allowElementCallback, allowSelectors) &&
24728 !isElementBlocked(target, ev, blockElementCallback, blockSelectors)
24729 ) {
24730 var targetElementList = [target];
24731 var curEl = target;
24732 while (curEl.parentNode && !isTag(curEl, 'body')) {
24733 targetElementList.push(curEl.parentNode);
24734 curEl = curEl.parentNode;
24735 }
24736
24737 var elementsJson = [];
24738 var href, explicitNoTrack = false;
24739 _.each(targetElementList, function(el) {
24740 var shouldTrackDetails = shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors);
24741
24742 // if the element or a parent element is an anchor tag
24743 // include the href as a property
24744 if (!blockAttrsSet['href'] && el.tagName.toLowerCase() === 'a') {
24745 href = el.getAttribute('href');
24746 href = shouldTrackDetails && shouldTrackValue(href) && href;
24747 }
24748
24749 if (isElementBlocked(el, ev, blockElementCallback, blockSelectors)) {
24750 explicitNoTrack = true;
24751 }
24752
24753 elementsJson.push(getPropertiesFromElement(el, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors));
24754 }, this);
24755
24756 if (!explicitNoTrack) {
24757 var docElement = document$1['documentElement'];
24758 props = {
24759 '$event_type': ev.type,
24760 '$host': win.location.host,
24761 '$pathname': win.location.pathname,
24762 '$elements': elementsJson,
24763 '$el_attr__href': href,
24764 '$viewportHeight': Math.max(docElement['clientHeight'], win['innerHeight'] || 0),
24765 '$viewportWidth': Math.max(docElement['clientWidth'], win['innerWidth'] || 0),
24766 '$pageHeight': document$1['body']['offsetHeight'] || 0,
24767 '$pageWidth': document$1['body']['offsetWidth'] || 0,
24768 };
24769 _.each(captureExtraAttrs, function(attr) {
24770 if (!blockAttrsSet[attr] && target.hasAttribute(attr)) {
24771 var attrVal = target.getAttribute(attr);
24772 if (shouldTrackValue(attrVal)) {
24773 props['$el_attr__' + attr] = attrVal;
24774 }
24775 }
24776 });
24777
24778 if (captureTextContent) {
24779 elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
24780 if (elementText && elementText.length) {
24781 props['$el_text'] = elementText;
24782 }
24783 }
24784
24785 if (ev.type === EV_CLICK) {
24786 _.each(CLICK_EVENT_PROPS, function(prop) {
24787 if (prop in ev) {
24788 props['$' + prop] = ev[prop];
24789 }
24790 });
24791 if (capturedForHeatMap) {
24792 props['$captured_for_heatmap'] = true;
24793 }
24794 target = guessRealClickTarget(ev);
24795 }
24796 // prioritize text content from "real" click target if different from original target
24797 if (captureTextContent) {
24798 var elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
24799 if (elementText && elementText.length) {
24800 props['$el_text'] = elementText;
24801 }
24802 }
24803
24804 if (target) {
24805 // target may have been recalculated; check allowlists and blocklists again
24806 if (
24807 !isElementAllowed(target, ev, allowElementCallback, allowSelectors) ||
24808 isElementBlocked(target, ev, blockElementCallback, blockSelectors)
24809 ) {
24810 return null;
24811 }
24812
24813 var targetProps = getPropertiesFromElement(target, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors);
24814 props['$target'] = targetProps;
24815 // pull up more props onto main event props
24816 props['$el_classes'] = targetProps['$classes'];
24817 _.extend(props, _.strip_empty_properties({
24818 '$el_id': targetProps['$id'],
24819 '$el_tag_name': targetProps['$tag_name']
24820 }));
24821 }
24822 }
24823 }
24824
24825 return props;
24826 }
24827
24828
24829 /**
24830 * Get the direct text content of an element, protecting against sensitive data collection.
24831 * Concats textContent of each of the element's text node children; this avoids potential
24832 * collection of sensitive data that could happen if we used element.textContent and the
24833 * element had sensitive child elements, since element.textContent includes child content.
24834 * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
24835 * @param {Element} el - element to get the text of
24836 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
24837 * @returns {string} the element's direct text content
24838 */
24839 function getSafeText(el, ev, allowElementCallback, allowSelectors) {
24840 var elText = '';
24841
24842 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) && el.childNodes && el.childNodes.length) {
24843 _.each(el.childNodes, function(child) {
24844 if (isTextNode(child) && child.textContent) {
24845 elText += _.trim(child.textContent)
24846 // scrub potentially sensitive values
24847 .split(/(\s+)/).filter(shouldTrackValue).join('')
24848 // normalize whitespace
24849 .replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ')
24850 // truncate
24851 .substring(0, 255);
24852 }
24853 });
24854 }
24855
24856 return _.trim(elText);
24857 }
24858
24859 function guessRealClickTarget(ev) {
24860 var target = ev.target;
24861 var composedPath = ev['composedPath']();
24862 for (var i = 0; i < composedPath.length; i++) {
24863 var node = composedPath[i];
24864 if (
24865 isTag(node, 'a') ||
24866 isTag(node, 'button') ||
24867 isTag(node, 'input') ||
24868 isTag(node, 'select') ||
24869 (node.getAttribute && node.getAttribute('role') === 'button')
24870 ) {
24871 target = node;
24872 break;
24873 }
24874 if (node === target) {
24875 break;
24876 }
24877 }
24878 return target;
24879 }
24880
24881 function isElementAllowed(el, ev, allowElementCallback, allowSelectors) {
24882 if (allowElementCallback) {
24883 try {
24884 if (!allowElementCallback(el, ev)) {
24885 return false;
24886 }
24887 } catch (err) {
24888 logger$1.critical('Error while checking element in allowElementCallback', err);
24889 return false;
24890 }
24891 }
24892
24893 if (!allowSelectors.length) {
24894 // no allowlist; all elements are fair game
24895 return true;
24896 }
24897
24898 for (var i = 0; i < allowSelectors.length; i++) {
24899 var sel = allowSelectors[i];
24900 try {
24901 if (el['matches'](sel)) {
24902 return true;
24903 }
24904 } catch (err) {
24905 logger$1.critical('Error while checking selector: ' + sel, err);
24906 }
24907 }
24908 return false;
24909 }
24910
24911 function isElementBlocked(el, ev, blockElementCallback, blockSelectors) {
24912 var i;
24913
24914 if (blockElementCallback) {
24915 try {
24916 if (blockElementCallback(el, ev)) {
24917 return true;
24918 }
24919 } catch (err) {
24920 logger$1.critical('Error while checking element in blockElementCallback', err);
24921 return true;
24922 }
24923 }
24924
24925 if (blockSelectors && blockSelectors.length) {
24926 // programmatically prevent tracking of elements that match CSS selectors
24927 for (i = 0; i < blockSelectors.length; i++) {
24928 var sel = blockSelectors[i];
24929 try {
24930 if (el['matches'](sel)) {
24931 return true;
24932 }
24933 } catch (err) {
24934 logger$1.critical('Error while checking selector: ' + sel, err);
24935 }
24936 }
24937 }
24938
24939 // allow users to programmatically prevent tracking of elements by adding default classes such as 'mp-no-track'
24940 var classes = getClasses(el);
24941 for (i = 0; i < OPT_OUT_CLASSES.length; i++) {
24942 if (classes[OPT_OUT_CLASSES[i]]) {
24943 return true;
24944 }
24945 }
24946
24947 return false;
24948 }
24949
24950 /*
24951 * Check whether a DOM node has nodeType Node.ELEMENT_NODE
24952 * @param {Node} node - node to check
24953 * @returns {boolean} whether node is of the correct nodeType
24954 */
24955 function isElementNode(node) {
24956 return node && node.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
24957 }
24958
24959 /*
24960 * Check whether an element is of a given tag type.
24961 * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
24962 * we want to match tagNames instead of specific references because something like
24963 * element === document.body won't always work because element might not be a native
24964 * element.
24965 * @param {Element} el - element to check
24966 * @param {string} tag - tag name (e.g., "div")
24967 * @returns {boolean} whether el is of the given tag type
24968 */
24969 function isTag(el, tag) {
24970 return el && el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
24971 }
24972
24973 /*
24974 * Check whether a DOM node is a TEXT_NODE
24975 * @param {Node} node - node to check
24976 * @returns {boolean} whether node is of type Node.TEXT_NODE
24977 */
24978 function isTextNode(node) {
24979 return node && node.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
24980 }
24981
24982 function minDOMApisSupported() {
24983 try {
24984 var testEl = document$1.createElement('div');
24985 return !!testEl['matches'];
24986 } catch (err) {
24987 return false;
24988 }
24989 }
24990
24991 function weakSetSupported() {
24992 return typeof WeakSet !== 'undefined';
24993 }
24994
24995 /*
24996 * Check whether a DOM event should be "tracked" or if it may contain sensitive data
24997 * using a variety of heuristics.
24998 * @param {Element} el - element to check
24999 * @param {Event} ev - event to check
25000 * @returns {boolean} whether the event should be tracked
25001 */
25002 function shouldTrackDomEvent(el, ev) {
25003 if (!el || isTag(el, 'html') || !isElementNode(el)) {
25004 return false;
25005 }
25006 var tag = el.tagName.toLowerCase();
25007 switch (tag) {
25008 case 'form':
25009 return ev.type === EV_SUBMIT;
25010 case 'input':
25011 if (['button', 'submit'].indexOf(el.getAttribute('type')) === -1) {
25012 return ev.type === EV_CHANGE;
25013 } else {
25014 return ev.type === EV_CLICK;
25015 }
25016 case 'select':
25017 case 'textarea':
25018 return ev.type === EV_CHANGE;
25019 default:
25020 return ev.type === EV_CLICK;
25021 }
25022 }
25023
25024 /*
25025 * Check whether a DOM element should be "tracked" or if it may contain sensitive data
25026 * using a variety of heuristics.
25027 * @param {Element} el - element to check
25028 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
25029 * @returns {boolean} whether the element should be tracked
25030 */
25031 function shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) {
25032 var i;
25033
25034 if (!isElementAllowed(el, ev, allowElementCallback, allowSelectors)) {
25035 return false;
25036 }
25037
25038 for (var curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
25039 var classes = getClasses(curEl);
25040 for (i = 0; i < SENSITIVE_DATA_CLASSES.length; i++) {
25041 if (classes[SENSITIVE_DATA_CLASSES[i]]) {
25042 return false;
25043 }
25044 }
25045 }
25046
25047 var elClasses = getClasses(el);
25048 for (i = 0; i < OPT_IN_CLASSES.length; i++) {
25049 if (elClasses[OPT_IN_CLASSES[i]]) {
25050 return true;
25051 }
25052 }
25053
25054 // don't send data from inputs or similar elements since there will always be
25055 // a risk of clientside javascript placing sensitive data in attributes
25056 if (
25057 isTag(el, 'input') ||
25058 isTag(el, 'select') ||
25059 isTag(el, 'textarea') ||
25060 el.getAttribute('contenteditable') === 'true'
25061 ) {
25062 return false;
25063 }
25064
25065 // don't include hidden or password fields
25066 var type = el.type || '';
25067 if (typeof type === 'string') { // it's possible for el.type to be a DOM element if el is a form with a child input[name="type"]
25068 switch(type.toLowerCase()) {
25069 case 'hidden':
25070 return false;
25071 case 'password':
25072 return false;
25073 }
25074 }
25075
25076 // filter out data from fields that look like sensitive fields
25077 var name = el.name || el.id || '';
25078 if (typeof name === 'string') { // it's possible for el.name or el.id to be a DOM element if el is a form with a child input[name="name"]
25079 var sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
25080 if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
25081 return false;
25082 }
25083 }
25084
25085 return true;
25086 }
25087
25088
25089 /*
25090 * Check whether a string value should be "tracked" or if it may contain sensitive data
25091 * using a variety of heuristics.
25092 * @param {string} value - string value to check
25093 * @returns {boolean} whether the element should be tracked
25094 */
25095 function shouldTrackValue(value) {
25096 if (value === null || _.isUndefined(value)) {
25097 return false;
25098 }
25099
25100 if (typeof value === 'string') {
25101 value = _.trim(value);
25102
25103 // check to see if input value looks like a credit card number
25104 // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
25105 var ccRegex = /^(?:(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}))$/;
25106 if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
25107 return false;
25108 }
25109
25110 // check to see if input value looks like a social security number
25111 var ssnRegex = /(^\d{3}-?\d{2}-?\d{4}$)/;
25112 if (ssnRegex.test(value)) {
25113 return false;
25114 }
25115 }
25116
25117 return true;
25118 }
25119
25120 /**
25121 * Creates a cross-browser compatible scroll end function with appropriate event listener.
25122 * For browsers that support scrollend, returns the original function with scrollend event.
25123 * For browsers without scrollend support, returns a debounced function that triggers
25124 * 100ms after the last scroll event to simulate scrollend behavior.
25125 * @param {Function} originalFunction - The function to call when scrolling ends
25126 * @returns {Object} Object containing listener function and eventType string
25127 * @returns {Function} returns.listener - The wrapped function to use as event listener
25128 * @returns {string} returns.eventType - The event type to listen for ('scrollend' or 'scroll')
25129 */
25130 function getPolyfillScrollEndFunction(originalFunction) {
25131 var supportsScrollEnd = 'onscrollend' in win;
25132 var polyfillFunction = safewrap(originalFunction);
25133 var polyfillEvent = EV_SCROLLEND;
25134 if (!supportsScrollEnd) {
25135 // Polyfill for browsers without scrollend support: wait 100ms after the last scroll event
25136 // https://developer.chrome.com/blog/scrollend-a-new-javascript-event
25137 var scrollTimer = null;
25138 var scrollDelayMs = 100;
25139
25140 polyfillFunction = safewrap(function() {
25141 clearTimeout(scrollTimer);
25142 scrollTimer = setTimeout(originalFunction, scrollDelayMs);
25143 });
25144
25145 polyfillEvent = EV_SCROLL;
25146 }
25147
25148 return {
25149 listener: polyfillFunction,
25150 eventType: polyfillEvent
25151 };
25152 }
25153
25154 function hasInlineEventHandlers(element) {
25155 for (var i = 0; i < EVENT_HANDLER_ATTRIBUTES.length; i++) {
25156 if (element.hasAttribute(EVENT_HANDLER_ATTRIBUTES[i])) {
25157 return true;
25158 }
25159 }
25160 return false;
25161 }
25162
25163 function hasInteractiveAriaRole(element) {
25164 var role = element.getAttribute('role');
25165 if (!role) return false;
25166
25167 // Handle invalid markup where multiple roles might be specified
25168 // Only the first token is recognized per ARIA spec
25169 var primaryRole = role.trim().split(/\s+/)[0].toLowerCase();
25170
25171 return INTERACTIVE_ARIA_ROLES[primaryRole];
25172 }
25173
25174 function hasAnyInteractivityIndicators(element) {
25175 var tagName = element.tagName.toLowerCase();
25176
25177 // Check for interactive HTML elements
25178 if (tagName === 'button' ||
25179 tagName === 'input' ||
25180 tagName === 'select' ||
25181 tagName === 'textarea' ||
25182 tagName === 'details' ||
25183 tagName === 'dialog') {
25184 return true;
25185 }
25186
25187 if (element.isContentEditable) {
25188 return true;
25189 }
25190
25191 if (element.onclick || element.onmousedown || element.onmouseup || element.ontouchstart || element.ontouchend) {
25192 return true;
25193 }
25194
25195 if (hasInlineEventHandlers(element)) {
25196 return true;
25197 }
25198
25199 if (hasInteractiveAriaRole(element)) {
25200 return true;
25201 }
25202
25203 if (tagName === 'a' && element.hasAttribute('href')) {
25204 return true;
25205 }
25206
25207 if (element.hasAttribute('tabindex')) {
25208 return true;
25209 }
25210
25211 return false;
25212 }
25213
25214
25215 function isDefinitelyNonInteractive(element) {
25216 if (!element || !element.tagName) {
25217 return true;
25218 }
25219
25220 var tagName = element.tagName.toLowerCase();
25221
25222 // These tags are definitely non-interactive
25223 if (ALWAYS_NON_INTERACTIVE_TAGS[tagName]) {
25224 return true;
25225 }
25226
25227 // For all other elements, we can only be certain they're non-interactive if they lack ALL indicators of interactivity
25228 // Check for any signs of interactivity
25229 if (hasAnyInteractivityIndicators(element)) {
25230 return false;
25231 }
25232
25233 // Check parent chain for interactive context
25234 var parent = element.parentElement;
25235 var depth = 0;
25236
25237 while (parent && depth < MAX_DEPTH) {
25238 if (hasAnyInteractivityIndicators(parent)) {
25239 return false; // Element is inside an interactive parent
25240 }
25241
25242 if (parent.getRootNode && parent.getRootNode() !== document$1) {
25243 var root = parent.getRootNode();
25244 if (root.host && hasAnyInteractivityIndicators(root.host)) {
25245 return false; // Inside an interactive shadow host
25246 }
25247 }
25248
25249 parent = parent.parentElement;
25250 depth++;
25251 }
25252
25253 // Pure text containers without any interactive context
25254 if (TEXT_CONTAINER_TAGS[tagName]) {
25255 // These are non-interactive ONLY if they have no interactive indicators (already checked as part of hasAnyInteractivityIndicators)
25256 return true;
25257 }
25258
25259 // Default: we can't be certain it's non-interactive
25260 return false;
25261 }
25262
25263 /** @const */ var DEFAULT_RAGE_CLICK_THRESHOLD_PX = 30;
25264 /** @const */ var DEFAULT_RAGE_CLICK_TIMEOUT_MS = 1000;
25265 /** @const */ var DEFAULT_RAGE_CLICK_CLICK_COUNT = 4;
25266
25267 function RageClickTracker() {
25268 this.clicks = [];
25269 }
25270
25271 RageClickTracker.prototype.isRageClick = function(x, y, options) {
25272 options = options || {};
25273 var thresholdPx = options['threshold_px'] || DEFAULT_RAGE_CLICK_THRESHOLD_PX;
25274 var timeoutMs = options['timeout_ms'] || DEFAULT_RAGE_CLICK_TIMEOUT_MS;
25275 var clickCount = options['click_count'] || DEFAULT_RAGE_CLICK_CLICK_COUNT;
25276 var timestamp = Date.now();
25277
25278 var lastClick = this.clicks[this.clicks.length - 1];
25279 if (
25280 lastClick &&
25281 timestamp - lastClick.timestamp < timeoutMs &&
25282 Math.sqrt(Math.pow(x - lastClick.x, 2) + Math.pow(y - lastClick.y, 2)) < thresholdPx
25283 ) {
25284 this.clicks.push({ x: x, y: y, timestamp: timestamp });
25285 if (this.clicks.length >= clickCount) {
25286 this.clicks = [];
25287 return true;
25288 }
25289 } else {
25290 this.clicks = [{ x: x, y: y, timestamp: timestamp }];
25291 }
25292 return false;
25293 };
25294
25295 function ShadowDOMObserver(changeCallback, observerConfig) {
25296 this.changeCallback = changeCallback || function() {};
25297 this.observerConfig = observerConfig;
25298
25299 this.observedShadowRoots = null;
25300 this.shadowObservers = [];
25301 }
25302
25303 ShadowDOMObserver.prototype.getEventTarget = function(event) {
25304 if (!this.observedShadowRoots) {
25305 return;
25306 }
25307 var path = this.getComposedPath(event);
25308 if (path && path.length) {
25309 return path[0];
25310 }
25311
25312 return event['target'] || event['srcElement'];
25313 };
25314
25315
25316 ShadowDOMObserver.prototype.getComposedPath = function(event) {
25317 if ('composedPath' in event) {
25318 return event['composedPath']();
25319 }
25320
25321 return [];
25322 };
25323 ShadowDOMObserver.prototype.observeFromEvent = function(event) {
25324 if (!this.observedShadowRoots) {
25325 return;
25326 }
25327
25328 var path = this.getComposedPath(event);
25329
25330 // Check each element in path for shadow roots
25331 for (var i = 0; i < path.length; i++) {
25332 var element = path[i];
25333
25334 if (element && element.shadowRoot) {
25335 this.observeShadowRoot(element.shadowRoot);
25336 }
25337 }
25338 };
25339
25340
25341 ShadowDOMObserver.prototype.observeShadowRoot = function(shadowRoot) {
25342 if (!this.observedShadowRoots || this.observedShadowRoots.has(shadowRoot)) {
25343 return;
25344 }
25345
25346 var self = this;
25347
25348 try {
25349 this.observedShadowRoots.add(shadowRoot);
25350
25351 var observer = new window.MutationObserver(function() {
25352 self.changeCallback();
25353 });
25354
25355 observer.observe(shadowRoot, this.observerConfig);
25356 this.shadowObservers.push(observer);
25357 } catch (e) {
25358 logger$1.critical('Error while observing shadow root', e);
25359 }
25360 };
25361
25362
25363 ShadowDOMObserver.prototype.start = function() {
25364 if (this.observedShadowRoots) {
25365 return;
25366 }
25367
25368 if (!weakSetSupported()) {
25369 logger$1.critical('Shadow DOM observation unavailable: WeakSet not supported');
25370 return;
25371 }
25372
25373 this.observedShadowRoots = new WeakSet();
25374 };
25375
25376 ShadowDOMObserver.prototype.stop = function() {
25377 if (!this.observedShadowRoots) {
25378 return;
25379 }
25380
25381 for (var i = 0; i < this.shadowObservers.length; i++) {
25382 try {
25383 this.shadowObservers[i].disconnect();
25384 } catch (e) {
25385 logger$1.critical('Error while disconnecting shadow DOM observer', e);
25386 }
25387 }
25388 this.shadowObservers = [];
25389 this.observedShadowRoots = null;
25390 };
25391
25392 /** @const */ var DEFAULT_DEAD_CLICK_TIMEOUT_MS = 500;
25393 /** @const */ var INTERACTION_EVENTS = [EV_CHANGE, EV_INPUT, EV_SUBMIT, EV_SELECT, EV_TOGGLE];
25394 /** @const */ var LAYOUT_EVENTS = [EV_SCROLLEND];
25395 /** @const */ var NAVIGATION_EVENTS = [EV_HASHCHANGE];
25396 /** @const */ var MUTATION_OBSERVER_CONFIG = {
25397 characterData: true,
25398 childList: true,
25399 subtree: true,
25400 attributes: true,
25401 attributeFilter: ['style', 'class', 'hidden', 'checked', 'selected', 'value', 'display', 'visibility']
25402 };
25403
25404
25405 function DeadClickTracker(onDeadClickCallback) {
25406 this.eventListeners = [];
25407 this.mutationObserver = null;
25408 this.shadowDOMObserver = null;
25409
25410 this.isTracking = false;
25411 this.lastChangeEventTimestamp = 0;
25412 this.pendingClicks = [];
25413 this.onDeadClickCallback = onDeadClickCallback;
25414 this.processingActive = false;
25415 this.processingTimeout = null;
25416 }
25417
25418
25419 DeadClickTracker.prototype.addClick = function(event) {
25420 var element = this.shadowDOMObserver && this.shadowDOMObserver.getEventTarget(event);
25421
25422 if (!element) {
25423 element = event['target'] || event['srcElement'];
25424 }
25425
25426 if (!element || isDefinitelyNonInteractive(element)) {
25427 return false;
25428 }
25429
25430 if (this.shadowDOMObserver) {
25431 this.shadowDOMObserver.observeFromEvent(event);
25432 }
25433 this.pendingClicks.push({
25434 element: element,
25435 event: event,
25436 timestamp: Date.now()
25437 });
25438 return true;
25439 };
25440
25441 DeadClickTracker.prototype.trackClick = function(event, config) {
25442 if (!this.isTracking) {
25443 return false;
25444 }
25445
25446 var added = this.addClick(event);
25447 if (added) {
25448 this.triggerProcessing(config);
25449 }
25450 return added;
25451 };
25452
25453 DeadClickTracker.prototype.getDeadClicks = function(config) {
25454 if (this.pendingClicks.length === 0) {
25455 return [];
25456 }
25457
25458 var timeoutMs = config['timeout_ms'];
25459 var now = Date.now();
25460 var clicksToEvaluate = this.pendingClicks.slice(); // Copy array
25461 this.pendingClicks = []; // Clear original
25462
25463 var deadClicks = [];
25464
25465 for (var i = 0; i < clicksToEvaluate.length; i++) {
25466 var click = clicksToEvaluate[i];
25467
25468 if (now - click.timestamp >= timeoutMs) {
25469 // Click has exceeded timeout, check if it's dead by looking for changes after this specific click
25470 if (!this.hasChangesAfter(click.timestamp)) {
25471 deadClicks.push(click);
25472 }
25473 } else {
25474 // Still pending - add back
25475 this.pendingClicks.push(click);
25476 }
25477 }
25478
25479 return deadClicks;
25480 };
25481
25482 DeadClickTracker.prototype.hasChangesAfter = function(timestamp) {
25483 // 100ms tolerance for race condition between when we record the click and the change event
25484 return this.lastChangeEventTimestamp >= (timestamp - 100);
25485 };
25486
25487 DeadClickTracker.prototype.recordChangeEvent = function() {
25488 this.lastChangeEventTimestamp = Date.now();
25489 };
25490
25491 DeadClickTracker.prototype.triggerProcessing = function(config) {
25492 // Prevent multiple concurrent processing chains
25493 if (this.processingActive) {
25494 return;
25495 }
25496 this.processingActive = true;
25497 this.processRecursively(config);
25498 };
25499
25500 DeadClickTracker.prototype.processRecursively = function(config) {
25501 if (!this.isTracking || !this.onDeadClickCallback) {
25502 this.processingActive = false;
25503 return;
25504 }
25505
25506 var timeoutMs = config['timeout_ms'];
25507 var self = this;
25508
25509 this.processingTimeout = setTimeout(function() {
25510 if (!self.processingActive) {
25511 return;
25512 }
25513
25514 var deadClicks = self.getDeadClicks(config);
25515
25516 for (var i = 0; i < deadClicks.length; i++) {
25517 self.onDeadClickCallback(deadClicks[i].event);
25518 }
25519
25520 if (self.pendingClicks.length > 0) {
25521 self.processRecursively(config);
25522 } else {
25523 self.processingActive = false;
25524 }
25525 }, timeoutMs);
25526 };
25527
25528 DeadClickTracker.prototype.startTracking = function() {
25529 if (this.isTracking) {
25530 return;
25531 }
25532
25533 this.isTracking = true;
25534
25535 var self = this;
25536
25537 INTERACTION_EVENTS.forEach(function(event) {
25538 var handler = function() {
25539 self.recordChangeEvent();
25540 };
25541 document.addEventListener(event, handler, { capture: true, passive: true });
25542 self.eventListeners.push({ target: document, event: event, handler: handler, options: { capture: true, passive: true } });
25543 });
25544 NAVIGATION_EVENTS.forEach(function(event) {
25545 var handler = function() {
25546 self.recordChangeEvent();
25547 };
25548 window.addEventListener(event, handler);
25549 self.eventListeners.push({ target: window, event: event, handler: handler });
25550 });
25551 LAYOUT_EVENTS.forEach(function(event) {
25552 var handler = function() {
25553 self.recordChangeEvent();
25554 };
25555 window.addEventListener(event, handler, { passive: true });
25556 self.eventListeners.push({ target: window, event: event, handler: handler, options: { passive: true } });
25557 });
25558 var selectionHandler = function() {
25559 self.recordChangeEvent();
25560 };
25561 document.addEventListener('selectionchange', selectionHandler);
25562 self.eventListeners.push({ target: document, event: 'selectionchange', handler: selectionHandler });
25563
25564 // Set up MutationObserver
25565 if (window.MutationObserver) {
25566 try {
25567 this.mutationObserver = new window.MutationObserver(function() {
25568 self.recordChangeEvent();
25569 });
25570
25571 this.mutationObserver.observe(document.body || document.documentElement, MUTATION_OBSERVER_CONFIG);
25572 } catch (e) {
25573 logger$1.critical('Error while setting up mutation observer', e);
25574 }
25575 }
25576
25577 // Set up Shadow DOM observer
25578 if (window.customElements) {
25579 try {
25580 this.shadowDOMObserver = new ShadowDOMObserver(
25581 function() {
25582 self.recordChangeEvent();
25583 },
25584 MUTATION_OBSERVER_CONFIG
25585 );
25586 this.shadowDOMObserver.start();
25587 } catch (e) {
25588 logger$1.critical('Error while setting up shadow DOM observer', e);
25589 this.shadowDOMObserver = null;
25590 }
25591 }
25592 };
25593
25594 DeadClickTracker.prototype.stopTracking = function() {
25595 if (!this.isTracking) {
25596 return;
25597 }
25598
25599 this.isTracking = false;
25600 this.pendingClicks = [];
25601 this.lastChangeEventTimestamp = 0;
25602 this.processingActive = false;
25603
25604 if (this.processingTimeout) {
25605 clearTimeout(this.processingTimeout);
25606 this.processingTimeout = null;
25607 }
25608
25609 // Remove all event listeners
25610 for (var i = 0; i < this.eventListeners.length; i++) {
25611 var listener = this.eventListeners[i];
25612 try {
25613 listener.target.removeEventListener(listener.event, listener.handler, listener.options);
25614 } catch (e) {
25615 logger$1.critical('Error while removing event listener', e);
25616 }
25617 }
25618 this.eventListeners = [];
25619
25620 if (this.mutationObserver) {
25621 try {
25622 this.mutationObserver.disconnect();
25623 } catch (e) {
25624 logger$1.critical('Error while disconnecting mutation observer', e);
25625 }
25626 this.mutationObserver = null;
25627 }
25628
25629 if (this.shadowDOMObserver) {
25630 try {
25631 this.shadowDOMObserver.stop();
25632 } catch (e) {
25633 logger$1.critical('Error while stopping shadow DOM observer', e);
25634 }
25635 this.shadowDOMObserver = null;
25636 }
25637 };
25638
25639 var AUTOCAPTURE_CONFIG_KEY = 'autocapture';
25640 var LEGACY_PAGEVIEW_CONFIG_KEY = 'track_pageview';
25641
25642 var PAGEVIEW_OPTION_FULL_URL = 'full-url';
25643 var PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING = 'url-with-path-and-query-string';
25644 var PAGEVIEW_OPTION_URL_WITH_PATH = 'url-with-path';
25645
25646 var CONFIG_ALLOW_ELEMENT_CALLBACK = 'allow_element_callback';
25647 var CONFIG_ALLOW_SELECTORS = 'allow_selectors';
25648 var CONFIG_ALLOW_URL_REGEXES = 'allow_url_regexes';
25649 var CONFIG_BLOCK_ATTRS = 'block_attrs';
25650 var CONFIG_BLOCK_ELEMENT_CALLBACK = 'block_element_callback';
25651 var CONFIG_BLOCK_SELECTORS = 'block_selectors';
25652 var CONFIG_BLOCK_URL_REGEXES = 'block_url_regexes';
25653 var CONFIG_CAPTURE_EXTRA_ATTRS = 'capture_extra_attrs';
25654 var CONFIG_CAPTURE_TEXT_CONTENT = 'capture_text_content';
25655 var CONFIG_SCROLL_CAPTURE_ALL = 'scroll_capture_all';
25656 var CONFIG_SCROLL_CHECKPOINTS = 'scroll_depth_percent_checkpoints';
25657 var CONFIG_TRACK_CLICK = 'click';
25658 var CONFIG_TRACK_DEAD_CLICK = 'dead_click';
25659 var CONFIG_TRACK_INPUT = 'input';
25660 var CONFIG_TRACK_PAGEVIEW = 'pageview';
25661 var CONFIG_TRACK_RAGE_CLICK = 'rage_click';
25662 var CONFIG_TRACK_SCROLL = 'scroll';
25663 var CONFIG_TRACK_PAGE_LEAVE = 'page_leave';
25664 var CONFIG_TRACK_SUBMIT = 'submit';
25665
25666 var CONFIG_DEFAULTS$1 = {};
25667 CONFIG_DEFAULTS$1[CONFIG_ALLOW_SELECTORS] = [];
25668 CONFIG_DEFAULTS$1[CONFIG_ALLOW_URL_REGEXES] = [];
25669 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ATTRS] = [];
25670 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ELEMENT_CALLBACK] = null;
25671 CONFIG_DEFAULTS$1[CONFIG_BLOCK_SELECTORS] = [];
25672 CONFIG_DEFAULTS$1[CONFIG_BLOCK_URL_REGEXES] = [];
25673 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_EXTRA_ATTRS] = [];
25674 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_TEXT_CONTENT] = false;
25675 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CAPTURE_ALL] = false;
25676 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CHECKPOINTS] = [25, 50, 75, 100];
25677 CONFIG_DEFAULTS$1[CONFIG_TRACK_CLICK] = true;
25678 CONFIG_DEFAULTS$1[CONFIG_TRACK_DEAD_CLICK] = true;
25679 CONFIG_DEFAULTS$1[CONFIG_TRACK_INPUT] = true;
25680 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGEVIEW] = PAGEVIEW_OPTION_FULL_URL;
25681 CONFIG_DEFAULTS$1[CONFIG_TRACK_RAGE_CLICK] = true;
25682 CONFIG_DEFAULTS$1[CONFIG_TRACK_SCROLL] = true;
25683 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGE_LEAVE] = false;
25684 CONFIG_DEFAULTS$1[CONFIG_TRACK_SUBMIT] = true;
25685
25686 var DEFAULT_PROPS = {
25687 '$mp_autocapture': true
25688 };
25689
25690 var MP_EV_CLICK = '$mp_click';
25691 var MP_EV_DEAD_CLICK = '$mp_dead_click';
25692 var MP_EV_INPUT = '$mp_input_change';
25693 var MP_EV_RAGE_CLICK = '$mp_rage_click';
25694 var MP_EV_SCROLL = '$mp_scroll';
25695 var MP_EV_SUBMIT = '$mp_submit';
25696 var MP_EV_PAGE_LEAVE = '$mp_page_leave';
25697
25698 /**
25699 * Autocapture: manages automatic event tracking
25700 * @constructor
25701 */
25702 var Autocapture = function(mp) {
25703 this.mp = mp;
25704 this.maxScrollViewDepth = 0;
25705 this.hasTrackedScrollSession = false;
25706 this.previousScrollHeight = 0;
25707 };
25708
25709 Autocapture.prototype.init = function() {
25710 if (!minDOMApisSupported()) {
25711 logger$1.critical('Autocapture unavailable: missing required DOM APIs');
25712 return;
25713 }
25714 this.initPageListeners();
25715 this.initPageviewTracking();
25716 this.initClickTracking();
25717 this.initDeadClickTracking();
25718 this.initInputTracking();
25719 this.initScrollTracking();
25720 this.initSubmitTracking();
25721 this.initRageClickTracking();
25722 this.initPageLeaveTracking();
25723 };
25724
25725 Autocapture.prototype.getFullConfig = function() {
25726 var autocaptureConfig = this.mp.get_config(AUTOCAPTURE_CONFIG_KEY);
25727 if (!autocaptureConfig) {
25728 // Autocapture is completely off
25729 return {};
25730 } else if (_.isObject(autocaptureConfig)) {
25731 return _.extend({}, CONFIG_DEFAULTS$1, autocaptureConfig);
25732 } else {
25733 // Autocapture config is non-object truthy value, return default
25734 return CONFIG_DEFAULTS$1;
25735 }
25736 };
25737
25738 Autocapture.prototype.getConfig = function(key) {
25739 return this.getFullConfig()[key];
25740 };
25741
25742 Autocapture.prototype.currentUrlBlocked = function() {
25743 var i;
25744 var currentUrl = _.info.currentUrl();
25745
25746 var allowUrlRegexes = this.getConfig(CONFIG_ALLOW_URL_REGEXES) || [];
25747 if (allowUrlRegexes.length) {
25748 // we're using an allowlist, only track if current URL matches
25749 var allowed = false;
25750 for (i = 0; i < allowUrlRegexes.length; i++) {
25751 var allowRegex = allowUrlRegexes[i];
25752 try {
25753 if (currentUrl.match(allowRegex)) {
25754 allowed = true;
25755 break;
25756 }
25757 } catch (err) {
25758 logger$1.critical('Error while checking block URL regex: ' + allowRegex, err);
25759 return true;
25760 }
25761 }
25762 if (!allowed) {
25763 // wasn't allowed by any regex
25764 return true;
25765 }
25766 }
25767
25768 var blockUrlRegexes = this.getConfig(CONFIG_BLOCK_URL_REGEXES) || [];
25769 if (!blockUrlRegexes || !blockUrlRegexes.length) {
25770 return false;
25771 }
25772
25773 for (i = 0; i < blockUrlRegexes.length; i++) {
25774 try {
25775 if (currentUrl.match(blockUrlRegexes[i])) {
25776 return true;
25777 }
25778 } catch (err) {
25779 logger$1.critical('Error while checking block URL regex: ' + blockUrlRegexes[i], err);
25780 return true;
25781 }
25782 }
25783 return false;
25784 };
25785
25786 Autocapture.prototype.pageviewTrackingConfig = function() {
25787 // supports both autocapture config and old track_pageview config
25788 if (this.mp.get_config(AUTOCAPTURE_CONFIG_KEY)) {
25789 return this.getConfig(CONFIG_TRACK_PAGEVIEW);
25790 } else {
25791 return this.mp.get_config(LEGACY_PAGEVIEW_CONFIG_KEY);
25792 }
25793 };
25794
25795 // helper for event handlers
25796 Autocapture.prototype.trackDomEvent = function(ev, mpEventName) {
25797 if (this.currentUrlBlocked()) {
25798 return;
25799 }
25800
25801 var isCapturedForHeatMap = this.mp.is_recording_heatmap_data() && (
25802 (mpEventName === MP_EV_CLICK && !this.getConfig(CONFIG_TRACK_CLICK)) ||
25803 (mpEventName === MP_EV_RAGE_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK)) ||
25804 (mpEventName === MP_EV_DEAD_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK))
25805 );
25806
25807 var props = getPropsForDOMEvent(ev, {
25808 allowElementCallback: this.getConfig(CONFIG_ALLOW_ELEMENT_CALLBACK),
25809 allowSelectors: this.getConfig(CONFIG_ALLOW_SELECTORS),
25810 blockAttrs: this.getConfig(CONFIG_BLOCK_ATTRS),
25811 blockElementCallback: this.getConfig(CONFIG_BLOCK_ELEMENT_CALLBACK),
25812 blockSelectors: this.getConfig(CONFIG_BLOCK_SELECTORS),
25813 captureExtraAttrs: this.getConfig(CONFIG_CAPTURE_EXTRA_ATTRS),
25814 captureTextContent: this.getConfig(CONFIG_CAPTURE_TEXT_CONTENT),
25815 capturedForHeatMap: isCapturedForHeatMap,
25816 });
25817 if (props) {
25818 _.extend(props, DEFAULT_PROPS);
25819 this.mp.track(mpEventName, props);
25820 }
25821 };
25822
25823 Autocapture.prototype.initPageListeners = function() {
25824 win.removeEventListener(EV_POPSTATE, this.listenerPopstate);
25825 win.removeEventListener(EV_HASHCHANGE, this.listenerHashchange);
25826
25827 if (!this.pageviewTrackingConfig() && !this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config('record_heatmap_data')) {
25828 // These are all the configs that use these listeners
25829 return;
25830 }
25831
25832 this.listenerPopstate = function() {
25833 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
25834 };
25835 this.listenerHashchange = function() {
25836 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
25837 };
25838
25839 win.addEventListener(EV_POPSTATE, this.listenerPopstate);
25840 win.addEventListener(EV_HASHCHANGE, this.listenerHashchange);
25841 var nativePushState = win.history.pushState;
25842 if (typeof nativePushState === 'function') {
25843 win.history.pushState = function(state, unused, url) {
25844 nativePushState.call(win.history, state, unused, url);
25845 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
25846 };
25847 }
25848 var nativeReplaceState = win.history.replaceState;
25849 if (typeof nativeReplaceState === 'function') {
25850 win.history.replaceState = function(state, unused, url) {
25851 nativeReplaceState.call(win.history, state, unused, url);
25852 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
25853 };
25854 }
25855 };
25856
25857 Autocapture.prototype._getClickTrackingConfig = function(configKey) {
25858 var config = this.getConfig(configKey);
25859
25860 if (!config) {
25861 return null; // click tracking disabled
25862 }
25863
25864 if (config === true) {
25865 return {}; // use defaults
25866 }
25867
25868 if (typeof config === 'object') {
25869 return config; // use custom configuration
25870 }
25871
25872 return {}; // fallback to defaults for any other truthy value
25873 };
25874
25875 Autocapture.prototype._trackPageLeave = function(ev, currentUrl, currentScrollHeight) {
25876 if (this.hasTrackedScrollSession) {
25877 // User has navigated away already ending their impression.
25878 return;
25879 }
25880
25881 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.is_recording_heatmap_data()) {
25882 return;
25883 }
25884
25885 this.hasTrackedScrollSession = true;
25886 var viewportHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
25887 var scrollPercentage = Math.round(Math.max(this.maxScrollViewDepth - viewportHeight, 0) / (currentScrollHeight - viewportHeight) * 100);
25888 var foldLinePercentage = Math.round((viewportHeight / currentScrollHeight) * 100);
25889 if (currentScrollHeight <= viewportHeight) {
25890 // If the content fits within the viewport, consider it fully scrolled
25891 scrollPercentage = 100;
25892 foldLinePercentage = 100;
25893 }
25894
25895 var props = _.extend({
25896 '$max_scroll_view_depth': this.maxScrollViewDepth,
25897 '$max_scroll_percentage': scrollPercentage,
25898 '$fold_line_percentage': foldLinePercentage,
25899 '$scroll_height': currentScrollHeight,
25900 '$event_type': ev.type,
25901 '$current_url': currentUrl || _.info.currentUrl(),
25902 '$viewportHeight': viewportHeight, // This is the fold line
25903 '$viewportWidth': Math.max(document$1.documentElement.clientWidth, win.innerWidth || 0),
25904 '$captured_for_heatmap': this.mp.is_recording_heatmap_data()
25905 }, DEFAULT_PROPS);
25906
25907 // Send with beacon transport to ensure event is sent before unload
25908 this.mp.track(MP_EV_PAGE_LEAVE, props, {transport: 'sendBeacon'});
25909 };
25910
25911 Autocapture.prototype._initScrollDepthTracking = function() {
25912 win.removeEventListener(EV_SCROLL, this.listenerScrollDepth);
25913 win.removeEventListener(EV_SCROLLEND, this.listenerScrollDepth);
25914
25915 if (!this.mp.get_config('record_heatmap_data')) {
25916 return;
25917 }
25918
25919 logger$1.log('Initializing scroll depth tracking');
25920
25921 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
25922
25923 var updateScrollDepth = function() {
25924 if (this.currentUrlBlocked()) {
25925 return;
25926 }
25927 var scrollViewHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0) + win.scrollY;
25928 if (scrollViewHeight > this.maxScrollViewDepth) {
25929 this.maxScrollViewDepth = scrollViewHeight;
25930 }
25931 this.previousScrollHeight = document$1.body.scrollHeight;
25932 }.bind(this);
25933
25934 var scrollEndPolyfill = getPolyfillScrollEndFunction(updateScrollDepth);
25935 this.listenerScrollDepth = scrollEndPolyfill.listener;
25936 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScrollDepth);
25937 };
25938
25939 Autocapture.prototype.initClickTracking = function() {
25940 win.removeEventListener(EV_CLICK, this.listenerClick);
25941
25942 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.get_config('record_heatmap_data')) {
25943 return;
25944 }
25945 logger$1.log('Initializing click tracking');
25946
25947 this.listenerClick = function(ev) {
25948 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.is_recording_heatmap_data()) {
25949 return;
25950 }
25951 this.trackDomEvent(ev, MP_EV_CLICK);
25952 }.bind(this);
25953 win.addEventListener(EV_CLICK, this.listenerClick);
25954 };
25955
25956 Autocapture.prototype.initDeadClickTracking = function() {
25957 var deadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
25958
25959 if (!deadClickConfig && !this.mp.get_config('record_heatmap_data')) {
25960 this.stopDeadClickTracking();
25961 return;
25962 }
25963
25964 logger$1.log('Initializing dead click tracking');
25965 if (!this._deadClickTracker) {
25966 this._deadClickTracker = new DeadClickTracker(function(deadClickEvent) {
25967 this.trackDomEvent(deadClickEvent, MP_EV_DEAD_CLICK);
25968 }.bind(this));
25969 this._deadClickTracker.startTracking();
25970 }
25971
25972 if (!this.listenerDeadClick) {
25973 this.listenerDeadClick = function(ev) {
25974 var currentDeadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
25975 if (!currentDeadClickConfig && !this.mp.is_recording_heatmap_data()) {
25976 return;
25977 }
25978 if (this.currentUrlBlocked()) {
25979 return;
25980 }
25981 // Normalize config to ensure timeout_ms is always set
25982 var normalizedConfig = currentDeadClickConfig || {};
25983 if (!normalizedConfig['timeout_ms']) {
25984 normalizedConfig['timeout_ms'] = DEFAULT_DEAD_CLICK_TIMEOUT_MS;
25985 }
25986 this._deadClickTracker.trackClick(ev, normalizedConfig);
25987 }.bind(this);
25988 win.addEventListener(EV_CLICK, this.listenerDeadClick);
25989 }
25990 };
25991
25992 Autocapture.prototype.initInputTracking = function() {
25993 win.removeEventListener(EV_CHANGE, this.listenerChange);
25994
25995 if (!this.getConfig(CONFIG_TRACK_INPUT)) {
25996 return;
25997 }
25998 logger$1.log('Initializing input tracking');
25999
26000 this.listenerChange = function(ev) {
26001 if (!this.getConfig(CONFIG_TRACK_INPUT)) {
26002 return;
26003 }
26004 this.trackDomEvent(ev, MP_EV_INPUT);
26005 }.bind(this);
26006 win.addEventListener(EV_CHANGE, this.listenerChange);
26007 };
26008
26009 Autocapture.prototype.initPageviewTracking = function() {
26010 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
26011
26012 if (!this.pageviewTrackingConfig()) {
26013 return;
26014 }
26015 logger$1.log('Initializing pageview tracking');
26016
26017 var previousTrackedUrl = '';
26018 var tracked = false;
26019 if (!this.currentUrlBlocked()) {
26020 tracked = this.mp.track_pageview(DEFAULT_PROPS);
26021 }
26022 if (tracked) {
26023 previousTrackedUrl = _.info.currentUrl();
26024 }
26025
26026 this.listenerLocationchange = safewrap(function() {
26027 if (this.currentUrlBlocked()) {
26028 return;
26029 }
26030
26031 var currentUrl = _.info.currentUrl();
26032 var shouldTrack = false;
26033 var didPathChange = currentUrl.split('#')[0].split('?')[0] !== previousTrackedUrl.split('#')[0].split('?')[0];
26034 var trackPageviewOption = this.pageviewTrackingConfig();
26035 if (trackPageviewOption === PAGEVIEW_OPTION_FULL_URL) {
26036 shouldTrack = currentUrl !== previousTrackedUrl;
26037 } else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING) {
26038 shouldTrack = currentUrl.split('#')[0] !== previousTrackedUrl.split('#')[0];
26039 } else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH) {
26040 shouldTrack = didPathChange;
26041 }
26042
26043 if (shouldTrack) {
26044 var tracked = this.mp.track_pageview(DEFAULT_PROPS);
26045 if (tracked) {
26046 previousTrackedUrl = currentUrl;
26047 }
26048 if (didPathChange) {
26049 this.lastScrollCheckpoint = 0;
26050 logger$1.log('Path change: re-initializing scroll depth checkpoints');
26051 }
26052 }
26053 }.bind(this));
26054 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
26055 };
26056
26057 Autocapture.prototype.initRageClickTracking = function() {
26058 win.removeEventListener(EV_CLICK, this.listenerRageClick);
26059
26060 var rageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
26061 if (!rageClickConfig && !this.mp.get_config('record_heatmap_data')) {
26062 return;
26063 }
26064
26065 logger$1.log('Initializing rage click tracking');
26066 if (!this._rageClickTracker) {
26067 this._rageClickTracker = new RageClickTracker();
26068 }
26069
26070 this.listenerRageClick = function(ev) {
26071 var currentRageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
26072 if (!currentRageClickConfig && !this.mp.is_recording_heatmap_data()) {
26073 return;
26074 }
26075
26076 if (this.currentUrlBlocked()) {
26077 return;
26078 }
26079
26080 if (this._rageClickTracker.isRageClick(ev['pageX'], ev['pageY'], currentRageClickConfig)) {
26081 this.trackDomEvent(ev, MP_EV_RAGE_CLICK);
26082 }
26083 }.bind(this);
26084 win.addEventListener(EV_CLICK, this.listenerRageClick);
26085 };
26086
26087 Autocapture.prototype.initScrollTracking = function() {
26088 win.removeEventListener(EV_SCROLLEND, this.listenerScroll);
26089 win.removeEventListener(EV_SCROLL, this.listenerScroll);
26090
26091
26092 if (!this.getConfig(CONFIG_TRACK_SCROLL)) {
26093 return;
26094 }
26095 logger$1.log('Initializing scroll tracking');
26096 this.lastScrollCheckpoint = 0;
26097
26098 var scrollTrackFunction = function() {
26099 if (!this.getConfig(CONFIG_TRACK_SCROLL)) {
26100 return;
26101 }
26102 if (this.currentUrlBlocked()) {
26103 return;
26104 }
26105
26106 var shouldTrack = this.getConfig(CONFIG_SCROLL_CAPTURE_ALL);
26107 var scrollCheckpoints = (this.getConfig(CONFIG_SCROLL_CHECKPOINTS) || [])
26108 .slice()
26109 .sort(function(a, b) { return a - b; });
26110
26111 var scrollTop = win.scrollY;
26112 var props = _.extend({'$scroll_top': scrollTop}, DEFAULT_PROPS);
26113 try {
26114 var scrollHeight = document$1.body.scrollHeight;
26115 var scrollPercentage = Math.round((scrollTop / (scrollHeight - win.innerHeight)) * 100);
26116 props['$scroll_height'] = scrollHeight;
26117 props['$scroll_percentage'] = scrollPercentage;
26118 if (scrollPercentage > this.lastScrollCheckpoint) {
26119 for (var i = 0; i < scrollCheckpoints.length; i++) {
26120 var checkpoint = scrollCheckpoints[i];
26121 if (
26122 scrollPercentage >= checkpoint &&
26123 this.lastScrollCheckpoint < checkpoint
26124 ) {
26125 props['$scroll_checkpoint'] = checkpoint;
26126 this.lastScrollCheckpoint = checkpoint;
26127 shouldTrack = true;
26128 }
26129 }
26130 }
26131 } catch (err) {
26132 logger$1.critical('Error while calculating scroll percentage', err);
26133 }
26134 if (shouldTrack) {
26135 this.mp.track(MP_EV_SCROLL, props);
26136 }
26137 }.bind(this);
26138
26139 var scrollEndPolyfill = getPolyfillScrollEndFunction(scrollTrackFunction);
26140 this.listenerScroll = scrollEndPolyfill.listener;
26141 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScroll);
26142 };
26143
26144 Autocapture.prototype.initSubmitTracking = function() {
26145 win.removeEventListener(EV_SUBMIT, this.listenerSubmit);
26146
26147 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) {
26148 return;
26149 }
26150 logger$1.log('Initializing submit tracking');
26151
26152 this.listenerSubmit = function(ev) {
26153 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) {
26154 return;
26155 }
26156 this.trackDomEvent(ev, MP_EV_SUBMIT);
26157 }.bind(this);
26158 win.addEventListener(EV_SUBMIT, this.listenerSubmit);
26159 };
26160
26161 Autocapture.prototype.initPageLeaveTracking = function() {
26162 // Capture page_leave both when the user navigates away from the page (visibilitychange) as well
26163 // as when they navigate to a different page within the SPA (popstate/pushstate/hashchange).
26164 document$1.removeEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
26165 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
26166 win.removeEventListener(EV_LOAD, this.listenerPageLoad);
26167
26168 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config('record_heatmap_data')) {
26169 return;
26170 }
26171
26172 logger$1.log('Initializing page visibility tracking.');
26173 this._initScrollDepthTracking();
26174 var previousTrackedUrl = _.info.currentUrl();
26175
26176 // Initialize previousScrollHeight on `load` which handles async loading
26177 // https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
26178 this.listenerPageLoad = function() {
26179 this.previousScrollHeight = document$1.body.scrollHeight;
26180 }.bind(this);
26181 win.addEventListener(EV_LOAD, this.listenerPageLoad);
26182
26183 // Track page navigation events similar to how initPageviewTracking does it
26184 this.listenerPageLeaveLocationchange = safewrap(function(ev) {
26185 if (this.currentUrlBlocked()) {
26186 return;
26187 }
26188
26189 var currentUrl = _.info.currentUrl();
26190 // Track all URL changes including query string or fragment changes as separate scroll sessions
26191 var shouldTrack = currentUrl !== previousTrackedUrl;
26192
26193 if (shouldTrack) {
26194 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
26195 previousTrackedUrl = currentUrl;
26196 // Fragment navigation should call scroll(end) and trigger listener, don't add window.scrollY here.
26197 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
26198 this.previousScrollHeight = document$1.body.scrollHeight;
26199 this.hasTrackedScrollSession = false;
26200 }
26201 }.bind(this));
26202 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
26203
26204 this.listenerPageLeaveVisibilitychange = function(ev) {
26205 if (document$1.hidden) {
26206 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
26207 }
26208 }.bind(this);
26209 document$1.addEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
26210 };
26211
26212 Autocapture.prototype.stopDeadClickTracking = function() {
26213 if (this.listenerDeadClick) {
26214 win.removeEventListener(EV_CLICK, this.listenerDeadClick);
26215 this.listenerDeadClick = null;
26216 }
26217
26218 if (this._deadClickTracker) {
26219 this._deadClickTracker.stopTracking();
26220 this._deadClickTracker = null;
26221 }
26222 };
26223
26224 // TODO integrate error_reporter from mixpanel instance
26225 safewrapClass(Autocapture);
26226
26227 var logger = console_with_prefix('flags');
26228
26229 var FLAGS_CONFIG_KEY = 'flags';
26230
26231 var CONFIG_CONTEXT = 'context';
26232 var CONFIG_DEFAULTS = {};
26233 CONFIG_DEFAULTS[CONFIG_CONTEXT] = {};
26234
26235 /**
26236 * FeatureFlagManager: support for Mixpanel's feature flagging product
26237 * @constructor
26238 */
26239 var FeatureFlagManager = function(initOptions) {
26240 this.fetch = win['fetch'];
26241 this.getFullApiRoute = initOptions.getFullApiRoute;
26242 this.getMpConfig = initOptions.getConfigFunc;
26243 this.setMpConfig = initOptions.setConfigFunc;
26244 this.getMpProperty = initOptions.getPropertyFunc;
26245 this.track = initOptions.trackingFunc;
26246 };
26247
26248 FeatureFlagManager.prototype.init = function() {
26249 if (!this.minApisSupported()) {
26250 logger.critical('Feature Flags unavailable: missing minimum required APIs');
26251 return;
26252 }
26253
26254 this.flags = null;
26255 this.fetchFlags();
26256
26257 this.trackedFeatures = new Set();
26258 };
26259
26260 FeatureFlagManager.prototype.getFullConfig = function() {
26261 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
26262 if (!ffConfig) {
26263 // flags are completely off
26264 return {};
26265 } else if (_.isObject(ffConfig)) {
26266 return _.extend({}, CONFIG_DEFAULTS, ffConfig);
26267 } else {
26268 // config is non-object truthy value, return default
26269 return CONFIG_DEFAULTS;
26270 }
26271 };
26272
26273 FeatureFlagManager.prototype.getConfig = function(key) {
26274 return this.getFullConfig()[key];
26275 };
26276
26277 FeatureFlagManager.prototype.isSystemEnabled = function() {
26278 return !!this.getMpConfig(FLAGS_CONFIG_KEY);
26279 };
26280
26281 FeatureFlagManager.prototype.updateContext = function(newContext, options) {
26282 if (!this.isSystemEnabled()) {
26283 logger.critical('Feature Flags not enabled, cannot update context');
26284 return Promise.resolve();
26285 }
26286
26287 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
26288 if (!_.isObject(ffConfig)) {
26289 ffConfig = {};
26290 }
26291 var oldContext = (options && options['replace']) ? {} : this.getConfig(CONFIG_CONTEXT);
26292 ffConfig[CONFIG_CONTEXT] = _.extend({}, oldContext, newContext);
26293
26294 this.setMpConfig(FLAGS_CONFIG_KEY, ffConfig);
26295 return this.fetchFlags();
26296 };
26297
26298 FeatureFlagManager.prototype.areFlagsReady = function() {
26299 if (!this.isSystemEnabled()) {
26300 logger.error('Feature Flags not enabled');
26301 }
26302 return !!this.flags;
26303 };
26304
26305 FeatureFlagManager.prototype.fetchFlags = function() {
26306 if (!this.isSystemEnabled()) {
26307 return Promise.resolve();
26308 }
26309
26310 var distinctId = this.getMpProperty('distinct_id');
26311 var deviceId = this.getMpProperty('$device_id');
26312 var traceparent = generateTraceparent();
26313 logger.log('Fetching flags for distinct ID: ' + distinctId);
26314
26315 var context = _.extend({'distinct_id': distinctId, 'device_id': deviceId}, this.getConfig(CONFIG_CONTEXT));
26316 var searchParams = new URLSearchParams();
26317 searchParams.set('context', JSON.stringify(context));
26318 searchParams.set('token', this.getMpConfig('token'));
26319 searchParams.set('mp_lib', 'web');
26320 searchParams.set('$lib_version', Config.LIB_VERSION);
26321 var url = this.getFullApiRoute() + '?' + searchParams.toString();
26322
26323 this._fetchInProgressStartTime = Date.now();
26324 this.fetchPromise = this.fetch.call(win, url, {
26325 'method': 'GET',
26326 'headers': {
26327 'Authorization': 'Basic ' + btoa(this.getMpConfig('token') + ':'),
26328 'traceparent': traceparent
26329 }
26330 }).then(function(response) {
26331 this.markFetchComplete();
26332 return response.json().then(function(responseBody) {
26333 var responseFlags = responseBody['flags'];
26334 if (!responseFlags) {
26335 throw new Error('No flags in API response');
26336 }
26337 var flags = new Map();
26338 _.each(responseFlags, function(data, key) {
26339 flags.set(key, {
26340 'key': data['variant_key'],
26341 'value': data['variant_value'],
26342 'experiment_id': data['experiment_id'],
26343 'is_experiment_active': data['is_experiment_active'],
26344 'is_qa_tester': data['is_qa_tester']
26345 });
26346 });
26347 this.flags = flags;
26348 this._traceparent = traceparent;
26349 }.bind(this)).catch(function(error) {
26350 this.markFetchComplete();
26351 logger.error(error);
26352 }.bind(this));
26353 }.bind(this)).catch(function(error) {
26354 this.markFetchComplete();
26355 logger.error(error);
26356 }.bind(this));
26357
26358 return this.fetchPromise;
26359 };
26360
26361 FeatureFlagManager.prototype.markFetchComplete = function() {
26362 if (!this._fetchInProgressStartTime) {
26363 logger.error('Fetch in progress started time not set, cannot mark fetch complete');
26364 return;
26365 }
26366 this._fetchStartTime = this._fetchInProgressStartTime;
26367 this._fetchCompleteTime = Date.now();
26368 this._fetchLatency = this._fetchCompleteTime - this._fetchStartTime;
26369 this._fetchInProgressStartTime = null;
26370 };
26371
26372 FeatureFlagManager.prototype.getVariant = function(featureName, fallback) {
26373 if (!this.fetchPromise) {
26374 return new Promise(function(resolve) {
26375 logger.critical('Feature Flags not initialized');
26376 resolve(fallback);
26377 });
26378 }
26379
26380 return this.fetchPromise.then(function() {
26381 return this.getVariantSync(featureName, fallback);
26382 }.bind(this)).catch(function(error) {
26383 logger.error(error);
26384 return fallback;
26385 });
26386 };
26387
26388 FeatureFlagManager.prototype.getVariantSync = function(featureName, fallback) {
26389 if (!this.areFlagsReady()) {
26390 logger.log('Flags not loaded yet');
26391 return fallback;
26392 }
26393 var feature = this.flags.get(featureName);
26394 if (!feature) {
26395 logger.log('No flag found: "' + featureName + '"');
26396 return fallback;
26397 }
26398 this.trackFeatureCheck(featureName, feature);
26399 return feature;
26400 };
26401
26402 FeatureFlagManager.prototype.getVariantValue = function(featureName, fallbackValue) {
26403 return this.getVariant(featureName, {'value': fallbackValue}).then(function(feature) {
26404 return feature['value'];
26405 }).catch(function(error) {
26406 logger.error(error);
26407 return fallbackValue;
26408 });
26409 };
26410
26411 // TODO remove deprecated method
26412 FeatureFlagManager.prototype.getFeatureData = function(featureName, fallbackValue) {
26413 logger.critical('mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead.');
26414 return this.getVariantValue(featureName, fallbackValue);
26415 };
26416
26417 FeatureFlagManager.prototype.getVariantValueSync = function(featureName, fallbackValue) {
26418 return this.getVariantSync(featureName, {'value': fallbackValue})['value'];
26419 };
26420
26421 FeatureFlagManager.prototype.isEnabled = function(featureName, fallbackValue) {
26422 return this.getVariantValue(featureName).then(function() {
26423 return this.isEnabledSync(featureName, fallbackValue);
26424 }.bind(this)).catch(function(error) {
26425 logger.error(error);
26426 return fallbackValue;
26427 });
26428 };
26429
26430 FeatureFlagManager.prototype.isEnabledSync = function(featureName, fallbackValue) {
26431 fallbackValue = fallbackValue || false;
26432 var val = this.getVariantValueSync(featureName, fallbackValue);
26433 if (val !== true && val !== false) {
26434 logger.error('Feature flag "' + featureName + '" value: ' + val + ' is not a boolean; returning fallback value: ' + fallbackValue);
26435 val = fallbackValue;
26436 }
26437 return val;
26438 };
26439
26440 FeatureFlagManager.prototype.trackFeatureCheck = function(featureName, feature) {
26441 if (this.trackedFeatures.has(featureName)) {
26442 return;
26443 }
26444 this.trackedFeatures.add(featureName);
26445
26446 var trackingProperties = {
26447 'Experiment name': featureName,
26448 'Variant name': feature['key'],
26449 '$experiment_type': 'feature_flag',
26450 'Variant fetch start time': new Date(this._fetchStartTime).toISOString(),
26451 'Variant fetch complete time': new Date(this._fetchCompleteTime).toISOString(),
26452 'Variant fetch latency (ms)': this._fetchLatency,
26453 'Variant fetch traceparent': this._traceparent,
26454 };
26455
26456 if (feature['experiment_id'] !== 'undefined') {
26457 trackingProperties['$experiment_id'] = feature['experiment_id'];
26458 }
26459 if (feature['is_experiment_active'] !== 'undefined') {
26460 trackingProperties['$is_experiment_active'] = feature['is_experiment_active'];
26461 }
26462 if (feature['is_qa_tester'] !== 'undefined') {
26463 trackingProperties['$is_qa_tester'] = feature['is_qa_tester'];
26464 }
26465
26466 this.track('$experiment_started', trackingProperties);
26467 };
26468
26469 FeatureFlagManager.prototype.minApisSupported = function() {
26470 return !!this.fetch &&
26471 typeof Promise !== 'undefined' &&
26472 typeof Map !== 'undefined' &&
26473 typeof Set !== 'undefined';
26474 };
26475
26476 safewrapClass(FeatureFlagManager);
26477
26478 FeatureFlagManager.prototype['are_flags_ready'] = FeatureFlagManager.prototype.areFlagsReady;
26479 FeatureFlagManager.prototype['get_variant'] = FeatureFlagManager.prototype.getVariant;
26480 FeatureFlagManager.prototype['get_variant_sync'] = FeatureFlagManager.prototype.getVariantSync;
26481 FeatureFlagManager.prototype['get_variant_value'] = FeatureFlagManager.prototype.getVariantValue;
26482 FeatureFlagManager.prototype['get_variant_value_sync'] = FeatureFlagManager.prototype.getVariantValueSync;
26483 FeatureFlagManager.prototype['is_enabled'] = FeatureFlagManager.prototype.isEnabled;
26484 FeatureFlagManager.prototype['is_enabled_sync'] = FeatureFlagManager.prototype.isEnabledSync;
26485 FeatureFlagManager.prototype['update_context'] = FeatureFlagManager.prototype.updateContext;
26486
26487 // Deprecated method
26488 FeatureFlagManager.prototype['get_feature_data'] = FeatureFlagManager.prototype.getFeatureData;
26489
26490 /* eslint camelcase: "off" */
26491
26492
26493 /**
26494 * DomTracker Object
26495 * @constructor
26496 */
26497 var DomTracker = function() {};
26498
26499
26500 // interface
26501 DomTracker.prototype.create_properties = function() {};
26502 DomTracker.prototype.event_handler = function() {};
26503 DomTracker.prototype.after_track_handler = function() {};
26504
26505 DomTracker.prototype.init = function(mixpanel_instance) {
26506 this.mp = mixpanel_instance;
26507 return this;
26508 };
26509
26510 /**
26511 * @param {Object|string} query
26512 * @param {string} event_name
26513 * @param {Object=} properties
26514 * @param {function=} user_callback
26515 */
26516 DomTracker.prototype.track = function(query, event_name, properties, user_callback) {
26517 var that = this;
26518 var elements = _.dom_query(query);
26519
26520 if (elements.length === 0) {
26521 console$1.error('The DOM query (' + query + ') returned 0 elements');
26522 return;
26523 }
26524
26525 _.each(elements, function(element) {
26526 _.register_event(element, this.override_event, function(e) {
26527 var options = {};
26528 var props = that.create_properties(properties, this);
26529 var timeout = that.mp.get_config('track_links_timeout');
26530
26531 that.event_handler(e, this, options);
26532
26533 // in case the mixpanel servers don't get back to us in time
26534 window.setTimeout(that.track_callback(user_callback, props, options, true), timeout);
26535
26536 // fire the tracking event
26537 that.mp.track(event_name, props, that.track_callback(user_callback, props, options));
26538 });
26539 }, this);
26540
26541 return true;
26542 };
26543
26544 /**
26545 * @param {function} user_callback
26546 * @param {Object} props
26547 * @param {boolean=} timeout_occured
26548 */
26549 DomTracker.prototype.track_callback = function(user_callback, props, options, timeout_occured) {
26550 timeout_occured = timeout_occured || false;
26551 var that = this;
26552
26553 return function() {
26554 // options is referenced from both callbacks, so we can have
26555 // a 'lock' of sorts to ensure only one fires
26556 if (options.callback_fired) { return; }
26557 options.callback_fired = true;
26558
26559 if (user_callback && user_callback(timeout_occured, props) === false) {
26560 // user can prevent the default functionality by
26561 // returning false from their callback
26562 return;
26563 }
26564
26565 that.after_track_handler(props, options, timeout_occured);
26566 };
26567 };
26568
26569 DomTracker.prototype.create_properties = function(properties, element) {
26570 var props;
26571
26572 if (typeof(properties) === 'function') {
26573 props = properties(element);
26574 } else {
26575 props = _.extend({}, properties);
26576 }
26577
26578 return props;
26579 };
26580
26581 /**
26582 * LinkTracker Object
26583 * @constructor
26584 * @extends DomTracker
26585 */
26586 var LinkTracker = function() {
26587 this.override_event = 'click';
26588 };
26589 _.inherit(LinkTracker, DomTracker);
26590
26591 LinkTracker.prototype.create_properties = function(properties, element) {
26592 var props = LinkTracker.superclass.create_properties.apply(this, arguments);
26593
26594 if (element.href) { props['url'] = element.href; }
26595
26596 return props;
26597 };
26598
26599 LinkTracker.prototype.event_handler = function(evt, element, options) {
26600 options.new_tab = (
26601 evt.which === 2 ||
26602 evt.metaKey ||
26603 evt.ctrlKey ||
26604 element.target === '_blank'
26605 );
26606 options.href = element.href;
26607
26608 if (!options.new_tab) {
26609 evt.preventDefault();
26610 }
26611 };
26612
26613 LinkTracker.prototype.after_track_handler = function(props, options) {
26614 if (options.new_tab) { return; }
26615
26616 setTimeout(function() {
26617 window.location = options.href;
26618 }, 0);
26619 };
26620
26621 /**
26622 * FormTracker Object
26623 * @constructor
26624 * @extends DomTracker
26625 */
26626 var FormTracker = function() {
26627 this.override_event = 'submit';
26628 };
26629 _.inherit(FormTracker, DomTracker);
26630
26631 FormTracker.prototype.event_handler = function(evt, element, options) {
26632 options.element = element;
26633 evt.preventDefault();
26634 };
26635
26636 FormTracker.prototype.after_track_handler = function(props, options) {
26637 setTimeout(function() {
26638 options.element.submit();
26639 }, 0);
26640 };
26641
26642 /* eslint camelcase: "off" */
26643
26644
26645 /** @const */ var SET_ACTION = '$set';
26646 /** @const */ var SET_ONCE_ACTION = '$set_once';
26647 /** @const */ var UNSET_ACTION = '$unset';
26648 /** @const */ var ADD_ACTION = '$add';
26649 /** @const */ var APPEND_ACTION = '$append';
26650 /** @const */ var UNION_ACTION = '$union';
26651 /** @const */ var REMOVE_ACTION = '$remove';
26652 /** @const */ var DELETE_ACTION = '$delete';
26653
26654 // Common internal methods for mixpanel.people and mixpanel.group APIs.
26655 // These methods shouldn't involve network I/O.
26656 var apiActions = {
26657 set_action: function(prop, to) {
26658 var data = {};
26659 var $set = {};
26660 if (_.isObject(prop)) {
26661 _.each(prop, function(v, k) {
26662 if (!this._is_reserved_property(k)) {
26663 $set[k] = v;
26664 }
26665 }, this);
26666 } else {
26667 $set[prop] = to;
26668 }
26669
26670 data[SET_ACTION] = $set;
26671 return data;
26672 },
26673
26674 unset_action: function(prop) {
26675 var data = {};
26676 var $unset = [];
26677 if (!_.isArray(prop)) {
26678 prop = [prop];
26679 }
26680
26681 _.each(prop, function(k) {
26682 if (!this._is_reserved_property(k)) {
26683 $unset.push(k);
26684 }
26685 }, this);
26686
26687 data[UNSET_ACTION] = $unset;
26688 return data;
26689 },
26690
26691 set_once_action: function(prop, to) {
26692 var data = {};
26693 var $set_once = {};
26694 if (_.isObject(prop)) {
26695 _.each(prop, function(v, k) {
26696 if (!this._is_reserved_property(k)) {
26697 $set_once[k] = v;
26698 }
26699 }, this);
26700 } else {
26701 $set_once[prop] = to;
26702 }
26703 data[SET_ONCE_ACTION] = $set_once;
26704 return data;
26705 },
26706
26707 union_action: function(list_name, values) {
26708 var data = {};
26709 var $union = {};
26710 if (_.isObject(list_name)) {
26711 _.each(list_name, function(v, k) {
26712 if (!this._is_reserved_property(k)) {
26713 $union[k] = _.isArray(v) ? v : [v];
26714 }
26715 }, this);
26716 } else {
26717 $union[list_name] = _.isArray(values) ? values : [values];
26718 }
26719 data[UNION_ACTION] = $union;
26720 return data;
26721 },
26722
26723 append_action: function(list_name, value) {
26724 var data = {};
26725 var $append = {};
26726 if (_.isObject(list_name)) {
26727 _.each(list_name, function(v, k) {
26728 if (!this._is_reserved_property(k)) {
26729 $append[k] = v;
26730 }
26731 }, this);
26732 } else {
26733 $append[list_name] = value;
26734 }
26735 data[APPEND_ACTION] = $append;
26736 return data;
26737 },
26738
26739 remove_action: function(list_name, value) {
26740 var data = {};
26741 var $remove = {};
26742 if (_.isObject(list_name)) {
26743 _.each(list_name, function(v, k) {
26744 if (!this._is_reserved_property(k)) {
26745 $remove[k] = v;
26746 }
26747 }, this);
26748 } else {
26749 $remove[list_name] = value;
26750 }
26751 data[REMOVE_ACTION] = $remove;
26752 return data;
26753 },
26754
26755 delete_action: function() {
26756 var data = {};
26757 data[DELETE_ACTION] = '';
26758 return data;
26759 }
26760 };
26761
26762 /* eslint camelcase: "off" */
26763
26764 /**
26765 * Mixpanel Group Object
26766 * @constructor
26767 */
26768 var MixpanelGroup = function() {};
26769
26770 _.extend(MixpanelGroup.prototype, apiActions);
26771
26772 MixpanelGroup.prototype._init = function(mixpanel_instance, group_key, group_id) {
26773 this._mixpanel = mixpanel_instance;
26774 this._group_key = group_key;
26775 this._group_id = group_id;
26776 };
26777
26778 /**
26779 * Set properties on a group.
26780 *
26781 * ### Usage:
26782 *
26783 * mixpanel.get_group('company', 'mixpanel').set('Location', '405 Howard');
26784 *
26785 * // or set multiple properties at once
26786 * mixpanel.get_group('company', 'mixpanel').set({
26787 * 'Location': '405 Howard',
26788 * 'Founded' : 2009,
26789 * });
26790 * // properties can be strings, integers, dates, or lists
26791 *
26792 * @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.
26793 * @param {*} [to] A value to set on the given property name
26794 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26795 */
26796 MixpanelGroup.prototype.set = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
26797 var data = this.set_action(prop, to);
26798 if (_.isObject(prop)) {
26799 callback = to;
26800 }
26801 return this._send_request(data, callback);
26802 });
26803
26804 /**
26805 * Set properties on a group, only if they do not yet exist.
26806 * This will not overwrite previous group property values, unlike
26807 * group.set().
26808 *
26809 * ### Usage:
26810 *
26811 * mixpanel.get_group('company', 'mixpanel').set_once('Location', '405 Howard');
26812 *
26813 * // or set multiple properties at once
26814 * mixpanel.get_group('company', 'mixpanel').set_once({
26815 * 'Location': '405 Howard',
26816 * 'Founded' : 2009,
26817 * });
26818 * // properties can be strings, integers, lists or dates
26819 *
26820 * @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.
26821 * @param {*} [to] A value to set on the given property name
26822 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26823 */
26824 MixpanelGroup.prototype.set_once = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
26825 var data = this.set_once_action(prop, to);
26826 if (_.isObject(prop)) {
26827 callback = to;
26828 }
26829 return this._send_request(data, callback);
26830 });
26831
26832 /**
26833 * Unset properties on a group permanently.
26834 *
26835 * ### Usage:
26836 *
26837 * mixpanel.get_group('company', 'mixpanel').unset('Founded');
26838 *
26839 * @param {String} prop The name of the property.
26840 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26841 */
26842 MixpanelGroup.prototype.unset = addOptOutCheckMixpanelGroup(function(prop, callback) {
26843 var data = this.unset_action(prop);
26844 return this._send_request(data, callback);
26845 });
26846
26847 /**
26848 * Merge a given list with a list-valued group property, excluding duplicate values.
26849 *
26850 * ### Usage:
26851 *
26852 * // merge a value to a list, creating it if needed
26853 * mixpanel.get_group('company', 'mixpanel').union('Location', ['San Francisco', 'London']);
26854 *
26855 * @param {String} list_name Name of the property.
26856 * @param {Array} values Values to merge with the given property
26857 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26858 */
26859 MixpanelGroup.prototype.union = addOptOutCheckMixpanelGroup(function(list_name, values, callback) {
26860 if (_.isObject(list_name)) {
26861 callback = values;
26862 }
26863 var data = this.union_action(list_name, values);
26864 return this._send_request(data, callback);
26865 });
26866
26867 /**
26868 * Permanently delete a group.
26869 *
26870 * ### Usage:
26871 *
26872 * mixpanel.get_group('company', 'mixpanel').delete();
26873 *
26874 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26875 */
26876 MixpanelGroup.prototype['delete'] = addOptOutCheckMixpanelGroup(function(callback) {
26877 // bracket notation above prevents a minification error related to reserved words
26878 var data = this.delete_action();
26879 return this._send_request(data, callback);
26880 });
26881
26882 /**
26883 * Remove a property from a group. The value will be ignored if doesn't exist.
26884 *
26885 * ### Usage:
26886 *
26887 * mixpanel.get_group('company', 'mixpanel').remove('Location', 'London');
26888 *
26889 * @param {String} list_name Name of the property.
26890 * @param {Object} value Value to remove from the given group property
26891 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26892 */
26893 MixpanelGroup.prototype.remove = addOptOutCheckMixpanelGroup(function(list_name, value, callback) {
26894 var data = this.remove_action(list_name, value);
26895 return this._send_request(data, callback);
26896 });
26897
26898 MixpanelGroup.prototype._send_request = function(data, callback) {
26899 data['$group_key'] = this._group_key;
26900 data['$group_id'] = this._group_id;
26901 data['$token'] = this._get_config('token');
26902
26903 var date_encoded_data = _.encodeDates(data);
26904 return this._mixpanel._track_or_batch({
26905 type: 'groups',
26906 data: date_encoded_data,
26907 endpoint: this._mixpanel.get_api_host('groups') + '/' + this._get_config('api_routes')['groups'],
26908 batcher: this._mixpanel.request_batchers.groups
26909 }, callback);
26910 };
26911
26912 MixpanelGroup.prototype._is_reserved_property = function(prop) {
26913 return prop === '$group_key' || prop === '$group_id';
26914 };
26915
26916 MixpanelGroup.prototype._get_config = function(conf) {
26917 return this._mixpanel.get_config(conf);
26918 };
26919
26920 MixpanelGroup.prototype.toString = function() {
26921 return this._mixpanel.toString() + '.group.' + this._group_key + '.' + this._group_id;
26922 };
26923
26924 // MixpanelGroup Exports
26925 MixpanelGroup.prototype['remove'] = MixpanelGroup.prototype.remove;
26926 MixpanelGroup.prototype['set'] = MixpanelGroup.prototype.set;
26927 MixpanelGroup.prototype['set_once'] = MixpanelGroup.prototype.set_once;
26928 MixpanelGroup.prototype['union'] = MixpanelGroup.prototype.union;
26929 MixpanelGroup.prototype['unset'] = MixpanelGroup.prototype.unset;
26930 MixpanelGroup.prototype['toString'] = MixpanelGroup.prototype.toString;
26931
26932 /* eslint camelcase: "off" */
26933
26934 /**
26935 * Mixpanel People Object
26936 * @constructor
26937 */
26938 var MixpanelPeople = function() {};
26939
26940 _.extend(MixpanelPeople.prototype, apiActions);
26941
26942 MixpanelPeople.prototype._init = function(mixpanel_instance) {
26943 this._mixpanel = mixpanel_instance;
26944 };
26945
26946 /*
26947 * Set properties on a user record.
26948 *
26949 * ### Usage:
26950 *
26951 * mixpanel.people.set('gender', 'm');
26952 *
26953 * // or set multiple properties at once
26954 * mixpanel.people.set({
26955 * 'Company': 'Acme',
26956 * 'Plan': 'Premium',
26957 * 'Upgrade date': new Date()
26958 * });
26959 * // properties can be strings, integers, dates, or lists
26960 *
26961 * @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.
26962 * @param {*} [to] A value to set on the given property name
26963 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
26964 */
26965 MixpanelPeople.prototype.set = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
26966 var data = this.set_action(prop, to);
26967 if (_.isObject(prop)) {
26968 callback = to;
26969 }
26970 // make sure that the referrer info has been updated and saved
26971 if (this._get_config('save_referrer')) {
26972 this._mixpanel['persistence'].update_referrer_info(document.referrer);
26973 }
26974
26975 // update $set object with default people properties
26976 data[SET_ACTION] = _.extend(
26977 {},
26978 _.info.people_properties(),
26979 data[SET_ACTION]
26980 );
26981 return this._send_request(data, callback);
26982 });
26983
26984 /*
26985 * Set properties on a user record, only if they do not yet exist.
26986 * This will not overwrite previous people property values, unlike
26987 * people.set().
26988 *
26989 * ### Usage:
26990 *
26991 * mixpanel.people.set_once('First Login Date', new Date());
26992 *
26993 * // or set multiple properties at once
26994 * mixpanel.people.set_once({
26995 * 'First Login Date': new Date(),
26996 * 'Starting Plan': 'Premium'
26997 * });
26998 *
26999 * // properties can be strings, integers or dates
27000 *
27001 * @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.
27002 * @param {*} [to] A value to set on the given property name
27003 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27004 */
27005 MixpanelPeople.prototype.set_once = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
27006 var data = this.set_once_action(prop, to);
27007 if (_.isObject(prop)) {
27008 callback = to;
27009 }
27010 return this._send_request(data, callback);
27011 });
27012
27013 /*
27014 * Unset properties on a user record (permanently removes the properties and their values from a profile).
27015 *
27016 * ### Usage:
27017 *
27018 * mixpanel.people.unset('gender');
27019 *
27020 * // or unset multiple properties at once
27021 * mixpanel.people.unset(['gender', 'Company']);
27022 *
27023 * @param {Array|String} prop If a string, this is the name of the property. If an array, this is a list of property names.
27024 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27025 */
27026 MixpanelPeople.prototype.unset = addOptOutCheckMixpanelPeople(function(prop, callback) {
27027 var data = this.unset_action(prop);
27028 return this._send_request(data, callback);
27029 });
27030
27031 /*
27032 * Increment/decrement numeric people analytics properties.
27033 *
27034 * ### Usage:
27035 *
27036 * mixpanel.people.increment('page_views', 1);
27037 *
27038 * // or, for convenience, if you're just incrementing a counter by
27039 * // 1, you can simply do
27040 * mixpanel.people.increment('page_views');
27041 *
27042 * // to decrement a counter, pass a negative number
27043 * mixpanel.people.increment('credits_left', -1);
27044 *
27045 * // like mixpanel.people.set(), you can increment multiple
27046 * // properties at once:
27047 * mixpanel.people.increment({
27048 * counter1: 1,
27049 * counter2: 6
27050 * });
27051 *
27052 * @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 numeric values.
27053 * @param {Number} [by] An amount to increment the given property
27054 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27055 */
27056 MixpanelPeople.prototype.increment = addOptOutCheckMixpanelPeople(function(prop, by, callback) {
27057 var data = {};
27058 var $add = {};
27059 if (_.isObject(prop)) {
27060 _.each(prop, function(v, k) {
27061 if (!this._is_reserved_property(k)) {
27062 if (isNaN(parseFloat(v))) {
27063 console$1.error('Invalid increment value passed to mixpanel.people.increment - must be a number');
27064 return;
27065 } else {
27066 $add[k] = v;
27067 }
27068 }
27069 }, this);
27070 callback = by;
27071 } else {
27072 // convenience: mixpanel.people.increment('property'); will
27073 // increment 'property' by 1
27074 if (_.isUndefined(by)) {
27075 by = 1;
27076 }
27077 $add[prop] = by;
27078 }
27079 data[ADD_ACTION] = $add;
27080
27081 return this._send_request(data, callback);
27082 });
27083
27084 /*
27085 * Append a value to a list-valued people analytics property.
27086 *
27087 * ### Usage:
27088 *
27089 * // append a value to a list, creating it if needed
27090 * mixpanel.people.append('pages_visited', 'homepage');
27091 *
27092 * // like mixpanel.people.set(), you can append multiple
27093 * // properties at once:
27094 * mixpanel.people.append({
27095 * list1: 'bob',
27096 * list2: 123
27097 * });
27098 *
27099 * @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.
27100 * @param {*} [value] value An item to append to the list
27101 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27102 */
27103 MixpanelPeople.prototype.append = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
27104 if (_.isObject(list_name)) {
27105 callback = value;
27106 }
27107 var data = this.append_action(list_name, value);
27108 return this._send_request(data, callback);
27109 });
27110
27111 /*
27112 * Remove a value from a list-valued people analytics property.
27113 *
27114 * ### Usage:
27115 *
27116 * mixpanel.people.remove('School', 'UCB');
27117 *
27118 * @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.
27119 * @param {*} [value] value Item to remove from the list
27120 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27121 */
27122 MixpanelPeople.prototype.remove = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
27123 if (_.isObject(list_name)) {
27124 callback = value;
27125 }
27126 var data = this.remove_action(list_name, value);
27127 return this._send_request(data, callback);
27128 });
27129
27130 /*
27131 * Merge a given list with a list-valued people analytics property,
27132 * excluding duplicate values.
27133 *
27134 * ### Usage:
27135 *
27136 * // merge a value to a list, creating it if needed
27137 * mixpanel.people.union('pages_visited', 'homepage');
27138 *
27139 * // like mixpanel.people.set(), you can append multiple
27140 * // properties at once:
27141 * mixpanel.people.union({
27142 * list1: 'bob',
27143 * list2: 123
27144 * });
27145 *
27146 * // like mixpanel.people.append(), you can append multiple
27147 * // values to the same list:
27148 * mixpanel.people.union({
27149 * list1: ['bob', 'billy']
27150 * });
27151 *
27152 * @param {Object|String} list_name If a string, this is the name of the property. If an object, this is an associative array of names and values.
27153 * @param {*} [value] Value / values to merge with the given property
27154 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27155 */
27156 MixpanelPeople.prototype.union = addOptOutCheckMixpanelPeople(function(list_name, values, callback) {
27157 if (_.isObject(list_name)) {
27158 callback = values;
27159 }
27160 var data = this.union_action(list_name, values);
27161 return this._send_request(data, callback);
27162 });
27163
27164 /*
27165 * Record that you have charged the current user a certain amount
27166 * of money. Charges recorded with track_charge() will appear in the
27167 * Mixpanel revenue report.
27168 *
27169 * ### Usage:
27170 *
27171 * // charge a user $50
27172 * mixpanel.people.track_charge(50);
27173 *
27174 * // charge a user $30.50 on the 2nd of january
27175 * mixpanel.people.track_charge(30.50, {
27176 * '$time': new Date('jan 1 2012')
27177 * });
27178 *
27179 * @param {Number} amount The amount of money charged to the current user
27180 * @param {Object} [properties] An associative array of properties associated with the charge
27181 * @param {Function} [callback] If provided, the callback will be called when the server responds
27182 * @deprecated
27183 */
27184 MixpanelPeople.prototype.track_charge = addOptOutCheckMixpanelPeople(function() {
27185 console$1.error('mixpanel.people.track_charge() is deprecated and no longer has any effect.');
27186 });
27187
27188 /*
27189 * Permanently clear all revenue report transactions from the
27190 * current user's people analytics profile.
27191 *
27192 * ### Usage:
27193 *
27194 * mixpanel.people.clear_charges();
27195 *
27196 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27197 * @deprecated
27198 */
27199 MixpanelPeople.prototype.clear_charges = function(callback) {
27200 return this.set('$transactions', [], callback);
27201 };
27202
27203 /*
27204 * Permanently deletes the current people analytics profile from
27205 * Mixpanel (using the current distinct_id).
27206 *
27207 * ### Usage:
27208 *
27209 * // remove the all data you have stored about the current user
27210 * mixpanel.people.delete_user();
27211 *
27212 */
27213 MixpanelPeople.prototype.delete_user = function() {
27214 if (!this._identify_called()) {
27215 console$1.error('mixpanel.people.delete_user() requires you to call identify() first');
27216 return;
27217 }
27218 var data = {'$delete': this._mixpanel.get_distinct_id()};
27219 return this._send_request(data);
27220 };
27221
27222 MixpanelPeople.prototype.toString = function() {
27223 return this._mixpanel.toString() + '.people';
27224 };
27225
27226 MixpanelPeople.prototype._send_request = function(data, callback) {
27227 data['$token'] = this._get_config('token');
27228 data['$distinct_id'] = this._mixpanel.get_distinct_id();
27229 var device_id = this._mixpanel.get_property('$device_id');
27230 var user_id = this._mixpanel.get_property('$user_id');
27231 var had_persisted_distinct_id = this._mixpanel.get_property('$had_persisted_distinct_id');
27232 if (device_id) {
27233 data['$device_id'] = device_id;
27234 }
27235 if (user_id) {
27236 data['$user_id'] = user_id;
27237 }
27238 if (had_persisted_distinct_id) {
27239 data['$had_persisted_distinct_id'] = had_persisted_distinct_id;
27240 }
27241
27242 var date_encoded_data = _.encodeDates(data);
27243
27244 if (!this._identify_called()) {
27245 this._enqueue(data);
27246 if (!_.isUndefined(callback)) {
27247 if (this._get_config('verbose')) {
27248 callback({status: -1, error: null});
27249 } else {
27250 callback(-1);
27251 }
27252 }
27253 return _.truncate(date_encoded_data, 255);
27254 }
27255
27256 return this._mixpanel._track_or_batch({
27257 type: 'people',
27258 data: date_encoded_data,
27259 endpoint: this._mixpanel.get_api_host('people') + '/' + this._get_config('api_routes')['engage'],
27260 batcher: this._mixpanel.request_batchers.people
27261 }, callback);
27262 };
27263
27264 MixpanelPeople.prototype._get_config = function(conf_var) {
27265 return this._mixpanel.get_config(conf_var);
27266 };
27267
27268 MixpanelPeople.prototype._identify_called = function() {
27269 return this._mixpanel._flags.identify_called === true;
27270 };
27271
27272 // Queue up engage operations if identify hasn't been called yet.
27273 MixpanelPeople.prototype._enqueue = function(data) {
27274 if (SET_ACTION in data) {
27275 this._mixpanel['persistence']._add_to_people_queue(SET_ACTION, data);
27276 } else if (SET_ONCE_ACTION in data) {
27277 this._mixpanel['persistence']._add_to_people_queue(SET_ONCE_ACTION, data);
27278 } else if (UNSET_ACTION in data) {
27279 this._mixpanel['persistence']._add_to_people_queue(UNSET_ACTION, data);
27280 } else if (ADD_ACTION in data) {
27281 this._mixpanel['persistence']._add_to_people_queue(ADD_ACTION, data);
27282 } else if (APPEND_ACTION in data) {
27283 this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, data);
27284 } else if (REMOVE_ACTION in data) {
27285 this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, data);
27286 } else if (UNION_ACTION in data) {
27287 this._mixpanel['persistence']._add_to_people_queue(UNION_ACTION, data);
27288 } else {
27289 console$1.error('Invalid call to _enqueue():', data);
27290 }
27291 };
27292
27293 MixpanelPeople.prototype._flush_one_queue = function(action, action_method, callback, queue_to_params_fn) {
27294 var _this = this;
27295 var queued_data = _.extend({}, this._mixpanel['persistence'].load_queue(action));
27296 var action_params = queued_data;
27297
27298 if (!_.isUndefined(queued_data) && _.isObject(queued_data) && !_.isEmptyObject(queued_data)) {
27299 _this._mixpanel['persistence']._pop_from_people_queue(action, queued_data);
27300 _this._mixpanel['persistence'].save();
27301 if (queue_to_params_fn) {
27302 action_params = queue_to_params_fn(queued_data);
27303 }
27304 action_method.call(_this, action_params, function(response, data) {
27305 // on bad response, we want to add it back to the queue
27306 if (response === 0) {
27307 _this._mixpanel['persistence']._add_to_people_queue(action, queued_data);
27308 }
27309 if (!_.isUndefined(callback)) {
27310 callback(response, data);
27311 }
27312 });
27313 }
27314 };
27315
27316 // Flush queued engage operations - order does not matter,
27317 // and there are network level race conditions anyway
27318 MixpanelPeople.prototype._flush = function(
27319 _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback
27320 ) {
27321 var _this = this;
27322
27323 this._flush_one_queue(SET_ACTION, this.set, _set_callback);
27324 this._flush_one_queue(SET_ONCE_ACTION, this.set_once, _set_once_callback);
27325 this._flush_one_queue(UNSET_ACTION, this.unset, _unset_callback, function(queue) { return _.keys(queue); });
27326 this._flush_one_queue(ADD_ACTION, this.increment, _add_callback);
27327 this._flush_one_queue(UNION_ACTION, this.union, _union_callback);
27328
27329 // we have to fire off each $append individually since there is
27330 // no concat method server side
27331 var $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);
27332 if (!_.isUndefined($append_queue) && _.isArray($append_queue) && $append_queue.length) {
27333 var $append_item;
27334 var append_callback = function(response, data) {
27335 if (response === 0) {
27336 _this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, $append_item);
27337 }
27338 if (!_.isUndefined(_append_callback)) {
27339 _append_callback(response, data);
27340 }
27341 };
27342 for (var i = $append_queue.length - 1; i >= 0; i--) {
27343 $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);
27344 $append_item = $append_queue.pop();
27345 _this._mixpanel['persistence'].save();
27346 if (!_.isEmptyObject($append_item)) {
27347 _this.append($append_item, append_callback);
27348 }
27349 }
27350 }
27351
27352 // same for $remove
27353 var $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);
27354 if (!_.isUndefined($remove_queue) && _.isArray($remove_queue) && $remove_queue.length) {
27355 var $remove_item;
27356 var remove_callback = function(response, data) {
27357 if (response === 0) {
27358 _this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, $remove_item);
27359 }
27360 if (!_.isUndefined(_remove_callback)) {
27361 _remove_callback(response, data);
27362 }
27363 };
27364 for (var j = $remove_queue.length - 1; j >= 0; j--) {
27365 $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);
27366 $remove_item = $remove_queue.pop();
27367 _this._mixpanel['persistence'].save();
27368 if (!_.isEmptyObject($remove_item)) {
27369 _this.remove($remove_item, remove_callback);
27370 }
27371 }
27372 }
27373 };
27374
27375 MixpanelPeople.prototype._is_reserved_property = function(prop) {
27376 return prop === '$distinct_id' || prop === '$token' || prop === '$device_id' || prop === '$user_id' || prop === '$had_persisted_distinct_id';
27377 };
27378
27379 // MixpanelPeople Exports
27380 MixpanelPeople.prototype['set'] = MixpanelPeople.prototype.set;
27381 MixpanelPeople.prototype['set_once'] = MixpanelPeople.prototype.set_once;
27382 MixpanelPeople.prototype['unset'] = MixpanelPeople.prototype.unset;
27383 MixpanelPeople.prototype['increment'] = MixpanelPeople.prototype.increment;
27384 MixpanelPeople.prototype['append'] = MixpanelPeople.prototype.append;
27385 MixpanelPeople.prototype['remove'] = MixpanelPeople.prototype.remove;
27386 MixpanelPeople.prototype['union'] = MixpanelPeople.prototype.union;
27387 MixpanelPeople.prototype['track_charge'] = MixpanelPeople.prototype.track_charge;
27388 MixpanelPeople.prototype['clear_charges'] = MixpanelPeople.prototype.clear_charges;
27389 MixpanelPeople.prototype['delete_user'] = MixpanelPeople.prototype.delete_user;
27390 MixpanelPeople.prototype['toString'] = MixpanelPeople.prototype.toString;
27391
27392 /* eslint camelcase: "off" */
27393
27394
27395 /*
27396 * Constants
27397 */
27398 /** @const */ var SET_QUEUE_KEY = '__mps';
27399 /** @const */ var SET_ONCE_QUEUE_KEY = '__mpso';
27400 /** @const */ var UNSET_QUEUE_KEY = '__mpus';
27401 /** @const */ var ADD_QUEUE_KEY = '__mpa';
27402 /** @const */ var APPEND_QUEUE_KEY = '__mpap';
27403 /** @const */ var REMOVE_QUEUE_KEY = '__mpr';
27404 /** @const */ var UNION_QUEUE_KEY = '__mpu';
27405 // This key is deprecated, but we want to check for it to see whether aliasing is allowed.
27406 /** @const */ var PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';
27407 /** @const */ var ALIAS_ID_KEY = '__alias';
27408 /** @const */ var EVENT_TIMERS_KEY = '__timers';
27409 /** @const */ var RESERVED_PROPERTIES = [
27410 SET_QUEUE_KEY,
27411 SET_ONCE_QUEUE_KEY,
27412 UNSET_QUEUE_KEY,
27413 ADD_QUEUE_KEY,
27414 APPEND_QUEUE_KEY,
27415 REMOVE_QUEUE_KEY,
27416 UNION_QUEUE_KEY,
27417 PEOPLE_DISTINCT_ID_KEY,
27418 ALIAS_ID_KEY,
27419 EVENT_TIMERS_KEY
27420 ];
27421
27422 /**
27423 * Mixpanel Persistence Object
27424 * @constructor
27425 */
27426 var MixpanelPersistence = function(config) {
27427 this['props'] = {};
27428 this.campaign_params_saved = false;
27429
27430 if (config['persistence_name']) {
27431 this.name = 'mp_' + config['persistence_name'];
27432 } else {
27433 this.name = 'mp_' + config['token'] + '_mixpanel';
27434 }
27435
27436 var storage_type = config['persistence'];
27437 if (storage_type !== 'cookie' && storage_type !== 'localStorage') {
27438 console$1.critical('Unknown persistence type ' + storage_type + '; falling back to cookie');
27439 storage_type = config['persistence'] = 'cookie';
27440 }
27441
27442 if (storage_type === 'localStorage' && _.localStorage.is_supported()) {
27443 this.storage = _.localStorage;
27444 } else {
27445 this.storage = _.cookie;
27446 }
27447
27448 this.load();
27449 this.update_config(config);
27450 this.upgrade();
27451 this.save();
27452 };
27453
27454 MixpanelPersistence.prototype.properties = function() {
27455 var p = {};
27456
27457 this.load();
27458
27459 // Filter out reserved properties
27460 _.each(this['props'], function(v, k) {
27461 if (!_.include(RESERVED_PROPERTIES, k)) {
27462 p[k] = v;
27463 }
27464 });
27465 return p;
27466 };
27467
27468 MixpanelPersistence.prototype.load = function() {
27469 if (this.disabled) { return; }
27470
27471 var entry = this.storage.parse(this.name);
27472
27473 if (entry) {
27474 this['props'] = _.extend({}, entry);
27475 }
27476 };
27477
27478 MixpanelPersistence.prototype.upgrade = function() {
27479 var old_cookie,
27480 old_localstorage;
27481
27482 // if transferring from cookie to localStorage or vice-versa, copy existing
27483 // super properties over to new storage mode
27484 if (this.storage === _.localStorage) {
27485 old_cookie = _.cookie.parse(this.name);
27486
27487 _.cookie.remove(this.name);
27488 _.cookie.remove(this.name, true);
27489
27490 if (old_cookie) {
27491 this.register_once(old_cookie);
27492 }
27493 } else if (this.storage === _.cookie) {
27494 old_localstorage = _.localStorage.parse(this.name);
27495
27496 _.localStorage.remove(this.name);
27497
27498 if (old_localstorage) {
27499 this.register_once(old_localstorage);
27500 }
27501 }
27502 };
27503
27504 MixpanelPersistence.prototype.save = function() {
27505 if (this.disabled) { return; }
27506
27507 this.storage.set(
27508 this.name,
27509 JSONStringify(this['props']),
27510 this.expire_days,
27511 this.cross_subdomain,
27512 this.secure,
27513 this.cross_site,
27514 this.cookie_domain
27515 );
27516 };
27517
27518 MixpanelPersistence.prototype.load_prop = function(key) {
27519 this.load();
27520 return this['props'][key];
27521 };
27522
27523 MixpanelPersistence.prototype.remove = function() {
27524 // remove both domain and subdomain cookies
27525 this.storage.remove(this.name, false, this.cookie_domain);
27526 this.storage.remove(this.name, true, this.cookie_domain);
27527 };
27528
27529 // removes the storage entry and deletes all loaded data
27530 // forced name for tests
27531 MixpanelPersistence.prototype.clear = function() {
27532 this.remove();
27533 this['props'] = {};
27534 };
27535
27536 /**
27537 * @param {Object} props
27538 * @param {*=} default_value
27539 * @param {number=} days
27540 */
27541 MixpanelPersistence.prototype.register_once = function(props, default_value, days) {
27542 if (_.isObject(props)) {
27543 if (typeof(default_value) === 'undefined') { default_value = 'None'; }
27544 this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
27545
27546 this.load();
27547
27548 _.each(props, function(val, prop) {
27549 if (!this['props'].hasOwnProperty(prop) || this['props'][prop] === default_value) {
27550 this['props'][prop] = val;
27551 }
27552 }, this);
27553
27554 this.save();
27555
27556 return true;
27557 }
27558 return false;
27559 };
27560
27561 /**
27562 * @param {Object} props
27563 * @param {number=} days
27564 */
27565 MixpanelPersistence.prototype.register = function(props, days) {
27566 if (_.isObject(props)) {
27567 this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
27568
27569 this.load();
27570 _.extend(this['props'], props);
27571 this.save();
27572
27573 return true;
27574 }
27575 return false;
27576 };
27577
27578 MixpanelPersistence.prototype.unregister = function(prop) {
27579 this.load();
27580 if (prop in this['props']) {
27581 delete this['props'][prop];
27582 this.save();
27583 }
27584 };
27585
27586 MixpanelPersistence.prototype.update_search_keyword = function(referrer) {
27587 this.register(_.info.searchInfo(referrer));
27588 };
27589
27590 // EXPORTED METHOD, we test this directly.
27591 MixpanelPersistence.prototype.update_referrer_info = function(referrer) {
27592 // If referrer doesn't exist, we want to note the fact that it was type-in traffic.
27593 this.register_once({
27594 '$initial_referrer': referrer || '$direct',
27595 '$initial_referring_domain': _.info.referringDomain(referrer) || '$direct'
27596 }, '');
27597 };
27598
27599 MixpanelPersistence.prototype.get_referrer_info = function() {
27600 return _.strip_empty_properties({
27601 '$initial_referrer': this['props']['$initial_referrer'],
27602 '$initial_referring_domain': this['props']['$initial_referring_domain']
27603 });
27604 };
27605
27606 MixpanelPersistence.prototype.update_config = function(config) {
27607 this.default_expiry = this.expire_days = config['cookie_expiration'];
27608 this.set_disabled(config['disable_persistence']);
27609 this.set_cookie_domain(config['cookie_domain']);
27610 this.set_cross_site(config['cross_site_cookie']);
27611 this.set_cross_subdomain(config['cross_subdomain_cookie']);
27612 this.set_secure(config['secure_cookie']);
27613 };
27614
27615 MixpanelPersistence.prototype.set_disabled = function(disabled) {
27616 this.disabled = disabled;
27617 if (this.disabled) {
27618 this.remove();
27619 } else {
27620 this.save();
27621 }
27622 };
27623
27624 MixpanelPersistence.prototype.set_cookie_domain = function(cookie_domain) {
27625 if (cookie_domain !== this.cookie_domain) {
27626 this.remove();
27627 this.cookie_domain = cookie_domain;
27628 this.save();
27629 }
27630 };
27631
27632 MixpanelPersistence.prototype.set_cross_site = function(cross_site) {
27633 if (cross_site !== this.cross_site) {
27634 this.cross_site = cross_site;
27635 this.remove();
27636 this.save();
27637 }
27638 };
27639
27640 MixpanelPersistence.prototype.set_cross_subdomain = function(cross_subdomain) {
27641 if (cross_subdomain !== this.cross_subdomain) {
27642 this.cross_subdomain = cross_subdomain;
27643 this.remove();
27644 this.save();
27645 }
27646 };
27647
27648 MixpanelPersistence.prototype.get_cross_subdomain = function() {
27649 return this.cross_subdomain;
27650 };
27651
27652 MixpanelPersistence.prototype.set_secure = function(secure) {
27653 if (secure !== this.secure) {
27654 this.secure = secure ? true : false;
27655 this.remove();
27656 this.save();
27657 }
27658 };
27659
27660 MixpanelPersistence.prototype._add_to_people_queue = function(queue, data) {
27661 var q_key = this._get_queue_key(queue),
27662 q_data = data[queue],
27663 set_q = this._get_or_create_queue(SET_ACTION),
27664 set_once_q = this._get_or_create_queue(SET_ONCE_ACTION),
27665 unset_q = this._get_or_create_queue(UNSET_ACTION),
27666 add_q = this._get_or_create_queue(ADD_ACTION),
27667 union_q = this._get_or_create_queue(UNION_ACTION),
27668 remove_q = this._get_or_create_queue(REMOVE_ACTION, []),
27669 append_q = this._get_or_create_queue(APPEND_ACTION, []);
27670
27671 if (q_key === SET_QUEUE_KEY) {
27672 // Update the set queue - we can override any existing values
27673 _.extend(set_q, q_data);
27674 // if there was a pending increment, override it
27675 // with the set.
27676 this._pop_from_people_queue(ADD_ACTION, q_data);
27677 // if there was a pending union, override it
27678 // with the set.
27679 this._pop_from_people_queue(UNION_ACTION, q_data);
27680 this._pop_from_people_queue(UNSET_ACTION, q_data);
27681 } else if (q_key === SET_ONCE_QUEUE_KEY) {
27682 // only queue the data if there is not already a set_once call for it.
27683 _.each(q_data, function(v, k) {
27684 if (!(k in set_once_q)) {
27685 set_once_q[k] = v;
27686 }
27687 });
27688 this._pop_from_people_queue(UNSET_ACTION, q_data);
27689 } else if (q_key === UNSET_QUEUE_KEY) {
27690 _.each(q_data, function(prop) {
27691
27692 // undo previously-queued actions on this key
27693 _.each([set_q, set_once_q, add_q, union_q], function(enqueued_obj) {
27694 if (prop in enqueued_obj) {
27695 delete enqueued_obj[prop];
27696 }
27697 });
27698 _.each(append_q, function(append_obj) {
27699 if (prop in append_obj) {
27700 delete append_obj[prop];
27701 }
27702 });
27703
27704 unset_q[prop] = true;
27705
27706 });
27707 } else if (q_key === ADD_QUEUE_KEY) {
27708 _.each(q_data, function(v, k) {
27709 // If it exists in the set queue, increment
27710 // the value
27711 if (k in set_q) {
27712 set_q[k] += v;
27713 } else {
27714 // If it doesn't exist, update the add
27715 // queue
27716 if (!(k in add_q)) {
27717 add_q[k] = 0;
27718 }
27719 add_q[k] += v;
27720 }
27721 }, this);
27722 this._pop_from_people_queue(UNSET_ACTION, q_data);
27723 } else if (q_key === UNION_QUEUE_KEY) {
27724 _.each(q_data, function(v, k) {
27725 if (_.isArray(v)) {
27726 if (!(k in union_q)) {
27727 union_q[k] = [];
27728 }
27729 // Prevent duplicate values
27730 _.each(v, function(item) {
27731 if (!_.include(union_q[k], item)) {
27732 union_q[k].push(item);
27733 }
27734 });
27735 }
27736 });
27737 this._pop_from_people_queue(UNSET_ACTION, q_data);
27738 } else if (q_key === REMOVE_QUEUE_KEY) {
27739 remove_q.push(q_data);
27740 this._pop_from_people_queue(APPEND_ACTION, q_data);
27741 } else if (q_key === APPEND_QUEUE_KEY) {
27742 append_q.push(q_data);
27743 this._pop_from_people_queue(UNSET_ACTION, q_data);
27744 }
27745
27746 console$1.log('MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):');
27747 console$1.log(data);
27748
27749 this.save();
27750 };
27751
27752 MixpanelPersistence.prototype._pop_from_people_queue = function(queue, data) {
27753 var q = this['props'][this._get_queue_key(queue)];
27754 if (!_.isUndefined(q)) {
27755 _.each(data, function(v, k) {
27756 if (queue === APPEND_ACTION || queue === REMOVE_ACTION) {
27757 // list actions: only remove if both k+v match
27758 // e.g. remove should not override append in a case like
27759 // append({foo: 'bar'}); remove({foo: 'qux'})
27760 _.each(q, function(queued_action) {
27761 if (queued_action[k] === v) {
27762 delete queued_action[k];
27763 }
27764 });
27765 } else {
27766 delete q[k];
27767 }
27768 }, this);
27769 }
27770 };
27771
27772 MixpanelPersistence.prototype.load_queue = function(queue) {
27773 return this.load_prop(this._get_queue_key(queue));
27774 };
27775
27776 MixpanelPersistence.prototype._get_queue_key = function(queue) {
27777 if (queue === SET_ACTION) {
27778 return SET_QUEUE_KEY;
27779 } else if (queue === SET_ONCE_ACTION) {
27780 return SET_ONCE_QUEUE_KEY;
27781 } else if (queue === UNSET_ACTION) {
27782 return UNSET_QUEUE_KEY;
27783 } else if (queue === ADD_ACTION) {
27784 return ADD_QUEUE_KEY;
27785 } else if (queue === APPEND_ACTION) {
27786 return APPEND_QUEUE_KEY;
27787 } else if (queue === REMOVE_ACTION) {
27788 return REMOVE_QUEUE_KEY;
27789 } else if (queue === UNION_ACTION) {
27790 return UNION_QUEUE_KEY;
27791 } else {
27792 console$1.error('Invalid queue:', queue);
27793 }
27794 };
27795
27796 MixpanelPersistence.prototype._get_or_create_queue = function(queue, default_val) {
27797 var key = this._get_queue_key(queue);
27798 default_val = _.isUndefined(default_val) ? {} : default_val;
27799 return this['props'][key] || (this['props'][key] = default_val);
27800 };
27801
27802 MixpanelPersistence.prototype.set_event_timer = function(event_name, timestamp) {
27803 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
27804 timers[event_name] = timestamp;
27805 this['props'][EVENT_TIMERS_KEY] = timers;
27806 this.save();
27807 };
27808
27809 MixpanelPersistence.prototype.remove_event_timer = function(event_name) {
27810 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
27811 var timestamp = timers[event_name];
27812 if (!_.isUndefined(timestamp)) {
27813 delete this['props'][EVENT_TIMERS_KEY][event_name];
27814 this.save();
27815 }
27816 return timestamp;
27817 };
27818
27819 /* eslint camelcase: "off" */
27820
27821 /*
27822 * Mixpanel JS Library
27823 *
27824 * Copyright 2012, Mixpanel, Inc. All Rights Reserved
27825 * http://mixpanel.com/
27826 *
27827 * Includes portions of Underscore.js
27828 * http://documentcloud.github.com/underscore/
27829 * (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
27830 * Released under the MIT License.
27831 */
27832
27833 /*
27834 SIMPLE STYLE GUIDE:
27835
27836 this.x === public function
27837 this._x === internal - only use within this file
27838 this.__x === private - only use within the class
27839
27840 Globals should be all caps
27841 */
27842
27843 var init_type; // MODULE or SNIPPET loader
27844 // allow bundlers to specify how extra code (recorder bundle) should be loaded
27845 // eslint-disable-next-line no-unused-vars
27846 var load_extra_bundle = function(src, _onload) {
27847 throw new Error(src + ' not available in this build.');
27848 };
27849
27850 var mixpanel_master; // main mixpanel instance / object
27851 var INIT_MODULE = 0;
27852 var INIT_SNIPPET = 1;
27853
27854 var IDENTITY_FUNC = function(x) {return x;};
27855
27856 /** @const */ var PRIMARY_INSTANCE_NAME = 'mixpanel';
27857 /** @const */ var PAYLOAD_TYPE_BASE64 = 'base64';
27858 /** @const */ var PAYLOAD_TYPE_JSON = 'json';
27859 /** @const */ var DEVICE_ID_PREFIX = '$device:';
27860
27861
27862 /*
27863 * Dynamic... constants? Is that an oxymoron?
27864 */
27865 // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
27866 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
27867 var USE_XHR = (win.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest());
27868
27869 // IE<10 does not support cross-origin XHR's but script tags
27870 // with defer won't block window.onload; ENQUEUE_REQUESTS
27871 // should only be true for Opera<12
27872 var ENQUEUE_REQUESTS = !USE_XHR && (userAgent.indexOf('MSIE') === -1) && (userAgent.indexOf('Mozilla') === -1);
27873
27874 // save reference to navigator.sendBeacon so it can be minified
27875 var sendBeacon = null;
27876 if (navigator['sendBeacon']) {
27877 sendBeacon = function() {
27878 // late reference to navigator.sendBeacon to allow patching/spying
27879 return navigator['sendBeacon'].apply(navigator, arguments);
27880 };
27881 }
27882
27883 var DEFAULT_API_ROUTES = {
27884 'track': 'track/',
27885 'engage': 'engage/',
27886 'groups': 'groups/',
27887 'record': 'record/',
27888 'flags': 'flags/'
27889 };
27890
27891 /*
27892 * Module-level globals
27893 */
27894 var DEFAULT_CONFIG = {
27895 'api_host': 'https://api-js.mixpanel.com',
27896 'api_hosts': {},
27897 'api_routes': DEFAULT_API_ROUTES,
27898 'api_extra_query_params': {},
27899 'api_method': 'POST',
27900 'api_transport': 'XHR',
27901 'api_payload_format': PAYLOAD_TYPE_BASE64,
27902 'app_host': 'https://mixpanel.com',
27903 'autocapture': false,
27904 'cdn': 'https://cdn.mxpnl.com',
27905 'cross_site_cookie': false,
27906 'cross_subdomain_cookie': true,
27907 'error_reporter': NOOP_FUNC,
27908 'flags': false,
27909 'persistence': 'cookie',
27910 'persistence_name': '',
27911 'cookie_domain': '',
27912 'cookie_name': '',
27913 'loaded': NOOP_FUNC,
27914 'mp_loader': null,
27915 'track_marketing': true,
27916 'track_pageview': false,
27917 'skip_first_touch_marketing': false,
27918 'store_google': true,
27919 'stop_utm_persistence': false,
27920 'save_referrer': true,
27921 'test': false,
27922 'verbose': false,
27923 'img': false,
27924 'debug': false,
27925 'track_links_timeout': 300,
27926 'cookie_expiration': 365,
27927 'upgrade': false,
27928 'disable_persistence': false,
27929 'disable_cookie': false,
27930 'secure_cookie': false,
27931 'ip': true,
27932 'opt_out_tracking_by_default': false,
27933 'opt_out_persistence_by_default': false,
27934 'opt_out_tracking_persistence_type': 'localStorage',
27935 'opt_out_tracking_cookie_prefix': null,
27936 'property_blacklist': [],
27937 'xhr_headers': {}, // { header: value, header2: value }
27938 'ignore_dnt': false,
27939 'batch_requests': true,
27940 'batch_size': 50,
27941 'batch_flush_interval_ms': 5000,
27942 'batch_request_timeout_ms': 90000,
27943 'batch_autostart': true,
27944 'hooks': {},
27945 'record_block_class': new RegExp('^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$'),
27946 'record_block_selector': 'img, video, audio',
27947 'record_canvas': false,
27948 'record_collect_fonts': false,
27949 'record_heatmap_data': false,
27950 'record_idle_timeout_ms': 30 * 60 * 1000, // 30 minutes
27951 'record_mask_text_class': new RegExp('^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$'),
27952 'record_mask_text_selector': '*',
27953 'record_max_ms': MAX_RECORDING_MS,
27954 'record_min_ms': 0,
27955 'record_sessions_percent': 0,
27956 'recorder_src': 'https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js'
27957 };
27958
27959 var DOM_LOADED = false;
27960
27961 /**
27962 * Mixpanel Library Object
27963 * @constructor
27964 */
27965 var MixpanelLib = function() {};
27966
27967
27968 /**
27969 * create_mplib(token:string, config:object, name:string)
27970 *
27971 * This function is used by the init method of MixpanelLib objects
27972 * as well as the main initializer at the end of the JSLib (that
27973 * initializes document.mixpanel as well as any additional instances
27974 * declared before this file has loaded).
27975 */
27976 var create_mplib = function(token, config, name) {
27977 var instance,
27978 target = (name === PRIMARY_INSTANCE_NAME) ? mixpanel_master : mixpanel_master[name];
27979
27980 if (target && init_type === INIT_MODULE) {
27981 instance = target;
27982 } else {
27983 if (target && !_.isArray(target)) {
27984 console$1.error('You have already initialized ' + name);
27985 return;
27986 }
27987 instance = new MixpanelLib();
27988 }
27989
27990 instance._cached_groups = {}; // cache groups in a pool
27991
27992 instance._init(token, config, name);
27993
27994 instance['people'] = new MixpanelPeople();
27995 instance['people']._init(instance);
27996
27997 if (!instance.get_config('skip_first_touch_marketing')) {
27998 // We need null UTM params in the object because
27999 // UTM parameters act as a tuple. If any UTM param
28000 // is present, then we set all UTM params including
28001 // empty ones together
28002 var utm_params = _.info.campaignParams(null);
28003 var initial_utm_params = {};
28004 var has_utm = false;
28005 _.each(utm_params, function(utm_value, utm_key) {
28006 initial_utm_params['initial_' + utm_key] = utm_value;
28007 if (utm_value) {
28008 has_utm = true;
28009 }
28010 });
28011 if (has_utm) {
28012 instance['people'].set_once(initial_utm_params);
28013 }
28014 }
28015
28016 // if any instance on the page has debug = true, we set the
28017 // global debug to be true
28018 Config.DEBUG = Config.DEBUG || instance.get_config('debug');
28019
28020 // if target is not defined, we called init after the lib already
28021 // loaded, so there won't be an array of things to execute
28022 if (!_.isUndefined(target) && _.isArray(target)) {
28023 // Crunch through the people queue first - we queue this data up &
28024 // flush on identify, so it's better to do all these operations first
28025 instance._execute_array.call(instance['people'], target['people']);
28026 instance._execute_array(target);
28027 }
28028
28029 return instance;
28030 };
28031
28032 // Initialization methods
28033
28034 /**
28035 * This function initializes a new instance of the Mixpanel tracking object.
28036 * All new instances are added to the main mixpanel object as sub properties (such as
28037 * mixpanel.library_name) and also returned by this function. To define a
28038 * second instance on the page, you would call:
28039 *
28040 * mixpanel.init('new token', { your: 'config' }, 'library_name');
28041 *
28042 * and use it like so:
28043 *
28044 * mixpanel.library_name.track(...);
28045 *
28046 * @param {String} token Your Mixpanel API token
28047 * @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>.
28048 * @param {String} [name] The name for the new mixpanel instance that you want created
28049 */
28050 MixpanelLib.prototype.init = function (token, config, name) {
28051 if (_.isUndefined(name)) {
28052 this.report_error('You must name your new library: init(token, config, name)');
28053 return;
28054 }
28055 if (name === PRIMARY_INSTANCE_NAME) {
28056 this.report_error('You must initialize the main mixpanel object right after you include the Mixpanel js snippet');
28057 return;
28058 }
28059
28060 var instance = create_mplib(token, config, name);
28061 mixpanel_master[name] = instance;
28062 instance._loaded();
28063
28064 return instance;
28065 };
28066
28067 // mixpanel._init(token:string, config:object, name:string)
28068 //
28069 // This function sets up the current instance of the mixpanel
28070 // library. The difference between this method and the init(...)
28071 // method is this one initializes the actual instance, whereas the
28072 // init(...) method sets up a new library and calls _init on it.
28073 //
28074 MixpanelLib.prototype._init = function(token, config, name) {
28075 config = config || {};
28076
28077 this['__loaded'] = true;
28078 this['config'] = {};
28079
28080 var variable_features = {};
28081
28082 // default to JSON payload for standard mixpanel.com API hosts
28083 if (!('api_payload_format' in config)) {
28084 var api_host = config['api_host'] || DEFAULT_CONFIG['api_host'];
28085 if (api_host.match(/\.mixpanel\.com/)) {
28086 variable_features['api_payload_format'] = PAYLOAD_TYPE_JSON;
28087 }
28088 }
28089
28090 this.set_config(_.extend({}, DEFAULT_CONFIG, variable_features, config, {
28091 'name': name,
28092 'token': token,
28093 'callback_fn': ((name === PRIMARY_INSTANCE_NAME) ? name : PRIMARY_INSTANCE_NAME + '.' + name) + '._jsc'
28094 }));
28095
28096 this['_jsc'] = NOOP_FUNC;
28097
28098 this.__dom_loaded_queue = [];
28099 this.__request_queue = [];
28100 this.__disabled_events = [];
28101 this._flags = {
28102 'disable_all_events': false,
28103 'identify_called': false
28104 };
28105
28106 // set up request queueing/batching
28107 this.request_batchers = {};
28108 this._batch_requests = this.get_config('batch_requests');
28109 if (this._batch_requests) {
28110 if (!_.localStorage.is_supported(true) || !USE_XHR) {
28111 this._batch_requests = false;
28112 console$1.log('Turning off Mixpanel request-queueing; needs XHR and localStorage support');
28113 _.each(this.get_batcher_configs(), function(batcher_config) {
28114 console$1.log('Clearing batch queue ' + batcher_config.queue_key);
28115 _.localStorage.remove(batcher_config.queue_key);
28116 });
28117 } else {
28118 this.init_batchers();
28119 if (sendBeacon && win.addEventListener) {
28120 // Before page closes or hides (user tabs away etc), attempt to flush any events
28121 // queued up via navigator.sendBeacon. Since sendBeacon doesn't report success/failure,
28122 // events will not be removed from the persistent store; if the site is loaded again,
28123 // the events will be flushed again on startup and deduplicated on the Mixpanel server
28124 // side.
28125 // There is no reliable way to capture only page close events, so we lean on the
28126 // visibilitychange and pagehide events as recommended at
28127 // https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event#usage_notes.
28128 // These events fire when the user clicks away from the current page/tab, so will occur
28129 // more frequently than page unload, but are the only mechanism currently for capturing
28130 // this scenario somewhat reliably.
28131 var flush_on_unload = _.bind(function() {
28132 if (!this.request_batchers.events.stopped) {
28133 this.request_batchers.events.flush({unloading: true});
28134 }
28135 }, this);
28136 win.addEventListener('pagehide', function(ev) {
28137 if (ev['persisted']) {
28138 flush_on_unload();
28139 }
28140 });
28141 win.addEventListener('visibilitychange', function() {
28142 if (document$1['visibilityState'] === 'hidden') {
28143 flush_on_unload();
28144 }
28145 });
28146 }
28147 }
28148 }
28149
28150 this['persistence'] = this['cookie'] = new MixpanelPersistence(this['config']);
28151 this.unpersisted_superprops = {};
28152 this._gdpr_init();
28153
28154 var uuid = _.UUID();
28155 if (!this.get_distinct_id()) {
28156 // There is no need to set the distinct id
28157 // or the device id if something was already stored
28158 // in the persitence
28159 this.register_once({
28160 'distinct_id': DEVICE_ID_PREFIX + uuid,
28161 '$device_id': uuid
28162 }, '');
28163 }
28164
28165 this.flags = new FeatureFlagManager({
28166 getFullApiRoute: _.bind(function() {
28167 return this.get_api_host('flags') + '/' + this.get_config('api_routes')['flags'];
28168 }, this),
28169 getConfigFunc: _.bind(this.get_config, this),
28170 setConfigFunc: _.bind(this.set_config, this),
28171 getPropertyFunc: _.bind(this.get_property, this),
28172 trackingFunc: _.bind(this.track, this)
28173 });
28174 this.flags.init();
28175 this['flags'] = this.flags;
28176
28177 this.autocapture = new Autocapture(this);
28178 this.autocapture.init();
28179
28180 this._init_tab_id();
28181 this._check_and_start_session_recording();
28182 };
28183
28184 /**
28185 * Assigns a unique UUID to this tab / window by leveraging sessionStorage.
28186 * This is primarily used for session recording, where data must be isolated to the current tab.
28187 */
28188 MixpanelLib.prototype._init_tab_id = function() {
28189 if (this.get_config('disable_persistence')) {
28190 console$1.log('Tab ID initialization skipped due to disable_persistence config');
28191 } else if (_.sessionStorage.is_supported()) {
28192 try {
28193 var key_suffix = this.get_config('name') + '_' + this.get_config('token');
28194 var tab_id_key = 'mp_tab_id_' + key_suffix;
28195
28196 // A flag is used to determine if sessionStorage is copied over and we need to generate a new tab ID.
28197 // This enforces a unique ID in the cases like duplicated tab, window.open(...)
28198 var should_generate_new_tab_id_key = 'mp_gen_new_tab_id_' + key_suffix;
28199 if (_.sessionStorage.get(should_generate_new_tab_id_key) || !_.sessionStorage.get(tab_id_key)) {
28200 _.sessionStorage.set(tab_id_key, '$tab-' + _.UUID());
28201 }
28202
28203 _.sessionStorage.set(should_generate_new_tab_id_key, '1');
28204 this.tab_id = _.sessionStorage.get(tab_id_key);
28205
28206 // Remove the flag when the tab is unloaded to indicate the stored tab ID can be reused. This event is not reliable to detect all page unloads,
28207 // but reliable in cases where the user remains in the tab e.g. a refresh or href navigation.
28208 // If the flag is absent, this indicates to the next SDK instance that we can reuse the stored tab_id.
28209 win.addEventListener('beforeunload', function () {
28210 _.sessionStorage.remove(should_generate_new_tab_id_key);
28211 });
28212 } catch(err) {
28213 this.report_error('Error initializing tab id', err);
28214 }
28215 } else {
28216 this.report_error('Session storage is not supported, cannot keep track of unique tab ID.');
28217 }
28218 };
28219
28220 MixpanelLib.prototype.get_tab_id = function () {
28221 return this.tab_id || null;
28222 };
28223
28224 MixpanelLib.prototype._should_load_recorder = function () {
28225 if (this.get_config('disable_persistence')) {
28226 console$1.log('Load recorder check skipped due to disable_persistence config');
28227 return Promise.resolve(false);
28228 }
28229
28230 var recording_registry_idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
28231 var tab_id = this.get_tab_id();
28232 return recording_registry_idb.init()
28233 .then(function () {
28234 return recording_registry_idb.getAll();
28235 })
28236 .then(function (recordings) {
28237 for (var i = 0; i < recordings.length; i++) {
28238 // if there are expired recordings in the registry, we should load the recorder to flush them
28239 // if there's a recording for this tab id, we should load the recorder to continue the recording
28240 if (isRecordingExpired(recordings[i]) || recordings[i]['tabId'] === tab_id) {
28241 return true;
28242 }
28243 }
28244 return false;
28245 })
28246 .catch(_.bind(function (err) {
28247 this.report_error('Error checking recording registry', err);
28248 }, this));
28249 };
28250
28251 MixpanelLib.prototype._check_and_start_session_recording = addOptOutCheckMixpanelLib(function(force_start) {
28252 if (!win['MutationObserver']) {
28253 console$1.critical('Browser does not support MutationObserver; skipping session recording');
28254 return;
28255 }
28256
28257 var loadRecorder = _.bind(function(startNewIfInactive) {
28258 var handleLoadedRecorder = _.bind(function() {
28259 this._recorder = this._recorder || new win['__mp_recorder'](this);
28260 this._recorder['resumeRecording'](startNewIfInactive);
28261 }, this);
28262
28263 if (_.isUndefined(win['__mp_recorder'])) {
28264 load_extra_bundle(this.get_config('recorder_src'), handleLoadedRecorder);
28265 } else {
28266 handleLoadedRecorder();
28267 }
28268 }, this);
28269
28270 /**
28271 * If the user is sampled or start_session_recording is called, we always load the recorder since it's guaranteed a recording should start.
28272 * 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.
28273 */
28274 var is_sampled = this.get_config('record_sessions_percent') > 0 && Math.random() * 100 <= this.get_config('record_sessions_percent');
28275 if (force_start || is_sampled) {
28276 loadRecorder(true);
28277 } else {
28278 this._should_load_recorder()
28279 .then(function (shouldLoad) {
28280 if (shouldLoad) {
28281 loadRecorder(false);
28282 }
28283 });
28284 }
28285 });
28286
28287 MixpanelLib.prototype.start_session_recording = function () {
28288 this._check_and_start_session_recording(true);
28289 };
28290
28291 MixpanelLib.prototype.stop_session_recording = function () {
28292 if (this._recorder) {
28293 return this._recorder['stopRecording']();
28294 }
28295 return Promise.resolve();
28296 };
28297
28298 MixpanelLib.prototype.pause_session_recording = function () {
28299 if (this._recorder) {
28300 return this._recorder['pauseRecording']();
28301 }
28302 return Promise.resolve();
28303 };
28304
28305 MixpanelLib.prototype.resume_session_recording = function () {
28306 if (this._recorder) {
28307 return this._recorder['resumeRecording']();
28308 }
28309 return Promise.resolve();
28310 };
28311
28312 MixpanelLib.prototype.is_recording_heatmap_data = function () {
28313 return this._get_session_replay_id() && this.get_config('record_heatmap_data');
28314 };
28315
28316 MixpanelLib.prototype.get_session_recording_properties = function () {
28317 var props = {};
28318 var replay_id = this._get_session_replay_id();
28319 if (replay_id) {
28320 props['$mp_replay_id'] = replay_id;
28321 }
28322 return props;
28323 };
28324
28325 MixpanelLib.prototype.get_session_replay_url = function () {
28326 var replay_url = null;
28327 var replay_id = this._get_session_replay_id();
28328 if (replay_id) {
28329 var query_params = _.HTTPBuildQuery({
28330 'replay_id': replay_id,
28331 'distinct_id': this.get_distinct_id(),
28332 'token': this.get_config('token')
28333 });
28334 replay_url = 'https://mixpanel.com/projects/replay-redirect?' + query_params;
28335 }
28336 return replay_url;
28337 };
28338
28339 MixpanelLib.prototype._get_session_replay_id = function () {
28340 var replay_id = null;
28341 if (this._recorder) {
28342 replay_id = this._recorder['replayId'];
28343 }
28344 return replay_id || null;
28345 };
28346
28347 // "private" public method to reach into the recorder in test cases
28348 MixpanelLib.prototype.__get_recorder = function () {
28349 return this._recorder;
28350 };
28351
28352 // Private methods
28353
28354 MixpanelLib.prototype._loaded = function() {
28355 this.get_config('loaded')(this);
28356 this._set_default_superprops();
28357 this['people'].set_once(this['persistence'].get_referrer_info());
28358
28359 // `store_google` is now deprecated and previously stored UTM parameters are cleared
28360 // from persistence by default.
28361 if (this.get_config('store_google') && this.get_config('stop_utm_persistence')) {
28362 var utm_params = _.info.campaignParams(null);
28363 _.each(utm_params, function(_utm_value, utm_key) {
28364 // We need to unregister persisted UTM parameters so old values
28365 // are not mixed with the new UTM parameters
28366 this.unregister(utm_key);
28367 }.bind(this));
28368 }
28369 };
28370
28371 // update persistence with info on referrer, UTM params, etc
28372 MixpanelLib.prototype._set_default_superprops = function() {
28373 this['persistence'].update_search_keyword(document$1.referrer);
28374 // Registering super properties for UTM persistence by 'store_google' is deprecated.
28375 if (this.get_config('store_google') && !this.get_config('stop_utm_persistence')) {
28376 this.register(_.info.campaignParams());
28377 }
28378 if (this.get_config('save_referrer')) {
28379 this['persistence'].update_referrer_info(document$1.referrer);
28380 }
28381 };
28382
28383 MixpanelLib.prototype._dom_loaded = function() {
28384 _.each(this.__dom_loaded_queue, function(item) {
28385 this._track_dom.apply(this, item);
28386 }, this);
28387
28388 if (!this.has_opted_out_tracking()) {
28389 _.each(this.__request_queue, function(item) {
28390 this._send_request.apply(this, item);
28391 }, this);
28392 }
28393
28394 delete this.__dom_loaded_queue;
28395 delete this.__request_queue;
28396 };
28397
28398 MixpanelLib.prototype._track_dom = function(DomClass, args) {
28399 if (this.get_config('img')) {
28400 this.report_error('You can\'t use DOM tracking functions with img = true.');
28401 return false;
28402 }
28403
28404 if (!DOM_LOADED) {
28405 this.__dom_loaded_queue.push([DomClass, args]);
28406 return false;
28407 }
28408
28409 var dt = new DomClass().init(this);
28410 return dt.track.apply(dt, args);
28411 };
28412
28413 /**
28414 * _prepare_callback() should be called by callers of _send_request for use
28415 * as the callback argument.
28416 *
28417 * If there is no callback, this returns null.
28418 * If we are going to make XHR/XDR requests, this returns a function.
28419 * If we are going to use script tags, this returns a string to use as the
28420 * callback GET param.
28421 */
28422 MixpanelLib.prototype._prepare_callback = function(callback, data) {
28423 if (_.isUndefined(callback)) {
28424 return null;
28425 }
28426
28427 if (USE_XHR) {
28428 var callback_function = function(response) {
28429 callback(response, data);
28430 };
28431 return callback_function;
28432 } else {
28433 // if the user gives us a callback, we store as a random
28434 // property on this instances jsc function and update our
28435 // callback string to reflect that.
28436 var jsc = this['_jsc'];
28437 var randomized_cb = '' + Math.floor(Math.random() * 100000000);
28438 var callback_string = this.get_config('callback_fn') + '[' + randomized_cb + ']';
28439 jsc[randomized_cb] = function(response) {
28440 delete jsc[randomized_cb];
28441 callback(response, data);
28442 };
28443 return callback_string;
28444 }
28445 };
28446
28447 MixpanelLib.prototype._send_request = function(url, data, options, callback) {
28448 var succeeded = true;
28449
28450 if (ENQUEUE_REQUESTS) {
28451 this.__request_queue.push(arguments);
28452 return succeeded;
28453 }
28454
28455 var DEFAULT_OPTIONS = {
28456 method: this.get_config('api_method'),
28457 transport: this.get_config('api_transport'),
28458 verbose: this.get_config('verbose')
28459 };
28460 var body_data = null;
28461
28462 if (!callback && (_.isFunction(options) || typeof options === 'string')) {
28463 callback = options;
28464 options = null;
28465 }
28466 options = _.extend(DEFAULT_OPTIONS, options || {});
28467 if (!USE_XHR) {
28468 options.method = 'GET';
28469 }
28470 var use_post = options.method === 'POST';
28471 var use_sendBeacon = sendBeacon && use_post && options.transport.toLowerCase() === 'sendbeacon';
28472
28473 // needed to correctly format responses
28474 var verbose_mode = options.verbose;
28475 if (data['verbose']) { verbose_mode = true; }
28476
28477 if (this.get_config('test')) { data['test'] = 1; }
28478 if (verbose_mode) { data['verbose'] = 1; }
28479 if (this.get_config('img')) { data['img'] = 1; }
28480 if (!USE_XHR) {
28481 if (callback) {
28482 data['callback'] = callback;
28483 } else if (verbose_mode || this.get_config('test')) {
28484 // Verbose output (from verbose mode, or an error in test mode) is a json blob,
28485 // which by itself is not valid javascript. Without a callback, this verbose output will
28486 // cause an error when returned via jsonp, so we force a no-op callback param.
28487 // See the ECMA script spec: http://www.ecma-international.org/ecma-262/5.1/#sec-12.4
28488 data['callback'] = '(function(){})';
28489 }
28490 }
28491
28492 data['ip'] = this.get_config('ip')?1:0;
28493 data['_'] = new Date().getTime().toString();
28494
28495 if (use_post) {
28496 body_data = 'data=' + encodeURIComponent(data['data']);
28497 delete data['data'];
28498 }
28499
28500 _.extend(data, this.get_config('api_extra_query_params'));
28501
28502 url += '?' + _.HTTPBuildQuery(data);
28503
28504 var lib = this;
28505 if ('img' in data) {
28506 var img = document$1.createElement('img');
28507 img.src = url;
28508 document$1.body.appendChild(img);
28509 } else if (use_sendBeacon) {
28510 try {
28511 succeeded = sendBeacon(url, body_data);
28512 } catch (e) {
28513 lib.report_error(e);
28514 succeeded = false;
28515 }
28516 try {
28517 if (callback) {
28518 callback(succeeded ? 1 : 0);
28519 }
28520 } catch (e) {
28521 lib.report_error(e);
28522 }
28523 } else if (USE_XHR) {
28524 try {
28525 var req = new XMLHttpRequest();
28526 req.open(options.method, url, true);
28527
28528 var headers = this.get_config('xhr_headers');
28529 if (use_post) {
28530 headers['Content-Type'] = 'application/x-www-form-urlencoded';
28531 }
28532 _.each(headers, function(headerValue, headerName) {
28533 req.setRequestHeader(headerName, headerValue);
28534 });
28535
28536 if (options.timeout_ms && typeof req.timeout !== 'undefined') {
28537 req.timeout = options.timeout_ms;
28538 var start_time = new Date().getTime();
28539 }
28540
28541 // send the mp_optout cookie
28542 // withCredentials cannot be modified until after calling .open on Android and Mobile Safari
28543 req.withCredentials = true;
28544 req.onreadystatechange = function () {
28545 if (req.readyState === 4) { // XMLHttpRequest.DONE == 4, except in safari 4
28546 if (req.status === 200) {
28547 if (callback) {
28548 if (verbose_mode) {
28549 var response;
28550 try {
28551 response = _.JSONDecode(req.responseText);
28552 } catch (e) {
28553 lib.report_error(e);
28554 if (options.ignore_json_errors) {
28555 response = req.responseText;
28556 } else {
28557 return;
28558 }
28559 }
28560 callback(response);
28561 } else {
28562 callback(Number(req.responseText));
28563 }
28564 }
28565 } else {
28566 var error;
28567 if (
28568 req.timeout &&
28569 !req.status &&
28570 new Date().getTime() - start_time >= req.timeout
28571 ) {
28572 error = 'timeout';
28573 } else {
28574 error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
28575 }
28576 lib.report_error(error);
28577 if (callback) {
28578 if (verbose_mode) {
28579 var response_headers = req['responseHeaders'] || {};
28580 callback({status: 0, httpStatusCode: req['status'], error: error, retryAfter: response_headers['Retry-After']});
28581 } else {
28582 callback(0);
28583 }
28584 }
28585 }
28586 }
28587 };
28588 req.send(body_data);
28589 } catch (e) {
28590 lib.report_error(e);
28591 succeeded = false;
28592 }
28593 } else {
28594 var script = document$1.createElement('script');
28595 script.type = 'text/javascript';
28596 script.async = true;
28597 script.defer = true;
28598 script.src = url;
28599 var s = document$1.getElementsByTagName('script')[0];
28600 s.parentNode.insertBefore(script, s);
28601 }
28602
28603 return succeeded;
28604 };
28605
28606 /**
28607 * _execute_array() deals with processing any mixpanel function
28608 * calls that were called before the Mixpanel library were loaded
28609 * (and are thus stored in an array so they can be called later)
28610 *
28611 * Note: we fire off all the mixpanel function calls && user defined
28612 * functions BEFORE we fire off mixpanel tracking calls. This is so
28613 * identify/register/set_config calls can properly modify early
28614 * tracking calls.
28615 *
28616 * @param {Array} array
28617 */
28618 MixpanelLib.prototype._execute_array = function(array) {
28619 var fn_name, alias_calls = [], other_calls = [], tracking_calls = [];
28620 _.each(array, function(item) {
28621 if (item) {
28622 fn_name = item[0];
28623 if (_.isArray(fn_name)) {
28624 tracking_calls.push(item); // chained call e.g. mixpanel.get_group().set()
28625 } else if (typeof(item) === 'function') {
28626 item.call(this);
28627 } else if (_.isArray(item) && fn_name === 'alias') {
28628 alias_calls.push(item);
28629 } else if (_.isArray(item) && fn_name.indexOf('track') !== -1 && typeof(this[fn_name]) === 'function') {
28630 tracking_calls.push(item);
28631 } else {
28632 other_calls.push(item);
28633 }
28634 }
28635 }, this);
28636
28637 var execute = function(calls, context) {
28638 _.each(calls, function(item) {
28639 if (_.isArray(item[0])) {
28640 // chained call
28641 var caller = context;
28642 _.each(item, function(call) {
28643 caller = caller[call[0]].apply(caller, call.slice(1));
28644 });
28645 } else {
28646 this[item[0]].apply(this, item.slice(1));
28647 }
28648 }, context);
28649 };
28650
28651 execute(alias_calls, this);
28652 execute(other_calls, this);
28653 execute(tracking_calls, this);
28654 };
28655
28656 // request queueing utils
28657
28658 MixpanelLib.prototype.are_batchers_initialized = function() {
28659 return !!this.request_batchers.events;
28660 };
28661
28662 MixpanelLib.prototype.get_batcher_configs = function() {
28663 var queue_prefix = '__mpq_' + this.get_config('token');
28664 this._batcher_configs = this._batcher_configs || {
28665 events: {type: 'events', api_name: 'track', queue_key: queue_prefix + '_ev'},
28666 people: {type: 'people', api_name: 'engage', queue_key: queue_prefix + '_pp'},
28667 groups: {type: 'groups', api_name: 'groups', queue_key: queue_prefix + '_gr'}
28668 };
28669 return this._batcher_configs;
28670 };
28671
28672 MixpanelLib.prototype.init_batchers = function() {
28673 if (!this.are_batchers_initialized()) {
28674 var batcher_for = _.bind(function(attrs) {
28675 return new RequestBatcher(
28676 attrs.queue_key,
28677 {
28678 libConfig: this['config'],
28679 errorReporter: this.get_config('error_reporter'),
28680 sendRequestFunc: _.bind(function(data, options, cb) {
28681 var api_routes = this.get_config('api_routes');
28682 this._send_request(
28683 this.get_api_host(attrs.api_name) + '/' + api_routes[attrs.api_name],
28684 this._encode_data_for_request(data),
28685 options,
28686 this._prepare_callback(cb, data)
28687 );
28688 }, this),
28689 beforeSendHook: _.bind(function(item) {
28690 return this._run_hook('before_send_' + attrs.type, item);
28691 }, this),
28692 stopAllBatchingFunc: _.bind(this.stop_batch_senders, this),
28693 usePersistence: true,
28694 }
28695 );
28696 }, this);
28697 var batcher_configs = this.get_batcher_configs();
28698 this.request_batchers = {
28699 events: batcher_for(batcher_configs.events),
28700 people: batcher_for(batcher_configs.people),
28701 groups: batcher_for(batcher_configs.groups)
28702 };
28703 }
28704 if (this.get_config('batch_autostart')) {
28705 this.start_batch_senders();
28706 }
28707 };
28708
28709 MixpanelLib.prototype.start_batch_senders = function() {
28710 this._batchers_were_started = true;
28711 if (this.are_batchers_initialized()) {
28712 this._batch_requests = true;
28713 _.each(this.request_batchers, function(batcher) {
28714 batcher.start();
28715 });
28716 }
28717 };
28718
28719 MixpanelLib.prototype.stop_batch_senders = function() {
28720 this._batch_requests = false;
28721 _.each(this.request_batchers, function(batcher) {
28722 batcher.stop();
28723 batcher.clear();
28724 });
28725 };
28726
28727 /**
28728 * push() keeps the standard async-array-push
28729 * behavior around after the lib is loaded.
28730 * This is only useful for external integrations that
28731 * do not wish to rely on our convenience methods
28732 * (created in the snippet).
28733 *
28734 * ### Usage:
28735 * mixpanel.push(['register', { a: 'b' }]);
28736 *
28737 * @param {Array} item A [function_name, args...] array to be executed
28738 */
28739 MixpanelLib.prototype.push = function(item) {
28740 this._execute_array([item]);
28741 };
28742
28743 /**
28744 * Disable events on the Mixpanel object. If passed no arguments,
28745 * this function disables tracking of any event. If passed an
28746 * array of event names, those events will be disabled, but other
28747 * events will continue to be tracked.
28748 *
28749 * Note: this function does not stop other mixpanel functions from
28750 * firing, such as register() or people.set().
28751 *
28752 * @param {Array} [events] An array of event names to disable
28753 */
28754 MixpanelLib.prototype.disable = function(events) {
28755 if (typeof(events) === 'undefined') {
28756 this._flags.disable_all_events = true;
28757 } else {
28758 this.__disabled_events = this.__disabled_events.concat(events);
28759 }
28760 };
28761
28762 MixpanelLib.prototype._encode_data_for_request = function(data) {
28763 var encoded_data = JSONStringify(data);
28764 if (this.get_config('api_payload_format') === PAYLOAD_TYPE_BASE64) {
28765 encoded_data = _.base64Encode(encoded_data);
28766 }
28767 return {'data': encoded_data};
28768 };
28769
28770 // internal method for handling track vs batch-enqueue logic
28771 MixpanelLib.prototype._track_or_batch = function(options, callback) {
28772 var truncated_data = _.truncate(options.data, 255);
28773 var endpoint = options.endpoint;
28774 var batcher = options.batcher;
28775 var should_send_immediately = options.should_send_immediately;
28776 var send_request_options = options.send_request_options || {};
28777 callback = callback || NOOP_FUNC;
28778
28779 var request_enqueued_or_initiated = true;
28780 var send_request_immediately = _.bind(function() {
28781 if (!send_request_options.skip_hooks) {
28782 truncated_data = this._run_hook('before_send_' + options.type, truncated_data);
28783 }
28784 if (truncated_data) {
28785 console$1.log('MIXPANEL REQUEST:');
28786 console$1.log(truncated_data);
28787 return this._send_request(
28788 endpoint,
28789 this._encode_data_for_request(truncated_data),
28790 send_request_options,
28791 this._prepare_callback(callback, truncated_data)
28792 );
28793 } else {
28794 return null;
28795 }
28796 }, this);
28797
28798 if (this._batch_requests && !should_send_immediately) {
28799 batcher.enqueue(truncated_data).then(function(succeeded) {
28800 if (succeeded) {
28801 callback(1, truncated_data);
28802 } else {
28803 send_request_immediately();
28804 }
28805 });
28806 } else {
28807 request_enqueued_or_initiated = send_request_immediately();
28808 }
28809
28810 return request_enqueued_or_initiated && truncated_data;
28811 };
28812
28813 /**
28814 * Track an event. This is the most important and
28815 * frequently used Mixpanel function.
28816 *
28817 * ### Usage:
28818 *
28819 * // track an event named 'Registered'
28820 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
28821 *
28822 * // track an event using navigator.sendBeacon
28823 * mixpanel.track('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});
28824 *
28825 * To track link clicks or form submissions, see track_links() or track_forms().
28826 *
28827 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
28828 * @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.
28829 * @param {Object} [options] Optional configuration for this track request.
28830 * @param {String} [options.transport] Transport method for network request ('xhr' or 'sendBeacon').
28831 * @param {Boolean} [options.send_immediately] Whether to bypass batching/queueing and send track request immediately.
28832 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
28833 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
28834 * with the tracking payload sent to the API server is returned; otherwise false.
28835 */
28836 MixpanelLib.prototype.track = addOptOutCheckMixpanelLib(function(event_name, properties, options, callback) {
28837 if (!callback && typeof options === 'function') {
28838 callback = options;
28839 options = null;
28840 }
28841 options = options || {};
28842 var transport = options['transport']; // external API, don't minify 'transport' prop
28843 if (transport) {
28844 options.transport = transport; // 'transport' prop name can be minified internally
28845 }
28846 var should_send_immediately = options['send_immediately'];
28847 if (typeof callback !== 'function') {
28848 callback = NOOP_FUNC;
28849 }
28850
28851 if (_.isUndefined(event_name)) {
28852 this.report_error('No event name provided to mixpanel.track');
28853 return;
28854 }
28855
28856 if (this._event_is_disabled(event_name)) {
28857 callback(0);
28858 return;
28859 }
28860
28861 // set defaults
28862 properties = _.extend({}, properties);
28863 properties['token'] = this.get_config('token');
28864
28865 // set $duration if time_event was previously called for this event
28866 var start_timestamp = this['persistence'].remove_event_timer(event_name);
28867 if (!_.isUndefined(start_timestamp)) {
28868 var duration_in_ms = new Date().getTime() - start_timestamp;
28869 properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));
28870 }
28871
28872 this._set_default_superprops();
28873
28874 var marketing_properties = this.get_config('track_marketing')
28875 ? _.info.marketingParams()
28876 : {};
28877
28878 // note: extend writes to the first object, so lets make sure we
28879 // don't write to the persistence properties object and info
28880 // properties object by passing in a new object
28881
28882 // update properties with pageview info and super-properties
28883 properties = _.extend(
28884 {},
28885 _.info.properties({'mp_loader': this.get_config('mp_loader')}),
28886 marketing_properties,
28887 this['persistence'].properties(),
28888 this.unpersisted_superprops,
28889 this.get_session_recording_properties(),
28890 properties
28891 );
28892
28893 var property_blacklist = this.get_config('property_blacklist');
28894 if (_.isArray(property_blacklist)) {
28895 _.each(property_blacklist, function(blacklisted_prop) {
28896 delete properties[blacklisted_prop];
28897 });
28898 } else {
28899 this.report_error('Invalid value for property_blacklist config: ' + property_blacklist);
28900 }
28901
28902 var data = {
28903 'event': event_name,
28904 'properties': properties
28905 };
28906 var ret = this._track_or_batch({
28907 type: 'events',
28908 data: data,
28909 endpoint: this.get_api_host('events') + '/' + this.get_config('api_routes')['track'],
28910 batcher: this.request_batchers.events,
28911 should_send_immediately: should_send_immediately,
28912 send_request_options: options
28913 }, callback);
28914
28915 return ret;
28916 });
28917
28918 /**
28919 * Register the current user into one/many groups.
28920 *
28921 * ### Usage:
28922 *
28923 * mixpanel.set_group('company', ['mixpanel', 'google']) // an array of IDs
28924 * mixpanel.set_group('company', 'mixpanel')
28925 * mixpanel.set_group('company', 128746312)
28926 *
28927 * @param {String} group_key Group key
28928 * @param {Array|String|Number} group_ids An array of group IDs, or a singular group ID
28929 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
28930 *
28931 */
28932 MixpanelLib.prototype.set_group = addOptOutCheckMixpanelLib(function(group_key, group_ids, callback) {
28933 if (!_.isArray(group_ids)) {
28934 group_ids = [group_ids];
28935 }
28936 var prop = {};
28937 prop[group_key] = group_ids;
28938 this.register(prop);
28939 return this['people'].set(group_key, group_ids, callback);
28940 });
28941
28942 /**
28943 * Add a new group for this user.
28944 *
28945 * ### Usage:
28946 *
28947 * mixpanel.add_group('company', 'mixpanel')
28948 *
28949 * @param {String} group_key Group key
28950 * @param {*} group_id A valid Mixpanel property type
28951 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
28952 */
28953 MixpanelLib.prototype.add_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
28954 var old_values = this.get_property(group_key);
28955 var prop = {};
28956 if (old_values === undefined) {
28957 prop[group_key] = [group_id];
28958 this.register(prop);
28959 } else {
28960 if (old_values.indexOf(group_id) === -1) {
28961 old_values.push(group_id);
28962 prop[group_key] = old_values;
28963 this.register(prop);
28964 }
28965 }
28966 return this['people'].union(group_key, group_id, callback);
28967 });
28968
28969 /**
28970 * Remove a group from this user.
28971 *
28972 * ### Usage:
28973 *
28974 * mixpanel.remove_group('company', 'mixpanel')
28975 *
28976 * @param {String} group_key Group key
28977 * @param {*} group_id A valid Mixpanel property type
28978 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
28979 */
28980 MixpanelLib.prototype.remove_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
28981 var old_value = this.get_property(group_key);
28982 // if the value doesn't exist, the persistent store is unchanged
28983 if (old_value !== undefined) {
28984 var idx = old_value.indexOf(group_id);
28985 if (idx > -1) {
28986 old_value.splice(idx, 1);
28987 this.register({group_key: old_value});
28988 }
28989 if (old_value.length === 0) {
28990 this.unregister(group_key);
28991 }
28992 }
28993 return this['people'].remove(group_key, group_id, callback);
28994 });
28995
28996 /**
28997 * Track an event with specific groups.
28998 *
28999 * ### Usage:
29000 *
29001 * mixpanel.track_with_groups('purchase', {'product': 'iphone'}, {'University': ['UCB', 'UCLA']})
29002 *
29003 * @param {String} event_name The name of the event (see `mixpanel.track()`)
29004 * @param {Object=} properties A set of properties to include with the event you're sending (see `mixpanel.track()`)
29005 * @param {Object=} groups An object mapping group name keys to one or more values
29006 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29007 */
29008 MixpanelLib.prototype.track_with_groups = addOptOutCheckMixpanelLib(function(event_name, properties, groups, callback) {
29009 var tracking_props = _.extend({}, properties || {});
29010 _.each(groups, function(v, k) {
29011 if (v !== null && v !== undefined) {
29012 tracking_props[k] = v;
29013 }
29014 });
29015 return this.track(event_name, tracking_props, callback);
29016 });
29017
29018 MixpanelLib.prototype._create_map_key = function (group_key, group_id) {
29019 return group_key + '_' + JSON.stringify(group_id);
29020 };
29021
29022 MixpanelLib.prototype._remove_group_from_cache = function (group_key, group_id) {
29023 delete this._cached_groups[this._create_map_key(group_key, group_id)];
29024 };
29025
29026 /**
29027 * Look up reference to a Mixpanel group
29028 *
29029 * ### Usage:
29030 *
29031 * mixpanel.get_group(group_key, group_id)
29032 *
29033 * @param {String} group_key Group key
29034 * @param {Object} group_id A valid Mixpanel property type
29035 * @returns {Object} A MixpanelGroup identifier
29036 */
29037 MixpanelLib.prototype.get_group = function (group_key, group_id) {
29038 var map_key = this._create_map_key(group_key, group_id);
29039 var group = this._cached_groups[map_key];
29040 if (group === undefined || group._group_key !== group_key || group._group_id !== group_id) {
29041 group = new MixpanelGroup();
29042 group._init(this, group_key, group_id);
29043 this._cached_groups[map_key] = group;
29044 }
29045 return group;
29046 };
29047
29048 /**
29049 * Track a default Mixpanel page view event, which includes extra default event properties to
29050 * improve page view data.
29051 *
29052 * ### Usage:
29053 *
29054 * // track a default $mp_web_page_view event
29055 * mixpanel.track_pageview();
29056 *
29057 * // track a page view event with additional event properties
29058 * mixpanel.track_pageview({'ab_test_variant': 'card-layout-b'});
29059 *
29060 * // example approach to track page views on different page types as event properties
29061 * mixpanel.track_pageview({'page': 'pricing'});
29062 * mixpanel.track_pageview({'page': 'homepage'});
29063 *
29064 * // UNCOMMON: Tracking a page view event with a custom event_name option. NOT expected to be used for
29065 * // individual pages on the same site or product. Use cases for custom event_name may be page
29066 * // views on different products or internal applications that are considered completely separate
29067 * mixpanel.track_pageview({'page': 'customer-search'}, {'event_name': '[internal] Admin Page View'});
29068 *
29069 * ### Notes:
29070 *
29071 * The `config.track_pageview` option for <a href="#mixpanelinit">mixpanel.init()</a>
29072 * may be turned on for tracking page loads automatically.
29073 *
29074 * // track only page loads
29075 * mixpanel.init(PROJECT_TOKEN, {track_pageview: true});
29076 *
29077 * // track when the URL changes in any manner
29078 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'full-url'});
29079 *
29080 * // track when the URL changes, ignoring any changes in the hash part
29081 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path-and-query-string'});
29082 *
29083 * // track when the path changes, ignoring any query parameter or hash changes
29084 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path'});
29085 *
29086 * @param {Object} [properties] An optional set of additional properties to send with the page view event
29087 * @param {Object} [options] Page view tracking options
29088 * @param {String} [options.event_name] - Alternate name for the tracking event
29089 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
29090 * with the tracking payload sent to the API server is returned; otherwise false.
29091 */
29092 MixpanelLib.prototype.track_pageview = addOptOutCheckMixpanelLib(function(properties, options) {
29093 if (typeof properties !== 'object') {
29094 properties = {};
29095 }
29096 options = options || {};
29097 var event_name = options['event_name'] || '$mp_web_page_view';
29098
29099 var default_page_properties = _.extend(
29100 _.info.mpPageViewProperties(),
29101 _.info.campaignParams(),
29102 _.info.clickParams()
29103 );
29104
29105 var event_properties = _.extend(
29106 {},
29107 default_page_properties,
29108 properties
29109 );
29110
29111 return this.track(event_name, event_properties);
29112 });
29113
29114 /**
29115 * Track clicks on a set of document elements. Selector must be a
29116 * valid query. Elements must exist on the page at the time track_links is called.
29117 *
29118 * ### Usage:
29119 *
29120 * // track click for link id #nav
29121 * mixpanel.track_links('#nav', 'Clicked Nav Link');
29122 *
29123 * ### Notes:
29124 *
29125 * This function will wait up to 300 ms for the Mixpanel
29126 * servers to respond. If they have not responded by that time
29127 * it will head to the link without ensuring that your event
29128 * has been tracked. To configure this timeout please see the
29129 * set_config() documentation below.
29130 *
29131 * If you pass a function in as the properties argument, the
29132 * function will receive the DOMElement that triggered the
29133 * event as an argument. You are expected to return an object
29134 * from the function; any properties defined on this object
29135 * will be sent to mixpanel as event properties.
29136 *
29137 * @type {Function}
29138 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
29139 * @param {String} event_name The name of the event to track
29140 * @param {Object|Function} [properties] A properties object or function that returns a dictionary of properties when passed a DOMElement
29141 */
29142 MixpanelLib.prototype.track_links = function() {
29143 return this._track_dom.call(this, LinkTracker, arguments);
29144 };
29145
29146 /**
29147 * Track form submissions. Selector must be a valid query.
29148 *
29149 * ### Usage:
29150 *
29151 * // track submission for form id 'register'
29152 * mixpanel.track_forms('#register', 'Created Account');
29153 *
29154 * ### Notes:
29155 *
29156 * This function will wait up to 300 ms for the mixpanel
29157 * servers to respond, if they have not responded by that time
29158 * it will head to the link without ensuring that your event
29159 * has been tracked. To configure this timeout please see the
29160 * set_config() documentation below.
29161 *
29162 * If you pass a function in as the properties argument, the
29163 * function will receive the DOMElement that triggered the
29164 * event as an argument. You are expected to return an object
29165 * from the function; any properties defined on this object
29166 * will be sent to mixpanel as event properties.
29167 *
29168 * @type {Function}
29169 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
29170 * @param {String} event_name The name of the event to track
29171 * @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
29172 */
29173 MixpanelLib.prototype.track_forms = function() {
29174 return this._track_dom.call(this, FormTracker, arguments);
29175 };
29176
29177 /**
29178 * Time an event by including the time between this call and a
29179 * later 'track' call for the same event in the properties sent
29180 * with the event.
29181 *
29182 * ### Usage:
29183 *
29184 * // time an event named 'Registered'
29185 * mixpanel.time_event('Registered');
29186 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
29187 *
29188 * When called for a particular event name, the next track call for that event
29189 * name will include the elapsed time between the 'time_event' and 'track'
29190 * calls. This value is stored as seconds in the '$duration' property.
29191 *
29192 * @param {String} event_name The name of the event.
29193 */
29194 MixpanelLib.prototype.time_event = function(event_name) {
29195 if (_.isUndefined(event_name)) {
29196 this.report_error('No event name provided to mixpanel.time_event');
29197 return;
29198 }
29199
29200 if (this._event_is_disabled(event_name)) {
29201 return;
29202 }
29203
29204 this['persistence'].set_event_timer(event_name, new Date().getTime());
29205 };
29206
29207 var REGISTER_DEFAULTS = {
29208 'persistent': true
29209 };
29210 /**
29211 * Helper to parse options param for register methods, maintaining
29212 * legacy support for plain "days" param instead of options object
29213 * @param {Number|Object} [days_or_options] 'days' option (Number), or Options object for register methods
29214 * @returns {Object} options object
29215 */
29216 var options_for_register = function(days_or_options) {
29217 var options;
29218 if (_.isObject(days_or_options)) {
29219 options = days_or_options;
29220 } else if (!_.isUndefined(days_or_options)) {
29221 options = {'days': days_or_options};
29222 } else {
29223 options = {};
29224 }
29225 return _.extend({}, REGISTER_DEFAULTS, options);
29226 };
29227
29228 /**
29229 * Register a set of super properties, which are included with all
29230 * events. This will overwrite previous super property values.
29231 *
29232 * ### Usage:
29233 *
29234 * // register 'Gender' as a super property
29235 * mixpanel.register({'Gender': 'Female'});
29236 *
29237 * // register several super properties when a user signs up
29238 * mixpanel.register({
29239 * 'Email': '[email protected]',
29240 * 'Account Type': 'Free'
29241 * });
29242 *
29243 * // register only for the current pageload
29244 * mixpanel.register({'Name': 'Pat'}, {persistent: false});
29245 *
29246 * @param {Object} properties An associative array of properties to store about the user
29247 * @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)
29248 * @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)
29249 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
29250 */
29251 MixpanelLib.prototype.register = function(props, days_or_options) {
29252 var options = options_for_register(days_or_options);
29253 if (options['persistent']) {
29254 this['persistence'].register(props, options['days']);
29255 } else {
29256 _.extend(this.unpersisted_superprops, props);
29257 }
29258 };
29259
29260 /**
29261 * Register a set of super properties only once. This will not
29262 * overwrite previous super property values, unlike register().
29263 *
29264 * ### Usage:
29265 *
29266 * // register a super property for the first time only
29267 * mixpanel.register_once({
29268 * 'First Login Date': new Date().toISOString()
29269 * });
29270 *
29271 * // register once, only for the current pageload
29272 * mixpanel.register_once({
29273 * 'First interaction time': new Date().toISOString()
29274 * }, 'None', {persistent: false});
29275 *
29276 * ### Notes:
29277 *
29278 * If default_value is specified, current super properties
29279 * with that value will be overwritten.
29280 *
29281 * @param {Object} properties An associative array of properties to store about the user
29282 * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'
29283 * @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)
29284 * @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)
29285 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
29286 */
29287 MixpanelLib.prototype.register_once = function(props, default_value, days_or_options) {
29288 var options = options_for_register(days_or_options);
29289 if (options['persistent']) {
29290 this['persistence'].register_once(props, default_value, options['days']);
29291 } else {
29292 if (typeof(default_value) === 'undefined') {
29293 default_value = 'None';
29294 }
29295 _.each(props, function(val, prop) {
29296 if (!this.unpersisted_superprops.hasOwnProperty(prop) || this.unpersisted_superprops[prop] === default_value) {
29297 this.unpersisted_superprops[prop] = val;
29298 }
29299 }, this);
29300 }
29301 };
29302
29303 /**
29304 * Delete a super property stored with the current user.
29305 *
29306 * @param {String} property The name of the super property to remove
29307 * @param {Object} [options]
29308 * @param {boolean} [options.persistent=true] - whether to look in persistent storage (cookie/localStorage)
29309 */
29310 MixpanelLib.prototype.unregister = function(property, options) {
29311 options = options_for_register(options);
29312 if (options['persistent']) {
29313 this['persistence'].unregister(property);
29314 } else {
29315 delete this.unpersisted_superprops[property];
29316 }
29317 };
29318
29319 MixpanelLib.prototype._register_single = function(prop, value) {
29320 var props = {};
29321 props[prop] = value;
29322 this.register(props);
29323 };
29324
29325 /**
29326 * Identify a user with a unique ID to track user activity across
29327 * devices, tie a user to their events, and create a user profile.
29328 * If you never call this method, unique visitors are tracked using
29329 * a UUID generated the first time they visit the site.
29330 *
29331 * Call identify when you know the identity of the current user,
29332 * typically after login or signup. We recommend against using
29333 * identify for anonymous visitors to your site.
29334 *
29335 * ### Notes:
29336 * If your project has
29337 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
29338 * enabled, the identify method will connect pre- and
29339 * post-authentication events when appropriate.
29340 *
29341 * If your project does not have ID Merge enabled, identify will
29342 * change the user's local distinct_id to the unique ID you pass.
29343 * Events tracked prior to authentication will not be connected
29344 * to the same user identity. If ID Merge is disabled, alias can
29345 * be used to connect pre- and post-registration events.
29346 *
29347 * @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.
29348 */
29349 MixpanelLib.prototype.identify = function(
29350 new_distinct_id, _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback
29351 ) {
29352 // Optional Parameters
29353 // _set_callback:function A callback to be run if and when the People set queue is flushed
29354 // _add_callback:function A callback to be run if and when the People add queue is flushed
29355 // _append_callback:function A callback to be run if and when the People append queue is flushed
29356 // _set_once_callback:function A callback to be run if and when the People set_once queue is flushed
29357 // _union_callback:function A callback to be run if and when the People union queue is flushed
29358 // _unset_callback:function A callback to be run if and when the People unset queue is flushed
29359
29360 var previous_distinct_id = this.get_distinct_id();
29361 if (new_distinct_id && previous_distinct_id !== new_distinct_id) {
29362 // we allow the following condition if previous distinct_id is same as new_distinct_id
29363 // so that you can force flush people updates for anonymous profiles.
29364 if (typeof new_distinct_id === 'string' && new_distinct_id.indexOf(DEVICE_ID_PREFIX) === 0) {
29365 this.report_error('distinct_id cannot have $device: prefix');
29366 return -1;
29367 }
29368 this.register({'$user_id': new_distinct_id});
29369 }
29370
29371 if (!this.get_property('$device_id')) {
29372 // The persisted distinct id might not actually be a device id at all
29373 // it might be a distinct id of the user from before
29374 var device_id = previous_distinct_id;
29375 this.register_once({
29376 '$had_persisted_distinct_id': true,
29377 '$device_id': device_id
29378 }, '');
29379 }
29380
29381 // identify only changes the distinct id if it doesn't match either the existing or the alias;
29382 // if it's new, blow away the alias as well.
29383 if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {
29384 this.unregister(ALIAS_ID_KEY);
29385 this.register({'distinct_id': new_distinct_id});
29386 }
29387 this._flags.identify_called = true;
29388 // Flush any queued up people requests
29389 this['people']._flush(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback);
29390
29391 // send an $identify event any time the distinct_id is changing - logic on the server
29392 // will determine whether or not to do anything with it.
29393 if (new_distinct_id !== previous_distinct_id) {
29394 this.track('$identify', {
29395 'distinct_id': new_distinct_id,
29396 '$anon_distinct_id': previous_distinct_id
29397 }, {skip_hooks: true});
29398 }
29399
29400 // check feature flags again if distinct id has changed
29401 if (new_distinct_id !== previous_distinct_id) {
29402 this.flags.fetchFlags();
29403 }
29404 };
29405
29406 /**
29407 * Clears super properties and generates a new random distinct_id for this instance.
29408 * Useful for clearing data when a user logs out.
29409 */
29410 MixpanelLib.prototype.reset = function() {
29411 this.stop_session_recording();
29412 this['persistence'].clear();
29413 this._flags.identify_called = false;
29414 var uuid = _.UUID();
29415 this.register_once({
29416 'distinct_id': DEVICE_ID_PREFIX + uuid,
29417 '$device_id': uuid
29418 }, '');
29419 this._check_and_start_session_recording();
29420 };
29421
29422 /**
29423 * Returns the current distinct id of the user. This is either the id automatically
29424 * generated by the library or the id that has been passed by a call to identify().
29425 *
29426 * ### Notes:
29427 *
29428 * get_distinct_id() can only be called after the Mixpanel library has finished loading.
29429 * init() has a loaded function available to handle this automatically. For example:
29430 *
29431 * // set distinct_id after the mixpanel library has loaded
29432 * mixpanel.init('YOUR PROJECT TOKEN', {
29433 * loaded: function(mixpanel) {
29434 * distinct_id = mixpanel.get_distinct_id();
29435 * }
29436 * });
29437 */
29438 MixpanelLib.prototype.get_distinct_id = function() {
29439 return this.get_property('distinct_id');
29440 };
29441
29442 /**
29443 * The alias method creates an alias which Mixpanel will use to
29444 * remap one id to another. Multiple aliases can point to the
29445 * same identifier.
29446 *
29447 * The following is a valid use of alias:
29448 *
29449 * mixpanel.alias('new_id', 'existing_id');
29450 * // You can add multiple id aliases to the existing ID
29451 * mixpanel.alias('newer_id', 'existing_id');
29452 *
29453 * Aliases can also be chained - the following is a valid example:
29454 *
29455 * mixpanel.alias('new_id', 'existing_id');
29456 * // chain newer_id - new_id - existing_id
29457 * mixpanel.alias('newer_id', 'new_id');
29458 *
29459 * Aliases cannot point to multiple identifiers - the following
29460 * example will not work:
29461 *
29462 * mixpanel.alias('new_id', 'existing_id');
29463 * // this is invalid as 'new_id' already points to 'existing_id'
29464 * mixpanel.alias('new_id', 'newer_id');
29465 *
29466 * ### Notes:
29467 *
29468 * If your project does not have
29469 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
29470 * enabled, the best practice is to call alias once when a unique
29471 * ID is first created for a user (e.g., when a user first registers
29472 * for an account). Do not use alias multiple times for a single
29473 * user without ID Merge enabled.
29474 *
29475 * @param {String} alias A unique identifier that you want to use for this user in the future.
29476 * @param {String} [original] The current identifier being used for this user.
29477 */
29478 MixpanelLib.prototype.alias = function(alias, original) {
29479 // If the $people_distinct_id key exists in persistence, there has been a previous
29480 // mixpanel.people.identify() call made for this user. It is VERY BAD to make an alias with
29481 // this ID, as it will duplicate users.
29482 if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {
29483 this.report_error('Attempting to create alias for existing People user - aborting.');
29484 return -2;
29485 }
29486
29487 var _this = this;
29488 if (_.isUndefined(original)) {
29489 original = this.get_distinct_id();
29490 }
29491 if (alias !== original) {
29492 this._register_single(ALIAS_ID_KEY, alias);
29493 return this.track('$create_alias', {
29494 'alias': alias,
29495 'distinct_id': original
29496 }, {
29497 skip_hooks: true
29498 }, function() {
29499 // Flush the people queue
29500 _this.identify(alias);
29501 });
29502 } else {
29503 this.report_error('alias matches current distinct_id - skipping api call.');
29504 this.identify(alias);
29505 return -1;
29506 }
29507 };
29508
29509 /**
29510 * Provide a string to recognize the user by. The string passed to
29511 * this method will appear in the Mixpanel Streams product rather
29512 * than an automatically generated name. Name tags do not have to
29513 * be unique.
29514 *
29515 * This value will only be included in Streams data.
29516 *
29517 * @param {String} name_tag A human readable name for the user
29518 * @deprecated
29519 */
29520 MixpanelLib.prototype.name_tag = function(name_tag) {
29521 this._register_single('mp_name_tag', name_tag);
29522 };
29523
29524 /**
29525 * Update the configuration of a mixpanel library instance.
29526 *
29527 * The default config is:
29528 *
29529 * {
29530 * // host for requests (customizable for e.g. a local proxy)
29531 * api_host: 'https://api-js.mixpanel.com',
29532 *
29533 * // endpoints for different types of requests
29534 * api_routes: {
29535 * track: 'track/',
29536 * engage: 'engage/',
29537 * groups: 'groups/',
29538 * }
29539 *
29540 * // HTTP method for tracking requests
29541 * api_method: 'POST'
29542 *
29543 * // transport for sending requests ('XHR' or 'sendBeacon')
29544 * // NB: sendBeacon should only be used for scenarios such as
29545 * // page unload where a "best-effort" attempt to send is
29546 * // acceptable; the sendBeacon API does not support callbacks
29547 * // or any way to know the result of the request. Mixpanel
29548 * // tracking via sendBeacon will not support any event-
29549 * // batching or retry mechanisms.
29550 * api_transport: 'XHR'
29551 *
29552 * // request-batching/queueing/retry
29553 * batch_requests: true,
29554 *
29555 * // maximum number of events/updates to send in a single
29556 * // network request
29557 * batch_size: 50,
29558 *
29559 * // milliseconds to wait between sending batch requests
29560 * batch_flush_interval_ms: 5000,
29561 *
29562 * // milliseconds to wait for network responses to batch requests
29563 * // before they are considered timed-out and retried
29564 * batch_request_timeout_ms: 90000,
29565 *
29566 * // override value for cookie domain, only useful for ensuring
29567 * // correct cross-subdomain cookies on unusual domains like
29568 * // subdomain.mainsite.avocat.fr; NB this cannot be used to
29569 * // set cookies on a different domain than the current origin
29570 * cookie_domain: ''
29571 *
29572 * // super properties cookie expiration (in days)
29573 * cookie_expiration: 365
29574 *
29575 * // if true, cookie will be set with SameSite=None; Secure
29576 * // this is only useful in special situations, like embedded
29577 * // 3rd-party iframes that set up a Mixpanel instance
29578 * cross_site_cookie: false
29579 *
29580 * // super properties span subdomains
29581 * cross_subdomain_cookie: true
29582 *
29583 * // debug mode
29584 * debug: false
29585 *
29586 * // if this is true, the mixpanel cookie or localStorage entry
29587 * // will be deleted, and no user persistence will take place
29588 * disable_persistence: false
29589 *
29590 * // if this is true, Mixpanel will automatically determine
29591 * // City, Region and Country data using the IP address of
29592 * //the client
29593 * ip: true
29594 *
29595 * // opt users out of tracking by this Mixpanel instance by default
29596 * opt_out_tracking_by_default: false
29597 *
29598 * // opt users out of browser data storage by this Mixpanel instance by default
29599 * opt_out_persistence_by_default: false
29600 *
29601 * // persistence mechanism used by opt-in/opt-out methods - cookie
29602 * // or localStorage - falls back to cookie if localStorage is unavailable
29603 * opt_out_tracking_persistence_type: 'localStorage'
29604 *
29605 * // customize the name of cookie/localStorage set by opt-in/opt-out methods
29606 * opt_out_tracking_cookie_prefix: null
29607 *
29608 * // type of persistent store for super properties (cookie/
29609 * // localStorage) if set to 'localStorage', any existing
29610 * // mixpanel cookie value with the same persistence_name
29611 * // will be transferred to localStorage and deleted
29612 * persistence: 'cookie'
29613 *
29614 * // name for super properties persistent store
29615 * persistence_name: ''
29616 *
29617 * // names of properties/superproperties which should never
29618 * // be sent with track() calls
29619 * property_blacklist: []
29620 *
29621 * // if this is true, mixpanel cookies will be marked as
29622 * // secure, meaning they will only be transmitted over https
29623 * secure_cookie: false
29624 *
29625 * // disables enriching user profiles with first touch marketing data
29626 * skip_first_touch_marketing: false
29627 *
29628 * // the amount of time track_links will
29629 * // wait for Mixpanel's servers to respond
29630 * track_links_timeout: 300
29631 *
29632 * // adds any UTM parameters and click IDs present on the page to any events fired
29633 * track_marketing: true
29634 *
29635 * // enables automatic page view tracking using default page view events through
29636 * // the track_pageview() method
29637 * track_pageview: false
29638 *
29639 * // if you set upgrade to be true, the library will check for
29640 * // a cookie from our old js library and import super
29641 * // properties from it, then the old cookie is deleted
29642 * // The upgrade config option only works in the initialization,
29643 * // so make sure you set it when you create the library.
29644 * upgrade: false
29645 *
29646 * // extra HTTP request headers to set for each API request, in
29647 * // the format {'Header-Name': value}
29648 * xhr_headers: {}
29649 *
29650 * // whether to ignore or respect the web browser's Do Not Track setting
29651 * ignore_dnt: false
29652 * }
29653 *
29654 *
29655 * @param {Object} config A dictionary of new configuration values to update
29656 */
29657 MixpanelLib.prototype.set_config = function(config) {
29658 if (_.isObject(config)) {
29659 _.extend(this['config'], config);
29660
29661 var new_batch_size = config['batch_size'];
29662 if (new_batch_size) {
29663 _.each(this.request_batchers, function(batcher) {
29664 batcher.resetBatchSize();
29665 });
29666 }
29667
29668 if (!this.get_config('persistence_name')) {
29669 this['config']['persistence_name'] = this['config']['cookie_name'];
29670 }
29671 if (!this.get_config('disable_persistence')) {
29672 this['config']['disable_persistence'] = this['config']['disable_cookie'];
29673 }
29674
29675 if (this['persistence']) {
29676 this['persistence'].update_config(this['config']);
29677 }
29678 Config.DEBUG = Config.DEBUG || this.get_config('debug');
29679
29680 if (('autocapture' in config || 'record_heatmap_data' in config) && this.autocapture) {
29681 this.autocapture.init();
29682 }
29683 }
29684 };
29685
29686 /**
29687 * returns the current config object for the library.
29688 */
29689 MixpanelLib.prototype.get_config = function(prop_name) {
29690 return this['config'][prop_name];
29691 };
29692
29693 /**
29694 * Fetch a hook function from config, with safe default, and run it
29695 * against the given arguments
29696 * @param {string} hook_name which hook to retrieve
29697 * @returns {any|null} return value of user-provided hook, or null if nothing was returned
29698 */
29699 MixpanelLib.prototype._run_hook = function(hook_name) {
29700 var ret = (this['config']['hooks'][hook_name] || IDENTITY_FUNC).apply(this, slice.call(arguments, 1));
29701 if (typeof ret === 'undefined') {
29702 this.report_error(hook_name + ' hook did not return a value');
29703 ret = null;
29704 }
29705 return ret;
29706 };
29707
29708 /**
29709 * Returns the value of the super property named property_name. If no such
29710 * property is set, get_property() will return the undefined value.
29711 *
29712 * ### Notes:
29713 *
29714 * get_property() can only be called after the Mixpanel library has finished loading.
29715 * init() has a loaded function available to handle this automatically. For example:
29716 *
29717 * // grab value for 'user_id' after the mixpanel library has loaded
29718 * mixpanel.init('YOUR PROJECT TOKEN', {
29719 * loaded: function(mixpanel) {
29720 * user_id = mixpanel.get_property('user_id');
29721 * }
29722 * });
29723 *
29724 * @param {String} property_name The name of the super property you want to retrieve
29725 */
29726 MixpanelLib.prototype.get_property = function(property_name) {
29727 return this['persistence'].load_prop([property_name]);
29728 };
29729
29730 /**
29731 * Get the API host for a specific endpoint type, falling back to the default api_host if not specified
29732 *
29733 * @param {String} endpoint_type The type of endpoint (e.g., "events", "people", "groups")
29734 * @returns {String} The API host to use for this endpoint
29735 */
29736 MixpanelLib.prototype.get_api_host = function(endpoint_type) {
29737 return this.get_config('api_hosts')[endpoint_type] || this.get_config('api_host');
29738 };
29739
29740 MixpanelLib.prototype.toString = function() {
29741 var name = this.get_config('name');
29742 if (name !== PRIMARY_INSTANCE_NAME) {
29743 name = PRIMARY_INSTANCE_NAME + '.' + name;
29744 }
29745 return name;
29746 };
29747
29748 MixpanelLib.prototype._event_is_disabled = function(event_name) {
29749 return _.isBlockedUA(userAgent) ||
29750 this._flags.disable_all_events ||
29751 _.include(this.__disabled_events, event_name);
29752 };
29753
29754 // perform some housekeeping around GDPR opt-in/out state
29755 MixpanelLib.prototype._gdpr_init = function() {
29756 var is_localStorage_requested = this.get_config('opt_out_tracking_persistence_type') === 'localStorage';
29757
29758 // try to convert opt-in/out cookies to localStorage if possible
29759 if (is_localStorage_requested && _.localStorage.is_supported()) {
29760 if (!this.has_opted_in_tracking() && this.has_opted_in_tracking({'persistence_type': 'cookie'})) {
29761 this.opt_in_tracking({'enable_persistence': false});
29762 }
29763 if (!this.has_opted_out_tracking() && this.has_opted_out_tracking({'persistence_type': 'cookie'})) {
29764 this.opt_out_tracking({'clear_persistence': false});
29765 }
29766 this.clear_opt_in_out_tracking({
29767 'persistence_type': 'cookie',
29768 'enable_persistence': false
29769 });
29770 }
29771
29772 // check whether the user has already opted out - if so, clear & disable persistence
29773 if (this.has_opted_out_tracking()) {
29774 this._gdpr_update_persistence({'clear_persistence': true});
29775
29776 // check whether we should opt out by default
29777 // note: we don't clear persistence here by default since opt-out default state is often
29778 // used as an initial state while GDPR information is being collected
29779 } else if (!this.has_opted_in_tracking() && (
29780 this.get_config('opt_out_tracking_by_default') || _.cookie.get('mp_optout')
29781 )) {
29782 _.cookie.remove('mp_optout');
29783 this.opt_out_tracking({
29784 'clear_persistence': this.get_config('opt_out_persistence_by_default')
29785 });
29786 }
29787 };
29788
29789 /**
29790 * Enable or disable persistence based on options
29791 * only enable/disable if persistence is not already in this state
29792 * @param {boolean} [options.clear_persistence] If true, will delete all data stored by the sdk in persistence and disable it
29793 * @param {boolean} [options.enable_persistence] If true, will re-enable sdk persistence
29794 */
29795 MixpanelLib.prototype._gdpr_update_persistence = function(options) {
29796 var disabled;
29797 if (options && options['clear_persistence']) {
29798 disabled = true;
29799 } else if (options && options['enable_persistence']) {
29800 disabled = false;
29801 } else {
29802 return;
29803 }
29804
29805 if (!this.get_config('disable_persistence') && this['persistence'].disabled !== disabled) {
29806 this['persistence'].set_disabled(disabled);
29807 }
29808
29809 if (disabled) {
29810 this.stop_batch_senders();
29811 this.stop_session_recording();
29812 } else {
29813 // only start batchers after opt-in if they have previously been started
29814 // in order to avoid unintentionally starting up batching for the first time
29815 if (this._batchers_were_started) {
29816 this.start_batch_senders();
29817 }
29818 }
29819 };
29820
29821 // call a base gdpr function after constructing the appropriate token and options args
29822 MixpanelLib.prototype._gdpr_call_func = function(func, options) {
29823 options = _.extend({
29824 'track': _.bind(this.track, this),
29825 'persistence_type': this.get_config('opt_out_tracking_persistence_type'),
29826 'cookie_prefix': this.get_config('opt_out_tracking_cookie_prefix'),
29827 'cookie_expiration': this.get_config('cookie_expiration'),
29828 'cross_site_cookie': this.get_config('cross_site_cookie'),
29829 'cross_subdomain_cookie': this.get_config('cross_subdomain_cookie'),
29830 'cookie_domain': this.get_config('cookie_domain'),
29831 'secure_cookie': this.get_config('secure_cookie'),
29832 'ignore_dnt': this.get_config('ignore_dnt')
29833 }, options);
29834
29835 // check if localStorage can be used for recording opt out status, fall back to cookie if not
29836 if (!_.localStorage.is_supported()) {
29837 options['persistence_type'] = 'cookie';
29838 }
29839
29840 return func(this.get_config('token'), {
29841 track: options['track'],
29842 trackEventName: options['track_event_name'],
29843 trackProperties: options['track_properties'],
29844 persistenceType: options['persistence_type'],
29845 persistencePrefix: options['cookie_prefix'],
29846 cookieDomain: options['cookie_domain'],
29847 cookieExpiration: options['cookie_expiration'],
29848 crossSiteCookie: options['cross_site_cookie'],
29849 crossSubdomainCookie: options['cross_subdomain_cookie'],
29850 secureCookie: options['secure_cookie'],
29851 ignoreDnt: options['ignore_dnt']
29852 });
29853 };
29854
29855 /**
29856 * Opt the user in to data tracking and cookies/localstorage for this Mixpanel instance
29857 *
29858 * ### Usage:
29859 *
29860 * // opt user in
29861 * mixpanel.opt_in_tracking();
29862 *
29863 * // opt user in with specific event name, properties, cookie configuration
29864 * mixpanel.opt_in_tracking({
29865 * track_event_name: 'User opted in',
29866 * track_event_properties: {
29867 * 'Email': '[email protected]'
29868 * },
29869 * cookie_expiration: 30,
29870 * secure_cookie: true
29871 * });
29872 *
29873 * @param {Object} [options] A dictionary of config options to override
29874 * @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)
29875 * @param {string} [options.track_event_name=$opt_in] Event name to be used for tracking the opt-in action
29876 * @param {Object} [options.track_properties] Set of properties to be tracked along with the opt-in action
29877 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
29878 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29879 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29880 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
29881 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
29882 * @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)
29883 * @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)
29884 * @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)
29885 */
29886 MixpanelLib.prototype.opt_in_tracking = function(options) {
29887 options = _.extend({
29888 'enable_persistence': true
29889 }, options);
29890
29891 this._gdpr_call_func(optIn, options);
29892 this._gdpr_update_persistence(options);
29893 };
29894
29895 /**
29896 * Opt the user out of data tracking and cookies/localstorage for this Mixpanel instance
29897 *
29898 * ### Usage:
29899 *
29900 * // opt user out
29901 * mixpanel.opt_out_tracking();
29902 *
29903 * // opt user out with different cookie configuration from Mixpanel instance
29904 * mixpanel.opt_out_tracking({
29905 * cookie_expiration: 30,
29906 * secure_cookie: true
29907 * });
29908 *
29909 * @param {Object} [options] A dictionary of config options to override
29910 * @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
29911 * @param {boolean} [options.clear_persistence=true] If true, will delete all data stored by the sdk in persistence
29912 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29913 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29914 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
29915 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
29916 * @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)
29917 * @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)
29918 * @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)
29919 */
29920 MixpanelLib.prototype.opt_out_tracking = function(options) {
29921 options = _.extend({
29922 'clear_persistence': true,
29923 'delete_user': true
29924 }, options);
29925
29926 // delete user and clear charges since these methods may be disabled by opt-out
29927 if (options['delete_user'] && this['people'] && this['people']._identify_called()) {
29928 this['people'].delete_user();
29929 this['people'].clear_charges();
29930 }
29931
29932 this._gdpr_call_func(optOut, options);
29933 this._gdpr_update_persistence(options);
29934 };
29935
29936 /**
29937 * Check whether the user has opted in to data tracking and cookies/localstorage for this Mixpanel instance
29938 *
29939 * ### Usage:
29940 *
29941 * var has_opted_in = mixpanel.has_opted_in_tracking();
29942 * // use has_opted_in value
29943 *
29944 * @param {Object} [options] A dictionary of config options to override
29945 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29946 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29947 * @returns {boolean} current opt-in status
29948 */
29949 MixpanelLib.prototype.has_opted_in_tracking = function(options) {
29950 return this._gdpr_call_func(hasOptedIn, options);
29951 };
29952
29953 /**
29954 * Check whether the user has opted out of data tracking and cookies/localstorage for this Mixpanel instance
29955 *
29956 * ### Usage:
29957 *
29958 * var has_opted_out = mixpanel.has_opted_out_tracking();
29959 * // use has_opted_out value
29960 *
29961 * @param {Object} [options] A dictionary of config options to override
29962 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29963 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29964 * @returns {boolean} current opt-out status
29965 */
29966 MixpanelLib.prototype.has_opted_out_tracking = function(options) {
29967 return this._gdpr_call_func(hasOptedOut, options);
29968 };
29969
29970 /**
29971 * Clear the user's opt in/out status of data tracking and cookies/localstorage for this Mixpanel instance
29972 *
29973 * ### Usage:
29974 *
29975 * // clear user's opt-in/out status
29976 * mixpanel.clear_opt_in_out_tracking();
29977 *
29978 * // clear user's opt-in/out status with specific cookie configuration - should match
29979 * // configuration used when opt_in_tracking/opt_out_tracking methods were called.
29980 * mixpanel.clear_opt_in_out_tracking({
29981 * cookie_expiration: 30,
29982 * secure_cookie: true
29983 * });
29984 *
29985 * @param {Object} [options] A dictionary of config options to override
29986 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
29987 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29988 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29989 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
29990 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
29991 * @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)
29992 * @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)
29993 * @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)
29994 */
29995 MixpanelLib.prototype.clear_opt_in_out_tracking = function(options) {
29996 options = _.extend({
29997 'enable_persistence': true
29998 }, options);
29999
30000 this._gdpr_call_func(clearOptInOut, options);
30001 this._gdpr_update_persistence(options);
30002 };
30003
30004 MixpanelLib.prototype.report_error = function(msg, err) {
30005 console$1.error.apply(console$1.error, arguments);
30006 try {
30007 if (!err && !(msg instanceof Error)) {
30008 msg = new Error(msg);
30009 }
30010 this.get_config('error_reporter')(msg, err);
30011 } catch(err) {
30012 console$1.error(err);
30013 }
30014 };
30015
30016 // EXPORTS (for closure compiler)
30017
30018 // MixpanelLib Exports
30019 MixpanelLib.prototype['init'] = MixpanelLib.prototype.init;
30020 MixpanelLib.prototype['reset'] = MixpanelLib.prototype.reset;
30021 MixpanelLib.prototype['disable'] = MixpanelLib.prototype.disable;
30022 MixpanelLib.prototype['time_event'] = MixpanelLib.prototype.time_event;
30023 MixpanelLib.prototype['track'] = MixpanelLib.prototype.track;
30024 MixpanelLib.prototype['track_links'] = MixpanelLib.prototype.track_links;
30025 MixpanelLib.prototype['track_forms'] = MixpanelLib.prototype.track_forms;
30026 MixpanelLib.prototype['track_pageview'] = MixpanelLib.prototype.track_pageview;
30027 MixpanelLib.prototype['register'] = MixpanelLib.prototype.register;
30028 MixpanelLib.prototype['register_once'] = MixpanelLib.prototype.register_once;
30029 MixpanelLib.prototype['unregister'] = MixpanelLib.prototype.unregister;
30030 MixpanelLib.prototype['identify'] = MixpanelLib.prototype.identify;
30031 MixpanelLib.prototype['alias'] = MixpanelLib.prototype.alias;
30032 MixpanelLib.prototype['name_tag'] = MixpanelLib.prototype.name_tag;
30033 MixpanelLib.prototype['set_config'] = MixpanelLib.prototype.set_config;
30034 MixpanelLib.prototype['get_config'] = MixpanelLib.prototype.get_config;
30035 MixpanelLib.prototype['get_api_host'] = MixpanelLib.prototype.get_api_host;
30036 MixpanelLib.prototype['get_property'] = MixpanelLib.prototype.get_property;
30037 MixpanelLib.prototype['get_distinct_id'] = MixpanelLib.prototype.get_distinct_id;
30038 MixpanelLib.prototype['toString'] = MixpanelLib.prototype.toString;
30039 MixpanelLib.prototype['opt_out_tracking'] = MixpanelLib.prototype.opt_out_tracking;
30040 MixpanelLib.prototype['opt_in_tracking'] = MixpanelLib.prototype.opt_in_tracking;
30041 MixpanelLib.prototype['has_opted_out_tracking'] = MixpanelLib.prototype.has_opted_out_tracking;
30042 MixpanelLib.prototype['has_opted_in_tracking'] = MixpanelLib.prototype.has_opted_in_tracking;
30043 MixpanelLib.prototype['clear_opt_in_out_tracking'] = MixpanelLib.prototype.clear_opt_in_out_tracking;
30044 MixpanelLib.prototype['get_group'] = MixpanelLib.prototype.get_group;
30045 MixpanelLib.prototype['set_group'] = MixpanelLib.prototype.set_group;
30046 MixpanelLib.prototype['add_group'] = MixpanelLib.prototype.add_group;
30047 MixpanelLib.prototype['remove_group'] = MixpanelLib.prototype.remove_group;
30048 MixpanelLib.prototype['track_with_groups'] = MixpanelLib.prototype.track_with_groups;
30049 MixpanelLib.prototype['start_batch_senders'] = MixpanelLib.prototype.start_batch_senders;
30050 MixpanelLib.prototype['stop_batch_senders'] = MixpanelLib.prototype.stop_batch_senders;
30051 MixpanelLib.prototype['start_session_recording'] = MixpanelLib.prototype.start_session_recording;
30052 MixpanelLib.prototype['stop_session_recording'] = MixpanelLib.prototype.stop_session_recording;
30053 MixpanelLib.prototype['pause_session_recording'] = MixpanelLib.prototype.pause_session_recording;
30054 MixpanelLib.prototype['resume_session_recording'] = MixpanelLib.prototype.resume_session_recording;
30055 MixpanelLib.prototype['get_session_recording_properties'] = MixpanelLib.prototype.get_session_recording_properties;
30056 MixpanelLib.prototype['get_session_replay_url'] = MixpanelLib.prototype.get_session_replay_url;
30057 MixpanelLib.prototype['get_tab_id'] = MixpanelLib.prototype.get_tab_id;
30058 MixpanelLib.prototype['DEFAULT_API_ROUTES'] = DEFAULT_API_ROUTES;
30059
30060 // Exports intended only for testing
30061 MixpanelLib.prototype['__get_recorder'] = MixpanelLib.prototype.__get_recorder;
30062
30063 // MixpanelPersistence Exports
30064 MixpanelPersistence.prototype['properties'] = MixpanelPersistence.prototype.properties;
30065 MixpanelPersistence.prototype['update_search_keyword'] = MixpanelPersistence.prototype.update_search_keyword;
30066 MixpanelPersistence.prototype['update_referrer_info'] = MixpanelPersistence.prototype.update_referrer_info;
30067 MixpanelPersistence.prototype['get_cross_subdomain'] = MixpanelPersistence.prototype.get_cross_subdomain;
30068 MixpanelPersistence.prototype['clear'] = MixpanelPersistence.prototype.clear;
30069
30070
30071 var instances = {};
30072 var extend_mp = function() {
30073 // add all the sub mixpanel instances
30074 _.each(instances, function(instance, name) {
30075 if (name !== PRIMARY_INSTANCE_NAME) { mixpanel_master[name] = instance; }
30076 });
30077
30078 // add private functions as _
30079 mixpanel_master['_'] = _;
30080 };
30081
30082 var override_mp_init_func = function() {
30083 // we override the snippets init function to handle the case where a
30084 // user initializes the mixpanel library after the script loads & runs
30085 mixpanel_master['init'] = function(token, config, name) {
30086 if (name) {
30087 // initialize a sub library
30088 if (!mixpanel_master[name]) {
30089 mixpanel_master[name] = instances[name] = create_mplib(token, config, name);
30090 mixpanel_master[name]._loaded();
30091 }
30092 return mixpanel_master[name];
30093 } else {
30094 var instance = mixpanel_master;
30095
30096 if (instances[PRIMARY_INSTANCE_NAME]) {
30097 // main mixpanel lib already initialized
30098 instance = instances[PRIMARY_INSTANCE_NAME];
30099 } else if (token) {
30100 // intialize the main mixpanel lib
30101 instance = create_mplib(token, config, PRIMARY_INSTANCE_NAME);
30102 instance._loaded();
30103 instances[PRIMARY_INSTANCE_NAME] = instance;
30104 }
30105
30106 mixpanel_master = instance;
30107 if (init_type === INIT_SNIPPET) {
30108 win[PRIMARY_INSTANCE_NAME] = mixpanel_master;
30109 }
30110 extend_mp();
30111 }
30112 };
30113 };
30114
30115 var add_dom_loaded_handler = function() {
30116 // Cross browser DOM Loaded support
30117 function dom_loaded_handler() {
30118 // function flag since we only want to execute this once
30119 if (dom_loaded_handler.done) { return; }
30120 dom_loaded_handler.done = true;
30121
30122 DOM_LOADED = true;
30123 ENQUEUE_REQUESTS = false;
30124
30125 _.each(instances, function(inst) {
30126 inst._dom_loaded();
30127 });
30128 }
30129
30130 function do_scroll_check() {
30131 try {
30132 document$1.documentElement.doScroll('left');
30133 } catch(e) {
30134 setTimeout(do_scroll_check, 1);
30135 return;
30136 }
30137
30138 dom_loaded_handler();
30139 }
30140
30141 if (document$1.addEventListener) {
30142 if (document$1.readyState === 'complete') {
30143 // safari 4 can fire the DOMContentLoaded event before loading all
30144 // external JS (including this file). you will see some copypasta
30145 // on the internet that checks for 'complete' and 'loaded', but
30146 // 'loaded' is an IE thing
30147 dom_loaded_handler();
30148 } else {
30149 document$1.addEventListener('DOMContentLoaded', dom_loaded_handler, false);
30150 }
30151 } else if (document$1.attachEvent) {
30152 // IE
30153 document$1.attachEvent('onreadystatechange', dom_loaded_handler);
30154
30155 // check to make sure we arn't in a frame
30156 var toplevel = false;
30157 try {
30158 toplevel = win.frameElement === null;
30159 } catch(e) {
30160 // noop
30161 }
30162
30163 if (document$1.documentElement.doScroll && toplevel) {
30164 do_scroll_check();
30165 }
30166 }
30167
30168 // fallback handler, always will work
30169 _.register_event(win, 'load', dom_loaded_handler, true);
30170 };
30171
30172 function init_as_module(bundle_loader) {
30173 load_extra_bundle = bundle_loader;
30174 init_type = INIT_MODULE;
30175 mixpanel_master = new MixpanelLib();
30176
30177 override_mp_init_func();
30178 mixpanel_master['init']();
30179 add_dom_loaded_handler();
30180
30181 return mixpanel_master;
30182 }
30183
30184 // For loading separate bundles asynchronously via script tag
30185 // so that we don't load them until they are needed at runtime.
30186
30187 // For builds that have everything in one bundle, no extra work.
30188 function loadNoop (_src, onload) {
30189 onload();
30190 }
30191
30192 /* eslint camelcase: "off" */
30193
30194 var mixpanel = init_as_module(loadNoop);
30195
30196
30197
30198
30199 /***/ }),
30200
30201 /***/ "@reduxjs/toolkit":
30202 /*!************************************************!*\
30203 !*** external "elementorVendors.reduxToolkit" ***!
30204 \************************************************/
30205 /***/ ((module) => {
30206
30207 "use strict";
30208 module.exports = elementorVendors.reduxToolkit;
30209
30210 /***/ }),
30211
30212 /***/ "@wordpress/i18n":
30213 /*!**************************!*\
30214 !*** external "wp.i18n" ***!
30215 \**************************/
30216 /***/ ((module) => {
30217
30218 "use strict";
30219 module.exports = wp.i18n;
30220
30221 /***/ })
30222
30223 /******/ });
30224 /************************************************************************/
30225 /******/ // The module cache
30226 /******/ var __webpack_module_cache__ = {};
30227 /******/
30228 /******/ // The require function
30229 /******/ function __webpack_require__(moduleId) {
30230 /******/ // Check if module is in cache
30231 /******/ var cachedModule = __webpack_module_cache__[moduleId];
30232 /******/ if (cachedModule !== undefined) {
30233 /******/ return cachedModule.exports;
30234 /******/ }
30235 /******/ // Create a new module (and put it into the cache)
30236 /******/ var module = __webpack_module_cache__[moduleId] = {
30237 /******/ // no module.id needed
30238 /******/ // no module.loaded needed
30239 /******/ exports: {}
30240 /******/ };
30241 /******/
30242 /******/ // Execute the module function
30243 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
30244 /******/
30245 /******/ // Return the exports of the module
30246 /******/ return module.exports;
30247 /******/ }
30248 /******/
30249 /************************************************************************/
30250 /******/ /* webpack/runtime/define property getters */
30251 /******/ (() => {
30252 /******/ // define getter functions for harmony exports
30253 /******/ __webpack_require__.d = (exports, definition) => {
30254 /******/ for(var key in definition) {
30255 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
30256 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
30257 /******/ }
30258 /******/ }
30259 /******/ };
30260 /******/ })();
30261 /******/
30262 /******/ /* webpack/runtime/hasOwnProperty shorthand */
30263 /******/ (() => {
30264 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
30265 /******/ })();
30266 /******/
30267 /******/ /* webpack/runtime/make namespace object */
30268 /******/ (() => {
30269 /******/ // define __esModule on exports
30270 /******/ __webpack_require__.r = (exports) => {
30271 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
30272 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
30273 /******/ }
30274 /******/ Object.defineProperty(exports, '__esModule', { value: true });
30275 /******/ };
30276 /******/ })();
30277 /******/
30278 /************************************************************************/
30279 var __webpack_exports__ = {};
30280 // This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
30281 (() => {
30282 "use strict";
30283 /*!******************************************!*\
30284 !*** ../core/common/assets/js/common.js ***!
30285 \******************************************/
30286
30287
30288 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
30289 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
30290 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
30291 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
30292 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
30293 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
30294 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
30295 var _helpers = _interopRequireDefault(__webpack_require__(/*! ./utils/helpers */ "../core/common/assets/js/utils/helpers.js"));
30296 var _storage = _interopRequireDefault(__webpack_require__(/*! ./utils/storage */ "../core/common/assets/js/utils/storage.js"));
30297 var _debug = _interopRequireDefault(__webpack_require__(/*! ./utils/debug */ "../core/common/assets/js/utils/debug.js"));
30298 var _ajax = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/ajax/assets/js/ajax */ "../core/common/modules/ajax/assets/js/ajax.js"));
30299 var _finder = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/finder/assets/js/finder */ "../core/common/modules/finder/assets/js/finder.js"));
30300 var _connect = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/connect/assets/js/connect */ "../core/common/modules/connect/assets/js/connect.js"));
30301 var _component = _interopRequireDefault(__webpack_require__(/*! ./components/wordpress/component */ "../core/common/assets/js/components/wordpress/component.js"));
30302 var _component2 = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/event-tracker/assets/js/data/component */ "../core/common/modules/event-tracker/assets/js/data/component.js"));
30303 var _events = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/event-tracker/assets/js/events */ "../core/common/modules/event-tracker/assets/js/events.js"));
30304 var _module = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/events-manager/assets/js/module */ "../core/common/modules/events-manager/assets/js/module.js"));
30305 var _notifications = _interopRequireDefault(__webpack_require__(/*! elementor-utils/notifications */ "../assets/dev/js/utils/notifications.js"));
30306 function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
30307 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
30308 function _superPropGet(t, o, e, r) { var p = (0, _get2.default)((0, _getPrototypeOf2.default)(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
30309 var ElementorCommonApp = /*#__PURE__*/function (_elementorModules$Vie) {
30310 function ElementorCommonApp() {
30311 (0, _classCallCheck2.default)(this, ElementorCommonApp);
30312 return _callSuper(this, ElementorCommonApp, arguments);
30313 }
30314 (0, _inherits2.default)(ElementorCommonApp, _elementorModules$Vie);
30315 return (0, _createClass2.default)(ElementorCommonApp, [{
30316 key: "setMarionetteTemplateCompiler",
30317 value: function setMarionetteTemplateCompiler() {
30318 Marionette.TemplateCache.prototype.compileTemplate = function (rawTemplate, options) {
30319 options = {
30320 evaluate: /<#([\s\S]+?)#>/g,
30321 interpolate: /{{{([\s\S]+?)}}}/g,
30322 escape: /{{([^}]+?)}}(?!})/g
30323 };
30324 return _.template(rawTemplate, options);
30325 };
30326 }
30327 }, {
30328 key: "getDefaultElements",
30329 value: function getDefaultElements() {
30330 return {
30331 $window: jQuery(window),
30332 $document: jQuery(document),
30333 $body: jQuery(document.body)
30334 };
30335 }
30336 }, {
30337 key: "initComponents",
30338 value: function initComponents() {
30339 this.events = new _events.default();
30340 this.eventsManager = new _module.default();
30341 this.debug = new _debug.default();
30342 this.helpers = new _helpers.default();
30343 this.storage = new _storage.default();
30344 this.dialogsManager = new DialogsManager.Instance();
30345 this.notifications = new _notifications.default();
30346 this.api = window.$e;
30347 $e.components.register(new _component2.default());
30348 elementorCommon.elements.$window.on('elementor:init-components', function () {
30349 $e.components.register(new _component.default());
30350 });
30351 this.initModules();
30352 }
30353 }, {
30354 key: "initModules",
30355 value: function initModules() {
30356 var _this = this;
30357 var activeModules = this.config.activeModules;
30358 var modules = {
30359 ajax: _ajax.default,
30360 finder: _finder.default,
30361 connect: _connect.default
30362 };
30363 activeModules.forEach(function (name) {
30364 if (modules[name]) {
30365 _this[name] = new modules[name](_this.config[name]);
30366 }
30367 });
30368 }
30369 }, {
30370 key: "compileArrayTemplateArgs",
30371 value: function compileArrayTemplateArgs(template, templateArgs) {
30372 return template.replace(/%(?:(\d+)\$)?s/g, function (match, number) {
30373 if (!number) {
30374 number = 1;
30375 }
30376 number--;
30377 return undefined !== templateArgs[number] ? templateArgs[number] : match;
30378 });
30379 }
30380 }, {
30381 key: "compileObjectTemplateArgs",
30382 value: function compileObjectTemplateArgs(template, templateArgs) {
30383 return template.replace(/{{(?:([ \w]+))}}/g, function (match, name) {
30384 return templateArgs[name] ? templateArgs[name] : match;
30385 });
30386 }
30387 }, {
30388 key: "compileTemplate",
30389 value: function compileTemplate(template, templateArgs) {
30390 return jQuery.isPlainObject(templateArgs) ? this.compileObjectTemplateArgs(template, templateArgs) : this.compileArrayTemplateArgs(template, templateArgs);
30391 }
30392 }, {
30393 key: "translate",
30394 value: function translate(stringKey, context, templateArgs, i18nStack) {
30395 if (context) {
30396 i18nStack = this.config[context].i18n;
30397 }
30398 if (!i18nStack) {
30399 i18nStack = this.config.i18n;
30400 }
30401 var string = i18nStack[stringKey];
30402 if (undefined === string) {
30403 string = stringKey;
30404 }
30405 if (templateArgs) {
30406 string = this.compileTemplate(string, templateArgs);
30407 }
30408 return string;
30409 }
30410 }, {
30411 key: "onInit",
30412 value: function onInit() {
30413 _superPropGet(ElementorCommonApp, "onInit", this, 3)([]);
30414 this.config = elementorCommonConfig;
30415 this.setMarionetteTemplateCompiler();
30416 }
30417 }]);
30418 }(elementorModules.ViewModule);
30419 window.elementorCommon = new ElementorCommonApp();
30420 elementorCommon.initComponents();
30421 })();
30422
30423 /******/ })()
30424 ;
30425 //# sourceMappingURL=common.js.map