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

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

30,431 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 this.getEventsManager().dispatchEvent(eventName, payload);
58 }
59 }, {
60 key: "toLowerSnake",
61 value: function toLowerSnake(value) {
62 if (!value || 'string' !== typeof value) {
63 return value;
64 }
65 return value.replace(/\s+/g, '_').toLowerCase();
66 }
67 }, {
68 key: "decodeHtmlEntities",
69 value: function decodeHtmlEntities(text) {
70 if (!text || 'string' !== typeof text) {
71 return text;
72 }
73 var doc = new DOMParser().parseFromString(text, 'text/html');
74 return doc.body.textContent || text;
75 }
76 }, {
77 key: "isInEditorContext",
78 value: function isInEditorContext() {
79 var _window$elementor;
80 return 'undefined' !== typeof window.elementor && !!((_window$elementor = window.elementor) !== null && _window$elementor !== void 0 && _window$elementor.documents);
81 }
82 }, {
83 key: "getFinderContext",
84 value: function getFinderContext() {
85 var _config$appTypes, _config$appTypes2, _config$locations, _config$locations2;
86 var config = this.getConfig();
87 var isEditor = this.isInEditorContext();
88 return {
89 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,
90 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)
91 };
92 }
93 }, {
94 key: "createBasePayload",
95 value: function createBasePayload() {
96 var _config$appTypes$edit, _config$appTypes3, _config$appTypes$edit2, _config$appTypes4;
97 var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
98 var config = this.getConfig();
99 return _objectSpread({
100 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',
101 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'
102 }, overrides);
103 }
104 }, {
105 key: "sendTopBarPublishDropdown",
106 value: function sendTopBarPublishDropdown(targetName) {
107 var _config$names, _config$triggers, _config$targetTypes, _config$interactionRe, _config$locations3, _config$secondaryLoca, _config$targetTypes2;
108 var config = this.getConfig();
109 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({
110 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers = config.triggers) === null || _config$triggers === void 0 ? void 0 : _config$triggers.click),
111 target_type: config === null || config === void 0 || (_config$targetTypes = config.targetTypes) === null || _config$targetTypes === void 0 ? void 0 : _config$targetTypes.dropdownItem,
112 target_name: targetName,
113 interaction_result: config === null || config === void 0 || (_config$interactionRe = config.interactionResults) === null || _config$interactionRe === void 0 ? void 0 : _config$interactionRe.actionSelected,
114 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations3 = config.locations) === null || _config$locations3 === void 0 ? void 0 : _config$locations3.topBar),
115 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca = config.secondaryLocations) === null || _config$secondaryLoca === void 0 ? void 0 : _config$secondaryLoca.publishDropdown),
116 location_l2: config === null || config === void 0 || (_config$targetTypes2 = config.targetTypes) === null || _config$targetTypes2 === void 0 ? void 0 : _config$targetTypes2.dropdownItem,
117 interaction_description: 'User selected an action from the publish dropdown'
118 }));
119 }
120 }, {
121 key: "sendTopBarPageList",
122 value: function sendTopBarPageList(targetName) {
123 var _config$names2, _config$triggers2, _config$targetTypes3, _config$interactionRe2, _config$interactionRe3, _config$locations4, _config$secondaryLoca2, _config$targetTypes4;
124 var isCreate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
125 var config = this.getConfig();
126 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({
127 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers2 = config.triggers) === null || _config$triggers2 === void 0 ? void 0 : _config$triggers2.click),
128 target_type: config === null || config === void 0 || (_config$targetTypes3 = config.targetTypes) === null || _config$targetTypes3 === void 0 ? void 0 : _config$targetTypes3.dropdownItem,
129 target_name: targetName,
130 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,
131 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations4 = config.locations) === null || _config$locations4 === void 0 ? void 0 : _config$locations4.topBar),
132 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca2 = config.secondaryLocations) === null || _config$secondaryLoca2 === void 0 ? void 0 : _config$secondaryLoca2.pageListDropdown),
133 location_l2: config === null || config === void 0 || (_config$targetTypes4 = config.targetTypes) === null || _config$targetTypes4 === void 0 ? void 0 : _config$targetTypes4.dropdownItem,
134 interaction_description: 'User selected an action from the page list dropdown'
135 }));
136 }
137 }, {
138 key: "sendSiteSettingsSession",
139 value: function sendSiteSettingsSession(_ref) {
140 var _config$names3, _config$triggers3, _config$interactionRe4, _config$locations5, _config$secondaryLoca3;
141 var targetType = _ref.targetType,
142 _ref$visitedItems = _ref.visitedItems,
143 visitedItems = _ref$visitedItems === void 0 ? [] : _ref$visitedItems,
144 _ref$savedItems = _ref.savedItems,
145 savedItems = _ref$savedItems === void 0 ? [] : _ref$savedItems,
146 state = _ref.state;
147 var config = this.getConfig();
148 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({
149 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers3 = config.triggers) === null || _config$triggers3 === void 0 ? void 0 : _config$triggers3.click),
150 target_type: targetType,
151 target_name: 'site_settings',
152 interaction_result: config === null || config === void 0 || (_config$interactionRe4 = config.interactionResults) === null || _config$interactionRe4 === void 0 ? void 0 : _config$interactionRe4.sessionEnd,
153 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations5 = config.locations) === null || _config$locations5 === void 0 ? void 0 : _config$locations5.leftPanel),
154 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca3 = config.secondaryLocations) === null || _config$secondaryLoca3 === void 0 ? void 0 : _config$secondaryLoca3.siteSettings),
155 interaction_description: 'Records areas visited as part of the site setting session',
156 metadata: {
157 visited_items: visitedItems,
158 saved_items: savedItems
159 },
160 state: state
161 }));
162 }
163 }, {
164 key: "sendELibraryNav",
165 value: function sendELibraryNav(tabName) {
166 var _config$names4, _config$triggers4, _config$targetTypes5, _config$interactionRe5, _config$locations6, _config$secondaryLoca4;
167 var config = this.getConfig();
168 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({
169 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers4 = config.triggers) === null || _config$triggers4 === void 0 ? void 0 : _config$triggers4.tabSelect),
170 target_type: config === null || config === void 0 || (_config$targetTypes5 = config.targetTypes) === null || _config$targetTypes5 === void 0 ? void 0 : _config$targetTypes5.tab,
171 target_name: this.toLowerSnake(tabName),
172 interaction_result: config === null || config === void 0 || (_config$interactionRe5 = config.interactionResults) === null || _config$interactionRe5 === void 0 ? void 0 : _config$interactionRe5.tabChanged,
173 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations6 = config.locations) === null || _config$locations6 === void 0 ? void 0 : _config$locations6.elementorLibrary),
174 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca4 = config.secondaryLocations) === null || _config$secondaryLoca4 === void 0 ? void 0 : _config$secondaryLoca4.libraryTabs),
175 interaction_description: 'User navigates within elementor library'
176 }));
177 }
178 }, {
179 key: "sendELibraryInsert",
180 value: function sendELibraryInsert(_ref2) {
181 var _config$triggers5, _config$targetTypes6, _config$interactionRe6, _config$locations7, _config$secondaryLoca5, _config$names5;
182 var assetId = _ref2.assetId,
183 assetName = _ref2.assetName,
184 libraryType = _ref2.libraryType,
185 _ref2$proRequired = _ref2.proRequired,
186 proRequired = _ref2$proRequired === void 0 ? false : _ref2$proRequired;
187 var config = this.getConfig();
188 var payload = this.createBasePayload({
189 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers5 = config.triggers) === null || _config$triggers5 === void 0 ? void 0 : _config$triggers5.insert),
190 target_type: config === null || config === void 0 || (_config$targetTypes6 = config.targetTypes) === null || _config$targetTypes6 === void 0 ? void 0 : _config$targetTypes6.button,
191 target_name: String(assetId),
192 interaction_result: config === null || config === void 0 || (_config$interactionRe6 = config.interactionResults) === null || _config$interactionRe6 === void 0 ? void 0 : _config$interactionRe6.assetInserted,
193 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations7 = config.locations) === null || _config$locations7 === void 0 ? void 0 : _config$locations7.elementorLibrary),
194 location_l1: this.toLowerSnake(libraryType),
195 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca5 = config.secondaryLocations) === null || _config$secondaryLoca5 === void 0 ? void 0 : _config$secondaryLoca5.assetCard),
196 interaction_description: 'User inserts block/pages from elementor library',
197 metadata: {
198 template_id: String(assetId),
199 template_name: this.decodeHtmlEntities(assetName) || ''
200 }
201 });
202 if (proRequired) {
203 payload.state = 'pro_plan_required';
204 }
205 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);
206 }
207 }, {
208 key: "sendELibraryFavorite",
209 value: function sendELibraryFavorite(_ref3) {
210 var _config$triggers6, _config$targetTypes7, _config$interactionRe7, _config$locations8, _config$secondaryLoca6, _config$names6;
211 var assetId = _ref3.assetId,
212 assetName = _ref3.assetName,
213 libraryType = _ref3.libraryType,
214 isFavorite = _ref3.isFavorite,
215 _ref3$proRequired = _ref3.proRequired,
216 proRequired = _ref3$proRequired === void 0 ? false : _ref3$proRequired;
217 var config = this.getConfig();
218 var payload = this.createBasePayload({
219 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers6 = config.triggers) === null || _config$triggers6 === void 0 ? void 0 : _config$triggers6.click),
220 target_type: config === null || config === void 0 || (_config$targetTypes7 = config.targetTypes) === null || _config$targetTypes7 === void 0 ? void 0 : _config$targetTypes7.toggle,
221 target_name: String(assetId),
222 interaction_result: config === null || config === void 0 || (_config$interactionRe7 = config.interactionResults) === null || _config$interactionRe7 === void 0 ? void 0 : _config$interactionRe7.assetFavorite,
223 target_value: Boolean(isFavorite),
224 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations8 = config.locations) === null || _config$locations8 === void 0 ? void 0 : _config$locations8.elementorLibrary),
225 location_l1: this.toLowerSnake(libraryType),
226 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca6 = config.secondaryLocations) === null || _config$secondaryLoca6 === void 0 ? void 0 : _config$secondaryLoca6.assetCard),
227 interaction_description: 'User favorite block/pages from elementor library',
228 metadata: {
229 template_id: String(assetId),
230 template_name: this.decodeHtmlEntities(assetName) || ''
231 }
232 });
233 if (proRequired) {
234 payload.state = 'pro_plan_required';
235 }
236 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);
237 }
238 }, {
239 key: "sendELibraryGenerateAi",
240 value: function sendELibraryGenerateAi(_ref4) {
241 var _config$names7, _config$triggers7, _config$targetTypes8, _config$interactionRe8, _config$locations9, _config$secondaryLoca7;
242 var assetId = _ref4.assetId,
243 assetName = _ref4.assetName,
244 libraryType = _ref4.libraryType;
245 var config = this.getConfig();
246 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({
247 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers7 = config.triggers) === null || _config$triggers7 === void 0 ? void 0 : _config$triggers7.click),
248 target_type: config === null || config === void 0 || (_config$targetTypes8 = config.targetTypes) === null || _config$targetTypes8 === void 0 ? void 0 : _config$targetTypes8.button,
249 target_name: String(assetId),
250 interaction_result: config === null || config === void 0 || (_config$interactionRe8 = config.interactionResults) === null || _config$interactionRe8 === void 0 ? void 0 : _config$interactionRe8.aiGenerate,
251 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations9 = config.locations) === null || _config$locations9 === void 0 ? void 0 : _config$locations9.elementorLibrary),
252 location_l1: this.toLowerSnake(libraryType),
253 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca7 = config.secondaryLocations) === null || _config$secondaryLoca7 === void 0 ? void 0 : _config$secondaryLoca7.assetCard),
254 interaction_description: 'User generated block/page based on a library asset',
255 metadata: {
256 template_id: String(assetId),
257 template_name: this.decodeHtmlEntities(assetName) || ''
258 }
259 }));
260 }
261 }, {
262 key: "sendFinderSearchInput",
263 value: function sendFinderSearchInput(_ref5) {
264 var _config$triggers8, _config$targetTypes9, _config$interactionRe9, _config$interactionRe0, _config$secondaryLoca8, _config$names8;
265 var resultsCount = _ref5.resultsCount,
266 _ref5$searchTerm = _ref5.searchTerm,
267 searchTerm = _ref5$searchTerm === void 0 ? null : _ref5$searchTerm;
268 var config = this.getConfig();
269 var hasResults = resultsCount > 0;
270 var finderContext = this.getFinderContext();
271 var payload = this.createBasePayload({
272 window_name: finderContext.windowName,
273 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers8 = config.triggers) === null || _config$triggers8 === void 0 ? void 0 : _config$triggers8.typing),
274 target_type: config === null || config === void 0 || (_config$targetTypes9 = config.targetTypes) === null || _config$targetTypes9 === void 0 ? void 0 : _config$targetTypes9.searchInput,
275 target_name: 'finder',
276 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,
277 target_location: finderContext.targetLocation,
278 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca8 = config.secondaryLocations) === null || _config$secondaryLoca8 === void 0 ? void 0 : _config$secondaryLoca8.finder),
279 interaction_description: 'Finder search input, follows debounce behavior',
280 metadata: {
281 results_count: resultsCount
282 }
283 });
284 if (!hasResults && searchTerm) {
285 payload.metadata.search_term = searchTerm;
286 }
287 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);
288 }
289 }, {
290 key: "sendFinderResultSelect",
291 value: function sendFinderResultSelect(choice) {
292 var _config$names9, _config$triggers9, _config$targetTypes0, _config$interactionRe1, _config$secondaryLoca9, _config$secondaryLoca0;
293 var config = this.getConfig();
294 var finderContext = this.getFinderContext();
295 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({
296 window_name: finderContext.windowName,
297 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers9 = config.triggers) === null || _config$triggers9 === void 0 ? void 0 : _config$triggers9.click),
298 target_type: config === null || config === void 0 || (_config$targetTypes0 = config.targetTypes) === null || _config$targetTypes0 === void 0 ? void 0 : _config$targetTypes0.searchResult,
299 target_name: choice,
300 interaction_result: config === null || config === void 0 || (_config$interactionRe1 = config.interactionResults) === null || _config$interactionRe1 === void 0 ? void 0 : _config$interactionRe1.selected,
301 target_location: finderContext.targetLocation,
302 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca9 = config.secondaryLocations) === null || _config$secondaryLoca9 === void 0 ? void 0 : _config$secondaryLoca9.finder),
303 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca0 = config.secondaryLocations) === null || _config$secondaryLoca0 === void 0 ? void 0 : _config$secondaryLoca0.finderResults),
304 interaction_description: 'Finder search results was selected'
305 }));
306 }
307 }, {
308 key: "sendCanvasEmptyBoxAction",
309 value: function sendCanvasEmptyBoxAction(_ref6) {
310 var _config$triggers0, _config$targetTypes1, _config$interactionRe10, _config$locations0, _config$secondaryLoca1, _config$names0;
311 var targetName = _ref6.targetName,
312 _ref6$metadata = _ref6.metadata,
313 metadata = _ref6$metadata === void 0 ? {} : _ref6$metadata,
314 _ref6$containerCreate = _ref6.containerCreated,
315 containerCreated = _ref6$containerCreate === void 0 ? null : _ref6$containerCreate;
316 var config = this.getConfig();
317 var payload = this.createBasePayload({
318 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers0 = config.triggers) === null || _config$triggers0 === void 0 ? void 0 : _config$triggers0.click),
319 target_type: config === null || config === void 0 || (_config$targetTypes1 = config.targetTypes) === null || _config$targetTypes1 === void 0 ? void 0 : _config$targetTypes1.buttons,
320 target_name: targetName,
321 interaction_result: config === null || config === void 0 || (_config$interactionRe10 = config.interactionResults) === null || _config$interactionRe10 === void 0 ? void 0 : _config$interactionRe10.selected,
322 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations0 = config.locations) === null || _config$locations0 === void 0 ? void 0 : _config$locations0.canvas),
323 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca1 = config.secondaryLocations) === null || _config$secondaryLoca1 === void 0 ? void 0 : _config$secondaryLoca1.emptyBox),
324 interaction_description: 'Empty box on canvas actions'
325 });
326 if (Object.keys(metadata).length > 0) {
327 payload.metadata = metadata;
328 }
329 if (containerCreated !== null) {
330 payload.state = containerCreated;
331 }
332 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);
333 }
334 }, {
335 key: "sendWidgetPanelSearch",
336 value: function sendWidgetPanelSearch(_ref7) {
337 var _config$triggers1, _config$targetTypes10, _config$interactionRe11, _config$interactionRe12, _config$locations1, _config$locations10, _config$secondaryLoca10, _config$names1;
338 var resultsCount = _ref7.resultsCount,
339 _ref7$userInput = _ref7.userInput,
340 userInput = _ref7$userInput === void 0 ? null : _ref7$userInput;
341 var config = this.getConfig();
342 var hasResults = resultsCount > 0;
343 var payload = this.createBasePayload({
344 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers1 = config.triggers) === null || _config$triggers1 === void 0 ? void 0 : _config$triggers1.typing),
345 target_type: config === null || config === void 0 || (_config$targetTypes10 = config.targetTypes) === null || _config$targetTypes10 === void 0 ? void 0 : _config$targetTypes10.searchWidget,
346 target_name: 'search_widget',
347 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,
348 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations1 = config.locations) === null || _config$locations1 === void 0 ? void 0 : _config$locations1.leftPanel),
349 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$locations10 = config.locations) === null || _config$locations10 === void 0 ? void 0 : _config$locations10.widgetPanel),
350 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca10 = config.secondaryLocations) === null || _config$secondaryLoca10 === void 0 ? void 0 : _config$secondaryLoca10.searchBar),
351 interaction_description: 'Widget search input, follows debounce behavior'
352 });
353 if (!hasResults && userInput) {
354 payload.metadata = {
355 user_input: userInput
356 };
357 }
358 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);
359 }
360 }, {
361 key: "createWpDashPayload",
362 value: function createWpDashPayload() {
363 var _config$appTypes$wpDa, _config$appTypes5, _config$locations11;
364 var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
365 var config = this.getConfig();
366 return this.createBasePayload(_objectSpread({
367 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',
368 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations11 = config.locations) === null || _config$locations11 === void 0 ? void 0 : _config$locations11.wpDashAdmin),
369 location_l2: ''
370 }, overrides));
371 }
372 }, {
373 key: "sendWpDashElementorMenuClick",
374 value: function sendWpDashElementorMenuClick() {
375 var _config$names10, _config$triggers10, _config$targetTypes11, _config$interactionRe13, _config$secondaryLoca11;
376 var config = this.getConfig();
377 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({
378 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers10 = config.triggers) === null || _config$triggers10 === void 0 ? void 0 : _config$triggers10.click),
379 target_type: config === null || config === void 0 || (_config$targetTypes11 = config.targetTypes) === null || _config$targetTypes11 === void 0 ? void 0 : _config$targetTypes11.wpDashAdminMenuItem,
380 target_name: 'elementor_menu_item',
381 interaction_result: config === null || config === void 0 || (_config$interactionRe13 = config.interactionResults) === null || _config$interactionRe13 === void 0 ? void 0 : _config$interactionRe13.elementorSideMenuOpened,
382 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca11 = config.secondaryLocations) === null || _config$secondaryLoca11 === void 0 ? void 0 : _config$secondaryLoca11.wpDashElementorCoreMenu),
383 interaction_description: 'core_user_clicked_elementor_menu_item'
384 }));
385 }
386 }, {
387 key: "sendWpDashEditorSubMenuHover",
388 value: function sendWpDashEditorSubMenuHover() {
389 var _config$names11, _config$triggers11, _config$targetTypes12, _config$interactionRe14, _config$secondaryLoca12;
390 var config = this.getConfig();
391 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({
392 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers11 = config.triggers) === null || _config$triggers11 === void 0 ? void 0 : _config$triggers11.hover),
393 target_type: config === null || config === void 0 || (_config$targetTypes12 = config.targetTypes) === null || _config$targetTypes12 === void 0 ? void 0 : _config$targetTypes12.wpDashEditorMenu,
394 target_name: 'wpdash_editor_sub_menu',
395 interaction_result: config === null || config === void 0 || (_config$interactionRe14 = config.interactionResults) === null || _config$interactionRe14 === void 0 ? void 0 : _config$interactionRe14.editorSubMenuOpened,
396 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca12 = config.secondaryLocations) === null || _config$secondaryLoca12 === void 0 ? void 0 : _config$secondaryLoca12.wpDashElementorCoreSubMenu),
397 interaction_description: 'core_user_hovered_sub_menu'
398 }));
399 }
400 }, {
401 key: "sendWpDashThemeBuilderClick",
402 value: function sendWpDashThemeBuilderClick() {
403 var _config$names12, _config$triggers12, _config$targetTypes13, _config$interactionRe15, _config$secondaryLoca13;
404 var config = this.getConfig();
405 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({
406 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers12 = config.triggers) === null || _config$triggers12 === void 0 ? void 0 : _config$triggers12.click),
407 target_type: config === null || config === void 0 || (_config$targetTypes13 = config.targetTypes) === null || _config$targetTypes13 === void 0 ? void 0 : _config$targetTypes13.wpDashSubMenuItem,
408 target_name: 'theme_builder_menu_item',
409 interaction_result: config === null || config === void 0 || (_config$interactionRe15 = config.interactionResults) === null || _config$interactionRe15 === void 0 ? void 0 : _config$interactionRe15.themeBuilderPromotionWindow,
410 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca13 = config.secondaryLocations) === null || _config$secondaryLoca13 === void 0 ? void 0 : _config$secondaryLoca13.wpDashThemeBuilder),
411 interaction_description: 'core_user_clicked_theme_builder_menu_item'
412 }));
413 }
414 }]);
415 }();
416 var createDebouncedFinderSearch = exports.createDebouncedFinderSearch = function createDebouncedFinderSearch() {
417 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300;
418 return _.debounce(function (resultsCount, searchTerm) {
419 EditorOneEventManager.sendFinderSearchInput({
420 resultsCount: resultsCount,
421 searchTerm: searchTerm
422 });
423 }, delay);
424 };
425 var createDebouncedWidgetPanelSearch = exports.createDebouncedWidgetPanelSearch = function createDebouncedWidgetPanelSearch() {
426 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2000;
427 return _.debounce(function (resultsCount, userInput) {
428 EditorOneEventManager.sendWidgetPanelSearch({
429 resultsCount: resultsCount,
430 userInput: userInput
431 });
432 }, delay);
433 };
434 var _default = exports["default"] = EditorOneEventManager;
435
436 /***/ }),
437
438 /***/ "../assets/dev/js/editor/utils/files-upload-handler.js":
439 /*!*************************************************************!*\
440 !*** ../assets/dev/js/editor/utils/files-upload-handler.js ***!
441 \*************************************************************/
442 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
443
444 "use strict";
445 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
446
447
448 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
449 Object.defineProperty(exports, "__esModule", ({
450 value: true
451 }));
452 exports["default"] = void 0;
453 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
454 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
455 var FilesUploadHandler = exports["default"] = /*#__PURE__*/function () {
456 function FilesUploadHandler() {
457 (0, _classCallCheck2.default)(this, FilesUploadHandler);
458 }
459 return (0, _createClass2.default)(FilesUploadHandler, null, [{
460 key: "isUploadEnabled",
461 value: function isUploadEnabled(mediaType) {
462 var unfilteredFilesTypes = ['svg', 'application/json'];
463 if (!unfilteredFilesTypes.includes(mediaType)) {
464 return true;
465 }
466 return elementorCommon.config.filesUpload.unfilteredFiles;
467 }
468 }, {
469 key: "setUploadTypeCaller",
470 value: function setUploadTypeCaller(frame) {
471 frame.uploader.uploader.param('uploadTypeCaller', 'elementor-wp-media-upload');
472 }
473 }, {
474 key: "getUnfilteredFilesNonAdminDialog",
475 value: function getUnfilteredFilesNonAdminDialog() {
476 return elementorCommon.dialogsManager.createWidget('alert', {
477 id: 'e-unfiltered-files-disabled-dialog',
478 headerMessage: __('Sorry, you can\'t upload that file yet', 'elementor'),
479 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'),
480 strings: {
481 confirm: __('Got it', 'elementor')
482 }
483 });
484 }
485 }, {
486 key: "getUnfilteredFilesNotEnabledDialog",
487 value: function getUnfilteredFilesNotEnabledDialog(callback) {
488 var elementorInstance = window.elementorAdmin || window.elementor;
489 if (!elementorInstance.config.user.is_administrator) {
490 return this.getUnfilteredFilesNonAdminDialog();
491 }
492 var onConfirm = function onConfirm() {
493 elementorCommon.ajax.addRequest('enable_unfiltered_files_upload', {}, true);
494 elementorCommon.config.filesUpload.unfilteredFiles = true;
495 callback();
496 };
497 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);
498 }
499 }, {
500 key: "getUnfilteredFilesNotEnabledImportTemplateDialog",
501 value: function getUnfilteredFilesNotEnabledImportTemplateDialog(callback) {
502 if (!(window.elementorAdmin || window.elementor).config.user.is_administrator) {
503 return this.getUnfilteredFilesNonAdminDialog();
504 }
505 return elementorCommon.dialogsManager.createWidget('confirm', {
506 id: 'e-enable-unfiltered-files-dialog-import-template',
507 headerMessage: __('Enable Unfiltered File Uploads', 'elementor'),
508 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'),
509 position: {
510 my: 'center center',
511 at: 'center center'
512 },
513 strings: {
514 confirm: __('Enable and Import', 'elementor'),
515 cancel: __('Import Without Enabling', 'elementor')
516 },
517 onConfirm: function onConfirm() {
518 elementorCommon.ajax.addRequest('enable_unfiltered_files_upload', {
519 success: function success() {
520 // This utility is used in both the admin and the Editor.
521 elementorCommon.config.filesUpload.unfilteredFiles = true;
522 callback();
523 }
524 }, true);
525 },
526 onCancel: function onCancel() {
527 return callback();
528 }
529 });
530 }
531 }]);
532 }();
533
534 /***/ }),
535
536 /***/ "../assets/dev/js/editor/utils/is-instanceof.js":
537 /*!******************************************************!*\
538 !*** ../assets/dev/js/editor/utils/is-instanceof.js ***!
539 \******************************************************/
540 /***/ ((__unused_webpack_module, exports) => {
541
542 "use strict";
543
544
545 Object.defineProperty(exports, "__esModule", ({
546 value: true
547 }));
548 exports["default"] = void 0;
549 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; } } }; }
550 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; } }
551 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; }
552 /**
553 * Some FileAPI objects such as FileList, DataTransferItem and DataTransferItemList has inconsistency with the retrieved
554 * object (from events, etc.) and the actual JavaScript object so a regular instanceof doesn't work. This function can
555 * check whether it's instanceof by using the objects constructor and prototype names.
556 *
557 * @param object
558 * @param constructors
559 * @return {boolean}
560 */
561 var _default = exports["default"] = function _default(object, constructors) {
562 constructors = Array.isArray(constructors) ? constructors : [constructors];
563 var _iterator = _createForOfIteratorHelper(constructors),
564 _step;
565 try {
566 for (_iterator.s(); !(_step = _iterator.n()).done;) {
567 var constructor = _step.value;
568 if (object.constructor.name === constructor.prototype[Symbol.toStringTag]) {
569 return true;
570 }
571 }
572 } catch (err) {
573 _iterator.e(err);
574 } finally {
575 _iterator.f();
576 }
577 return false;
578 };
579
580 /***/ }),
581
582 /***/ "../assets/dev/js/modules/imports/args-object.js":
583 /*!*******************************************************!*\
584 !*** ../assets/dev/js/modules/imports/args-object.js ***!
585 \*******************************************************/
586 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
587
588 "use strict";
589
590
591 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
592 Object.defineProperty(exports, "__esModule", ({
593 value: true
594 }));
595 exports["default"] = void 0;
596 var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js"));
597 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
598 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
599 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
600 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
601 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
602 var _instanceType = _interopRequireDefault(__webpack_require__(/*! ./instance-type */ "../assets/dev/js/modules/imports/instance-type.js"));
603 var _isInstanceof = _interopRequireDefault(__webpack_require__(/*! ../../editor/utils/is-instanceof */ "../assets/dev/js/editor/utils/is-instanceof.js"));
604 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)); }
605 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
606 var ArgsObject = exports["default"] = /*#__PURE__*/function (_InstanceType) {
607 /**
608 * Function constructor().
609 *
610 * Create ArgsObject.
611 *
612 * @param {{}} args
613 */
614 function ArgsObject(args) {
615 var _this;
616 (0, _classCallCheck2.default)(this, ArgsObject);
617 _this = _callSuper(this, ArgsObject);
618 _this.args = args;
619 return _this;
620 }
621
622 /**
623 * Function requireArgument().
624 *
625 * Validate property in args.
626 *
627 * @param {string} property
628 * @param {{}} args
629 *
630 * @throws {Error}
631 */
632 (0, _inherits2.default)(ArgsObject, _InstanceType);
633 return (0, _createClass2.default)(ArgsObject, [{
634 key: "requireArgument",
635 value: function requireArgument(property) {
636 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.args;
637 if (!Object.prototype.hasOwnProperty.call(args, property)) {
638 throw Error("".concat(property, " is required."));
639 }
640 }
641
642 /**
643 * Function requireArgumentType().
644 *
645 * Validate property in args using `type === typeof(args.whatever)`.
646 *
647 * @param {string} property
648 * @param {string} type
649 * @param {{}} args
650 *
651 * @throws {Error}
652 */
653 }, {
654 key: "requireArgumentType",
655 value: function requireArgumentType(property, type) {
656 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
657 this.requireArgument(property, args);
658 if ((0, _typeof2.default)(args[property]) !== type) {
659 throw Error("".concat(property, " invalid type: ").concat(type, "."));
660 }
661 }
662
663 /**
664 * Function requireArgumentInstance().
665 *
666 * Validate property in args using `args.whatever instanceof instance`.
667 *
668 * @param {string} property
669 * @param {*} instance
670 * @param {{}} args
671 *
672 * @throws {Error}
673 */
674 }, {
675 key: "requireArgumentInstance",
676 value: function requireArgumentInstance(property, instance) {
677 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
678 this.requireArgument(property, args);
679 if (!(args[property] instanceof instance) && !(0, _isInstanceof.default)(args[property], instance)) {
680 throw Error("".concat(property, " invalid instance."));
681 }
682 }
683
684 /**
685 * Function requireArgumentConstructor().
686 *
687 * Validate property in args using `type === args.whatever.constructor`.
688 *
689 * @param {string} property
690 * @param {*} type
691 * @param {{}} args
692 *
693 * @throws {Error}
694 */
695 }, {
696 key: "requireArgumentConstructor",
697 value: function requireArgumentConstructor(property, type) {
698 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
699 this.requireArgument(property, args);
700
701 // Note: Converting the constructor to string in order to avoid equation issues
702 // due to different memory addresses between iframes (window.Object !== window.top.Object).
703 if (args[property].constructor.toString() !== type.prototype.constructor.toString()) {
704 throw Error("".concat(property, " invalid constructor type."));
705 }
706 }
707 }], [{
708 key: "getInstanceType",
709 value: function getInstanceType() {
710 return 'ArgsObject';
711 }
712 }]);
713 }(_instanceType.default);
714
715 /***/ }),
716
717 /***/ "../assets/dev/js/modules/imports/instance-type.js":
718 /*!*********************************************************!*\
719 !*** ../assets/dev/js/modules/imports/instance-type.js ***!
720 \*********************************************************/
721 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
722
723 "use strict";
724
725
726 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
727 Object.defineProperty(exports, "__esModule", ({
728 value: true
729 }));
730 exports["default"] = void 0;
731 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
732 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
733 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
734 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
735 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; }
736 var InstanceType = exports["default"] = /*#__PURE__*/function () {
737 function InstanceType() {
738 var _this = this;
739 (0, _classCallCheck2.default)(this, InstanceType);
740 // Since anonymous classes sometimes do not get validated by babel, do it manually.
741 var target = this instanceof InstanceType ? this.constructor : void 0;
742 var prototypes = [];
743 while (target.__proto__ && target.__proto__.name) {
744 prototypes.push(target.__proto__);
745 target = target.__proto__;
746 }
747 prototypes.reverse().forEach(function (proto) {
748 return _this instanceof proto;
749 });
750 }
751 return (0, _createClass2.default)(InstanceType, null, [{
752 key: Symbol.hasInstance,
753 value: function value(target) {
754 /**
755 * This is function extending being called each time JS uses instanceOf, since babel use it each time it create new class
756 * its give's opportunity to mange capabilities of instanceOf operator.
757 * saving current class each time will give option later to handle instanceOf manually.
758 */
759 var result = _superPropGet(InstanceType, Symbol.hasInstance, this, 2)([target]);
760
761 // Act normal when validate a class, which does not have instance type.
762 if (target && !target.constructor.getInstanceType) {
763 return result;
764 }
765 if (target) {
766 if (!target.instanceTypes) {
767 target.instanceTypes = [];
768 }
769 if (!result) {
770 if (this.getInstanceType() === target.constructor.getInstanceType()) {
771 result = true;
772 }
773 }
774 if (result) {
775 var name = this.getInstanceType === InstanceType.getInstanceType ? 'BaseInstanceType' : this.getInstanceType();
776 if (-1 === target.instanceTypes.indexOf(name)) {
777 target.instanceTypes.push(name);
778 }
779 }
780 }
781 if (!result && target) {
782 // Check if the given 'target', is instance of known types.
783 result = target.instanceTypes && Array.isArray(target.instanceTypes) && -1 !== target.instanceTypes.indexOf(this.getInstanceType());
784 }
785 return result;
786 }
787 }, {
788 key: "getInstanceType",
789 value: function getInstanceType() {
790 elementorModules.ForceMethodImplementation();
791 }
792 }]);
793 }();
794
795 /***/ }),
796
797 /***/ "../assets/dev/js/modules/imports/module.js":
798 /*!**************************************************!*\
799 !*** ../assets/dev/js/modules/imports/module.js ***!
800 \**************************************************/
801 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
802
803 "use strict";
804
805
806 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
807 var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js"));
808 var Module = function Module() {
809 var $ = jQuery,
810 instanceParams = arguments,
811 self = this,
812 events = {};
813 var settings;
814 var ensureClosureMethods = function ensureClosureMethods() {
815 $.each(self, function (methodName) {
816 var oldMethod = self[methodName];
817 if ('function' !== typeof oldMethod) {
818 return;
819 }
820 self[methodName] = function () {
821 return oldMethod.apply(self, arguments);
822 };
823 });
824 };
825 var initSettings = function initSettings() {
826 settings = self.getDefaultSettings();
827 var instanceSettings = instanceParams[0];
828 if (instanceSettings) {
829 $.extend(true, settings, instanceSettings);
830 }
831 };
832 var init = function init() {
833 self.__construct.apply(self, instanceParams);
834 ensureClosureMethods();
835 initSettings();
836 self.trigger('init');
837 };
838 this.getItems = function (items, itemKey) {
839 if (itemKey) {
840 var keyStack = itemKey.split('.'),
841 currentKey = keyStack.splice(0, 1);
842 if (!keyStack.length) {
843 return items[currentKey];
844 }
845 if (!items[currentKey]) {
846 return;
847 }
848 return this.getItems(items[currentKey], keyStack.join('.'));
849 }
850 return items;
851 };
852 this.getSettings = function (setting) {
853 return this.getItems(settings, setting);
854 };
855 this.setSettings = function (settingKey, value, settingsContainer) {
856 if (!settingsContainer) {
857 settingsContainer = settings;
858 }
859 if ('object' === (0, _typeof2.default)(settingKey)) {
860 $.extend(settingsContainer, settingKey);
861 return self;
862 }
863 var keyStack = settingKey.split('.'),
864 currentKey = keyStack.splice(0, 1);
865 if (!keyStack.length) {
866 settingsContainer[currentKey] = value;
867 return self;
868 }
869 if (!settingsContainer[currentKey]) {
870 settingsContainer[currentKey] = {};
871 }
872 return self.setSettings(keyStack.join('.'), value, settingsContainer[currentKey]);
873 };
874 this.getErrorMessage = function (type, functionName) {
875 var message;
876 switch (type) {
877 case 'forceMethodImplementation':
878 message = "The method '".concat(functionName, "' must to be implemented in the inheritor child.");
879 break;
880 default:
881 message = 'An error occurs';
882 }
883 return message;
884 };
885
886 // TODO: This function should be deleted ?.
887 this.forceMethodImplementation = function (functionName) {
888 throw new Error(this.getErrorMessage('forceMethodImplementation', functionName));
889 };
890 this.on = function (eventName, callback) {
891 if ('object' === (0, _typeof2.default)(eventName)) {
892 $.each(eventName, function (singleEventName) {
893 self.on(singleEventName, this);
894 });
895 return self;
896 }
897 var eventNames = eventName.split(' ');
898 eventNames.forEach(function (singleEventName) {
899 if (!events[singleEventName]) {
900 events[singleEventName] = [];
901 }
902 events[singleEventName].push(callback);
903 });
904 return self;
905 };
906 this.off = function (eventName, callback) {
907 if (!events[eventName]) {
908 return self;
909 }
910 if (!callback) {
911 delete events[eventName];
912 return self;
913 }
914 var callbackIndex = events[eventName].indexOf(callback);
915 if (-1 !== callbackIndex) {
916 delete events[eventName][callbackIndex];
917
918 // Reset array index (for next off on same event).
919 events[eventName] = events[eventName].filter(function (val) {
920 return val;
921 });
922 }
923 return self;
924 };
925 this.trigger = function (eventName) {
926 var methodName = 'on' + eventName[0].toUpperCase() + eventName.slice(1),
927 params = Array.prototype.slice.call(arguments, 1);
928 if (self[methodName]) {
929 self[methodName].apply(self, params);
930 }
931 var callbacks = events[eventName];
932 if (!callbacks) {
933 return self;
934 }
935 $.each(callbacks, function (index, callback) {
936 callback.apply(self, params);
937 });
938 return self;
939 };
940 init();
941 };
942 Module.prototype.__construct = function () {};
943 Module.prototype.getDefaultSettings = function () {
944 return {};
945 };
946 Module.prototype.getConstructorID = function () {
947 return this.constructor.name;
948 };
949 Module.extend = function (properties) {
950 var $ = jQuery,
951 parent = this;
952 var child = function child() {
953 return parent.apply(this, arguments);
954 };
955 $.extend(child, parent);
956 child.prototype = Object.create($.extend({}, parent.prototype, properties));
957 child.prototype.constructor = child;
958 child.__super__ = parent.prototype;
959 return child;
960 };
961 module.exports = Module;
962
963 /***/ }),
964
965 /***/ "../assets/dev/js/utils/notifications.js":
966 /*!***********************************************!*\
967 !*** ../assets/dev/js/utils/notifications.js ***!
968 \***********************************************/
969 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
970
971 "use strict";
972
973
974 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
975 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
976 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; }
977 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; }
978 module.exports = elementorModules.Module.extend({
979 initToast: function initToast() {
980 var toast = elementorCommon.dialogsManager.createWidget('buttons', {
981 id: 'elementor-toast',
982 position: {
983 my: 'center bottom',
984 at: 'center bottom-10',
985 of: '#elementor-panel-inner',
986 autoRefresh: true
987 },
988 hide: {
989 onClick: true,
990 auto: true,
991 autoDelay: 10000
992 },
993 effects: {
994 show: function show() {
995 var $widget = toast.getElements('widget');
996 $widget.show();
997 toast.refreshPosition();
998 var top = parseInt($widget.css('top'), 10);
999 $widget.hide().css('top', top + 100);
1000 $widget.animate({
1001 opacity: 'show',
1002 height: 'show',
1003 paddingBottom: 'show',
1004 paddingTop: 'show',
1005 top: top
1006 }, {
1007 easing: 'linear',
1008 duration: 300
1009 });
1010 },
1011 hide: function hide() {
1012 var $widget = toast.getElements('widget'),
1013 top = parseInt($widget.css('top'), 10);
1014 $widget.animate({
1015 opacity: 'hide',
1016 height: 'hide',
1017 paddingBottom: 'hide',
1018 paddingTop: 'hide',
1019 top: top + 100
1020 }, {
1021 easing: 'linear',
1022 duration: 300
1023 });
1024 }
1025 },
1026 button: {
1027 tag: 'button'
1028 }
1029 });
1030
1031 // Add role="status" and aria-live for screen reader announcement
1032 toast.getElements('widget').attr({
1033 role: 'status',
1034 'aria-live': 'polite',
1035 'aria-atomic': 'true'
1036 });
1037 this.getToast = function () {
1038 return toast;
1039 };
1040 },
1041 showToast: function showToast(options) {
1042 var toast = this.getToast();
1043 toast.setMessage(options.message);
1044 toast.getElements('buttonsWrapper').empty();
1045 toast.focusedButton = null;
1046 toast.buttons = [];
1047 var isPositionValid = this.isPositionValid(options === null || options === void 0 ? void 0 : options.position);
1048 if (!isPositionValid) {
1049 this.positionToWindow();
1050 }
1051 if (options !== null && options !== void 0 && options.position && isPositionValid) {
1052 toast.setSettings('position', options.position);
1053 }
1054 if (options.buttons) {
1055 options.buttons.forEach(function (button) {
1056 toast.addButton(button);
1057 });
1058 }
1059 if (options.classes) {
1060 toast.getElements('widget').addClass(options.classes);
1061 }
1062 if (options.sticky) {
1063 toast.setSettings({
1064 hide: {
1065 auto: false,
1066 onClick: false
1067 }
1068 });
1069 }
1070 return toast.show();
1071 },
1072 isPositionValid: function isPositionValid(position) {
1073 var _position$of;
1074 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;
1075 if (!positionToCheck) {
1076 return false;
1077 }
1078 return !!document.querySelector(positionToCheck);
1079 },
1080 positionToWindow: function positionToWindow() {
1081 var toast = this.getToast();
1082 var position = _objectSpread(_objectSpread({}, toast.getSettings('position')), {}, {
1083 my: 'right top',
1084 at: 'right-10 top+42',
1085 // 42px is the default admin bar height + 10px
1086 of: ''
1087 });
1088 toast.setSettings('position', position);
1089 toast.getElements('widget').addClass('dialog-position-window');
1090 },
1091 onInit: function onInit() {
1092 this.initToast();
1093 }
1094 });
1095
1096 /***/ }),
1097
1098 /***/ "../assets/dev/js/utils/tiers.js":
1099 /*!***************************************!*\
1100 !*** ../assets/dev/js/utils/tiers.js ***!
1101 \***************************************/
1102 /***/ ((__unused_webpack_module, exports) => {
1103
1104 "use strict";
1105
1106
1107 Object.defineProperty(exports, "__esModule", ({
1108 value: true
1109 }));
1110 exports.isTierAtLeast = exports.TIERS_PRIORITY = exports.TIERS = void 0;
1111 var TIERS_PRIORITY = exports.TIERS_PRIORITY = Object.freeze(['free', 'essential', 'essential-oct2023', 'advanced', 'expert', 'agency']);
1112
1113 /**
1114 * @type {Readonly<{
1115 * free: string;
1116 * essential: string;
1117 * 'essential-oct2023': string;
1118 * advanced: string;
1119 * expert: string;
1120 * agency: string;
1121 * }>}
1122 */
1123 var TIERS = exports.TIERS = Object.freeze(TIERS_PRIORITY.reduce(function (acc, tier) {
1124 acc[tier] = tier;
1125 return acc;
1126 }, {}));
1127 var isTierAtLeast = exports.isTierAtLeast = function isTierAtLeast(currentTier, expectedTier) {
1128 var currentTierIndex = TIERS_PRIORITY.indexOf(currentTier);
1129 var expectedTierIndex = TIERS_PRIORITY.indexOf(expectedTier);
1130 if (-1 === currentTierIndex || -1 === expectedTierIndex) {
1131 return false;
1132 }
1133 return currentTierIndex >= expectedTierIndex;
1134 };
1135
1136 /***/ }),
1137
1138 /***/ "../assets/dev/js/utils/time.js":
1139 /*!**************************************!*\
1140 !*** ../assets/dev/js/utils/time.js ***!
1141 \**************************************/
1142 /***/ ((__unused_webpack_module, exports) => {
1143
1144 "use strict";
1145
1146
1147 Object.defineProperty(exports, "__esModule", ({
1148 value: true
1149 }));
1150 exports["default"] = getUserTimestamp;
1151 /**
1152 * Returns the timestamp in ISO8601 format with the UTC timezone offset.
1153 *
1154 * @since 3.6.0
1155 *
1156 * @param {Date} date
1157 * @return {Date} timestamp
1158 */
1159 function getUserTimestamp() {
1160 var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
1161 var timezoneOffset = date.getTimezoneOffset();
1162
1163 // Local time for the user
1164 var UTCTimestamp = new Date(date.getTime() - timezoneOffset * 60000).toISOString();
1165
1166 // Remove the Z suffix from the string.
1167 UTCTimestamp = UTCTimestamp.slice(0, -1);
1168
1169 // Create the offset string in the format `+HH:00` (or minus (-) prefix for negative offset instead of plus)
1170 var decimalTimezoneOffset = timezoneOffset / 60,
1171 // Negative offsets include a '-' sign in the getTimezoneOffset value, positive values need a '+' prefix (ISO8601).
1172 sign = 0 <= decimalTimezoneOffset ? '+' : '-',
1173 hours = Math.abs(Math.floor(decimalTimezoneOffset)),
1174 minutes = Math.abs(decimalTimezoneOffset % 1) * 60,
1175 addZeroToHour = 10 > hours ? '0' : '',
1176 addZeroToMinutes = 10 > minutes ? '0' : '';
1177 var formattedTimezoneOffset = sign + addZeroToHour + hours + ':' + addZeroToMinutes + minutes;
1178 return UTCTimestamp + formattedTimezoneOffset;
1179 }
1180
1181 /***/ }),
1182
1183 /***/ "../core/common/assets/js/components/wordpress/commands-data/index.js":
1184 /*!****************************************************************************!*\
1185 !*** ../core/common/assets/js/components/wordpress/commands-data/index.js ***!
1186 \****************************************************************************/
1187 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1188
1189 "use strict";
1190
1191
1192 Object.defineProperty(exports, "__esModule", ({
1193 value: true
1194 }));
1195 Object.defineProperty(exports, "Media", ({
1196 enumerable: true,
1197 get: function get() {
1198 return _media.Media;
1199 }
1200 }));
1201 var _media = __webpack_require__(/*! ./media */ "../core/common/assets/js/components/wordpress/commands-data/media.js");
1202
1203 /***/ }),
1204
1205 /***/ "../core/common/assets/js/components/wordpress/commands-data/media.js":
1206 /*!****************************************************************************!*\
1207 !*** ../core/common/assets/js/components/wordpress/commands-data/media.js ***!
1208 \****************************************************************************/
1209 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1210
1211 "use strict";
1212 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
1213
1214
1215 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1216 Object.defineProperty(exports, "__esModule", ({
1217 value: true
1218 }));
1219 exports.Media = void 0;
1220 var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "../node_modules/@babel/runtime/regenerator/index.js"));
1221 var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
1222 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1223 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1224 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1225 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1226 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
1227 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1228 var _commandData = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-data */ "../modules/web-cli/assets/js/modules/command-data.js"));
1229 var _filesUploadHandler = _interopRequireDefault(__webpack_require__(/*! elementor-editor/utils/files-upload-handler */ "../assets/dev/js/editor/utils/files-upload-handler.js"));
1230 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)); }
1231 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1232 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; }
1233 var Media = exports.Media = /*#__PURE__*/function (_CommandData) {
1234 function Media() {
1235 (0, _classCallCheck2.default)(this, Media);
1236 return _callSuper(this, Media, arguments);
1237 }
1238 (0, _inherits2.default)(Media, _CommandData);
1239 return (0, _createClass2.default)(Media, [{
1240 key: "validateArgs",
1241 value: function validateArgs() {
1242 this.requireArgumentInstance('file', File);
1243 }
1244 }, {
1245 key: "getRequestData",
1246 value: function getRequestData() {
1247 var requestData = _superPropGet(Media, "getRequestData", this, 3)([]);
1248 requestData.namespace = 'wp';
1249 requestData.version = '2';
1250 return requestData;
1251 }
1252 }, {
1253 key: "applyBeforeCreate",
1254 value: function applyBeforeCreate(args) {
1255 var _args$options;
1256 args.headers = {
1257 'Content-Disposition': "attachment; filename=".concat(this.file.name),
1258 'Content-Type': this.file.type
1259 };
1260 args.query = {
1261 uploadTypeCaller: 'elementor-wp-media-upload'
1262 };
1263 args.data = this.file;
1264 if ((_args$options = args.options) !== null && _args$options !== void 0 && _args$options.progress) {
1265 this.toast = elementor.notifications.showToast({
1266 // eslint-disable-next-line @wordpress/i18n-ellipsis
1267 message: __('Uploading...'),
1268 sticky: true
1269 });
1270 }
1271 return args;
1272 }
1273 }, {
1274 key: "applyAfterCreate",
1275 value: function applyAfterCreate(data, args) {
1276 var _args$options2;
1277 if ((_args$options2 = args.options) !== null && _args$options2 !== void 0 && _args$options2.progress) {
1278 this.toast.hide();
1279 }
1280 return data;
1281 }
1282 }, {
1283 key: "run",
1284 value: function () {
1285 var _run = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
1286 return _regenerator.default.wrap(function (_context) {
1287 while (1) switch (_context.prev = _context.next) {
1288 case 0:
1289 this.file = this.args.file;
1290 if (!(this.file.size > parseInt(window._wpPluploadSettings.defaults.filters.max_file_size, 10))) {
1291 _context.next = 1;
1292 break;
1293 }
1294 throw new Error(__('The file exceeds the maximum upload size for this site.', 'elementor'));
1295 case 1:
1296 if (!(!window._wpPluploadSettings.defaults.filters.mime_types[0].extensions.split(',').includes(this.file.name.split('.').pop()) && !elementor.config.filesUpload.unfilteredFiles)) {
1297 _context.next = 2;
1298 break;
1299 }
1300 _filesUploadHandler.default.getUnfilteredFilesNotEnabledDialog(function () {}).show();
1301 return _context.abrupt("return");
1302 case 2:
1303 _context.next = 3;
1304 return _superPropGet(Media, "run", this, 3)([]);
1305 case 3:
1306 return _context.abrupt("return", _context.sent);
1307 case 4:
1308 case "end":
1309 return _context.stop();
1310 }
1311 }, _callee, this);
1312 }));
1313 function run() {
1314 return _run.apply(this, arguments);
1315 }
1316 return run;
1317 }()
1318 }], [{
1319 key: "getEndpointFormat",
1320 value: function getEndpointFormat() {
1321 // 'wp/media' to 'media' since `requestData.namespace` is 'wp'.
1322 return 'media';
1323 }
1324 }]);
1325 }(_commandData.default);
1326
1327 /***/ }),
1328
1329 /***/ "../core/common/assets/js/components/wordpress/component.js":
1330 /*!******************************************************************!*\
1331 !*** ../core/common/assets/js/components/wordpress/component.js ***!
1332 \******************************************************************/
1333 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1334
1335 "use strict";
1336
1337
1338 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1339 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
1340 Object.defineProperty(exports, "__esModule", ({
1341 value: true
1342 }));
1343 exports["default"] = void 0;
1344 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1345 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1346 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1347 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1348 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1349 var _componentBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
1350 var dataCommands = _interopRequireWildcard(__webpack_require__(/*! ./commands-data/ */ "../core/common/assets/js/components/wordpress/commands-data/index.js"));
1351 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); }
1352 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)); }
1353 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1354 var Component = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
1355 function Component() {
1356 (0, _classCallCheck2.default)(this, Component);
1357 return _callSuper(this, Component, arguments);
1358 }
1359 (0, _inherits2.default)(Component, _ComponentBase);
1360 return (0, _createClass2.default)(Component, [{
1361 key: "getNamespace",
1362 value: function getNamespace() {
1363 return 'wp';
1364 }
1365 }, {
1366 key: "defaultData",
1367 value: function defaultData() {
1368 return this.importCommands(dataCommands);
1369 }
1370 }]);
1371 }(_componentBase.default);
1372
1373 /***/ }),
1374
1375 /***/ "../core/common/assets/js/utils/debug.js":
1376 /*!***********************************************!*\
1377 !*** ../core/common/assets/js/utils/debug.js ***!
1378 \***********************************************/
1379 /***/ ((module) => {
1380
1381 "use strict";
1382
1383
1384 // Moved from assets/dev/js/editor/utils
1385 var Debug = function Debug() {
1386 var self = this,
1387 errorStack = [],
1388 settings = {},
1389 elements = {};
1390 var initSettings = function initSettings() {
1391 settings = {
1392 debounceDelay: 500,
1393 urlsToWatch: ['elementor/assets']
1394 };
1395 };
1396 var initElements = function initElements() {
1397 elements.$window = jQuery(window);
1398 };
1399 var onError = function onError(event) {
1400 var _event$originalEvent;
1401 var error = (_event$originalEvent = event.originalEvent) === null || _event$originalEvent === void 0 ? void 0 : _event$originalEvent.error;
1402 if (!error) {
1403 return;
1404 }
1405 var isInWatchList = false,
1406 urlsToWatch = settings.urlsToWatch;
1407 jQuery.each(urlsToWatch, function () {
1408 if (-1 !== error.stack.indexOf(this)) {
1409 isInWatchList = true;
1410 return false;
1411 }
1412 });
1413 if (!isInWatchList) {
1414 return;
1415 }
1416 self.addError({
1417 type: error.name,
1418 message: error.message,
1419 url: event.originalEvent.filename,
1420 line: event.originalEvent.lineno,
1421 column: event.originalEvent.colno
1422 });
1423 };
1424 var bindEvents = function bindEvents() {
1425 elements.$window.on('error', onError);
1426 };
1427 var init = function init() {
1428 initSettings();
1429 initElements();
1430 bindEvents();
1431 self.sendErrors = _.debounce(self.sendErrors, settings.debounceDelay);
1432 };
1433 this.addURLToWatch = function (url) {
1434 settings.urlsToWatch.push(url);
1435 };
1436 this.addCustomError = function (error, category, tag) {
1437 var errorInfo = {
1438 type: error.name,
1439 message: error.message,
1440 url: error.fileName || error.sourceURL,
1441 line: error.lineNumber || error.line,
1442 column: error.columnNumber || error.column,
1443 customFields: {
1444 category: category || 'general',
1445 tag: tag
1446 }
1447 };
1448 if (!errorInfo.url) {
1449 var stackInfo = error.stack.match(/\n {4}at (.*?(?=:(\d+):(\d+)))/);
1450 if (stackInfo) {
1451 errorInfo.url = stackInfo[1];
1452 errorInfo.line = stackInfo[2];
1453 errorInfo.column = stackInfo[3];
1454 }
1455 }
1456 this.addError(errorInfo);
1457 };
1458 this.addError = function (errorParams) {
1459 var defaultParams = {
1460 type: 'Error',
1461 timestamp: Math.floor(new Date().getTime() / 1000),
1462 message: null,
1463 url: null,
1464 line: null,
1465 column: null,
1466 customFields: {}
1467 };
1468 errorStack.push(jQuery.extend(true, defaultParams, errorParams));
1469 self.sendErrors();
1470 };
1471 this.sendErrors = function () {
1472 // Avoid recursions on errors in ajax
1473 elements.$window.off('error', onError);
1474 jQuery.ajax({
1475 url: elementorCommon.config.ajax.url,
1476 method: 'POST',
1477 data: {
1478 action: 'elementor_js_log',
1479 _nonce: elementorCommon.ajax.getSettings('nonce'),
1480 data: errorStack
1481 },
1482 success: function success() {
1483 errorStack = [];
1484
1485 // Restore error handler
1486 elements.$window.on('error', onError);
1487 }
1488 });
1489 };
1490 init();
1491 };
1492 module.exports = Debug;
1493
1494 /***/ }),
1495
1496 /***/ "../core/common/assets/js/utils/helpers.js":
1497 /*!*************************************************!*\
1498 !*** ../core/common/assets/js/utils/helpers.js ***!
1499 \*************************************************/
1500 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1501
1502 "use strict";
1503
1504
1505 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1506 Object.defineProperty(exports, "__esModule", ({
1507 value: true
1508 }));
1509 exports["default"] = void 0;
1510 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1511 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1512 var Helpers = exports["default"] = /*#__PURE__*/function () {
1513 function Helpers() {
1514 (0, _classCallCheck2.default)(this, Helpers);
1515 }
1516 return (0, _createClass2.default)(Helpers, [{
1517 key: "consoleWarn",
1518 value:
1519 /**
1520 * @param {*} args
1521 * @deprecated since 3.7.0, use `elementorDevTools.consoleWarn()` instead.
1522 */
1523 function consoleWarn() {
1524 var _elementorDevTools;
1525 (_elementorDevTools = elementorDevTools).consoleWarn.apply(_elementorDevTools, arguments);
1526
1527 // This is is self is deprecated.
1528 elementorDevTools.deprecation.deprecated('elementorCommon.helpers.consoleWarn()', '3.7.0', 'elementorDevTools.consoleWarn()');
1529 }
1530
1531 /**
1532 * @param {string} message
1533 * @deprecated since 3.7.0, use `console.error()` instead.
1534 */
1535 }, {
1536 key: "consoleError",
1537 value: function consoleError(message) {
1538 // eslint-disable-next-line no-console
1539 console.error(message);
1540
1541 // This is is self is deprecated.
1542 elementorDevTools.deprecation.deprecated('elementorCommon.helpers.consoleError()', '3.7.0', 'console.error()');
1543 }
1544 }, {
1545 key: "cloneObject",
1546 value: function cloneObject(object) {
1547 return JSON.parse(JSON.stringify(object));
1548 }
1549 }, {
1550 key: "upperCaseWords",
1551 value: function upperCaseWords(string) {
1552 return (string + '').replace(/^(.)|\s+(.)/g, function ($1) {
1553 return $1.toUpperCase();
1554 });
1555 }
1556 }, {
1557 key: "getUniqueId",
1558 value: function getUniqueId() {
1559 return Math.random().toString(16).substr(2, 7);
1560 }
1561 }]);
1562 }();
1563
1564 /***/ }),
1565
1566 /***/ "../core/common/assets/js/utils/storage.js":
1567 /*!*************************************************!*\
1568 !*** ../core/common/assets/js/utils/storage.js ***!
1569 \*************************************************/
1570 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1571
1572 "use strict";
1573
1574
1575 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1576 Object.defineProperty(exports, "__esModule", ({
1577 value: true
1578 }));
1579 exports["default"] = void 0;
1580 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1581 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1582 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1583 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1584 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1585 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)); }
1586 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1587 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
1588 function _default() {
1589 (0, _classCallCheck2.default)(this, _default);
1590 return _callSuper(this, _default, arguments);
1591 }
1592 (0, _inherits2.default)(_default, _elementorModules$Mod);
1593 return (0, _createClass2.default)(_default, [{
1594 key: "get",
1595 value: function get(key, options) {
1596 options = options || {};
1597 var storage;
1598 try {
1599 storage = options.session ? sessionStorage : localStorage;
1600 } catch (e) {
1601 return key ? undefined : {};
1602 }
1603 var elementorStorage = storage.getItem('elementor');
1604 if (elementorStorage) {
1605 elementorStorage = JSON.parse(elementorStorage);
1606 } else {
1607 elementorStorage = {};
1608 }
1609 if (!elementorStorage.__expiration) {
1610 elementorStorage.__expiration = {};
1611 }
1612 var expiration = elementorStorage.__expiration;
1613 var expirationToCheck = [];
1614 if (key) {
1615 if (expiration[key]) {
1616 expirationToCheck = [key];
1617 }
1618 } else {
1619 expirationToCheck = Object.keys(expiration);
1620 }
1621 var entryExpired = false;
1622 expirationToCheck.forEach(function (expirationKey) {
1623 if (new Date(expiration[expirationKey]) < new Date()) {
1624 delete elementorStorage[expirationKey];
1625 delete expiration[expirationKey];
1626 entryExpired = true;
1627 }
1628 });
1629 if (entryExpired) {
1630 this.save(elementorStorage, options.session);
1631 }
1632 if (key) {
1633 return elementorStorage[key];
1634 }
1635 return elementorStorage;
1636 }
1637 }, {
1638 key: "set",
1639 value: function set(key, value, options) {
1640 options = options || {};
1641 var elementorStorage = this.get(null, options);
1642 elementorStorage[key] = value;
1643 if (options.lifetimeInSeconds) {
1644 var date = new Date();
1645 date.setTime(date.getTime() + options.lifetimeInSeconds * 1000);
1646 elementorStorage.__expiration[key] = date.getTime();
1647 }
1648 this.save(elementorStorage, options.session);
1649 }
1650 }, {
1651 key: "save",
1652 value: function save(object, session) {
1653 var storage;
1654 try {
1655 storage = session ? sessionStorage : localStorage;
1656 } catch (e) {
1657 return;
1658 }
1659 storage.setItem('elementor', JSON.stringify(object));
1660 }
1661 }]);
1662 }(elementorModules.Module);
1663
1664 /***/ }),
1665
1666 /***/ "../core/common/modules/ajax/assets/js/ajax.js":
1667 /*!*****************************************************!*\
1668 !*** ../core/common/modules/ajax/assets/js/ajax.js ***!
1669 \*****************************************************/
1670 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1671
1672 "use strict";
1673
1674
1675 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1676 Object.defineProperty(exports, "__esModule", ({
1677 value: true
1678 }));
1679 exports["default"] = void 0;
1680 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
1681 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1682 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1683 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1684 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1685 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1686 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)); }
1687 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1688 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
1689 function _default() {
1690 var _this;
1691 (0, _classCallCheck2.default)(this, _default);
1692 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1693 args[_key] = arguments[_key];
1694 }
1695 _this = _callSuper(this, _default, [].concat(args));
1696 _this.requests = {};
1697 _this.cache = {};
1698 _this.initRequestConstants();
1699 _this.debounceSendBatch = _.debounce(_this.sendBatch.bind(_this), 500);
1700 return _this;
1701 }
1702 (0, _inherits2.default)(_default, _elementorModules$Mod);
1703 return (0, _createClass2.default)(_default, [{
1704 key: "getDefaultSettings",
1705 value: function getDefaultSettings() {
1706 return {
1707 ajaxParams: {
1708 type: 'POST',
1709 url: elementorCommon.config.ajax.url,
1710 data: {},
1711 dataType: 'json'
1712 },
1713 actionPrefix: 'elementor_'
1714 };
1715 }
1716 }, {
1717 key: "initRequestConstants",
1718 value: function initRequestConstants() {
1719 this.requestConstants = {
1720 _nonce: this.getSettings('nonce')
1721 };
1722 }
1723 }, {
1724 key: "addRequestConstant",
1725 value: function addRequestConstant(key, value) {
1726 this.requestConstants[key] = value;
1727 }
1728 }, {
1729 key: "getCacheKey",
1730 value: function getCacheKey(request) {
1731 return JSON.stringify({
1732 unique_id: request.unique_id,
1733 data: request.data
1734 });
1735 }
1736 }, {
1737 key: "loadObjects",
1738 value: function loadObjects(options) {
1739 var _this2 = this;
1740 var dataCollection = {};
1741 var deferredArray = [];
1742 if (options.before) {
1743 options.before();
1744 }
1745 options.ids.forEach(function (objectId) {
1746 deferredArray.push(_this2.load({
1747 action: options.action,
1748 unique_id: options.data.unique_id + objectId,
1749 data: jQuery.extend({
1750 id: objectId
1751 }, options.data)
1752 }).done(function (data) {
1753 return dataCollection = jQuery.extend(dataCollection, data);
1754 }));
1755 });
1756 jQuery.when.apply(jQuery, deferredArray).done(function () {
1757 return options.success(dataCollection);
1758 });
1759 }
1760 }, {
1761 key: "load",
1762 value: function load(request, immediately) {
1763 var _this3 = this;
1764 if (!request.unique_id) {
1765 request.unique_id = request.action;
1766 }
1767 if (request.before) {
1768 request.before();
1769 }
1770 var deferred;
1771 var cacheKey = this.getCacheKey(request);
1772 if (_.has(this.cache, cacheKey)) {
1773 deferred = jQuery.Deferred().done(request.success).resolve(this.cache[cacheKey]);
1774 } else {
1775 var _request$error;
1776 deferred = this.addRequest(request.action, {
1777 data: request.data,
1778 unique_id: request.unique_id,
1779 success: function success(data) {
1780 return _this3.cache[cacheKey] = data;
1781 },
1782 error: (_request$error = request.error) !== null && _request$error !== void 0 ? _request$error : function () {}
1783 }, immediately).done(request.success);
1784 }
1785 return deferred;
1786 }
1787 }, {
1788 key: "cancelRequest",
1789 value: function cancelRequest(requestId) {
1790 var request = this.requests[requestId];
1791 if (!request) {
1792 return null;
1793 }
1794 if (request.options.deferred.jqXhr) {
1795 return request.options.deferred.jqXhr.abort('Request canceled');
1796 }
1797 if (request.options.deferred) {
1798 return request.options.deferred.reject('Request canceled');
1799 }
1800 }
1801 }, {
1802 key: "addRequest",
1803 value: function addRequest(action, options, immediately) {
1804 options = options || {};
1805 if (!options.unique_id) {
1806 options.unique_id = action;
1807 }
1808 options.deferred = jQuery.Deferred().done(options.success).fail(options.error).always(options.complete);
1809 var request = {
1810 action: action,
1811 options: options
1812 };
1813 if (immediately) {
1814 var requests = {};
1815 requests[options.unique_id] = request;
1816 options.deferred.jqXhr = this.sendBatch(requests);
1817 } else {
1818 this.requests[options.unique_id] = request;
1819 this.debounceSendBatch();
1820 }
1821 return options.deferred;
1822 }
1823 }, {
1824 key: "sendBatch",
1825 value: function sendBatch(requests) {
1826 var actions = {};
1827 if (!requests) {
1828 requests = this.requests;
1829
1830 // Empty for next batch.
1831 this.requests = {};
1832 }
1833 Object.entries(requests).forEach(function (_ref) {
1834 var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
1835 id = _ref2[0],
1836 request = _ref2[1];
1837 return actions[id] = {
1838 action: request.action,
1839 data: request.options.data
1840 };
1841 });
1842 return this.send('ajax', {
1843 data: {
1844 actions: JSON.stringify(actions)
1845 },
1846 success: function success(data) {
1847 Object.entries(data.responses).forEach(function (_ref3) {
1848 var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
1849 id = _ref4[0],
1850 response = _ref4[1];
1851 var options = requests[id].options;
1852 if (options) {
1853 if (response.success) {
1854 options.deferred.resolve(response.data);
1855 } else if (!response.success) {
1856 options.deferred.reject(response.data);
1857 }
1858 }
1859 });
1860 },
1861 error: function error(data) {
1862 return Object.values(requests).forEach(function (args) {
1863 if (args.options) {
1864 args.options.deferred.reject(data);
1865 }
1866 });
1867 }
1868 });
1869 }
1870 }, {
1871 key: "prepareSend",
1872 value: function prepareSend(action, options) {
1873 var _this4 = this;
1874 var settings = this.getSettings(),
1875 ajaxParams = elementorCommon.helpers.cloneObject(settings.ajaxParams);
1876 options = options || {};
1877 action = settings.actionPrefix + action;
1878 jQuery.extend(ajaxParams, options);
1879 var requestConstants = elementorCommon.helpers.cloneObject(this.requestConstants);
1880 requestConstants.action = action;
1881 var isFormData = ajaxParams.data instanceof FormData;
1882 Object.entries(requestConstants).forEach(function (_ref5) {
1883 var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
1884 key = _ref6[0],
1885 value = _ref6[1];
1886 if (isFormData) {
1887 ajaxParams.data.append(key, value);
1888 } else {
1889 ajaxParams.data[key] = value;
1890 }
1891 });
1892 var successCallback = ajaxParams.success,
1893 errorCallback = ajaxParams.error;
1894 if (successCallback || errorCallback) {
1895 ajaxParams.success = function (response) {
1896 if (response.success && successCallback) {
1897 successCallback(response.data);
1898 }
1899 if (!response.success && errorCallback) {
1900 errorCallback(response.data);
1901 }
1902 };
1903 if (errorCallback) {
1904 ajaxParams.error = function (data) {
1905 return errorCallback(data);
1906 };
1907 } else {
1908 ajaxParams.error = function (xmlHttpRequest) {
1909 if (xmlHttpRequest.readyState || 'abort' !== xmlHttpRequest.statusText) {
1910 _this4.trigger('request:unhandledError', xmlHttpRequest);
1911 }
1912 };
1913 }
1914 }
1915 return ajaxParams;
1916 }
1917 }, {
1918 key: "send",
1919 value: function send(action, options) {
1920 return jQuery.ajax(this.prepareSend(action, options));
1921 }
1922 }, {
1923 key: "addRequestCache",
1924 value: function addRequestCache(request, data) {
1925 var cacheKey = this.getCacheKey(request);
1926 this.cache[cacheKey] = data;
1927 }
1928 }, {
1929 key: "invalidateCache",
1930 value: function invalidateCache(request) {
1931 var cacheKey = this.getCacheKey(request);
1932 delete this.cache[cacheKey];
1933 }
1934 }]);
1935 }(elementorModules.Module);
1936
1937 /***/ }),
1938
1939 /***/ "../core/common/modules/connect/assets/js/connect.js":
1940 /*!***********************************************************!*\
1941 !*** ../core/common/modules/connect/assets/js/connect.js ***!
1942 \***********************************************************/
1943 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1944
1945 "use strict";
1946 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
1947
1948
1949 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1950 Object.defineProperty(exports, "__esModule", ({
1951 value: true
1952 }));
1953 exports["default"] = void 0;
1954 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1955 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1956 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1957 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1958 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
1959 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1960 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)); }
1961 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1962 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; }
1963 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Vie) {
1964 function _default() {
1965 (0, _classCallCheck2.default)(this, _default);
1966 return _callSuper(this, _default, arguments);
1967 }
1968 (0, _inherits2.default)(_default, _elementorModules$Vie);
1969 return (0, _createClass2.default)(_default, [{
1970 key: "addPopupPlugin",
1971 value: function addPopupPlugin() {
1972 var counter = 0;
1973 jQuery.fn.elementorConnect = function (options) {
1974 var _this = this;
1975 // Open the Connect Dialog in a popup window.
1976 if (options !== null && options !== void 0 && options.popup) {
1977 jQuery(this).on('click', function (event) {
1978 var _options$popup, _options$popup2;
1979 event.preventDefault();
1980 var width = ((_options$popup = options.popup) === null || _options$popup === void 0 ? void 0 : _options$popup.width) || 600,
1981 height = ((_options$popup2 = options.popup) === null || _options$popup2 === void 0 ? void 0 : _options$popup2.height) || 700;
1982 window.open(jQuery(_this).attr('href') + '&mode=popup', 'elementorConnect', "toolbar=no, menubar=no, width=".concat(width, ", height=").concat(height, ", top=200, left=0"));
1983 });
1984 delete options.popup;
1985 }
1986 var settings = jQuery.extend({
1987 // These are the defaults.
1988 success: function success() {
1989 return location.reload();
1990 },
1991 error: function error() {
1992 elementor.notifications.showToast({
1993 message: __('Unable to connect', 'elementor')
1994 });
1995 },
1996 parseUrl: function parseUrl(url) {
1997 return url;
1998 } // Allow to change the url, e.g: replace placeholders like '%%template_type%%' with actual value.
1999 }, options);
2000 this.each(function () {
2001 counter++;
2002 var $this = jQuery(this),
2003 callbackId = 'cb' + counter;
2004 $this.attr({
2005 target: '_blank',
2006 rel: 'opener',
2007 href: settings.parseUrl($this.attr('href') + '&mode=popup&callback_id=' + callbackId)
2008 });
2009 elementorCommon.elements.$window.on('elementor/connect/success/' + callbackId, settings.success).on('elementor/connect/error/' + callbackId, settings.error);
2010 });
2011 return this;
2012 };
2013 }
2014 }, {
2015 key: "getDefaultSettings",
2016 value: function getDefaultSettings() {
2017 return {
2018 selectors: {
2019 connectButton: '#elementor-template-library-connect__button'
2020 }
2021 };
2022 }
2023 }, {
2024 key: "getDefaultElements",
2025 value: function getDefaultElements() {
2026 return {
2027 $connectButton: jQuery(this.getSettings('selectors.connectButton'))
2028 };
2029 }
2030 }, {
2031 key: "applyPopup",
2032 value: function applyPopup() {
2033 this.elements.$connectButton.elementorConnect();
2034 }
2035 }, {
2036 key: "onInit",
2037 value: function onInit() {
2038 _superPropGet(_default, "onInit", this, 3)([]);
2039 this.addPopupPlugin();
2040 this.applyPopup();
2041 }
2042 }]);
2043 }(elementorModules.ViewModule);
2044
2045 /***/ }),
2046
2047 /***/ "../core/common/modules/event-tracker/assets/js/data/commands-data/index.js":
2048 /*!**********************************************************************************!*\
2049 !*** ../core/common/modules/event-tracker/assets/js/data/commands-data/index.js ***!
2050 \**********************************************************************************/
2051 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2052
2053 "use strict";
2054
2055
2056 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2057 Object.defineProperty(exports, "__esModule", ({
2058 value: true
2059 }));
2060 exports.Index = void 0;
2061 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2062 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2063 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2064 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2065 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2066 var _commandData = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-data */ "../modules/web-cli/assets/js/modules/command-data.js"));
2067 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)); }
2068 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2069 var Index = exports.Index = /*#__PURE__*/function (_CommandData) {
2070 function Index() {
2071 (0, _classCallCheck2.default)(this, Index);
2072 return _callSuper(this, Index, arguments);
2073 }
2074 (0, _inherits2.default)(Index, _CommandData);
2075 return (0, _createClass2.default)(Index, null, [{
2076 key: "getEndpointFormat",
2077 value: function getEndpointFormat() {
2078 return 'send-event';
2079 }
2080 }]);
2081 }(_commandData.default);
2082
2083 /***/ }),
2084
2085 /***/ "../core/common/modules/event-tracker/assets/js/data/component.js":
2086 /*!************************************************************************!*\
2087 !*** ../core/common/modules/event-tracker/assets/js/data/component.js ***!
2088 \************************************************************************/
2089 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2090
2091 "use strict";
2092
2093
2094 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2095 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2096 Object.defineProperty(exports, "__esModule", ({
2097 value: true
2098 }));
2099 exports["default"] = void 0;
2100 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2101 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2102 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2103 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2104 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2105 var _componentBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
2106 var commandsData = _interopRequireWildcard(__webpack_require__(/*! ./commands-data/ */ "../core/common/modules/event-tracker/assets/js/data/commands-data/index.js"));
2107 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); }
2108 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)); }
2109 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2110 var Component = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
2111 function Component() {
2112 (0, _classCallCheck2.default)(this, Component);
2113 return _callSuper(this, Component, arguments);
2114 }
2115 (0, _inherits2.default)(Component, _ComponentBase);
2116 return (0, _createClass2.default)(Component, [{
2117 key: "getNamespace",
2118 value: function getNamespace() {
2119 return 'event-tracker';
2120 }
2121 }, {
2122 key: "defaultData",
2123 value: function defaultData() {
2124 return this.importCommands(commandsData);
2125 }
2126 }]);
2127 }(_componentBase.default);
2128
2129 /***/ }),
2130
2131 /***/ "../core/common/modules/event-tracker/assets/js/events.js":
2132 /*!****************************************************************!*\
2133 !*** ../core/common/modules/event-tracker/assets/js/events.js ***!
2134 \****************************************************************/
2135 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2136
2137 "use strict";
2138
2139
2140 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2141 Object.defineProperty(exports, "__esModule", ({
2142 value: true
2143 }));
2144 exports["default"] = void 0;
2145 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2146 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2147 var _time = _interopRequireDefault(__webpack_require__(/*! elementor-utils/time */ "../assets/dev/js/utils/time.js"));
2148 var Events = exports["default"] = /*#__PURE__*/function () {
2149 function Events() {
2150 (0, _classCallCheck2.default)(this, Events);
2151 }
2152 return (0, _createClass2.default)(Events, [{
2153 key: "dispatchEvent",
2154 value: function dispatchEvent(eventData) {
2155 if (!eventData) {
2156 return;
2157 }
2158 eventData.ts = (0, _time.default)();
2159
2160 // No need to wait for response, no need to block browser in any way.
2161 $e.data.create('event-tracker/index', {
2162 event_data: eventData
2163 });
2164 }
2165 }]);
2166 }();
2167
2168 /***/ }),
2169
2170 /***/ "../core/common/modules/events-manager/assets/js/events-config.js":
2171 /*!************************************************************************!*\
2172 !*** ../core/common/modules/events-manager/assets/js/events-config.js ***!
2173 \************************************************************************/
2174 /***/ ((__unused_webpack_module, exports) => {
2175
2176 "use strict";
2177
2178
2179 Object.defineProperty(exports, "__esModule", ({
2180 value: true
2181 }));
2182 exports["default"] = void 0;
2183 var eventsConfig = {
2184 appTypes: {
2185 editor: 'editor',
2186 wpAdmin: 'wpadmin',
2187 wpDash: 'wpdash'
2188 },
2189 targetTypes: {
2190 dropdownItem: 'dropdown_item',
2191 button: 'button',
2192 tab: 'tab',
2193 toggle: 'toggle',
2194 searchInput: 'search_input',
2195 searchResult: 'search_result',
2196 buttons: 'buttons',
2197 searchWidget: 'search_widget',
2198 wpDashAdminMenuItem: 'wpdash_admin_menu_item',
2199 wpDashEditorMenu: 'wpdash_editor_menu',
2200 wpDashSubMenuItem: 'wpdash_sub_menu_item'
2201 },
2202 interactionResults: {
2203 actionSelected: 'action_selected',
2204 navigate: 'navigate',
2205 create: 'create',
2206 sessionEnd: 'session_end',
2207 tabChanged: 'tab_changed',
2208 assetInserted: 'asset_inserted',
2209 assetFavorite: 'asset_favorite',
2210 aiGenerate: 'ai_generate',
2211 resultsUpdated: 'results_updated',
2212 noResults: 'no_results',
2213 selected: 'selected',
2214 promotionViewed: 'promotion_viewed',
2215 upgradeNow: 'upgrade_now',
2216 elementorSideMenuOpened: 'elementor_side_menu_opened',
2217 editorSubMenuOpened: 'wpdash_editor_sub_menu_opened',
2218 themeBuilderPromotionWindow: 'theme_builder_promotion_window'
2219 },
2220 targetNames: {
2221 publishDropdown: {
2222 saveDraft: 'save_draft',
2223 saveAsTemplate: 'save_as_template',
2224 viewPage: 'view_page',
2225 copyAndShare: 'copy_and_share'
2226 },
2227 pageList: {
2228 addNewPage: 'add_new_page'
2229 }
2230 },
2231 triggers: {
2232 click: 'Click',
2233 rightClick: 'Right Click',
2234 doubleClick: 'Double Click',
2235 accordionClick: 'Accordion Click',
2236 toggleClick: 'Toggle Click',
2237 dropdownClick: 'Click Dropdown',
2238 editorLoaded: 'Editor Loaded',
2239 visible: 'Visible',
2240 pageLoaded: 'Page Loaded',
2241 typing: 'Typing',
2242 tabSelect: 'Tab Select',
2243 insert: 'Insert',
2244 hover: 'Hover'
2245 },
2246 locations: {
2247 widgetPanel: 'Widget Panel',
2248 topBar: 'Top Bar',
2249 sidebar: 'Sidebar',
2250 elementorEditor: 'Elementor Editor',
2251 templatesLibrary: {
2252 library: 'Templates Library'
2253 },
2254 app: {
2255 import: 'Import Kit',
2256 export: 'Export Kit',
2257 kitLibrary: 'Kit Library',
2258 cloudKitLibrary: 'Cloud Kit Library'
2259 },
2260 variables: 'Variables Panel',
2261 variablesManager: 'Variables Manager',
2262 admin: 'WP admin',
2263 wpDashAdmin: 'wpdash_admin',
2264 structurePanel: 'Structure Panel',
2265 canvas: 'Canvas',
2266 leftPanel: 'Left Panel',
2267 elementorLibrary: 'Elementor Library',
2268 components: {
2269 instanceEditingPanel: 'Instance Editing Panel'
2270 }
2271 },
2272 secondaryLocations: {
2273 layout: 'Layout Section',
2274 basic: 'Basic Section',
2275 'pro-elements': 'Pro Section',
2276 general: 'General Section',
2277 'theme-elements': 'Site Section',
2278 'theme-elements-single': 'Single Section',
2279 'woocommerce-elements': 'WooCommerce Section',
2280 wordpress: 'WordPress Section',
2281 categories: 'Widgets Tab',
2282 global: 'Globals Tab',
2283 'whats-new': 'What\'s New',
2284 'document-settings': 'Document Settings icon',
2285 'preview-page': 'Preview Page',
2286 'publish-button': 'Publish Button',
2287 'widget-panel': 'Widget Panel Icon',
2288 finder: 'Finder',
2289 help: 'Help',
2290 elementorLogoDropdown: 'top_bar_elementor_logo_dropdown',
2291 elementorLogo: 'Elementor Logo',
2292 eLogoMenu: 'E-logo Menu',
2293 notes: 'Notes',
2294 siteSettings: 'Site Settings',
2295 structure: 'Structure',
2296 documentNameDropdown: 'Document Name dropdown',
2297 responsiveControls: 'Responsive controls',
2298 launchpad: 'launchpad',
2299 checklistHeader: 'Checklist Header',
2300 checklistSteps: 'Checklist Steps',
2301 userPreferences: 'User Preferences',
2302 contextMenu: 'Context Menu',
2303 templateLibrary: {
2304 saveModal: 'Save to Modal',
2305 moveModal: 'Move to Modal',
2306 bulkMoveModal: 'Bulk Move to Modal',
2307 copyModal: 'Copy to Modal',
2308 bulkCopyModal: 'Bulk Copy to Modal',
2309 saveModalSelectFolder: 'Save to Modal - select folder',
2310 saveModalSelectConnect: 'Save to Modal - connect',
2311 saveModalSelectUpgrade: 'Save to Modal - upgrade',
2312 importModal: 'Import Modal',
2313 newFolderModal: 'New Folder Modal',
2314 deleteDialog: 'Delete Dialog',
2315 deleteFolderDialog: 'Delete Folder Dialog',
2316 renameDialog: 'Rename Dialog',
2317 createFolderDialog: 'Create Folder Dialog',
2318 applySettingsDialog: 'Apply Settings Dialog',
2319 cloudTab: 'Cloud Tab',
2320 siteTab: 'Site Tab',
2321 cloudTabFolder: 'Cloud Tab - Folder',
2322 cloudTabConnect: 'Cloud Tab - Connect',
2323 cloudTabUpgrade: 'Cloud Tab - Upgrade',
2324 morePopup: 'Context Menu',
2325 quotaBar: 'Quota Bar'
2326 },
2327 kitLibrary: {
2328 cloudKitLibrary: 'kits_cloud_library',
2329 cloudKitLibraryConnect: 'kits_cloud_library_connect',
2330 cloudKitLibraryUpgrade: 'kits_cloud_library_upgrade',
2331 kitExportCustomization: 'kit_export_customization',
2332 kitExport: 'kit_export',
2333 kitExportCustomizationEdit: 'kit_export_customization_edit',
2334 kitExportSummary: 'kit_export_summary',
2335 kitImportUploadBox: 'kit_import_upload_box',
2336 kitImportCustomization: 'kit_import_customization',
2337 kitImportSummary: 'kit_import_summary'
2338 },
2339 variablesPopover: 'Variables Popover',
2340 admin: {
2341 pluginToolsTab: 'plugin_tools_tab',
2342 pluginWebsiteTemplatesTab: 'plugin_website_templates_tab'
2343 },
2344 componentsTab: 'Components Tab',
2345 canvasElement: 'Canvas Element',
2346 publishDropdown: 'Publish Dropdown',
2347 pageListDropdown: 'Page List Dropdown',
2348 emptyBox: 'Empty Box',
2349 searchBar: 'Search Bar',
2350 finderResults: 'Finder Results',
2351 libraryTabs: 'Library Tabs',
2352 assetCard: 'Asset Card',
2353 wpDashElementorCoreMenu: 'elementor_editor_core_menu',
2354 wpDashElementorCoreSubMenu: 'elementor_editor_core_sub_menu',
2355 wpDashThemeBuilder: 'wpdash_core_sub_menu_theme_builder'
2356 },
2357 elements: {
2358 accordionSection: 'Accordion section',
2359 buttonIcon: 'Button Icon',
2360 mainCta: 'Main CTA',
2361 button: 'Button',
2362 link: 'Link',
2363 dropdown: 'Dropdown',
2364 toggle: 'Toggle',
2365 launchpadChecklist: 'Checklist popup'
2366 },
2367 names: {
2368 v1: {
2369 layout: 'v1_widgets_tab_layout_section',
2370 basic: 'v1_widgets_tab_basic_section',
2371 'pro-elements': 'v1_widgets_tab_pro_section',
2372 general: 'v1_widgets_tab_general_section',
2373 'theme-elements': 'v1_widgets_tab_site_section',
2374 'theme-elements-single': 'v1_widgets_tab_single_section',
2375 'woocommerce-elements': 'v1_widgets_tab_woocommerce_section',
2376 wordpress: 'v1_widgets_tab_wordpress_section',
2377 categories: 'v1_widgets_tab',
2378 global: 'v1_globals_tab'
2379 },
2380 topBar: {
2381 whatsNew: 'top_bar_whats_new',
2382 documentSettings: 'top_bar_document_settings_icon',
2383 previewPage: 'top_bar_preview_page',
2384 publishButton: 'top_bar_publish_button',
2385 widgetPanel: 'top_bar_widget_panel_icon',
2386 finder: 'top_bar_finder',
2387 help: 'top_bar_help',
2388 history: 'top_bar_elementor_logo_dropdown_history',
2389 userPreferences: 'top_bar_elementor_logo_dropdown_user_preferences',
2390 keyboardShortcuts: 'top_bar_elementor_logo_dropdown_keyboard_shortcuts',
2391 exitToWordpress: 'top_bar_elementor_logo_dropdown_exit_to_wordpress',
2392 themeBuilder: 'top_bar_elementor_logo_dropdown_theme_builder',
2393 notes: 'top_bar_notes',
2394 siteSettings: 'top_bar_site_setting',
2395 structure: 'top_bar_structure',
2396 documentNameDropdown: 'top_bar_document_name_dropdown',
2397 responsiveControls: 'top_bar_responsive_controls',
2398 launchpadOn: 'top_bar_checklist_icon_show',
2399 launchpadOff: 'top_bar_checklist_icon_hide',
2400 elementorLogoDropdown: 'open_e_menu',
2401 connectAccount: 'connect_account',
2402 accountConnected: 'account_connected'
2403 },
2404 // ChecklistSteps event names are generated dynamically, based on stepId and action type taken: title, action, done, undone, upgrade
2405 elementorEditor: {
2406 editorLoaded: 'editor_loaded',
2407 checklist: {
2408 checklistHeaderClose: 'checklist_header_close_icon',
2409 checklistFirstPopup: 'checklist popup triggered'
2410 },
2411 userPreferences: {
2412 checklistShow: 'checklist_userpreferences_toggle_show',
2413 checklistHide: 'checklist_userpreferences_toggle_hide'
2414 }
2415 },
2416 variables: {
2417 open: 'open_variables_popover',
2418 add: 'add_new_variable',
2419 connect: 'connect_variable',
2420 save: 'save_new_variable',
2421 update: 'update_variable',
2422 openManager: 'open_variables_manager',
2423 saveChanges: 'save_variables_changes',
2424 delete: 'delete_variable',
2425 variableSyncToV3: 'variable_sync_to_v3'
2426 },
2427 design_system: {
2428 importOpened: 'design_system_import_opened',
2429 fileSelected: 'design_system_file_selected',
2430 validationFailed: 'design_system_validation_failed',
2431 conflictChoice: 'design_system_conflict_choice',
2432 confirmed: 'design_system_import_confirmed',
2433 imported: 'design_system_imported',
2434 importFailed: 'design_system_import_failed',
2435 export: 'design_system_export',
2436 opened: 'design_system_opened'
2437 },
2438 components: {
2439 createClicked: 'component_create_clicked',
2440 createCancelled: 'component_creation_cancelled',
2441 created: 'component_created',
2442 instanceAdded: 'component_instance_added',
2443 edited: 'component_edited',
2444 propertiesPanelOpened: 'component_properties_panel_opened',
2445 propertiesGroupCreated: 'component_properties_group_created',
2446 propertyExposed: 'component_property_exposed',
2447 propertyRemoved: 'component_property_removed',
2448 detached: 'component_detached'
2449 },
2450 global_classes: {
2451 classApplied: 'class_applied',
2452 classRemoved: 'class_removed',
2453 classManagerFilterCleared: 'class_manager_filter_cleared',
2454 classDeleted: 'class_deleted',
2455 classPublishConflict: 'class_publish_conflict',
2456 classRenamed: 'class_renamed',
2457 classCreated: 'class_created',
2458 classManagerSearched: 'class_manager_searched',
2459 classManagerFiltersOpened: 'class_manager_filters_opened',
2460 classManagerOpened: 'class_manager_opened',
2461 classManagerReorder: 'class_manager_reorder',
2462 classManagerFilterUsed: 'class_manager_filter_used',
2463 classUsageLocate: 'class_usage_locate',
2464 classUsageHovered: 'class_usage_hovered',
2465 classStyled: 'class_styled',
2466 classStateClicked: 'class_state_clicked',
2467 classUsageClicked: 'class_usage_clicked',
2468 classDuplicate: 'class_duplicate',
2469 classSyncToV3PopupShown: 'class_sync_to_v3_popup_shown',
2470 classSyncToV3: 'class_sync_to_v3',
2471 classSyncToV3PopupClick: 'class_sync_to_v3_popup_click'
2472 },
2473 editorOne: {
2474 topBarPublishDropdown: 'top_bar_publish_dropdown',
2475 topBarPageList: 'top_bar_page_list',
2476 siteSettingsSession: 'site_settings_session',
2477 eLibraryNav: 'e_library_nav',
2478 eLibraryInsert: 'e_library_insert',
2479 eLibraryFavorite: 'e_library_favorite',
2480 eLibraryGenerateAi: 'e_library_generate_ai',
2481 finderSearchInput: 'finder_search_input',
2482 finderResultSelect: 'finder_result_select',
2483 canvasEmptyBoxAction: 'canvas_empty_box_action',
2484 widgetPanelSearch: 'widget_panel_search',
2485 wpDashElementorMenuClick: 'wpdash_elementor_menu_click',
2486 wpDashEditorSubMenuHover: 'wpdash_editor_sub_menu_hover',
2487 wpDashThemeBuilderClick: 'wpdash_theme_builder_click'
2488 },
2489 interactions: {
2490 created: 'interactions_created'
2491 },
2492 promotions: {
2493 viewPromotion: 'view_promotion',
2494 upgradePromotionClick: 'upgrade_promotion_click'
2495 }
2496 }
2497 };
2498 var _default = exports["default"] = eventsConfig;
2499
2500 /***/ }),
2501
2502 /***/ "../core/common/modules/events-manager/assets/js/module.js":
2503 /*!*****************************************************************!*\
2504 !*** ../core/common/modules/events-manager/assets/js/module.js ***!
2505 \*****************************************************************/
2506 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2507
2508 "use strict";
2509
2510
2511 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2512 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2513 Object.defineProperty(exports, "__esModule", ({
2514 value: true
2515 }));
2516 exports["default"] = void 0;
2517 var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "../node_modules/@babel/runtime/regenerator/index.js"));
2518 var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
2519 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2520 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2521 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2522 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2523 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2524 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
2525 var _eventsConfig = _interopRequireDefault(__webpack_require__(/*! ./events-config */ "../core/common/modules/events-manager/assets/js/events-config.js"));
2526 var _mixpanelBrowser = _interopRequireWildcard(__webpack_require__(/*! mixpanel-browser */ "../node_modules/mixpanel-browser/dist/mixpanel.module.js"));
2527 var _tiers = __webpack_require__(/*! elementor-utils/tiers */ "../assets/dev/js/utils/tiers.js");
2528 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); }
2529 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; }
2530 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; }
2531 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)); }
2532 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2533 /** @type {Mixpanel | null} */
2534 var mixpanelInstance = null;
2535 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
2536 function _default() {
2537 var _this;
2538 (0, _classCallCheck2.default)(this, _default);
2539 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2540 args[_key] = arguments[_key];
2541 }
2542 _this = _callSuper(this, _default, [].concat(args));
2543 (0, _defineProperty2.default)(_this, "trackingEnabled", false);
2544 (0, _defineProperty2.default)(_this, "availableExperiments", []);
2545 return _this;
2546 }
2547 (0, _inherits2.default)(_default, _elementorModules$Mod);
2548 return (0, _createClass2.default)(_default, [{
2549 key: "onInit",
2550 value: function onInit() {
2551 var _this2 = this;
2552 this.config = _eventsConfig.default;
2553 if (!this.canSendEvents()) {
2554 return;
2555 }
2556 this.initializeMixpanel(function () {
2557 return _this2.enableTracking();
2558 });
2559 }
2560 }, {
2561 key: "initializeMixpanel",
2562 value: function initializeMixpanel(onLoaded) {
2563 if (mixpanelInstance && mixpanelInstance.isInitialized) {
2564 onLoaded(mixpanelInstance);
2565 } else {
2566 var _elementorCommon$conf, _elementorCommon$conf2, _elementorCommon$conf3, _elementorCommon$conf4, _elementorCommon$conf5;
2567 mixpanelInstance = _mixpanelBrowser.default.init((_elementorCommon$conf = elementorCommon.config.editor_events) === null || _elementorCommon$conf === void 0 ? void 0 : _elementorCommon$conf.token, {
2568 persistence: 'localStorage',
2569 persistence_name: 'elementor-builder-editor',
2570 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,
2571 autocapture: false,
2572 flags: true,
2573 api_host: 'https://api-eu.mixpanel.com',
2574 loaded: onLoaded,
2575 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,
2576 record_idle_timeout_ms: 60 * 1000,
2577 // 60 Seconds
2578 record_min_ms: 5 * 1000,
2579 // 5 Seconds
2580 record_mask_text_selector: '',
2581 remote_settings_mode: 'strict'
2582 }, 'elementor-builder-editor');
2583 }
2584 elementorCommon.config.editor_events.mixpanelInstance = mixpanelInstance;
2585 }
2586 }, {
2587 key: "enableTracking",
2588 value: function enableTracking() {
2589 var _elementorCommon$conf6;
2590 if (!this.isMixpanelReady()) {
2591 return;
2592 }
2593 var userId = (_elementorCommon$conf6 = elementorCommon.config.editor_events) === null || _elementorCommon$conf6 === void 0 ? void 0 : _elementorCommon$conf6.user_id;
2594 mixpanelInstance.register({
2595 appType: 'Editor'
2596 });
2597 if (userId) {
2598 var _elementorCommon$conf7;
2599 mixpanelInstance.identify(userId);
2600 mixpanelInstance.people.set_once({
2601 $user_id: userId,
2602 $last_login: new Date().toISOString(),
2603 $plan_type: ((_elementorCommon$conf7 = elementorCommon.config.library_connect) === null || _elementorCommon$conf7 === void 0 ? void 0 : _elementorCommon$conf7.plan_type) || _tiers.TIERS.free
2604 });
2605 }
2606 this.trackingEnabled = true;
2607 this.availableExperiments = Object.keys(elementorCommon.config.experimentalFeatures || {});
2608 }
2609 }, {
2610 key: "dispatchEvent",
2611 value: function dispatchEvent(name, data) {
2612 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2613 if (!this.canSendEvents()) {
2614 return;
2615 }
2616 try {
2617 var _elementorCommon$conf8, _elementorCommon$conf9, _elementorCommon$conf0, _elementorCommon$conf1, _elementorCommon$conf10, _elementorCommon$conf11, _elementorCommon$conf12, _elementorCommon$conf13, _elementorCommon$conf14;
2618 if (!this.trackingEnabled) {
2619 this.enableTracking();
2620 }
2621 var eventData = _objectSpread({
2622 user_id: ((_elementorCommon$conf8 = elementorCommon.config.editor_events) === null || _elementorCommon$conf8 === void 0 ? void 0 : _elementorCommon$conf8.user_id) || null,
2623 user_roles: ((_elementorCommon$conf9 = elementorCommon.config.library_connect) === null || _elementorCommon$conf9 === void 0 ? void 0 : _elementorCommon$conf9.user_roles) || [],
2624 subscription_id: ((_elementorCommon$conf0 = elementorCommon.config.editor_events) === null || _elementorCommon$conf0 === void 0 ? void 0 : _elementorCommon$conf0.subscription_id) || null,
2625 user_tier: ((_elementorCommon$conf1 = elementorCommon.config.library_connect) === null || _elementorCommon$conf1 === void 0 ? void 0 : _elementorCommon$conf1.current_access_tier) || null,
2626 url: (_elementorCommon$conf10 = elementorCommon.config.editor_events) === null || _elementorCommon$conf10 === void 0 ? void 0 : _elementorCommon$conf10.site_url,
2627 wp_version: (_elementorCommon$conf11 = elementorCommon.config.editor_events) === null || _elementorCommon$conf11 === void 0 ? void 0 : _elementorCommon$conf11.wp_version,
2628 client_id: (_elementorCommon$conf12 = elementorCommon.config.editor_events) === null || _elementorCommon$conf12 === void 0 ? void 0 : _elementorCommon$conf12.site_key,
2629 app_version: (_elementorCommon$conf13 = elementorCommon.config.editor_events) === null || _elementorCommon$conf13 === void 0 ? void 0 : _elementorCommon$conf13.elementor_version,
2630 site_language: (_elementorCommon$conf14 = elementorCommon.config.editor_events) === null || _elementorCommon$conf14 === void 0 ? void 0 : _elementorCommon$conf14.site_language,
2631 experiments: this.availableExperiments
2632 }, data);
2633 mixpanelInstance.track(name, eventData, options);
2634 } catch (error) {
2635 var _elementorCommon$conf15;
2636 if ((_elementorCommon$conf15 = elementorCommon.config.editor_events) !== null && _elementorCommon$conf15 !== void 0 && _elementorCommon$conf15.debug) {
2637 // eslint-disable-next-line no-console
2638 console.error('Events Manager dispatch failed:', error);
2639 }
2640 }
2641 }
2642 }, {
2643 key: "featureFlagIsActive",
2644 value: function () {
2645 var _featureFlagIsActive = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(flagName) {
2646 var _mixpanelInstance;
2647 var isEnabled;
2648 return _regenerator.default.wrap(function (_context) {
2649 while (1) switch (_context.prev = _context.next) {
2650 case 0:
2651 if (!('function' !== typeof ((_mixpanelInstance = mixpanelInstance) === null || _mixpanelInstance === void 0 || (_mixpanelInstance = _mixpanelInstance.flags) === null || _mixpanelInstance === void 0 ? void 0 : _mixpanelInstance.is_enabled))) {
2652 _context.next = 1;
2653 break;
2654 }
2655 return _context.abrupt("return", false);
2656 case 1:
2657 _context.next = 2;
2658 return mixpanelInstance.flags.is_enabled(flagName, false);
2659 case 2:
2660 isEnabled = _context.sent;
2661 return _context.abrupt("return", true === isEnabled);
2662 case 3:
2663 case "end":
2664 return _context.stop();
2665 }
2666 }, _callee);
2667 }));
2668 function featureFlagIsActive(_x) {
2669 return _featureFlagIsActive.apply(this, arguments);
2670 }
2671 return featureFlagIsActive;
2672 }()
2673 }, {
2674 key: "getExperimentVariant",
2675 value: function () {
2676 var _getExperimentVariant = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2(experimentName) {
2677 var defaultValue,
2678 _elementorCommon$conf16,
2679 _elementorCommon$conf17,
2680 isAbTestingEnabled,
2681 variant,
2682 _args2 = arguments,
2683 _t;
2684 return _regenerator.default.wrap(function (_context2) {
2685 while (1) switch (_context2.prev = _context2.next) {
2686 case 0:
2687 defaultValue = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 'control';
2688 _context2.prev = 1;
2689 if (this.canSendEvents()) {
2690 _context2.next = 2;
2691 break;
2692 }
2693 return _context2.abrupt("return", defaultValue);
2694 case 2:
2695 isAbTestingEnabled = (_elementorCommon$conf16 = (_elementorCommon$conf17 = elementorCommon.config.editor_events) === null || _elementorCommon$conf17 === void 0 ? void 0 : _elementorCommon$conf17.flags_enabled) !== null && _elementorCommon$conf16 !== void 0 ? _elementorCommon$conf16 : false;
2696 if (isAbTestingEnabled) {
2697 _context2.next = 3;
2698 break;
2699 }
2700 return _context2.abrupt("return", defaultValue);
2701 case 3:
2702 if (mixpanelInstance) {
2703 _context2.next = 4;
2704 break;
2705 }
2706 return _context2.abrupt("return", defaultValue);
2707 case 4:
2708 if (!this.trackingEnabled) {
2709 this.enableTracking();
2710 }
2711 if (mixpanelInstance.flags) {
2712 _context2.next = 5;
2713 break;
2714 }
2715 return _context2.abrupt("return", defaultValue);
2716 case 5:
2717 if (!('function' !== typeof mixpanelInstance.flags.get_variant_value)) {
2718 _context2.next = 6;
2719 break;
2720 }
2721 return _context2.abrupt("return", defaultValue);
2722 case 6:
2723 _context2.next = 7;
2724 return mixpanelInstance.flags.get_variant_value(experimentName, defaultValue);
2725 case 7:
2726 variant = _context2.sent;
2727 if (!(undefined === variant || null === variant)) {
2728 _context2.next = 8;
2729 break;
2730 }
2731 return _context2.abrupt("return", defaultValue);
2732 case 8:
2733 return _context2.abrupt("return", variant);
2734 case 9:
2735 _context2.prev = 9;
2736 _t = _context2["catch"](1);
2737 return _context2.abrupt("return", defaultValue);
2738 case 10:
2739 case "end":
2740 return _context2.stop();
2741 }
2742 }, _callee2, this, [[1, 9]]);
2743 }));
2744 function getExperimentVariant(_x2) {
2745 return _getExperimentVariant.apply(this, arguments);
2746 }
2747 return getExperimentVariant;
2748 }()
2749 }, {
2750 key: "startExperiment",
2751 value: function startExperiment(experimentName, experimentVariant) {
2752 if (!this.trackingEnabled) {
2753 return;
2754 }
2755 mixpanelInstance.track('$experiment_started', {
2756 'Experiment name': experimentName,
2757 'Variant name': experimentVariant
2758 });
2759 }
2760 }, {
2761 key: "isMixpanelReady",
2762 value: function isMixpanelReady() {
2763 if ('undefined' === typeof mixpanelInstance || !mixpanelInstance) {
2764 return false;
2765 }
2766 try {
2767 var distinctId = mixpanelInstance.get_distinct_id();
2768 return distinctId !== undefined && distinctId !== null;
2769 } catch (error) {
2770 return false;
2771 }
2772 }
2773 }, {
2774 key: "canSendEvents",
2775 value: function canSendEvents() {
2776 var _elementorCommon;
2777 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);
2778 }
2779 }, {
2780 key: "getMixpanelInstance",
2781 value: function getMixpanelInstance() {
2782 return this.isMixpanelReady() ? mixpanelInstance : undefined;
2783 }
2784 }]);
2785 }(elementorModules.Module);
2786
2787 /***/ }),
2788
2789 /***/ "../core/common/modules/finder/assets/js/commands/index.js":
2790 /*!*****************************************************************!*\
2791 !*** ../core/common/modules/finder/assets/js/commands/index.js ***!
2792 \*****************************************************************/
2793 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2794
2795 "use strict";
2796
2797
2798 Object.defineProperty(exports, "__esModule", ({
2799 value: true
2800 }));
2801 Object.defineProperty(exports, "NavigateDown", ({
2802 enumerable: true,
2803 get: function get() {
2804 return _navigateDown.NavigateDown;
2805 }
2806 }));
2807 Object.defineProperty(exports, "NavigateSelect", ({
2808 enumerable: true,
2809 get: function get() {
2810 return _navigateSelect.NavigateSelect;
2811 }
2812 }));
2813 Object.defineProperty(exports, "NavigateUp", ({
2814 enumerable: true,
2815 get: function get() {
2816 return _navigateUp.NavigateUp;
2817 }
2818 }));
2819 var _navigateDown = __webpack_require__(/*! ./navigate-down */ "../core/common/modules/finder/assets/js/commands/navigate-down.js");
2820 var _navigateSelect = __webpack_require__(/*! ./navigate-select */ "../core/common/modules/finder/assets/js/commands/navigate-select.js");
2821 var _navigateUp = __webpack_require__(/*! ./navigate-up */ "../core/common/modules/finder/assets/js/commands/navigate-up.js");
2822
2823 /***/ }),
2824
2825 /***/ "../core/common/modules/finder/assets/js/commands/navigate-down.js":
2826 /*!*************************************************************************!*\
2827 !*** ../core/common/modules/finder/assets/js/commands/navigate-down.js ***!
2828 \*************************************************************************/
2829 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2830
2831 "use strict";
2832
2833
2834 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2835 Object.defineProperty(exports, "__esModule", ({
2836 value: true
2837 }));
2838 exports["default"] = exports.NavigateDown = void 0;
2839 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2840 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2841 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2842 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2843 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2844 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2845 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)); }
2846 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2847 var NavigateDown = exports.NavigateDown = /*#__PURE__*/function (_CommandBase) {
2848 function NavigateDown() {
2849 (0, _classCallCheck2.default)(this, NavigateDown);
2850 return _callSuper(this, NavigateDown, arguments);
2851 }
2852 (0, _inherits2.default)(NavigateDown, _CommandBase);
2853 return (0, _createClass2.default)(NavigateDown, [{
2854 key: "apply",
2855 value: function apply() {
2856 this.component.getItemsView().activateNextItem();
2857 }
2858 }]);
2859 }(_commandBase.default);
2860 var _default = exports["default"] = NavigateDown;
2861
2862 /***/ }),
2863
2864 /***/ "../core/common/modules/finder/assets/js/commands/navigate-select.js":
2865 /*!***************************************************************************!*\
2866 !*** ../core/common/modules/finder/assets/js/commands/navigate-select.js ***!
2867 \***************************************************************************/
2868 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2869
2870 "use strict";
2871
2872
2873 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2874 Object.defineProperty(exports, "__esModule", ({
2875 value: true
2876 }));
2877 exports["default"] = exports.NavigateSelect = void 0;
2878 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2879 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2880 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2881 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2882 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2883 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2884 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)); }
2885 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2886 var NavigateSelect = exports.NavigateSelect = /*#__PURE__*/function (_CommandBase) {
2887 function NavigateSelect() {
2888 (0, _classCallCheck2.default)(this, NavigateSelect);
2889 return _callSuper(this, NavigateSelect, arguments);
2890 }
2891 (0, _inherits2.default)(NavigateSelect, _CommandBase);
2892 return (0, _createClass2.default)(NavigateSelect, [{
2893 key: "apply",
2894 value: function apply(args) {
2895 this.component.getItemsView().goToActiveItem(args);
2896 }
2897 }]);
2898 }(_commandBase.default);
2899 var _default = exports["default"] = NavigateSelect;
2900
2901 /***/ }),
2902
2903 /***/ "../core/common/modules/finder/assets/js/commands/navigate-up.js":
2904 /*!***********************************************************************!*\
2905 !*** ../core/common/modules/finder/assets/js/commands/navigate-up.js ***!
2906 \***********************************************************************/
2907 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2908
2909 "use strict";
2910
2911
2912 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2913 Object.defineProperty(exports, "__esModule", ({
2914 value: true
2915 }));
2916 exports["default"] = exports.NavigateUp = void 0;
2917 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2918 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2919 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2920 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2921 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2922 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2923 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)); }
2924 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2925 var NavigateUp = exports.NavigateUp = /*#__PURE__*/function (_CommandBase) {
2926 function NavigateUp() {
2927 (0, _classCallCheck2.default)(this, NavigateUp);
2928 return _callSuper(this, NavigateUp, arguments);
2929 }
2930 (0, _inherits2.default)(NavigateUp, _CommandBase);
2931 return (0, _createClass2.default)(NavigateUp, [{
2932 key: "apply",
2933 value: function apply() {
2934 this.component.getItemsView().activateNextItem(true);
2935 }
2936 }]);
2937 }(_commandBase.default);
2938 var _default = exports["default"] = NavigateUp;
2939
2940 /***/ }),
2941
2942 /***/ "../core/common/modules/finder/assets/js/component.js":
2943 /*!************************************************************!*\
2944 !*** ../core/common/modules/finder/assets/js/component.js ***!
2945 \************************************************************/
2946 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2947
2948 "use strict";
2949
2950
2951 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2952 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2953 Object.defineProperty(exports, "__esModule", ({
2954 value: true
2955 }));
2956 exports["default"] = void 0;
2957 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
2958 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2959 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2960 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2961 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2962 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
2963 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2964 var _componentModalBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-modal-base */ "../modules/web-cli/assets/js/modules/component-modal-base.js"));
2965 var _layout = _interopRequireDefault(__webpack_require__(/*! ./modal/views/layout */ "../core/common/modules/finder/assets/js/modal/views/layout.js"));
2966 var commands = _interopRequireWildcard(__webpack_require__(/*! ./commands/ */ "../core/common/modules/finder/assets/js/commands/index.js"));
2967 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); }
2968 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; }
2969 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; }
2970 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)); }
2971 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2972 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; }
2973 var Component = exports["default"] = /*#__PURE__*/function (_ComponentModalBase) {
2974 function Component() {
2975 (0, _classCallCheck2.default)(this, Component);
2976 return _callSuper(this, Component, arguments);
2977 }
2978 (0, _inherits2.default)(Component, _ComponentModalBase);
2979 return (0, _createClass2.default)(Component, [{
2980 key: "getNamespace",
2981 value: function getNamespace() {
2982 return 'finder';
2983 }
2984 }, {
2985 key: "defaultShortcuts",
2986 value: function defaultShortcuts() {
2987 var _this = this;
2988 return {
2989 '': {
2990 keys: 'ctrl+e'
2991 },
2992 'navigate-down': {
2993 keys: 'down',
2994 scopes: [this.getNamespace()],
2995 dependency: function dependency() {
2996 return _this.getItemsView();
2997 }
2998 },
2999 'navigate-up': {
3000 keys: 'up',
3001 scopes: [this.getNamespace()],
3002 dependency: function dependency() {
3003 return _this.getItemsView();
3004 }
3005 },
3006 'navigate-select': {
3007 keys: 'enter',
3008 scopes: [this.getNamespace()],
3009 dependency: function dependency() {
3010 return _this.getItemsView().$activeItem;
3011 }
3012 }
3013 };
3014 }
3015 }, {
3016 key: "defaultCommands",
3017 value: function defaultCommands() {
3018 var modalCommands = _superPropGet(Component, "defaultCommands", this, 3)([]);
3019 return _objectSpread(_objectSpread({
3020 'navigate/down': function navigate_down() {
3021 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/down' )", '3.0.0', "$e.run( 'finder/navigate-down' )");
3022 $e.run('finder/navigate-down');
3023 },
3024 'navigate/up': function navigate_up() {
3025 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/up' )", '3.0.0', "$e.run( 'finder/navigate-up' )");
3026 $e.run('finder/navigate-up');
3027 },
3028 'navigate/select': function navigate_select(event) {
3029 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/select', event )", '3.0.0', "$e.run( 'finder/navigate-select', event )");
3030
3031 // TODO: Fix $e.shortcuts use args. ( args.event ).
3032 $e.run('finder/navigate-select', event);
3033 }
3034 }, modalCommands), this.importCommands(commands));
3035 }
3036 }, {
3037 key: "getModalLayout",
3038 value: function getModalLayout() {
3039 return _layout.default;
3040 }
3041 }, {
3042 key: "getItemsView",
3043 value: function getItemsView() {
3044 return this.layout.modalContent.currentView.content.currentView;
3045 }
3046 }]);
3047 }(_componentModalBase.default);
3048
3049 /***/ }),
3050
3051 /***/ "../core/common/modules/finder/assets/js/finder.js":
3052 /*!*********************************************************!*\
3053 !*** ../core/common/modules/finder/assets/js/finder.js ***!
3054 \*********************************************************/
3055 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3056
3057 "use strict";
3058
3059
3060 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3061 Object.defineProperty(exports, "__esModule", ({
3062 value: true
3063 }));
3064 exports["default"] = void 0;
3065 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3066 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3067 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3068 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3069 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3070 var _component = _interopRequireDefault(__webpack_require__(/*! ./component */ "../core/common/modules/finder/assets/js/component.js"));
3071 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)); }
3072 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3073 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
3074 function _default() {
3075 (0, _classCallCheck2.default)(this, _default);
3076 return _callSuper(this, _default, arguments);
3077 }
3078 (0, _inherits2.default)(_default, _elementorModules$Mod);
3079 return (0, _createClass2.default)(_default, [{
3080 key: "onInit",
3081 value: function onInit() {
3082 // TODO: Temp fix, do not load finder in theme-builder.
3083 // Better to pass into '$e' constructor the app owner. ( admin, editor, preview, iframe ).
3084 if (window.top !== window) {
3085 return;
3086 }
3087 this.channel = Backbone.Radio.channel('ELEMENTOR:finder');
3088 $e.components.register(new _component.default({
3089 manager: this
3090 }));
3091 }
3092 }]);
3093 }(elementorModules.Module);
3094
3095 /***/ }),
3096
3097 /***/ "../core/common/modules/finder/assets/js/modal/model/item.js":
3098 /*!*******************************************************************!*\
3099 !*** ../core/common/modules/finder/assets/js/modal/model/item.js ***!
3100 \*******************************************************************/
3101 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3102
3103 "use strict";
3104
3105
3106 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3107 Object.defineProperty(exports, "__esModule", ({
3108 value: true
3109 }));
3110 exports["default"] = void 0;
3111 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3112 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3113 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3114 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3115 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3116 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)); }
3117 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3118 var _default = exports["default"] = /*#__PURE__*/function (_Backbone$Model) {
3119 function _default() {
3120 (0, _classCallCheck2.default)(this, _default);
3121 return _callSuper(this, _default, arguments);
3122 }
3123 (0, _inherits2.default)(_default, _Backbone$Model);
3124 return (0, _createClass2.default)(_default, [{
3125 key: "defaults",
3126 value: function defaults() {
3127 return {
3128 description: '',
3129 icon: 'settings',
3130 url: '',
3131 keywords: [],
3132 actions: [],
3133 lock: null
3134 };
3135 }
3136 }]);
3137 }(Backbone.Model);
3138
3139 /***/ }),
3140
3141 /***/ "../core/common/modules/finder/assets/js/modal/views/categories.js":
3142 /*!*************************************************************************!*\
3143 !*** ../core/common/modules/finder/assets/js/modal/views/categories.js ***!
3144 \*************************************************************************/
3145 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3146
3147 "use strict";
3148
3149
3150 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3151 Object.defineProperty(exports, "__esModule", ({
3152 value: true
3153 }));
3154 exports["default"] = void 0;
3155 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3156 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3157 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3158 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3159 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3160 var _category = _interopRequireDefault(__webpack_require__(/*! ./category */ "../core/common/modules/finder/assets/js/modal/views/category.js"));
3161 var _dynamicCategory = _interopRequireDefault(__webpack_require__(/*! ./dynamic-category */ "../core/common/modules/finder/assets/js/modal/views/dynamic-category.js"));
3162 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)); }
3163 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3164 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$Composite) {
3165 function _default() {
3166 (0, _classCallCheck2.default)(this, _default);
3167 return _callSuper(this, _default, arguments);
3168 }
3169 (0, _inherits2.default)(_default, _Marionette$Composite);
3170 return (0, _createClass2.default)(_default, [{
3171 key: "id",
3172 value: function id() {
3173 return 'elementor-finder__results-container';
3174 }
3175 }, {
3176 key: "ui",
3177 value: function ui() {
3178 this.selectors = {
3179 noResults: '#elementor-finder__no-results',
3180 categoryItem: '.elementor-finder__results__item'
3181 };
3182 return this.selectors;
3183 }
3184 }, {
3185 key: "events",
3186 value: function events() {
3187 return {
3188 'mouseenter @ui.categoryItem': 'onCategoryItemMouseEnter'
3189 };
3190 }
3191 }, {
3192 key: "getTemplate",
3193 value: function getTemplate() {
3194 return '#tmpl-elementor-finder-results-container';
3195 }
3196 }, {
3197 key: "getChildView",
3198 value: function getChildView(childModel) {
3199 return childModel.get('dynamic') ? _dynamicCategory.default : _category.default;
3200 }
3201 }, {
3202 key: "initialize",
3203 value: function initialize() {
3204 this.$activeItem = null;
3205 this.childViewContainer = '#elementor-finder__results';
3206 this.collection = new Backbone.Collection(Object.values(elementorCommon.finder.getSettings('data')));
3207 }
3208 }, {
3209 key: "activateItem",
3210 value: function activateItem($item) {
3211 if (this.$activeItem) {
3212 this.$activeItem.removeClass('elementor-active');
3213 }
3214 $item.addClass('elementor-active');
3215 this.$activeItem = $item;
3216 }
3217 }, {
3218 key: "activateNextItem",
3219 value: function activateNextItem(reverse) {
3220 var $allItems = jQuery(this.selectors.categoryItem);
3221 var nextItemIndex = 0;
3222 if (this.$activeItem) {
3223 nextItemIndex = $allItems.index(this.$activeItem) + (reverse ? -1 : 1);
3224 if (nextItemIndex >= $allItems.length) {
3225 nextItemIndex = 0;
3226 } else if (nextItemIndex < 0) {
3227 nextItemIndex = $allItems.length - 1;
3228 }
3229 }
3230 var $nextItem = $allItems.eq(nextItemIndex);
3231 this.activateItem($nextItem);
3232 $nextItem[0].scrollIntoView({
3233 block: 'nearest'
3234 });
3235 }
3236 }, {
3237 key: "goToActiveItem",
3238 value: function goToActiveItem(event) {
3239 var $a = this.$activeItem.children('a'),
3240 isControlClicked = $e.shortcuts.isControlEvent(event);
3241 if (isControlClicked) {
3242 $a.attr('target', '_blank');
3243 }
3244 $a[0].click();
3245 if (isControlClicked) {
3246 $a.removeAttr('target');
3247 }
3248 }
3249 }, {
3250 key: "onCategoryItemMouseEnter",
3251 value: function onCategoryItemMouseEnter(event) {
3252 this.activateItem(jQuery(event.currentTarget));
3253 }
3254 }, {
3255 key: "onChildviewToggleVisibility",
3256 value: function onChildviewToggleVisibility() {
3257 var allCategoriesAreEmpty = this.children.every(function (child) {
3258 return !child.isVisible;
3259 });
3260 this.ui.noResults.toggle(allCategoriesAreEmpty);
3261 }
3262 }]);
3263 }(Marionette.CompositeView);
3264
3265 /***/ }),
3266
3267 /***/ "../core/common/modules/finder/assets/js/modal/views/category.js":
3268 /*!***********************************************************************!*\
3269 !*** ../core/common/modules/finder/assets/js/modal/views/category.js ***!
3270 \***********************************************************************/
3271 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3272
3273 "use strict";
3274
3275
3276 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3277 Object.defineProperty(exports, "__esModule", ({
3278 value: true
3279 }));
3280 exports["default"] = void 0;
3281 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3282 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3283 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3284 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3285 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3286 var _item = _interopRequireDefault(__webpack_require__(/*! ./item */ "../core/common/modules/finder/assets/js/modal/views/item.js"));
3287 var _item2 = _interopRequireDefault(__webpack_require__(/*! ../model/item */ "../core/common/modules/finder/assets/js/modal/model/item.js"));
3288 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)); }
3289 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3290 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$Composite) {
3291 function _default() {
3292 (0, _classCallCheck2.default)(this, _default);
3293 return _callSuper(this, _default, arguments);
3294 }
3295 (0, _inherits2.default)(_default, _Marionette$Composite);
3296 return (0, _createClass2.default)(_default, [{
3297 key: "className",
3298 value: function className() {
3299 return 'elementor-finder__results__category';
3300 }
3301 }, {
3302 key: "getTemplate",
3303 value: function getTemplate() {
3304 return '#tmpl-elementor-finder__results__category';
3305 }
3306 }, {
3307 key: "getChildView",
3308 value: function getChildView() {
3309 return _item.default;
3310 }
3311 }, {
3312 key: "initialize",
3313 value: function initialize() {
3314 this.childViewContainer = '.elementor-finder__results__category__items';
3315 this.isVisible = true;
3316 var items = this.model.get('items');
3317 if (items) {
3318 items = Object.values(items);
3319 }
3320 this.collection = new Backbone.Collection(items, {
3321 model: _item2.default
3322 });
3323 }
3324 }, {
3325 key: "filter",
3326 value: function filter(childModel) {
3327 var textFilter = this.getTextFilter();
3328 if (childModel.get('title').toLowerCase().indexOf(textFilter) >= 0) {
3329 return true;
3330 }
3331 return childModel.get('keywords').some(function (keyword) {
3332 return keyword.indexOf(textFilter) >= 0;
3333 });
3334 }
3335 }, {
3336 key: "getTextFilter",
3337 value: function getTextFilter() {
3338 return elementorCommon.finder.channel.request('filter:text').trim().toLowerCase();
3339 }
3340 }, {
3341 key: "toggleElement",
3342 value: function toggleElement() {
3343 var isCurrentlyVisible = !!this.children.length;
3344 if (isCurrentlyVisible !== this.isVisible) {
3345 this.isVisible = isCurrentlyVisible;
3346 this.$el.toggle(isCurrentlyVisible);
3347 this.triggerMethod('toggle:visibility');
3348 }
3349 }
3350 }, {
3351 key: "onRender",
3352 value: function onRender() {
3353 this.listenTo(elementorCommon.finder.channel, 'filter:change', this.onFilterChange.bind(this));
3354 }
3355 }, {
3356 key: "onFilterChange",
3357 value: function onFilterChange() {
3358 this._renderChildren();
3359 }
3360 }, {
3361 key: "onRenderCollection",
3362 value: function onRenderCollection() {
3363 this.toggleElement();
3364 }
3365 }]);
3366 }(Marionette.CompositeView);
3367
3368 /***/ }),
3369
3370 /***/ "../core/common/modules/finder/assets/js/modal/views/content.js":
3371 /*!**********************************************************************!*\
3372 !*** ../core/common/modules/finder/assets/js/modal/views/content.js ***!
3373 \**********************************************************************/
3374 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3375
3376 "use strict";
3377
3378
3379 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3380 Object.defineProperty(exports, "__esModule", ({
3381 value: true
3382 }));
3383 exports["default"] = void 0;
3384 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3385 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3386 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3387 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3388 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3389 var _categories = _interopRequireDefault(__webpack_require__(/*! ./categories */ "../core/common/modules/finder/assets/js/modal/views/categories.js"));
3390 var _editorOneEvents = __webpack_require__(/*! elementor-editor-utils/editor-one-events */ "../assets/dev/js/editor/utils/editor-one-events.js");
3391 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)); }
3392 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3393 var FINDER_SEARCH_DEBOUNCE_MS = 300;
3394 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$LayoutVie) {
3395 function _default() {
3396 (0, _classCallCheck2.default)(this, _default);
3397 return _callSuper(this, _default, arguments);
3398 }
3399 (0, _inherits2.default)(_default, _Marionette$LayoutVie);
3400 return (0, _createClass2.default)(_default, [{
3401 key: "id",
3402 value: function id() {
3403 return 'elementor-finder';
3404 }
3405 }, {
3406 key: "getTemplate",
3407 value: function getTemplate() {
3408 return '#tmpl-elementor-finder';
3409 }
3410 }, {
3411 key: "ui",
3412 value: function ui() {
3413 return {
3414 searchInput: '#elementor-finder__search__input'
3415 };
3416 }
3417 }, {
3418 key: "events",
3419 value: function events() {
3420 return {
3421 'input @ui.searchInput': 'onSearchInputInput'
3422 };
3423 }
3424 }, {
3425 key: "regions",
3426 value: function regions() {
3427 return {
3428 content: '#elementor-finder__content'
3429 };
3430 }
3431 }, {
3432 key: "initialize",
3433 value: function initialize() {
3434 this.debouncedTrackSearch = (0, _editorOneEvents.createDebouncedFinderSearch)(FINDER_SEARCH_DEBOUNCE_MS);
3435 }
3436 }, {
3437 key: "showCategoriesView",
3438 value: function showCategoriesView() {
3439 this.content.show(new _categories.default());
3440 }
3441 }, {
3442 key: "getResultsCount",
3443 value: function getResultsCount() {
3444 if (!this.content.currentView) {
3445 return 0;
3446 }
3447 var $visibleItems = this.content.currentView.$el.find('.elementor-finder__results__item:visible');
3448 return $visibleItems.length;
3449 }
3450 }, {
3451 key: "onSearchInputInput",
3452 value: function onSearchInputInput() {
3453 var _this = this;
3454 var value = this.ui.searchInput.val();
3455 if (value) {
3456 elementorCommon.finder.channel.reply('filter:text', value).trigger('filter:change');
3457 if (!(this.content.currentView instanceof _categories.default)) {
3458 this.showCategoriesView();
3459 }
3460 setTimeout(function () {
3461 var resultsCount = _this.getResultsCount();
3462 _this.debouncedTrackSearch(resultsCount, value);
3463 }, 50);
3464 }
3465 this.content.currentView.$el.toggle(!!value);
3466 }
3467 }, {
3468 key: "onDestroy",
3469 value: function onDestroy() {
3470 var _this$debouncedTrackS;
3471 if ((_this$debouncedTrackS = this.debouncedTrackSearch) !== null && _this$debouncedTrackS !== void 0 && _this$debouncedTrackS.cancel) {
3472 this.debouncedTrackSearch.cancel();
3473 }
3474 }
3475 }]);
3476 }(Marionette.LayoutView);
3477
3478 /***/ }),
3479
3480 /***/ "../core/common/modules/finder/assets/js/modal/views/dynamic-category.js":
3481 /*!*******************************************************************************!*\
3482 !*** ../core/common/modules/finder/assets/js/modal/views/dynamic-category.js ***!
3483 \*******************************************************************************/
3484 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3485
3486 "use strict";
3487
3488
3489 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3490 Object.defineProperty(exports, "__esModule", ({
3491 value: true
3492 }));
3493 exports["default"] = void 0;
3494 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3495 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3496 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3497 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3498 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
3499 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3500 var _category = _interopRequireDefault(__webpack_require__(/*! ./category */ "../core/common/modules/finder/assets/js/modal/views/category.js"));
3501 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)); }
3502 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3503 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; }
3504 var _default = exports["default"] = /*#__PURE__*/function (_Category) {
3505 function _default() {
3506 (0, _classCallCheck2.default)(this, _default);
3507 return _callSuper(this, _default, arguments);
3508 }
3509 (0, _inherits2.default)(_default, _Category);
3510 return (0, _createClass2.default)(_default, [{
3511 key: "className",
3512 value: function className() {
3513 return _superPropGet(_default, "className", this, 3)([]) + ' elementor-finder__results__category--dynamic';
3514 }
3515 }, {
3516 key: "ui",
3517 value: function ui() {
3518 return {
3519 title: '.elementor-finder__results__category__title'
3520 };
3521 }
3522 }, {
3523 key: "fetchData",
3524 value: function fetchData() {
3525 var _this = this;
3526 this.ui.loadingIcon.show();
3527 elementorCommon.ajax.addRequest('finder_get_category_items', {
3528 data: {
3529 category: this.model.get('name'),
3530 filter: this.getTextFilter()
3531 },
3532 success: function success(data) {
3533 if (_this.isDestroyed) {
3534 return;
3535 }
3536 _this.collection.set(data);
3537 _this.toggleElement();
3538 _this.ui.loadingIcon.hide();
3539 }
3540 });
3541 }
3542 }, {
3543 key: "filter",
3544 value: function filter() {
3545 return true;
3546 }
3547 }, {
3548 key: "onFilterChange",
3549 value: function onFilterChange() {
3550 this.fetchData();
3551 }
3552 }, {
3553 key: "onRender",
3554 value: function onRender() {
3555 _superPropGet(_default, "onRender", this, 3)([]);
3556 this.ui.loadingIcon = jQuery('<i>', {
3557 class: 'eicon-loading eicon-animation-spin'
3558 });
3559 this.ui.title.after(this.ui.loadingIcon);
3560 this.fetchData();
3561 }
3562 }]);
3563 }(_category.default);
3564
3565 /***/ }),
3566
3567 /***/ "../core/common/modules/finder/assets/js/modal/views/item.js":
3568 /*!*******************************************************************!*\
3569 !*** ../core/common/modules/finder/assets/js/modal/views/item.js ***!
3570 \*******************************************************************/
3571 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3572
3573 "use strict";
3574 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
3575
3576
3577 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3578 Object.defineProperty(exports, "__esModule", ({
3579 value: true
3580 }));
3581 exports["default"] = void 0;
3582 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3583 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3584 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3585 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3586 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3587 var _editorOneEvents = __webpack_require__(/*! elementor-editor-utils/editor-one-events */ "../assets/dev/js/editor/utils/editor-one-events.js");
3588 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)); }
3589 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3590 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$ItemView) {
3591 function _default() {
3592 (0, _classCallCheck2.default)(this, _default);
3593 return _callSuper(this, _default, arguments);
3594 }
3595 (0, _inherits2.default)(_default, _Marionette$ItemView);
3596 return (0, _createClass2.default)(_default, [{
3597 key: "className",
3598 value: function className() {
3599 return 'elementor-finder__results__item';
3600 }
3601 }, {
3602 key: "getTemplate",
3603 value: function getTemplate() {
3604 return '#tmpl-elementor-finder__results__item';
3605 }
3606 }, {
3607 key: "events",
3608 value: function events() {
3609 this.$el[0].addEventListener('click', this.onClick.bind(this), true);
3610 }
3611 }, {
3612 key: "trackResultSelect",
3613 value: function trackResultSelect() {
3614 var title = this.model.get('title');
3615 _editorOneEvents.EditorOneEventManager.sendFinderResultSelect(title);
3616 }
3617 }, {
3618 key: "onClick",
3619 value: function onClick(e) {
3620 var _this = this;
3621 var lockOptions = this.model.get('lock');
3622 if (!(lockOptions !== null && lockOptions !== void 0 && lockOptions.is_locked)) {
3623 this.trackResultSelect();
3624 return;
3625 }
3626 e.preventDefault();
3627 e.stopImmediatePropagation();
3628 elementorCommon.dialogsManager.createWidget('confirm', {
3629 id: 'elementor-finder__lock-dialog',
3630 headerMessage: lockOptions.content.heading,
3631 message: lockOptions.content.description,
3632 position: {
3633 my: 'center center',
3634 at: 'center center'
3635 },
3636 strings: {
3637 confirm: lockOptions.button.text,
3638 cancel: __('Cancel', 'elementor')
3639 },
3640 onConfirm: function onConfirm() {
3641 _this.trackResultSelect();
3642 var link = _this.replaceLockLinkPlaceholders(lockOptions.button.url);
3643 window.open(link, '_blank');
3644 }
3645 }).show();
3646 }
3647 }, {
3648 key: "replaceLockLinkPlaceholders",
3649 value: function replaceLockLinkPlaceholders(link) {
3650 return link.replace(/%%utm_source%%/g, 'finder').replace(/%%utm_medium%%/g, 'wp-dash');
3651 }
3652 }]);
3653 }(Marionette.ItemView);
3654
3655 /***/ }),
3656
3657 /***/ "../core/common/modules/finder/assets/js/modal/views/layout.js":
3658 /*!*********************************************************************!*\
3659 !*** ../core/common/modules/finder/assets/js/modal/views/layout.js ***!
3660 \*********************************************************************/
3661 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3662
3663 "use strict";
3664 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
3665
3666
3667 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3668 Object.defineProperty(exports, "__esModule", ({
3669 value: true
3670 }));
3671 exports["default"] = void 0;
3672 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3673 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3674 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3675 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3676 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
3677 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3678 var _content = _interopRequireDefault(__webpack_require__(/*! ./content */ "../core/common/modules/finder/assets/js/modal/views/content.js"));
3679 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)); }
3680 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3681 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; }
3682 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$com) {
3683 function _default() {
3684 (0, _classCallCheck2.default)(this, _default);
3685 return _callSuper(this, _default, arguments);
3686 }
3687 (0, _inherits2.default)(_default, _elementorModules$com);
3688 return (0, _createClass2.default)(_default, [{
3689 key: "getModalOptions",
3690 value: function getModalOptions() {
3691 return {
3692 id: 'elementor-finder__modal',
3693 draggable: true,
3694 effects: {
3695 show: 'show',
3696 hide: 'hide'
3697 },
3698 position: {
3699 enable: false
3700 }
3701 };
3702 }
3703 }, {
3704 key: "getLogoOptions",
3705 value: function getLogoOptions() {
3706 return {
3707 title: __('Finder', 'elementor')
3708 };
3709 }
3710 }, {
3711 key: "initialize",
3712 value: function initialize() {
3713 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3714 args[_key] = arguments[_key];
3715 }
3716 _superPropGet(_default, "initialize", this, 3)(args);
3717 this.showLogo();
3718 this.showContentView();
3719 }
3720 }, {
3721 key: "showContentView",
3722 value: function showContentView() {
3723 this.modalContent.show(new _content.default());
3724 }
3725 }, {
3726 key: "showModal",
3727 value: function showModal() {
3728 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
3729 args[_key2] = arguments[_key2];
3730 }
3731 _superPropGet(_default, "showModal", this, 3)(args);
3732 this.modalContent.currentView.ui.searchInput.focus();
3733 }
3734 }]);
3735 }(elementorModules.common.views.modal.Layout);
3736
3737 /***/ }),
3738
3739 /***/ "../modules/web-cli/assets/js/core/data/errors/base-error.js":
3740 /*!*******************************************************************!*\
3741 !*** ../modules/web-cli/assets/js/core/data/errors/base-error.js ***!
3742 \*******************************************************************/
3743 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3744
3745 "use strict";
3746
3747
3748 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3749 Object.defineProperty(exports, "__esModule", ({
3750 value: true
3751 }));
3752 exports["default"] = void 0;
3753 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3754 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3755 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3756 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3757 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3758 var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js"));
3759 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
3760 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
3761 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../../../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
3762 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; }
3763 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; }
3764 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)); }
3765 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3766 var BaseError = exports["default"] = /*#__PURE__*/function (_Error) {
3767 /**
3768 * Error constructor.
3769 *
3770 * @param {string} message
3771 * @param {string} code
3772 * @param {*} data
3773 */
3774 function BaseError() {
3775 var _this;
3776 var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
3777 var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
3778 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
3779 (0, _classCallCheck2.default)(this, BaseError);
3780 _this = _callSuper(this, BaseError, [message]);
3781 /**
3782 * The server error code.
3783 *
3784 * @type {string}
3785 */
3786 (0, _defineProperty2.default)(_this, "code", '');
3787 /**
3788 * Additional data about the current error.
3789 *
3790 * @type {*[]}
3791 */
3792 (0, _defineProperty2.default)(_this, "data", []);
3793 _this.code = code;
3794 _this.data = data;
3795 return _this;
3796 }
3797
3798 /**
3799 * Notify a message when the error occurs.
3800 */
3801 (0, _inherits2.default)(BaseError, _Error);
3802 return (0, _createClass2.default)(BaseError, [{
3803 key: "notify",
3804 value: function notify() {
3805 _console.default.error(_objectSpread({
3806 message: this.message
3807 }, this));
3808 }
3809 }], [{
3810 key: "create",
3811 value:
3812 /**
3813 * Static helper function to create the error.
3814 *
3815 * @param {string} message
3816 * @param {string} code
3817 * @param {*} data
3818 * @return {BaseError} error
3819 */
3820 function create(message) {
3821 var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
3822 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
3823 return new this(message, code, data);
3824 }
3825
3826 /**
3827 * Returns the status code of the error.
3828 */
3829 }, {
3830 key: "getHTTPErrorCode",
3831 value: function getHTTPErrorCode() {
3832 (0, _forceMethodImplementation.default)();
3833 }
3834 }]);
3835 }(/*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
3836
3837 /***/ }),
3838
3839 /***/ "../modules/web-cli/assets/js/core/data/errors/default-error.js":
3840 /*!**********************************************************************!*\
3841 !*** ../modules/web-cli/assets/js/core/data/errors/default-error.js ***!
3842 \**********************************************************************/
3843 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3844
3845 "use strict";
3846
3847
3848 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3849 Object.defineProperty(exports, "__esModule", ({
3850 value: true
3851 }));
3852 exports["default"] = exports.DefaultError = void 0;
3853 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3854 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3855 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3856 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3857 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3858 var _baseError = _interopRequireDefault(__webpack_require__(/*! ./base-error */ "../modules/web-cli/assets/js/core/data/errors/base-error.js"));
3859 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)); }
3860 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3861 var DefaultError = exports.DefaultError = /*#__PURE__*/function (_BaseError) {
3862 function DefaultError() {
3863 (0, _classCallCheck2.default)(this, DefaultError);
3864 return _callSuper(this, DefaultError, arguments);
3865 }
3866 (0, _inherits2.default)(DefaultError, _BaseError);
3867 return (0, _createClass2.default)(DefaultError, null, [{
3868 key: "getHTTPErrorCode",
3869 value: function getHTTPErrorCode() {
3870 return 501;
3871 }
3872 }]);
3873 }(_baseError.default);
3874 var _default = exports["default"] = DefaultError;
3875
3876 /***/ }),
3877
3878 /***/ "../modules/web-cli/assets/js/core/data/errors/error-404.js":
3879 /*!******************************************************************!*\
3880 !*** ../modules/web-cli/assets/js/core/data/errors/error-404.js ***!
3881 \******************************************************************/
3882 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3883
3884 "use strict";
3885
3886
3887 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3888 Object.defineProperty(exports, "__esModule", ({
3889 value: true
3890 }));
3891 exports["default"] = exports.Error404 = void 0;
3892 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3893 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3894 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3895 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3896 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3897 var _baseError = _interopRequireDefault(__webpack_require__(/*! ./base-error */ "../modules/web-cli/assets/js/core/data/errors/base-error.js"));
3898 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
3899 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)); }
3900 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3901 var Error404 = exports.Error404 = /*#__PURE__*/function (_BaseError) {
3902 function Error404() {
3903 (0, _classCallCheck2.default)(this, Error404);
3904 return _callSuper(this, Error404, arguments);
3905 }
3906 (0, _inherits2.default)(Error404, _BaseError);
3907 return (0, _createClass2.default)(Error404, [{
3908 key: "notify",
3909 value: function notify() {
3910 _console.default.warn(this.message);
3911 }
3912 }], [{
3913 key: "getHTTPErrorCode",
3914 value: function getHTTPErrorCode() {
3915 return 404;
3916 }
3917 }]);
3918 }(_baseError.default);
3919 var _default = exports["default"] = Error404;
3920
3921 /***/ }),
3922
3923 /***/ "../modules/web-cli/assets/js/core/data/errors/index.js":
3924 /*!**************************************************************!*\
3925 !*** ../modules/web-cli/assets/js/core/data/errors/index.js ***!
3926 \**************************************************************/
3927 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3928
3929 "use strict";
3930
3931
3932 Object.defineProperty(exports, "__esModule", ({
3933 value: true
3934 }));
3935 Object.defineProperty(exports, "DefaultError", ({
3936 enumerable: true,
3937 get: function get() {
3938 return _defaultError.DefaultError;
3939 }
3940 }));
3941 Object.defineProperty(exports, "Error404", ({
3942 enumerable: true,
3943 get: function get() {
3944 return _error.Error404;
3945 }
3946 }));
3947 var _defaultError = __webpack_require__(/*! ./default-error */ "../modules/web-cli/assets/js/core/data/errors/default-error.js");
3948 var _error = __webpack_require__(/*! ./error-404 */ "../modules/web-cli/assets/js/core/data/errors/error-404.js");
3949
3950 /***/ }),
3951
3952 /***/ "../modules/web-cli/assets/js/modules/command-base.js":
3953 /*!************************************************************!*\
3954 !*** ../modules/web-cli/assets/js/modules/command-base.js ***!
3955 \************************************************************/
3956 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3957
3958 "use strict";
3959
3960
3961 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3962 Object.defineProperty(exports, "__esModule", ({
3963 value: true
3964 }));
3965 exports["default"] = void 0;
3966 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3967 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3968 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3969 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3970 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3971 var _commandInfra = _interopRequireDefault(__webpack_require__(/*! ./command-infra */ "../modules/web-cli/assets/js/modules/command-infra.js"));
3972 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
3973 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)); }
3974 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3975 /**
3976 * @name $e.modules.CommandBase
3977 */
3978 var CommandBase = exports["default"] = /*#__PURE__*/function (_CommandInfra) {
3979 function CommandBase() {
3980 (0, _classCallCheck2.default)(this, CommandBase);
3981 return _callSuper(this, CommandBase, arguments);
3982 }
3983 (0, _inherits2.default)(CommandBase, _CommandInfra);
3984 return (0, _createClass2.default)(CommandBase, [{
3985 key: "onBeforeRun",
3986 value: function onBeforeRun() {
3987 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3988 $e.hooks.runUIBefore(this.command, args);
3989 }
3990 }, {
3991 key: "onAfterRun",
3992 value: function onAfterRun() {
3993 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3994 var result = arguments.length > 1 ? arguments[1] : undefined;
3995 $e.hooks.runUIAfter(this.command, args, result);
3996 }
3997 }, {
3998 key: "onBeforeApply",
3999 value: function onBeforeApply() {
4000 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4001 $e.hooks.runDataDependency(this.command, args);
4002 }
4003 }, {
4004 key: "onAfterApply",
4005 value: function onAfterApply() {
4006 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4007 var result = arguments.length > 1 ? arguments[1] : undefined;
4008 return $e.hooks.runDataAfter(this.command, args, result);
4009 }
4010 }, {
4011 key: "onCatchApply",
4012 value: function onCatchApply(e) {
4013 this.runCatchHooks(e);
4014 }
4015
4016 /**
4017 * Run all the catch hooks.
4018 *
4019 * @param {Error} e
4020 */
4021 }, {
4022 key: "runCatchHooks",
4023 value: function runCatchHooks(e) {
4024 $e.hooks.runDataCatch(this.command, this.args, e);
4025 $e.hooks.runUICatch(this.command, this.args, e);
4026 }
4027
4028 /**
4029 * TODO - Remove - Backwards compatibility.
4030 *
4031 * Function requireContainer().
4032 *
4033 * Validate `arg.container` & `arg.containers`.
4034 *
4035 * @param {{}} args
4036 * @deprecated since 3.7.0, extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase` instead.
4037 *
4038 * @throws {Error}
4039 */
4040 }, {
4041 key: "requireContainer",
4042 value: function requireContainer() {
4043 var _this = this;
4044 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.args;
4045 _deprecation.default.deprecated('requireContainer()', '3.7.0', 'Extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase`');
4046 if (!args.container && !args.containers) {
4047 throw Error('container or containers are required.');
4048 }
4049 if (args.container && args.containers) {
4050 throw Error('container and containers cannot go together please select one of them.');
4051 }
4052 var containers = args.containers || [args.container];
4053 containers.forEach(function (container) {
4054 _this.requireArgumentInstance('container', elementorModules.editor.Container, {
4055 container: container
4056 });
4057 });
4058 }
4059 }], [{
4060 key: "getInstanceType",
4061 value: function getInstanceType() {
4062 return 'CommandBase';
4063 }
4064 }]);
4065 }(_commandInfra.default);
4066
4067 /***/ }),
4068
4069 /***/ "../modules/web-cli/assets/js/modules/command-callback-base.js":
4070 /*!*********************************************************************!*\
4071 !*** ../modules/web-cli/assets/js/modules/command-callback-base.js ***!
4072 \*********************************************************************/
4073 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4074
4075 "use strict";
4076
4077
4078 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4079 Object.defineProperty(exports, "__esModule", ({
4080 value: true
4081 }));
4082 exports["default"] = void 0;
4083 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4084 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4085 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4086 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4087 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4088 var _commandBase = _interopRequireDefault(__webpack_require__(/*! ./command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4089 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)); }
4090 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4091 /**
4092 * To support pure callbacks in the API(commands.js), to ensure they have registered with the proper context.
4093 */
4094 var CommandCallbackBase = exports["default"] = /*#__PURE__*/function (_CommandBase) {
4095 function CommandCallbackBase() {
4096 (0, _classCallCheck2.default)(this, CommandCallbackBase);
4097 return _callSuper(this, CommandCallbackBase, arguments);
4098 }
4099 (0, _inherits2.default)(CommandCallbackBase, _CommandBase);
4100 return (0, _createClass2.default)(CommandCallbackBase, [{
4101 key: "apply",
4102 value: function apply() {
4103 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4104 return this.constructor.getCallback()(args);
4105 }
4106 }], [{
4107 key: "getInstanceType",
4108 value: function getInstanceType() {
4109 return 'CommandCallbackBase';
4110 }
4111
4112 /**
4113 * Get original callback of the command.
4114 *
4115 * Support pure callbacks ( Non command-base ).
4116 *
4117 * @return {()=>{}} Command Results.
4118 */
4119 }, {
4120 key: "getCallback",
4121 value: function getCallback() {
4122 return this.registerConfig.callback;
4123 }
4124 }]);
4125 }(_commandBase.default);
4126
4127 /***/ }),
4128
4129 /***/ "../modules/web-cli/assets/js/modules/command-data.js":
4130 /*!************************************************************!*\
4131 !*** ../modules/web-cli/assets/js/modules/command-data.js ***!
4132 \************************************************************/
4133 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4134
4135 "use strict";
4136
4137
4138 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4139 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
4140 Object.defineProperty(exports, "__esModule", ({
4141 value: true
4142 }));
4143 exports["default"] = void 0;
4144 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4145 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4146 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4147 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4148 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4149 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4150 var _commandBase = _interopRequireDefault(__webpack_require__(/*! ./command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4151 var errors = _interopRequireWildcard(__webpack_require__(/*! ../core/data/errors/ */ "../modules/web-cli/assets/js/core/data/errors/index.js"));
4152 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); }
4153 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)); }
4154 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4155 /**
4156 * @name $e.modules.CommandData
4157 */
4158 /**
4159 * @typedef {('create'|'delete'|'get'|'update'|'options')} DataTypes
4160 */
4161 /**
4162 * @typedef {{}} RequestData
4163 */
4164 /**
4165 * @typedef {import('../core/data/errors/base-error')} BaseError
4166 */
4167 var CommandData = exports["default"] = /*#__PURE__*/function (_CommandBase) {
4168 function CommandData(args) {
4169 var _this$args$options;
4170 var _this;
4171 var commandsAPI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : $e.data;
4172 (0, _classCallCheck2.default)(this, CommandData);
4173 _this = _callSuper(this, CommandData, [args, commandsAPI]);
4174 /**
4175 * Data returned from remote.
4176 *
4177 * @type {*}
4178 */
4179 (0, _defineProperty2.default)(_this, "data", void 0);
4180 /**
4181 * Fetch type.
4182 *
4183 * @type {DataTypes}
4184 */
4185 (0, _defineProperty2.default)(_this, "type", void 0);
4186 if ((_this$args$options = _this.args.options) !== null && _this$args$options !== void 0 && _this$args$options.type) {
4187 _this.type = _this.args.options.type;
4188 }
4189 return _this;
4190 }
4191
4192 /**
4193 * Function getEndpointFormat().
4194 *
4195 * @return {null|string} endpoint format
4196 */
4197 (0, _inherits2.default)(CommandData, _CommandBase);
4198 return (0, _createClass2.default)(CommandData, [{
4199 key: "getApplyMethods",
4200 value:
4201 /**
4202 * @param {DataTypes} type
4203 *
4204 * @return {boolean|{before: (function(*=): {}), after: (function({}, *=): {})}} apply methods
4205 */
4206 function getApplyMethods() {
4207 var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.type;
4208 var before, after;
4209 switch (type) {
4210 case 'create':
4211 before = this.applyBeforeCreate;
4212 after = this.applyAfterCreate;
4213 break;
4214 case 'delete':
4215 before = this.applyBeforeDelete;
4216 after = this.applyAfterDelete;
4217 break;
4218 case 'get':
4219 before = this.applyBeforeGet;
4220 after = this.applyAfterGet;
4221 break;
4222 case 'update':
4223 before = this.applyBeforeUpdate;
4224 after = this.applyAfterUpdate;
4225 break;
4226 case 'options':
4227 before = this.applyBeforeOptions;
4228 after = this.applyAfterOptions;
4229 break;
4230 default:
4231 return false;
4232 }
4233 return {
4234 before: before.bind(this),
4235 after: after.bind(this)
4236 };
4237 }
4238
4239 /**
4240 * Function getRequestData().
4241 *
4242 * @return {RequestData} request data
4243 */
4244 }, {
4245 key: "getRequestData",
4246 value: function getRequestData() {
4247 return {
4248 type: this.type,
4249 args: this.args,
4250 timestamp: new Date().getTime(),
4251 component: this.component,
4252 command: this.command,
4253 endpoint: $e.data.commandToEndpoint(this.command, JSON.parse(JSON.stringify(this.args)), this.constructor.getEndpointFormat())
4254 };
4255 }
4256 }, {
4257 key: "apply",
4258 value: function apply() {
4259 var _this2 = this;
4260 var applyMethods = this.getApplyMethods();
4261
4262 // Run 'before' method.
4263 this.args = applyMethods.before(this.args);
4264 var requestData = this.getRequestData();
4265 return $e.data.fetch(requestData).then(function (data) {
4266 _this2.data = data;
4267
4268 // Run 'after' method.
4269 _this2.data = applyMethods.after(data, _this2.args);
4270 _this2.data = {
4271 data: _this2.data
4272 };
4273
4274 // Append requestData.
4275 _this2.data = Object.assign({
4276 __requestData__: requestData
4277 }, _this2.data);
4278 return _this2.data;
4279 });
4280 }
4281
4282 /**
4283 * @param {*} [args={}]
4284 * @return {{}} filtered args
4285 */
4286 }, {
4287 key: "applyBeforeCreate",
4288 value: function applyBeforeCreate() {
4289 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4290 return args;
4291 }
4292
4293 /**
4294 * @param {{}} data
4295 * @param {*} [args={}]
4296 * @return {{}} filtered result
4297 */
4298 }, {
4299 key: "applyAfterCreate",
4300 value: function applyAfterCreate(data) {
4301 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4302 // eslint-disable-line no-unused-vars
4303 return data;
4304 }
4305
4306 /**
4307 * @param {*} [args={}]
4308 * @return {{}} filtered args
4309 */
4310 }, {
4311 key: "applyBeforeDelete",
4312 value: function applyBeforeDelete() {
4313 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4314 return args;
4315 }
4316
4317 /**
4318 * @param {{}} data
4319 * @param {*} [args={}]
4320 * @return {{}} filtered result
4321 */
4322 }, {
4323 key: "applyAfterDelete",
4324 value: function applyAfterDelete(data) {
4325 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4326 // eslint-disable-line no-unused-vars
4327 return data;
4328 }
4329
4330 /**
4331 * @param {*} [args={}]
4332 * @return {{}} filtered args
4333 */
4334 }, {
4335 key: "applyBeforeGet",
4336 value: function applyBeforeGet() {
4337 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4338 return args;
4339 }
4340
4341 /**
4342 * @param {{}} data
4343 * @param {*} [args={}]
4344 * @return {{}} filtered result
4345 */
4346 }, {
4347 key: "applyAfterGet",
4348 value: function applyAfterGet(data) {
4349 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4350 // eslint-disable-line no-unused-vars
4351 return data;
4352 }
4353
4354 /**
4355 * @param {*} [args={}]
4356 * @return {{}} filtered args
4357 */
4358 }, {
4359 key: "applyBeforeUpdate",
4360 value: function applyBeforeUpdate() {
4361 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4362 return args;
4363 }
4364
4365 /**
4366 * @param {{}} data
4367 * @param {*} [args={}]
4368 * @return {{}} filtered result
4369 */
4370 }, {
4371 key: "applyAfterUpdate",
4372 value: function applyAfterUpdate(data) {
4373 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4374 // eslint-disable-line no-unused-vars
4375 return data;
4376 }
4377
4378 /**
4379 * @param {*} [args={}]
4380 * @return {{}} filtered args
4381 */
4382 }, {
4383 key: "applyBeforeOptions",
4384 value: function applyBeforeOptions() {
4385 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4386 return args;
4387 }
4388
4389 /**
4390 * @param {{}} data
4391 * @param {*} [args={}]
4392 * @return {{}} filtered result
4393 */
4394 }, {
4395 key: "applyAfterOptions",
4396 value: function applyAfterOptions(data) {
4397 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4398 // eslint-disable-line no-unused-vars
4399 return data;
4400 }
4401
4402 /**
4403 * @param {BaseError} e
4404 */
4405 }, {
4406 key: "applyAfterCatch",
4407 value: function applyAfterCatch(e) {
4408 e.notify();
4409 }
4410 }, {
4411 key: "onCatchApply",
4412 value: function onCatchApply(e) {
4413 var _e;
4414 // TODO: If the errors that returns from the server is consistent remove the '?' from 'e'
4415 var httpErrorCode = ((_e = e) === null || _e === void 0 || (_e = _e.data) === null || _e === void 0 ? void 0 : _e.status) || 501;
4416 var dataError = Object.values(errors).find(function (error) {
4417 return error.getHTTPErrorCode() === httpErrorCode;
4418 });
4419 if (!dataError) {
4420 dataError = errors.DefaultError;
4421 }
4422 e = dataError.create(e.message, e.code, e.data || []);
4423 this.runCatchHooks(e);
4424 this.applyAfterCatch(e);
4425 }
4426 }], [{
4427 key: "getInstanceType",
4428 value: function getInstanceType() {
4429 return 'CommandData';
4430 }
4431 }, {
4432 key: "getEndpointFormat",
4433 value: function getEndpointFormat() {
4434 return null;
4435 }
4436 }]);
4437 }(_commandBase.default);
4438
4439 /***/ }),
4440
4441 /***/ "../modules/web-cli/assets/js/modules/command-infra.js":
4442 /*!*************************************************************!*\
4443 !*** ../modules/web-cli/assets/js/modules/command-infra.js ***!
4444 \*************************************************************/
4445 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4446
4447 "use strict";
4448
4449
4450 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4451 Object.defineProperty(exports, "__esModule", ({
4452 value: true
4453 }));
4454 exports["default"] = void 0;
4455 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4456 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4457 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4458 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4459 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4460 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4461 var _argsObject = _interopRequireDefault(__webpack_require__(/*! elementor-assets-js/modules/imports/args-object */ "../assets/dev/js/modules/imports/args-object.js"));
4462 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
4463 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)); }
4464 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4465 /**
4466 * @typedef {import('../modules/component-base')} ComponentBase
4467 */
4468 var CommandInfra = exports["default"] = /*#__PURE__*/function (_ArgsObject) {
4469 /**
4470 * Function constructor().
4471 *
4472 * Create Commands Base.
4473 *
4474 * @param {{}} args
4475 */
4476 function CommandInfra() {
4477 var _this;
4478 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4479 (0, _classCallCheck2.default)(this, CommandInfra);
4480 _this = _callSuper(this, CommandInfra, [args]);
4481 if (!_this.constructor.registerConfig) {
4482 throw RangeError('Doing it wrong: Each command type should have `registerConfig`.');
4483 }
4484
4485 // Acknowledge self about which command it run.
4486 _this.command = _this.constructor.getCommand();
4487
4488 // Assign instance of current component.
4489 _this.component = _this.constructor.getComponent();
4490
4491 // Who ever need do something before without `super` the constructor can use `initialize` method.
4492 _this.initialize(args);
4493
4494 // Refresh args, maybe the changed via `initialize`.
4495 args = _this.args;
4496
4497 // Validate args before run.
4498 _this.validateArgs(args);
4499 return _this;
4500 }
4501
4502 /**
4503 * Function initialize().
4504 *
4505 * Initialize command, called after construction.
4506 *
4507 * @param {{}} args
4508 */
4509 (0, _inherits2.default)(CommandInfra, _ArgsObject);
4510 return (0, _createClass2.default)(CommandInfra, [{
4511 key: "currentCommand",
4512 get:
4513 /**
4514 * @deprecated since 3.7.0, use `this.command` instead.
4515 */
4516 function get() {
4517 _deprecation.default.deprecated('this.currentCommand', '3.7.0', 'this.command');
4518 return this.command;
4519 }
4520 }, {
4521 key: "initialize",
4522 value: function initialize() {
4523 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4524 } // eslint-disable-line no-unused-vars
4525
4526 /**
4527 * Function validateArgs().
4528 *
4529 * Validate command arguments.
4530 *
4531 * @param {{}} args
4532 */
4533 }, {
4534 key: "validateArgs",
4535 value: function validateArgs() {
4536 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4537 } // eslint-disable-line no-unused-vars
4538
4539 // eslint-disable-next-line jsdoc/require-returns-check
4540 /**
4541 * Function apply().
4542 *
4543 * Do the actual command.
4544 *
4545 * @param {{}} args
4546 *
4547 * @return {*} Command results.
4548 */
4549 }, {
4550 key: "apply",
4551 value: function apply() {
4552 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4553 // eslint-disable-line no-unused-vars
4554 elementorModules.ForceMethodImplementation();
4555 }
4556
4557 /**
4558 * Function run().
4559 *
4560 * Run command with history & hooks.
4561 *
4562 * @return {*} Command results.
4563 */
4564 }, {
4565 key: "run",
4566 value: function run() {
4567 return this.apply(this.args);
4568 }
4569
4570 /**
4571 * Function onBeforeRun.
4572 *
4573 * Called before run().
4574 *
4575 * @param {{}} args
4576 */
4577 }, {
4578 key: "onBeforeRun",
4579 value: function onBeforeRun() {
4580 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4581 } // eslint-disable-line no-unused-vars
4582
4583 /**
4584 * Function onAfterRun.
4585 *
4586 * Called after run().
4587 *
4588 * @param {{}} args
4589 * @param {*} result
4590 */
4591 }, {
4592 key: "onAfterRun",
4593 value: function onAfterRun() {
4594 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4595 var result = arguments.length > 1 ? arguments[1] : undefined;
4596 } // eslint-disable-line no-unused-vars
4597
4598 /**
4599 * Function onBeforeApply.
4600 *
4601 * Called before apply().
4602 *
4603 * @param {{}} args
4604 */
4605 }, {
4606 key: "onBeforeApply",
4607 value: function onBeforeApply() {
4608 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4609 } // eslint-disable-line no-unused-vars
4610
4611 /**
4612 * Function onAfterApply.
4613 *
4614 * Called after apply().
4615 *
4616 * @param {{}} args
4617 * @param {*} result
4618 */
4619 }, {
4620 key: "onAfterApply",
4621 value: function onAfterApply() {
4622 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4623 var result = arguments.length > 1 ? arguments[1] : undefined;
4624 } // eslint-disable-line no-unused-vars
4625
4626 /**
4627 * Function onCatchApply.
4628 *
4629 * Called after apply() failed.
4630 *
4631 * @param {Error} e
4632 */
4633 }, {
4634 key: "onCatchApply",
4635 value: function onCatchApply(e) {} // eslint-disable-line no-unused-vars
4636 }], [{
4637 key: "getInstanceType",
4638 value: function getInstanceType() {
4639 return 'CommandInfra';
4640 }
4641
4642 /**
4643 * Get info of command.
4644 *
4645 * @return {Object} Extra information about the command.
4646 */
4647 }, {
4648 key: "getInfo",
4649 value: function getInfo() {
4650 return {};
4651 }
4652
4653 /**
4654 * @return {string} Self command name.
4655 */
4656 }, {
4657 key: "getCommand",
4658 value: function getCommand() {
4659 return this.registerConfig.command;
4660 }
4661
4662 /**
4663 * @return {ComponentBase} Self component
4664 */
4665 }, {
4666 key: "getComponent",
4667 value: function getComponent() {
4668 return this.registerConfig.component;
4669 }
4670 }, {
4671 key: "setRegisterConfig",
4672 value: function setRegisterConfig(config) {
4673 this.registerConfig = Object.freeze(config);
4674 }
4675 }]);
4676 }(_argsObject.default);
4677 /**
4678 * @type {Object}
4679 */
4680 (0, _defineProperty2.default)(CommandInfra, "registerConfig", null);
4681
4682 /***/ }),
4683
4684 /***/ "../modules/web-cli/assets/js/modules/commands/close.js":
4685 /*!**************************************************************!*\
4686 !*** ../modules/web-cli/assets/js/modules/commands/close.js ***!
4687 \**************************************************************/
4688 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4689
4690 "use strict";
4691
4692
4693 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4694 Object.defineProperty(exports, "__esModule", ({
4695 value: true
4696 }));
4697 exports["default"] = exports.Close = void 0;
4698 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4699 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4700 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4701 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4702 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4703 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4704 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)); }
4705 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4706 var Close = exports.Close = /*#__PURE__*/function (_CommandBase) {
4707 function Close() {
4708 (0, _classCallCheck2.default)(this, Close);
4709 return _callSuper(this, Close, arguments);
4710 }
4711 (0, _inherits2.default)(Close, _CommandBase);
4712 return (0, _createClass2.default)(Close, [{
4713 key: "apply",
4714 value: function apply() {
4715 this.component.close();
4716 }
4717 }]);
4718 }(_commandBase.default);
4719 var _default = exports["default"] = Close;
4720
4721 /***/ }),
4722
4723 /***/ "../modules/web-cli/assets/js/modules/commands/index.js":
4724 /*!**************************************************************!*\
4725 !*** ../modules/web-cli/assets/js/modules/commands/index.js ***!
4726 \**************************************************************/
4727 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4728
4729 "use strict";
4730
4731
4732 Object.defineProperty(exports, "__esModule", ({
4733 value: true
4734 }));
4735 Object.defineProperty(exports, "Close", ({
4736 enumerable: true,
4737 get: function get() {
4738 return _close.Close;
4739 }
4740 }));
4741 Object.defineProperty(exports, "Open", ({
4742 enumerable: true,
4743 get: function get() {
4744 return _open.Open;
4745 }
4746 }));
4747 Object.defineProperty(exports, "Toggle", ({
4748 enumerable: true,
4749 get: function get() {
4750 return _toggle.Toggle;
4751 }
4752 }));
4753 var _close = __webpack_require__(/*! ./close */ "../modules/web-cli/assets/js/modules/commands/close.js");
4754 var _open = __webpack_require__(/*! ./open */ "../modules/web-cli/assets/js/modules/commands/open.js");
4755 var _toggle = __webpack_require__(/*! ./toggle */ "../modules/web-cli/assets/js/modules/commands/toggle.js");
4756
4757 /***/ }),
4758
4759 /***/ "../modules/web-cli/assets/js/modules/commands/open.js":
4760 /*!*************************************************************!*\
4761 !*** ../modules/web-cli/assets/js/modules/commands/open.js ***!
4762 \*************************************************************/
4763 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4764
4765 "use strict";
4766
4767
4768 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4769 Object.defineProperty(exports, "__esModule", ({
4770 value: true
4771 }));
4772 exports["default"] = exports.Open = void 0;
4773 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4774 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4775 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4776 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4777 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4778 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4779 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)); }
4780 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4781 var Open = exports.Open = /*#__PURE__*/function (_CommandBase) {
4782 function Open() {
4783 (0, _classCallCheck2.default)(this, Open);
4784 return _callSuper(this, Open, arguments);
4785 }
4786 (0, _inherits2.default)(Open, _CommandBase);
4787 return (0, _createClass2.default)(Open, [{
4788 key: "apply",
4789 value: function apply() {
4790 $e.route(this.component.getNamespace());
4791 }
4792 }]);
4793 }(_commandBase.default);
4794 var _default = exports["default"] = Open;
4795
4796 /***/ }),
4797
4798 /***/ "../modules/web-cli/assets/js/modules/commands/toggle.js":
4799 /*!***************************************************************!*\
4800 !*** ../modules/web-cli/assets/js/modules/commands/toggle.js ***!
4801 \***************************************************************/
4802 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4803
4804 "use strict";
4805
4806
4807 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4808 Object.defineProperty(exports, "__esModule", ({
4809 value: true
4810 }));
4811 exports["default"] = exports.Toggle = void 0;
4812 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4813 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4814 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4815 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4816 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4817 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4818 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)); }
4819 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4820 var Toggle = exports.Toggle = /*#__PURE__*/function (_CommandBase) {
4821 function Toggle() {
4822 (0, _classCallCheck2.default)(this, Toggle);
4823 return _callSuper(this, Toggle, arguments);
4824 }
4825 (0, _inherits2.default)(Toggle, _CommandBase);
4826 return (0, _createClass2.default)(Toggle, [{
4827 key: "apply",
4828 value: function apply() {
4829 if (this.component.isOpen) {
4830 this.component.close();
4831 } else {
4832 $e.route(this.component.getNamespace());
4833 }
4834 }
4835 }]);
4836 }(_commandBase.default);
4837 var _default = exports["default"] = Toggle;
4838
4839 /***/ }),
4840
4841 /***/ "../modules/web-cli/assets/js/modules/component-base.js":
4842 /*!**************************************************************!*\
4843 !*** ../modules/web-cli/assets/js/modules/component-base.js ***!
4844 \**************************************************************/
4845 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4846
4847 "use strict";
4848
4849
4850 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4851 Object.defineProperty(exports, "__esModule", ({
4852 value: true
4853 }));
4854 exports["default"] = void 0;
4855 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4856 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
4857 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4858 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4859 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4860 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4861 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4862 var _commandCallbackBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-callback-base */ "../modules/web-cli/assets/js/modules/command-callback-base.js"));
4863 var _toolkit = __webpack_require__(/*! @reduxjs/toolkit */ "@reduxjs/toolkit");
4864 var _module = _interopRequireDefault(__webpack_require__(/*! elementor/assets/dev/js/modules/imports/module.js */ "../assets/dev/js/modules/imports/module.js"));
4865 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
4866 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
4867 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; }
4868 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; }
4869 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)); }
4870 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4871 /**
4872 * @typedef {import('./command-infra')} CommandInfra
4873 * @typedef {import('./hook-base')} HookBase
4874 * @typedef {import('../core/states/ui-state-base')} UiStateBase
4875 */
4876 var ComponentBase = exports["default"] = /*#__PURE__*/function (_Module) {
4877 function ComponentBase() {
4878 (0, _classCallCheck2.default)(this, ComponentBase);
4879 return _callSuper(this, ComponentBase, arguments);
4880 }
4881 (0, _inherits2.default)(ComponentBase, _Module);
4882 return (0, _createClass2.default)(ComponentBase, [{
4883 key: "__construct",
4884 value: function __construct() {
4885 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4886 if (args.manager) {
4887 this.manager = args.manager;
4888 }
4889 this.commands = this.defaultCommands();
4890 this.commandsInternal = this.defaultCommandsInternal();
4891 this.hooks = this.defaultHooks();
4892 this.routes = this.defaultRoutes();
4893 this.tabs = this.defaultTabs();
4894 this.shortcuts = this.defaultShortcuts();
4895 this.utils = this.defaultUtils();
4896 this.data = this.defaultData();
4897 this.uiStates = this.defaultUiStates();
4898 this.states = this.defaultStates();
4899 this.defaultRoute = '';
4900 this.currentTab = '';
4901 }
4902 }, {
4903 key: "registerAPI",
4904 value: function registerAPI() {
4905 var _this = this;
4906 Object.entries(this.getTabs()).forEach(function (tab) {
4907 return _this.registerTabRoute(tab[0]);
4908 });
4909 Object.entries(this.getRoutes()).forEach(function (_ref) {
4910 var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
4911 route = _ref2[0],
4912 callback = _ref2[1];
4913 return _this.registerRoute(route, callback);
4914 });
4915 Object.entries(this.getCommands()).forEach(function (_ref3) {
4916 var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
4917 command = _ref4[0],
4918 callback = _ref4[1];
4919 return _this.registerCommand(command, callback);
4920 });
4921 Object.entries(this.getCommandsInternal()).forEach(function (_ref5) {
4922 var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
4923 command = _ref6[0],
4924 callback = _ref6[1];
4925 return _this.registerCommandInternal(command, callback);
4926 });
4927 Object.values(this.getHooks()).forEach(function (instance) {
4928 return _this.registerHook(instance);
4929 });
4930 Object.entries(this.getData()).forEach(function (_ref7) {
4931 var _ref8 = (0, _slicedToArray2.default)(_ref7, 2),
4932 command = _ref8[0],
4933 callback = _ref8[1];
4934 return _this.registerData(command, callback);
4935 });
4936 Object.values(this.getUiStates()).forEach(function (instance) {
4937 return _this.registerUiState(instance);
4938 });
4939 Object.entries(this.getStates()).forEach(function (_ref9) {
4940 var _ref0 = (0, _slicedToArray2.default)(_ref9, 2),
4941 id = _ref0[0],
4942 state = _ref0[1];
4943 return _this.registerState(id, state);
4944 });
4945 }
4946
4947 // eslint-disable-next-line jsdoc/require-returns-check
4948 /**
4949 * @return {string} namespace
4950 */
4951 }, {
4952 key: "getNamespace",
4953 value: function getNamespace() {
4954 (0, _forceMethodImplementation.default)();
4955 }
4956
4957 /**
4958 * @deprecated since 3.7.0, use `getServiceName()` instead.
4959 */
4960 }, {
4961 key: "getRootContainer",
4962 value: function getRootContainer() {
4963 _deprecation.default.deprecated('getRootContainer()', '3.7.0', 'getServiceName()');
4964 return this.getServiceName();
4965 }
4966 }, {
4967 key: "getServiceName",
4968 value: function getServiceName() {
4969 return this.getNamespace().split('/')[0];
4970 }
4971 }, {
4972 key: "store",
4973 get: function get() {
4974 return $e.store.get(this.getNamespace());
4975 }
4976 }, {
4977 key: "defaultTabs",
4978 value: function defaultTabs() {
4979 return {};
4980 }
4981 }, {
4982 key: "defaultRoutes",
4983 value: function defaultRoutes() {
4984 return {};
4985 }
4986 }, {
4987 key: "defaultCommands",
4988 value: function defaultCommands() {
4989 return {};
4990 }
4991 }, {
4992 key: "defaultCommandsInternal",
4993 value: function defaultCommandsInternal() {
4994 return {};
4995 }
4996 }, {
4997 key: "defaultHooks",
4998 value: function defaultHooks() {
4999 return {};
5000 }
5001
5002 /**
5003 * Get the component's default UI states.
5004 *
5005 * @return {Object} default UI states
5006 */
5007 }, {
5008 key: "defaultUiStates",
5009 value: function defaultUiStates() {
5010 return {};
5011 }
5012
5013 /**
5014 * Get the component's Redux slice settings.
5015 *
5016 * @return {Object} Redux slice settings
5017 */
5018 }, {
5019 key: "defaultStates",
5020 value: function defaultStates() {
5021 return {};
5022 }
5023 }, {
5024 key: "defaultShortcuts",
5025 value: function defaultShortcuts() {
5026 return {};
5027 }
5028 }, {
5029 key: "defaultUtils",
5030 value: function defaultUtils() {
5031 return {};
5032 }
5033 }, {
5034 key: "defaultData",
5035 value: function defaultData() {
5036 return {};
5037 }
5038 }, {
5039 key: "getCommands",
5040 value: function getCommands() {
5041 return this.commands;
5042 }
5043 }, {
5044 key: "getCommandsInternal",
5045 value: function getCommandsInternal() {
5046 return this.commandsInternal;
5047 }
5048 }, {
5049 key: "getHooks",
5050 value: function getHooks() {
5051 return this.hooks;
5052 }
5053
5054 /**
5055 * Retrieve the component's UI states.
5056 *
5057 * @return {Object} UI states
5058 */
5059 }, {
5060 key: "getUiStates",
5061 value: function getUiStates() {
5062 return this.uiStates;
5063 }
5064
5065 /**
5066 * Retrieve the component's Redux Slice.
5067 *
5068 * @return {Object} Redux Slice
5069 */
5070 }, {
5071 key: "getStates",
5072 value: function getStates() {
5073 return this.states;
5074 }
5075 }, {
5076 key: "getRoutes",
5077 value: function getRoutes() {
5078 return this.routes;
5079 }
5080 }, {
5081 key: "getTabs",
5082 value: function getTabs() {
5083 return this.tabs;
5084 }
5085 }, {
5086 key: "getShortcuts",
5087 value: function getShortcuts() {
5088 return this.shortcuts;
5089 }
5090 }, {
5091 key: "getData",
5092 value: function getData() {
5093 return this.data;
5094 }
5095
5096 /**
5097 * @param {string} command
5098 * @param {(()=>{}|CommandInfra)} context
5099 * @param {'default'|'internal'|'data'} commandsType
5100 */
5101 }, {
5102 key: "registerCommand",
5103 value: function registerCommand(command, context) {
5104 var commandsType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'default';
5105 var commandsManager;
5106 switch (commandsType) {
5107 case 'default':
5108 commandsManager = $e.commands;
5109 break;
5110 case 'internal':
5111 commandsManager = $e.commandsInternal;
5112 break;
5113 case 'data':
5114 commandsManager = $e.data;
5115 break;
5116 default:
5117 throw new Error("Invalid commands type: '".concat(command, "'"));
5118 }
5119 var fullCommand = this.getNamespace() + '/' + command,
5120 instanceType = context.getInstanceType ? context.getInstanceType() : false,
5121 registerConfig = {
5122 command: fullCommand,
5123 component: this
5124 };
5125
5126 // Support pure callback.
5127 if (!instanceType) {
5128 if ($e.devTools) {
5129 $e.devTools.log.warn("Attach command-callback-base, on command: '".concat(fullCommand, "', context is unknown type."));
5130 }
5131 registerConfig.callback = context;
5132
5133 // Unique class.
5134 context = /*#__PURE__*/function (_CommandCallbackBase) {
5135 function context() {
5136 (0, _classCallCheck2.default)(this, context);
5137 return _callSuper(this, context, arguments);
5138 }
5139 (0, _inherits2.default)(context, _CommandCallbackBase);
5140 return (0, _createClass2.default)(context);
5141 }(_commandCallbackBase.default);
5142 }
5143 context.setRegisterConfig(registerConfig);
5144 commandsManager.register(this, command, context);
5145 }
5146
5147 /**
5148 * @param {HookBase} instance
5149 */
5150 }, {
5151 key: "registerHook",
5152 value: function registerHook(instance) {
5153 return instance.register();
5154 }
5155 }, {
5156 key: "registerCommandInternal",
5157 value: function registerCommandInternal(command, context) {
5158 this.registerCommand(command, context, 'internal');
5159 }
5160
5161 /**
5162 * Register a UI state.
5163 *
5164 * @param {UiStateBase} instance - UI state instance.
5165 *
5166 * @return {void}
5167 */
5168 }, {
5169 key: "registerUiState",
5170 value: function registerUiState(instance) {
5171 $e.uiStates.register(instance);
5172 }
5173
5174 /**
5175 * Register a Redux Slice.
5176 *
5177 * @param {string} id - State id.
5178 * @param {Object} stateConfig - The state config.
5179 *
5180 * @return {void}
5181 */
5182 }, {
5183 key: "registerState",
5184 value: function registerState(id, stateConfig) {
5185 id = this.getNamespace() + (id ? "/".concat(id) : '');
5186 var slice = (0, _toolkit.createSlice)(_objectSpread(_objectSpread({}, stateConfig), {}, {
5187 name: id
5188 }));
5189 $e.store.register(id, slice);
5190 }
5191 }, {
5192 key: "registerRoute",
5193 value: function registerRoute(route, callback) {
5194 $e.routes.register(this, route, callback);
5195 }
5196 }, {
5197 key: "registerData",
5198 value: function registerData(command, context) {
5199 this.registerCommand(command, context, 'data');
5200 }
5201 }, {
5202 key: "unregisterRoute",
5203 value: function unregisterRoute(route) {
5204 $e.routes.unregister(this, route);
5205 }
5206 }, {
5207 key: "registerTabRoute",
5208 value: function registerTabRoute(tab) {
5209 var _this2 = this;
5210 this.registerRoute(tab, function (args) {
5211 return _this2.activateTab(tab, args);
5212 });
5213 }
5214 }, {
5215 key: "dependency",
5216 value: function dependency() {
5217 return true;
5218 }
5219 }, {
5220 key: "open",
5221 value: function open() {
5222 return true;
5223 }
5224 }, {
5225 key: "close",
5226 value: function close() {
5227 if (!this.isOpen) {
5228 return false;
5229 }
5230 this.isOpen = false;
5231 this.inactivate();
5232 $e.routes.clearCurrent(this.getNamespace());
5233 $e.routes.clearHistory(this.getServiceName());
5234 return true;
5235 }
5236 }, {
5237 key: "activate",
5238 value: function activate() {
5239 $e.components.activate(this.getNamespace());
5240 }
5241 }, {
5242 key: "inactivate",
5243 value: function inactivate() {
5244 $e.components.inactivate(this.getNamespace());
5245 }
5246 }, {
5247 key: "isActive",
5248 value: function isActive() {
5249 return $e.components.isActive(this.getNamespace());
5250 }
5251 }, {
5252 key: "onRoute",
5253 value: function onRoute(route) {
5254 this.toggleRouteClass(route, true);
5255 this.toggleHistoryClass();
5256 this.activate();
5257 this.trigger('route/open', route);
5258 }
5259 }, {
5260 key: "onCloseRoute",
5261 value: function onCloseRoute(route) {
5262 this.toggleRouteClass(route, false);
5263 this.inactivate();
5264 this.trigger('route/close', route);
5265 }
5266 }, {
5267 key: "setDefaultRoute",
5268 value: function setDefaultRoute(route) {
5269 this.defaultRoute = this.getNamespace() + '/' + route;
5270 }
5271 }, {
5272 key: "getDefaultRoute",
5273 value: function getDefaultRoute() {
5274 return this.defaultRoute;
5275 }
5276 }, {
5277 key: "removeTab",
5278 value: function removeTab(tab) {
5279 delete this.tabs[tab];
5280 this.unregisterRoute(tab);
5281 }
5282 }, {
5283 key: "hasTab",
5284 value: function hasTab(tab) {
5285 return !!this.tabs[tab];
5286 }
5287 }, {
5288 key: "addTab",
5289 value: function addTab(tab, args, position) {
5290 var _this3 = this;
5291 this.tabs[tab] = args;
5292 // It can be 0.
5293 if ('undefined' !== typeof position) {
5294 var newTabs = {};
5295 var ids = Object.keys(this.tabs);
5296 // Remove new tab
5297 ids.pop();
5298
5299 // Add it to position.
5300 ids.splice(position, 0, tab);
5301 ids.forEach(function (id) {
5302 newTabs[id] = _this3.tabs[id];
5303 });
5304 this.tabs = newTabs;
5305 }
5306 this.registerTabRoute(tab);
5307 }
5308 }, {
5309 key: "getTabsWrapperSelector",
5310 value: function getTabsWrapperSelector() {
5311 return '';
5312 }
5313 }, {
5314 key: "getTabRoute",
5315 value: function getTabRoute(tab) {
5316 return this.getNamespace() + '/' + tab;
5317 }
5318 }, {
5319 key: "renderTab",
5320 value: function renderTab(tab) {} // eslint-disable-line
5321 }, {
5322 key: "activateTab",
5323 value: function activateTab(tab, args) {
5324 var _this4 = this;
5325 this.renderTab(tab, args);
5326 jQuery(this.getTabsWrapperSelector() + ' .elementor-component-tab').off('click').on('click', function (event) {
5327 $e.route(_this4.getTabRoute(event.currentTarget.dataset.tab), args);
5328 }).removeClass('elementor-active').filter('[data-tab="' + tab + '"]').addClass('elementor-active');
5329 }
5330 }, {
5331 key: "getActiveTabConfig",
5332 value: function getActiveTabConfig() {
5333 return this.tabs[this.currentTab] || {};
5334 }
5335 }, {
5336 key: "getBodyClass",
5337 value: function getBodyClass(route) {
5338 return 'e-route-' + route.replace(/\//g, '-');
5339 }
5340
5341 /**
5342 * If command includes uppercase character convert it to lowercase and add `-`.
5343 * e.g: `CopyAll` is converted to `copy-all`.
5344 *
5345 * @param {string} commandName
5346 */
5347 }, {
5348 key: "normalizeCommandName",
5349 value: function normalizeCommandName(commandName) {
5350 return commandName.replace(/[A-Z]/g, function (match, offset) {
5351 return (offset > 0 ? '-' : '') + match.toLowerCase();
5352 });
5353 }
5354
5355 /**
5356 * @param {{}} commandsFromImport
5357 * @return {{}} imported commands
5358 */
5359 }, {
5360 key: "importCommands",
5361 value: function importCommands(commandsFromImport) {
5362 var _this5 = this;
5363 var commands = {};
5364
5365 // Convert `Commands` to `ComponentBase` workable format.
5366 Object.entries(commandsFromImport).forEach(function (_ref1) {
5367 var _ref10 = (0, _slicedToArray2.default)(_ref1, 2),
5368 className = _ref10[0],
5369 Class = _ref10[1];
5370 var command = _this5.normalizeCommandName(className);
5371 commands[command] = Class;
5372 });
5373 return commands;
5374 }
5375 }, {
5376 key: "importHooks",
5377 value: function importHooks(hooksFromImport) {
5378 var hooks = {};
5379 for (var key in hooksFromImport) {
5380 var hook = new hooksFromImport[key]();
5381 hooks[hook.getId()] = hook;
5382 }
5383 return hooks;
5384 }
5385
5386 /**
5387 * Import & initialize the component's UI states.
5388 * Should be used inside `defaultUiState()`.
5389 *
5390 * @param {Object} statesFromImport - UI states from import.
5391 *
5392 * @return {Object} UI States
5393 */
5394 }, {
5395 key: "importUiStates",
5396 value: function importUiStates(statesFromImport) {
5397 var _this6 = this;
5398 var uiStates = {};
5399 Object.values(statesFromImport).forEach(function (className) {
5400 var uiState = new className(_this6);
5401 uiStates[uiState.getId()] = uiState;
5402 });
5403 return uiStates;
5404 }
5405
5406 /**
5407 * Set a UI state value.
5408 * TODO: Should we provide such function? Maybe the developer should implicitly pass the full state ID?
5409 *
5410 * @param {string} state - Non-prefixed state ID.
5411 * @param {*} value - New state value.
5412 *
5413 * @return {void}
5414 */
5415 }, {
5416 key: "setUiState",
5417 value: function setUiState(state, value) {
5418 $e.uiStates.set("".concat(this.getNamespace(), "/").concat(state), value);
5419 }
5420 }, {
5421 key: "toggleRouteClass",
5422 value: function toggleRouteClass(route, state) {
5423 document.body.classList.toggle(this.getBodyClass(route), state);
5424 }
5425 }, {
5426 key: "toggleHistoryClass",
5427 value: function toggleHistoryClass() {
5428 document.body.classList.toggle('e-routes-has-history', !!$e.routes.getHistory(this.getServiceName()).length);
5429 }
5430 }]);
5431 }(_module.default);
5432
5433 /***/ }),
5434
5435 /***/ "../modules/web-cli/assets/js/modules/component-modal-base.js":
5436 /*!********************************************************************!*\
5437 !*** ../modules/web-cli/assets/js/modules/component-modal-base.js ***!
5438 \********************************************************************/
5439 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5440
5441 "use strict";
5442
5443
5444 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5445 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
5446 Object.defineProperty(exports, "__esModule", ({
5447 value: true
5448 }));
5449 exports["default"] = void 0;
5450 var _readOnlyError2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/readOnlyError */ "../node_modules/@babel/runtime/helpers/readOnlyError.js"));
5451 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5452 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5453 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
5454 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
5455 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
5456 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
5457 var _componentBase = _interopRequireDefault(__webpack_require__(/*! ./component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
5458 var commands = _interopRequireWildcard(__webpack_require__(/*! ./commands/ */ "../modules/web-cli/assets/js/modules/commands/index.js"));
5459 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
5460 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); }
5461 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)); }
5462 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
5463 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; }
5464 var ComponentModalBase = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
5465 function ComponentModalBase() {
5466 (0, _classCallCheck2.default)(this, ComponentModalBase);
5467 return _callSuper(this, ComponentModalBase, arguments);
5468 }
5469 (0, _inherits2.default)(ComponentModalBase, _ComponentBase);
5470 return (0, _createClass2.default)(ComponentModalBase, [{
5471 key: "registerAPI",
5472 value: function registerAPI() {
5473 var _this = this;
5474 _superPropGet(ComponentModalBase, "registerAPI", this, 3)([]);
5475 $e.shortcuts.register('esc', {
5476 scopes: [this.getNamespace()],
5477 callback: function callback() {
5478 return _this.close();
5479 }
5480 });
5481 }
5482 }, {
5483 key: "defaultCommands",
5484 value: function defaultCommands() {
5485 return this.importCommands(commands);
5486 }
5487 }, {
5488 key: "defaultRoutes",
5489 value: function defaultRoutes() {
5490 return {
5491 '': function _() {/* Nothing to do, it's already rendered. */}
5492 };
5493 }
5494 }, {
5495 key: "open",
5496 value: function open() {
5497 var _this2 = this;
5498 if (!this.layout) {
5499 var layout = this.getModalLayout();
5500 this.layout = new layout({
5501 component: this
5502 });
5503 this.layout.getModal().on('hide', function () {
5504 return _this2.close();
5505 });
5506 }
5507 this.layout.showModal();
5508 return true;
5509 }
5510 }, {
5511 key: "close",
5512 value: function close() {
5513 if (!_superPropGet(ComponentModalBase, "close", this, 3)([])) {
5514 return false;
5515 }
5516 var close = elementor.hooks.applyFilters('component/modal/close', this.layout.getModal().hide.bind(this.layout.getModal()), this);
5517 close();
5518 return true;
5519 }
5520 }, {
5521 key: "getModalLayout",
5522 value: function getModalLayout() {
5523 (0, _forceMethodImplementation.default)();
5524 }
5525 }]);
5526 }(_componentBase.default);
5527
5528 /***/ }),
5529
5530 /***/ "../modules/web-cli/assets/js/utils/console.js":
5531 /*!*****************************************************!*\
5532 !*** ../modules/web-cli/assets/js/utils/console.js ***!
5533 \*****************************************************/
5534 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5535
5536 "use strict";
5537
5538
5539 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5540 Object.defineProperty(exports, "__esModule", ({
5541 value: true
5542 }));
5543 exports["default"] = void 0;
5544 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5545 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5546 var Console = exports["default"] = /*#__PURE__*/function () {
5547 function Console() {
5548 (0, _classCallCheck2.default)(this, Console);
5549 }
5550 return (0, _createClass2.default)(Console, null, [{
5551 key: "error",
5552 value: function error(message) {
5553 // Show an error if devTools is available.
5554 if ($e.devTools) {
5555 $e.devTools.log.error(message);
5556 }
5557
5558 // If not a 'Hook-Break' then show error.
5559 if (!(message instanceof $e.modules.HookBreak)) {
5560 // eslint-disable-next-line no-console
5561 console.error(message);
5562 }
5563 }
5564 }, {
5565 key: "warn",
5566 value: function warn() {
5567 var _console;
5568 var style = "font-size: 12px; background-image: url(\"".concat(elementorWebCliConfig.urls.assets, "images/logo-icon.png\"); background-repeat: no-repeat; background-size: contain;");
5569 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
5570 args[_key] = arguments[_key];
5571 }
5572 args.unshift('%c %c', style, '');
5573 (_console = console).warn.apply(_console, args); // eslint-disable-line no-console
5574 }
5575 }]);
5576 }();
5577
5578 /***/ }),
5579
5580 /***/ "../modules/web-cli/assets/js/utils/deprecation.js":
5581 /*!*********************************************************!*\
5582 !*** ../modules/web-cli/assets/js/utils/deprecation.js ***!
5583 \*********************************************************/
5584 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5585
5586 "use strict";
5587
5588
5589 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5590 Object.defineProperty(exports, "__esModule", ({
5591 value: true
5592 }));
5593 exports["default"] = void 0;
5594 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
5595 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5596 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5597 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
5598 // Copied from `modules/dev-tools/assets/js/deprecation.js`
5599 /**
5600 * @typedef {Object} Version
5601 * @property {number} major1 The first number
5602 * @property {number} major2 The second number
5603 * @property {number} minor The third number
5604 * @property {string} build The fourth number
5605 */
5606
5607 var softDeprecated = function softDeprecated(name, version, replacement) {
5608 if (elementorWebCliConfig.isDebug) {
5609 deprecatedMessage('soft', name, version, replacement);
5610 }
5611 };
5612 var hardDeprecated = function hardDeprecated(name, version, replacement) {
5613 deprecatedMessage('hard', name, version, replacement);
5614 };
5615 var deprecatedMessage = function deprecatedMessage(type, name, version, replacement) {
5616 var message = "`".concat(name, "` is ").concat(type, " deprecated since ").concat(version);
5617 if (replacement) {
5618 message += " - Use `".concat(replacement, "` instead");
5619 }
5620 _console.default.warn(message);
5621 };
5622 var Deprecation = exports["default"] = /*#__PURE__*/function () {
5623 function Deprecation() {
5624 (0, _classCallCheck2.default)(this, Deprecation);
5625 }
5626 return (0, _createClass2.default)(Deprecation, null, [{
5627 key: "deprecated",
5628 value: function deprecated(name, version, replacement) {
5629 if (this.isHardDeprecated(version)) {
5630 hardDeprecated(name, version, replacement);
5631 } else {
5632 softDeprecated(name, version, replacement);
5633 }
5634 }
5635
5636 /**
5637 * @param {string} version
5638 *
5639 * @return {Version}
5640 */
5641 }, {
5642 key: "parseVersion",
5643 value: function parseVersion(version) {
5644 var versionParts = version.split('.');
5645 if (versionParts.length < 3 || versionParts.length > 4) {
5646 throw new RangeError('Invalid Semantic Version string provided');
5647 }
5648 var _versionParts = (0, _slicedToArray2.default)(versionParts, 4),
5649 major1 = _versionParts[0],
5650 major2 = _versionParts[1],
5651 minor = _versionParts[2],
5652 _versionParts$ = _versionParts[3],
5653 build = _versionParts$ === void 0 ? '' : _versionParts$;
5654 return {
5655 major1: parseInt(major1),
5656 major2: parseInt(major2),
5657 minor: parseInt(minor),
5658 build: build
5659 };
5660 }
5661
5662 /**
5663 * Get total of major.
5664 *
5665 * 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,
5666 * versions with major2 more then 9 will be added to total.
5667 *
5668 * @param {Version} versionObj
5669 *
5670 * @return {number}
5671 */
5672 }, {
5673 key: "getTotalMajor",
5674 value: function getTotalMajor(versionObj) {
5675 var total = parseInt("".concat(versionObj.major1).concat(versionObj.major2, "0"));
5676 total = Number((total / 10).toFixed(0));
5677 if (versionObj.major2 > 9) {
5678 total = versionObj.major2 - 9;
5679 }
5680 return total;
5681 }
5682
5683 /**
5684 * @param {string} version1
5685 * @param {string} version2
5686 *
5687 * @return {number}
5688 */
5689 }, {
5690 key: "compareVersion",
5691 value: function compareVersion(version1, version2) {
5692 var _this = this;
5693 return [this.parseVersion(version1), this.parseVersion(version2)].map(function (versionObj) {
5694 return _this.getTotalMajor(versionObj);
5695 }).reduce(function (acc, major) {
5696 return acc - major;
5697 });
5698 }
5699
5700 /**
5701 * @param {string} version
5702 *
5703 * @return {boolean}
5704 */
5705 }, {
5706 key: "isSoftDeprecated",
5707 value: function isSoftDeprecated(version) {
5708 var total = this.compareVersion(version, elementorWebCliConfig.version);
5709 return total <= 4;
5710 }
5711
5712 /**
5713 * @param {string} version
5714 * @return {boolean}
5715 */
5716 }, {
5717 key: "isHardDeprecated",
5718 value: function isHardDeprecated(version) {
5719 var total = this.compareVersion(version, elementorWebCliConfig.version);
5720 return total < 0 || total >= 8;
5721 }
5722 }]);
5723 }();
5724
5725 /***/ }),
5726
5727 /***/ "../modules/web-cli/assets/js/utils/force-method-implementation.js":
5728 /*!*************************************************************************!*\
5729 !*** ../modules/web-cli/assets/js/utils/force-method-implementation.js ***!
5730 \*************************************************************************/
5731 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5732
5733 "use strict";
5734
5735
5736 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5737 Object.defineProperty(exports, "__esModule", ({
5738 value: true
5739 }));
5740 exports["default"] = exports.ForceMethodImplementation = void 0;
5741 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5742 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5743 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
5744 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
5745 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
5746 var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js"));
5747 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)); }
5748 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
5749 // TODO: Copied from `assets/dev/js/modules/imports/force-method-implementation.js`;
5750 var ForceMethodImplementation = exports.ForceMethodImplementation = /*#__PURE__*/function (_Error) {
5751 function ForceMethodImplementation() {
5752 var _this;
5753 var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
5754 (0, _classCallCheck2.default)(this, ForceMethodImplementation);
5755 _this = _callSuper(this, ForceMethodImplementation, ["".concat(info.isStatic ? 'static ' : '').concat(info.fullName, "() should be implemented, please provide '").concat(info.functionName || info.fullName, "' functionality.")]);
5756 Error.captureStackTrace(_this, ForceMethodImplementation);
5757 return _this;
5758 }
5759 (0, _inherits2.default)(ForceMethodImplementation, _Error);
5760 return (0, _createClass2.default)(ForceMethodImplementation);
5761 }(/*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
5762 var _default = exports["default"] = function _default() {
5763 var stack = Error().stack,
5764 caller = stack.split('\n')[2].trim(),
5765 callerName = caller.startsWith('at new') ? 'constructor' : caller.split(' ')[1],
5766 info = {};
5767 info.functionName = callerName;
5768 info.fullName = callerName;
5769 if (info.functionName.includes('.')) {
5770 var parts = info.functionName.split('.');
5771 info.className = parts[0];
5772 info.functionName = parts[1];
5773 } else {
5774 info.isStatic = true;
5775 }
5776 throw new ForceMethodImplementation(info);
5777 };
5778
5779 /***/ }),
5780
5781 /***/ "../node_modules/@babel/runtime/helpers/OverloadYield.js":
5782 /*!***************************************************************!*\
5783 !*** ../node_modules/@babel/runtime/helpers/OverloadYield.js ***!
5784 \***************************************************************/
5785 /***/ ((module) => {
5786
5787 function _OverloadYield(e, d) {
5788 this.v = e, this.k = d;
5789 }
5790 module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
5791
5792 /***/ }),
5793
5794 /***/ "../node_modules/@babel/runtime/helpers/arrayLikeToArray.js":
5795 /*!******************************************************************!*\
5796 !*** ../node_modules/@babel/runtime/helpers/arrayLikeToArray.js ***!
5797 \******************************************************************/
5798 /***/ ((module) => {
5799
5800 function _arrayLikeToArray(r, a) {
5801 (null == a || a > r.length) && (a = r.length);
5802 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
5803 return n;
5804 }
5805 module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
5806
5807 /***/ }),
5808
5809 /***/ "../node_modules/@babel/runtime/helpers/arrayWithHoles.js":
5810 /*!****************************************************************!*\
5811 !*** ../node_modules/@babel/runtime/helpers/arrayWithHoles.js ***!
5812 \****************************************************************/
5813 /***/ ((module) => {
5814
5815 function _arrayWithHoles(r) {
5816 if (Array.isArray(r)) return r;
5817 }
5818 module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
5819
5820 /***/ }),
5821
5822 /***/ "../node_modules/@babel/runtime/helpers/assertThisInitialized.js":
5823 /*!***********************************************************************!*\
5824 !*** ../node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
5825 \***********************************************************************/
5826 /***/ ((module) => {
5827
5828 function _assertThisInitialized(e) {
5829 if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
5830 return e;
5831 }
5832 module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
5833
5834 /***/ }),
5835
5836 /***/ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js":
5837 /*!******************************************************************!*\
5838 !*** ../node_modules/@babel/runtime/helpers/asyncToGenerator.js ***!
5839 \******************************************************************/
5840 /***/ ((module) => {
5841
5842 function asyncGeneratorStep(n, t, e, r, o, a, c) {
5843 try {
5844 var i = n[a](c),
5845 u = i.value;
5846 } catch (n) {
5847 return void e(n);
5848 }
5849 i.done ? t(u) : Promise.resolve(u).then(r, o);
5850 }
5851 function _asyncToGenerator(n) {
5852 return function () {
5853 var t = this,
5854 e = arguments;
5855 return new Promise(function (r, o) {
5856 var a = n.apply(t, e);
5857 function _next(n) {
5858 asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
5859 }
5860 function _throw(n) {
5861 asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
5862 }
5863 _next(void 0);
5864 });
5865 };
5866 }
5867 module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
5868
5869 /***/ }),
5870
5871 /***/ "../node_modules/@babel/runtime/helpers/classCallCheck.js":
5872 /*!****************************************************************!*\
5873 !*** ../node_modules/@babel/runtime/helpers/classCallCheck.js ***!
5874 \****************************************************************/
5875 /***/ ((module) => {
5876
5877 function _classCallCheck(a, n) {
5878 if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
5879 }
5880 module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
5881
5882 /***/ }),
5883
5884 /***/ "../node_modules/@babel/runtime/helpers/construct.js":
5885 /*!***********************************************************!*\
5886 !*** ../node_modules/@babel/runtime/helpers/construct.js ***!
5887 \***********************************************************/
5888 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5889
5890 var isNativeReflectConstruct = __webpack_require__(/*! ./isNativeReflectConstruct.js */ "../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js");
5891 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
5892 function _construct(t, e, r) {
5893 if (isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
5894 var o = [null];
5895 o.push.apply(o, e);
5896 var p = new (t.bind.apply(t, o))();
5897 return r && setPrototypeOf(p, r.prototype), p;
5898 }
5899 module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports;
5900
5901 /***/ }),
5902
5903 /***/ "../node_modules/@babel/runtime/helpers/createClass.js":
5904 /*!*************************************************************!*\
5905 !*** ../node_modules/@babel/runtime/helpers/createClass.js ***!
5906 \*************************************************************/
5907 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5908
5909 var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/toPropertyKey.js");
5910 function _defineProperties(e, r) {
5911 for (var t = 0; t < r.length; t++) {
5912 var o = r[t];
5913 o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);
5914 }
5915 }
5916 function _createClass(e, r, t) {
5917 return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
5918 writable: !1
5919 }), e;
5920 }
5921 module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
5922
5923 /***/ }),
5924
5925 /***/ "../node_modules/@babel/runtime/helpers/defineProperty.js":
5926 /*!****************************************************************!*\
5927 !*** ../node_modules/@babel/runtime/helpers/defineProperty.js ***!
5928 \****************************************************************/
5929 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5930
5931 var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/toPropertyKey.js");
5932 function _defineProperty(e, r, t) {
5933 return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
5934 value: t,
5935 enumerable: !0,
5936 configurable: !0,
5937 writable: !0
5938 }) : e[r] = t, e;
5939 }
5940 module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
5941
5942 /***/ }),
5943
5944 /***/ "../node_modules/@babel/runtime/helpers/get.js":
5945 /*!*****************************************************!*\
5946 !*** ../node_modules/@babel/runtime/helpers/get.js ***!
5947 \*****************************************************/
5948 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5949
5950 var superPropBase = __webpack_require__(/*! ./superPropBase.js */ "../node_modules/@babel/runtime/helpers/superPropBase.js");
5951 function _get() {
5952 return module.exports = _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
5953 var p = superPropBase(e, t);
5954 if (p) {
5955 var n = Object.getOwnPropertyDescriptor(p, t);
5956 return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
5957 }
5958 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _get.apply(null, arguments);
5959 }
5960 module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports;
5961
5962 /***/ }),
5963
5964 /***/ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js":
5965 /*!****************************************************************!*\
5966 !*** ../node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
5967 \****************************************************************/
5968 /***/ ((module) => {
5969
5970 function _getPrototypeOf(t) {
5971 return module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
5972 return t.__proto__ || Object.getPrototypeOf(t);
5973 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _getPrototypeOf(t);
5974 }
5975 module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
5976
5977 /***/ }),
5978
5979 /***/ "../node_modules/@babel/runtime/helpers/inherits.js":
5980 /*!**********************************************************!*\
5981 !*** ../node_modules/@babel/runtime/helpers/inherits.js ***!
5982 \**********************************************************/
5983 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5984
5985 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
5986 function _inherits(t, e) {
5987 if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
5988 t.prototype = Object.create(e && e.prototype, {
5989 constructor: {
5990 value: t,
5991 writable: !0,
5992 configurable: !0
5993 }
5994 }), Object.defineProperty(t, "prototype", {
5995 writable: !1
5996 }), e && setPrototypeOf(t, e);
5997 }
5998 module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports;
5999
6000 /***/ }),
6001
6002 /***/ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js":
6003 /*!***********************************************************************!*\
6004 !*** ../node_modules/@babel/runtime/helpers/interopRequireDefault.js ***!
6005 \***********************************************************************/
6006 /***/ ((module) => {
6007
6008 function _interopRequireDefault(e) {
6009 return e && e.__esModule ? e : {
6010 "default": e
6011 };
6012 }
6013 module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
6014
6015 /***/ }),
6016
6017 /***/ "../node_modules/@babel/runtime/helpers/isNativeFunction.js":
6018 /*!******************************************************************!*\
6019 !*** ../node_modules/@babel/runtime/helpers/isNativeFunction.js ***!
6020 \******************************************************************/
6021 /***/ ((module) => {
6022
6023 function _isNativeFunction(t) {
6024 try {
6025 return -1 !== Function.toString.call(t).indexOf("[native code]");
6026 } catch (n) {
6027 return "function" == typeof t;
6028 }
6029 }
6030 module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports;
6031
6032 /***/ }),
6033
6034 /***/ "../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js":
6035 /*!**************************************************************************!*\
6036 !*** ../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js ***!
6037 \**************************************************************************/
6038 /***/ ((module) => {
6039
6040 function _isNativeReflectConstruct() {
6041 try {
6042 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
6043 } catch (t) {}
6044 return (module.exports = _isNativeReflectConstruct = function _isNativeReflectConstruct() {
6045 return !!t;
6046 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6047 }
6048 module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports;
6049
6050 /***/ }),
6051
6052 /***/ "../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js":
6053 /*!**********************************************************************!*\
6054 !*** ../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js ***!
6055 \**********************************************************************/
6056 /***/ ((module) => {
6057
6058 function _iterableToArrayLimit(r, l) {
6059 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
6060 if (null != t) {
6061 var e,
6062 n,
6063 i,
6064 u,
6065 a = [],
6066 f = !0,
6067 o = !1;
6068 try {
6069 if (i = (t = t.call(r)).next, 0 === l) {
6070 if (Object(t) !== t) return;
6071 f = !1;
6072 } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
6073 } catch (r) {
6074 o = !0, n = r;
6075 } finally {
6076 try {
6077 if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
6078 } finally {
6079 if (o) throw n;
6080 }
6081 }
6082 return a;
6083 }
6084 }
6085 module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
6086
6087 /***/ }),
6088
6089 /***/ "../node_modules/@babel/runtime/helpers/nonIterableRest.js":
6090 /*!*****************************************************************!*\
6091 !*** ../node_modules/@babel/runtime/helpers/nonIterableRest.js ***!
6092 \*****************************************************************/
6093 /***/ ((module) => {
6094
6095 function _nonIterableRest() {
6096 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6097 }
6098 module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
6099
6100 /***/ }),
6101
6102 /***/ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js":
6103 /*!***************************************************************************!*\
6104 !*** ../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
6105 \***************************************************************************/
6106 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6107
6108 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6109 var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized.js */ "../node_modules/@babel/runtime/helpers/assertThisInitialized.js");
6110 function _possibleConstructorReturn(t, e) {
6111 if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
6112 if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
6113 return assertThisInitialized(t);
6114 }
6115 module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports;
6116
6117 /***/ }),
6118
6119 /***/ "../node_modules/@babel/runtime/helpers/readOnlyError.js":
6120 /*!***************************************************************!*\
6121 !*** ../node_modules/@babel/runtime/helpers/readOnlyError.js ***!
6122 \***************************************************************/
6123 /***/ ((module) => {
6124
6125 function _readOnlyError(r) {
6126 throw new TypeError('"' + r + '" is read-only');
6127 }
6128 module.exports = _readOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports;
6129
6130 /***/ }),
6131
6132 /***/ "../node_modules/@babel/runtime/helpers/regenerator.js":
6133 /*!*************************************************************!*\
6134 !*** ../node_modules/@babel/runtime/helpers/regenerator.js ***!
6135 \*************************************************************/
6136 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6137
6138 var regeneratorDefine = __webpack_require__(/*! ./regeneratorDefine.js */ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js");
6139 function _regenerator() {
6140 /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
6141 var e,
6142 t,
6143 r = "function" == typeof Symbol ? Symbol : {},
6144 n = r.iterator || "@@iterator",
6145 o = r.toStringTag || "@@toStringTag";
6146 function i(r, n, o, i) {
6147 var c = n && n.prototype instanceof Generator ? n : Generator,
6148 u = Object.create(c.prototype);
6149 return regeneratorDefine(u, "_invoke", function (r, n, o) {
6150 var i,
6151 c,
6152 u,
6153 f = 0,
6154 p = o || [],
6155 y = !1,
6156 G = {
6157 p: 0,
6158 n: 0,
6159 v: e,
6160 a: d,
6161 f: d.bind(e, 4),
6162 d: function d(t, r) {
6163 return i = t, c = 0, u = e, G.n = r, a;
6164 }
6165 };
6166 function d(r, n) {
6167 for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
6168 var o,
6169 i = p[t],
6170 d = G.p,
6171 l = i[2];
6172 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));
6173 }
6174 if (o || r > 1) return a;
6175 throw y = !0, n;
6176 }
6177 return function (o, p, l) {
6178 if (f > 1) throw TypeError("Generator is already running");
6179 for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
6180 i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
6181 try {
6182 if (f = 2, i) {
6183 if (c || (o = "next"), t = i[o]) {
6184 if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
6185 if (!t.done) return t;
6186 u = t.value, c < 2 && (c = 0);
6187 } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
6188 i = e;
6189 } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
6190 } catch (t) {
6191 i = e, c = 1, u = t;
6192 } finally {
6193 f = 1;
6194 }
6195 }
6196 return {
6197 value: t,
6198 done: y
6199 };
6200 };
6201 }(r, o, i), !0), u;
6202 }
6203 var a = {};
6204 function Generator() {}
6205 function GeneratorFunction() {}
6206 function GeneratorFunctionPrototype() {}
6207 t = Object.getPrototypeOf;
6208 var c = [][n] ? t(t([][n]())) : (regeneratorDefine(t = {}, n, function () {
6209 return this;
6210 }), t),
6211 u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
6212 function f(e) {
6213 return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
6214 }
6215 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 () {
6216 return this;
6217 }), regeneratorDefine(u, "toString", function () {
6218 return "[object Generator]";
6219 }), (module.exports = _regenerator = function _regenerator() {
6220 return {
6221 w: i,
6222 m: f
6223 };
6224 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6225 }
6226 module.exports = _regenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
6227
6228 /***/ }),
6229
6230 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsync.js":
6231 /*!******************************************************************!*\
6232 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsync.js ***!
6233 \******************************************************************/
6234 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6235
6236 var regeneratorAsyncGen = __webpack_require__(/*! ./regeneratorAsyncGen.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");
6237 function _regeneratorAsync(n, e, r, t, o) {
6238 var a = regeneratorAsyncGen(n, e, r, t, o);
6239 return a.next().then(function (n) {
6240 return n.done ? n.value : a.next();
6241 });
6242 }
6243 module.exports = _regeneratorAsync, module.exports.__esModule = true, module.exports["default"] = module.exports;
6244
6245 /***/ }),
6246
6247 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js":
6248 /*!*********************************************************************!*\
6249 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js ***!
6250 \*********************************************************************/
6251 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6252
6253 var regenerator = __webpack_require__(/*! ./regenerator.js */ "../node_modules/@babel/runtime/helpers/regenerator.js");
6254 var regeneratorAsyncIterator = __webpack_require__(/*! ./regeneratorAsyncIterator.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");
6255 function _regeneratorAsyncGen(r, e, t, o, n) {
6256 return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise);
6257 }
6258 module.exports = _regeneratorAsyncGen, module.exports.__esModule = true, module.exports["default"] = module.exports;
6259
6260 /***/ }),
6261
6262 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js":
6263 /*!**************************************************************************!*\
6264 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js ***!
6265 \**************************************************************************/
6266 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6267
6268 var OverloadYield = __webpack_require__(/*! ./OverloadYield.js */ "../node_modules/@babel/runtime/helpers/OverloadYield.js");
6269 var regeneratorDefine = __webpack_require__(/*! ./regeneratorDefine.js */ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js");
6270 function AsyncIterator(t, e) {
6271 function n(r, o, i, f) {
6272 try {
6273 var c = t[r](o),
6274 u = c.value;
6275 return u instanceof OverloadYield ? e.resolve(u.v).then(function (t) {
6276 n("next", t, i, f);
6277 }, function (t) {
6278 n("throw", t, i, f);
6279 }) : e.resolve(u).then(function (t) {
6280 c.value = t, i(c);
6281 }, function (t) {
6282 return n("throw", t, i, f);
6283 });
6284 } catch (t) {
6285 f(t);
6286 }
6287 }
6288 var r;
6289 this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () {
6290 return this;
6291 })), regeneratorDefine(this, "_invoke", function (t, o, i) {
6292 function f() {
6293 return new e(function (e, r) {
6294 n(t, i, e, r);
6295 });
6296 }
6297 return r = r ? r.then(f, f) : f();
6298 }, !0);
6299 }
6300 module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;
6301
6302 /***/ }),
6303
6304 /***/ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js":
6305 /*!*******************************************************************!*\
6306 !*** ../node_modules/@babel/runtime/helpers/regeneratorDefine.js ***!
6307 \*******************************************************************/
6308 /***/ ((module) => {
6309
6310 function _regeneratorDefine(e, r, n, t) {
6311 var i = Object.defineProperty;
6312 try {
6313 i({}, "", {});
6314 } catch (e) {
6315 i = 0;
6316 }
6317 module.exports = _regeneratorDefine = function regeneratorDefine(e, r, n, t) {
6318 function o(r, n) {
6319 _regeneratorDefine(e, r, function (e) {
6320 return this._invoke(r, n, e);
6321 });
6322 }
6323 r ? i ? i(e, r, {
6324 value: n,
6325 enumerable: !t,
6326 configurable: !t,
6327 writable: !t
6328 }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
6329 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _regeneratorDefine(e, r, n, t);
6330 }
6331 module.exports = _regeneratorDefine, module.exports.__esModule = true, module.exports["default"] = module.exports;
6332
6333 /***/ }),
6334
6335 /***/ "../node_modules/@babel/runtime/helpers/regeneratorKeys.js":
6336 /*!*****************************************************************!*\
6337 !*** ../node_modules/@babel/runtime/helpers/regeneratorKeys.js ***!
6338 \*****************************************************************/
6339 /***/ ((module) => {
6340
6341 function _regeneratorKeys(e) {
6342 var n = Object(e),
6343 r = [];
6344 for (var t in n) r.unshift(t);
6345 return function e() {
6346 for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e;
6347 return e.done = !0, e;
6348 };
6349 }
6350 module.exports = _regeneratorKeys, module.exports.__esModule = true, module.exports["default"] = module.exports;
6351
6352 /***/ }),
6353
6354 /***/ "../node_modules/@babel/runtime/helpers/regeneratorRuntime.js":
6355 /*!********************************************************************!*\
6356 !*** ../node_modules/@babel/runtime/helpers/regeneratorRuntime.js ***!
6357 \********************************************************************/
6358 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6359
6360 var OverloadYield = __webpack_require__(/*! ./OverloadYield.js */ "../node_modules/@babel/runtime/helpers/OverloadYield.js");
6361 var regenerator = __webpack_require__(/*! ./regenerator.js */ "../node_modules/@babel/runtime/helpers/regenerator.js");
6362 var regeneratorAsync = __webpack_require__(/*! ./regeneratorAsync.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsync.js");
6363 var regeneratorAsyncGen = __webpack_require__(/*! ./regeneratorAsyncGen.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");
6364 var regeneratorAsyncIterator = __webpack_require__(/*! ./regeneratorAsyncIterator.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");
6365 var regeneratorKeys = __webpack_require__(/*! ./regeneratorKeys.js */ "../node_modules/@babel/runtime/helpers/regeneratorKeys.js");
6366 var regeneratorValues = __webpack_require__(/*! ./regeneratorValues.js */ "../node_modules/@babel/runtime/helpers/regeneratorValues.js");
6367 function _regeneratorRuntime() {
6368 "use strict";
6369
6370 var r = regenerator(),
6371 e = r.m(_regeneratorRuntime),
6372 t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor;
6373 function n(r) {
6374 var e = "function" == typeof r && r.constructor;
6375 return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name));
6376 }
6377 var o = {
6378 "throw": 1,
6379 "return": 2,
6380 "break": 3,
6381 "continue": 3
6382 };
6383 function a(r) {
6384 var e, t;
6385 return function (n) {
6386 e || (e = {
6387 stop: function stop() {
6388 return t(n.a, 2);
6389 },
6390 "catch": function _catch() {
6391 return n.v;
6392 },
6393 abrupt: function abrupt(r, e) {
6394 return t(n.a, o[r], e);
6395 },
6396 delegateYield: function delegateYield(r, o, a) {
6397 return e.resultName = o, t(n.d, regeneratorValues(r), a);
6398 },
6399 finish: function finish(r) {
6400 return t(n.f, r);
6401 }
6402 }, t = function t(r, _t, o) {
6403 n.p = e.prev, n.n = e.next;
6404 try {
6405 return r(_t, o);
6406 } finally {
6407 e.next = n.n;
6408 }
6409 }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n;
6410 try {
6411 return r.call(this, e);
6412 } finally {
6413 n.p = e.prev, n.n = e.next;
6414 }
6415 };
6416 }
6417 return (module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
6418 return {
6419 wrap: function wrap(e, t, n, o) {
6420 return r.w(a(e), t, n, o && o.reverse());
6421 },
6422 isGeneratorFunction: n,
6423 mark: r.m,
6424 awrap: function awrap(r, e) {
6425 return new OverloadYield(r, e);
6426 },
6427 AsyncIterator: regeneratorAsyncIterator,
6428 async: function async(r, e, t, o, u) {
6429 return (n(e) ? regeneratorAsyncGen : regeneratorAsync)(a(r), e, t, o, u);
6430 },
6431 keys: regeneratorKeys,
6432 values: regeneratorValues
6433 };
6434 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6435 }
6436 module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
6437
6438 /***/ }),
6439
6440 /***/ "../node_modules/@babel/runtime/helpers/regeneratorValues.js":
6441 /*!*******************************************************************!*\
6442 !*** ../node_modules/@babel/runtime/helpers/regeneratorValues.js ***!
6443 \*******************************************************************/
6444 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6445
6446 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6447 function _regeneratorValues(e) {
6448 if (null != e) {
6449 var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
6450 r = 0;
6451 if (t) return t.call(e);
6452 if ("function" == typeof e.next) return e;
6453 if (!isNaN(e.length)) return {
6454 next: function next() {
6455 return e && r >= e.length && (e = void 0), {
6456 value: e && e[r++],
6457 done: !e
6458 };
6459 }
6460 };
6461 }
6462 throw new TypeError(_typeof(e) + " is not iterable");
6463 }
6464 module.exports = _regeneratorValues, module.exports.__esModule = true, module.exports["default"] = module.exports;
6465
6466 /***/ }),
6467
6468 /***/ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js":
6469 /*!****************************************************************!*\
6470 !*** ../node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
6471 \****************************************************************/
6472 /***/ ((module) => {
6473
6474 function _setPrototypeOf(t, e) {
6475 return module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
6476 return t.__proto__ = e, t;
6477 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _setPrototypeOf(t, e);
6478 }
6479 module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
6480
6481 /***/ }),
6482
6483 /***/ "../node_modules/@babel/runtime/helpers/slicedToArray.js":
6484 /*!***************************************************************!*\
6485 !*** ../node_modules/@babel/runtime/helpers/slicedToArray.js ***!
6486 \***************************************************************/
6487 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6488
6489 var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles.js */ "../node_modules/@babel/runtime/helpers/arrayWithHoles.js");
6490 var iterableToArrayLimit = __webpack_require__(/*! ./iterableToArrayLimit.js */ "../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js");
6491 var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray.js */ "../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js");
6492 var nonIterableRest = __webpack_require__(/*! ./nonIterableRest.js */ "../node_modules/@babel/runtime/helpers/nonIterableRest.js");
6493 function _slicedToArray(r, e) {
6494 return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();
6495 }
6496 module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
6497
6498 /***/ }),
6499
6500 /***/ "../node_modules/@babel/runtime/helpers/superPropBase.js":
6501 /*!***************************************************************!*\
6502 !*** ../node_modules/@babel/runtime/helpers/superPropBase.js ***!
6503 \***************************************************************/
6504 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6505
6506 var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js");
6507 function _superPropBase(t, o) {
6508 for (; !{}.hasOwnProperty.call(t, o) && null !== (t = getPrototypeOf(t)););
6509 return t;
6510 }
6511 module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports;
6512
6513 /***/ }),
6514
6515 /***/ "../node_modules/@babel/runtime/helpers/toPrimitive.js":
6516 /*!*************************************************************!*\
6517 !*** ../node_modules/@babel/runtime/helpers/toPrimitive.js ***!
6518 \*************************************************************/
6519 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6520
6521 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6522 function toPrimitive(t, r) {
6523 if ("object" != _typeof(t) || !t) return t;
6524 var e = t[Symbol.toPrimitive];
6525 if (void 0 !== e) {
6526 var i = e.call(t, r || "default");
6527 if ("object" != _typeof(i)) return i;
6528 throw new TypeError("@@toPrimitive must return a primitive value.");
6529 }
6530 return ("string" === r ? String : Number)(t);
6531 }
6532 module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
6533
6534 /***/ }),
6535
6536 /***/ "../node_modules/@babel/runtime/helpers/toPropertyKey.js":
6537 /*!***************************************************************!*\
6538 !*** ../node_modules/@babel/runtime/helpers/toPropertyKey.js ***!
6539 \***************************************************************/
6540 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6541
6542 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6543 var toPrimitive = __webpack_require__(/*! ./toPrimitive.js */ "../node_modules/@babel/runtime/helpers/toPrimitive.js");
6544 function toPropertyKey(t) {
6545 var i = toPrimitive(t, "string");
6546 return "symbol" == _typeof(i) ? i : i + "";
6547 }
6548 module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
6549
6550 /***/ }),
6551
6552 /***/ "../node_modules/@babel/runtime/helpers/typeof.js":
6553 /*!********************************************************!*\
6554 !*** ../node_modules/@babel/runtime/helpers/typeof.js ***!
6555 \********************************************************/
6556 /***/ ((module) => {
6557
6558 function _typeof(o) {
6559 "@babel/helpers - typeof";
6560
6561 return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
6562 return typeof o;
6563 } : function (o) {
6564 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
6565 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
6566 }
6567 module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
6568
6569 /***/ }),
6570
6571 /***/ "../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js":
6572 /*!****************************************************************************!*\
6573 !*** ../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js ***!
6574 \****************************************************************************/
6575 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6576
6577 var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray.js */ "../node_modules/@babel/runtime/helpers/arrayLikeToArray.js");
6578 function _unsupportedIterableToArray(r, a) {
6579 if (r) {
6580 if ("string" == typeof r) return arrayLikeToArray(r, a);
6581 var t = {}.toString.call(r).slice(8, -1);
6582 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;
6583 }
6584 }
6585 module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
6586
6587 /***/ }),
6588
6589 /***/ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js":
6590 /*!*****************************************************************!*\
6591 !*** ../node_modules/@babel/runtime/helpers/wrapNativeSuper.js ***!
6592 \*****************************************************************/
6593 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6594
6595 var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js");
6596 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
6597 var isNativeFunction = __webpack_require__(/*! ./isNativeFunction.js */ "../node_modules/@babel/runtime/helpers/isNativeFunction.js");
6598 var construct = __webpack_require__(/*! ./construct.js */ "../node_modules/@babel/runtime/helpers/construct.js");
6599 function _wrapNativeSuper(t) {
6600 var r = "function" == typeof Map ? new Map() : void 0;
6601 return module.exports = _wrapNativeSuper = function _wrapNativeSuper(t) {
6602 if (null === t || !isNativeFunction(t)) return t;
6603 if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
6604 if (void 0 !== r) {
6605 if (r.has(t)) return r.get(t);
6606 r.set(t, Wrapper);
6607 }
6608 function Wrapper() {
6609 return construct(t, arguments, getPrototypeOf(this).constructor);
6610 }
6611 return Wrapper.prototype = Object.create(t.prototype, {
6612 constructor: {
6613 value: Wrapper,
6614 enumerable: !1,
6615 writable: !0,
6616 configurable: !0
6617 }
6618 }), setPrototypeOf(Wrapper, t);
6619 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _wrapNativeSuper(t);
6620 }
6621 module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports;
6622
6623 /***/ }),
6624
6625 /***/ "../node_modules/@babel/runtime/regenerator/index.js":
6626 /*!***********************************************************!*\
6627 !*** ../node_modules/@babel/runtime/regenerator/index.js ***!
6628 \***********************************************************/
6629 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6630
6631 // TODO(Babel 8): Remove this file.
6632
6633 var runtime = __webpack_require__(/*! ../helpers/regeneratorRuntime */ "../node_modules/@babel/runtime/helpers/regeneratorRuntime.js")();
6634 module.exports = runtime;
6635
6636 // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
6637 try {
6638 regeneratorRuntime = runtime;
6639 } catch (accidentalStrictMode) {
6640 if (typeof globalThis === "object") {
6641 globalThis.regeneratorRuntime = runtime;
6642 } else {
6643 Function("r", "regeneratorRuntime = r")(runtime);
6644 }
6645 }
6646
6647
6648 /***/ }),
6649
6650 /***/ "../node_modules/mixpanel-browser/dist/mixpanel.module.js":
6651 /*!****************************************************************!*\
6652 !*** ../node_modules/mixpanel-browser/dist/mixpanel.module.js ***!
6653 \****************************************************************/
6654 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
6655
6656 "use strict";
6657 __webpack_require__.r(__webpack_exports__);
6658 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6659 /* harmony export */ "default": () => (/* binding */ mixpanel)
6660 /* harmony export */ });
6661 // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
6662 var win;
6663 if (typeof(window) === 'undefined') {
6664 var loc = {
6665 hostname: ''
6666 };
6667 win = {
6668 crypto: {randomUUID: function() {throw Error('unsupported');}},
6669 navigator: { userAgent: '', onLine: true },
6670 document: {
6671 createElement: function() { return {}; },
6672 location: loc,
6673 referrer: ''
6674 },
6675 screen: { width: 0, height: 0 },
6676 location: loc,
6677 addEventListener: function() {},
6678 removeEventListener: function() {}
6679 };
6680 } else {
6681 win = window;
6682 }
6683
6684 function _array_like_to_array(arr, len) {
6685 if (len == null || len > arr.length) len = arr.length;
6686 for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
6687 return arr2;
6688 }
6689 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
6690 try {
6691 var info = gen[key](arg);
6692 var value = info.value;
6693 } catch (error) {
6694 reject(error);
6695 return;
6696 }
6697 if (info.done) {
6698 resolve(value);
6699 } else {
6700 Promise.resolve(value).then(_next, _throw);
6701 }
6702 }
6703 function _async_to_generator(fn) {
6704 return function() {
6705 var self = this, args = arguments;
6706 return new Promise(function(resolve, reject) {
6707 var gen = fn.apply(self, args);
6708 function _next(value) {
6709 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
6710 }
6711 function _throw(err) {
6712 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
6713 }
6714 _next(undefined);
6715 });
6716 };
6717 }
6718 function _construct(Parent, args, Class) {
6719 if (_is_native_reflect_construct()) {
6720 _construct = Reflect.construct;
6721 } else {
6722 _construct = function construct(Parent, args, Class) {
6723 var a = [
6724 null
6725 ];
6726 a.push.apply(a, args);
6727 var Constructor = Function.bind.apply(Parent, a);
6728 var instance = new Constructor();
6729 if (Class) _set_prototype_of(instance, Class.prototype);
6730 return instance;
6731 };
6732 }
6733 return _construct.apply(null, arguments);
6734 }
6735 function _defineProperties(target, props) {
6736 for(var i = 0; i < props.length; i++){
6737 var descriptor = props[i];
6738 descriptor.enumerable = descriptor.enumerable || false;
6739 descriptor.configurable = true;
6740 if ("value" in descriptor) descriptor.writable = true;
6741 Object.defineProperty(target, descriptor.key, descriptor);
6742 }
6743 }
6744 function _create_class(Constructor, protoProps, staticProps) {
6745 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
6746 return Constructor;
6747 }
6748 function _extends() {
6749 _extends = Object.assign || function(target) {
6750 for(var i = 1; i < arguments.length; i++){
6751 var source = arguments[i];
6752 for(var key in source){
6753 if (Object.prototype.hasOwnProperty.call(source, key)) {
6754 target[key] = source[key];
6755 }
6756 }
6757 }
6758 return target;
6759 };
6760 return _extends.apply(this, arguments);
6761 }
6762 function _get_prototype_of(o) {
6763 _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
6764 return o.__proto__ || Object.getPrototypeOf(o);
6765 };
6766 return _get_prototype_of(o);
6767 }
6768 function _inherits(subClass, superClass) {
6769 if (typeof superClass !== "function" && superClass !== null) {
6770 throw new TypeError("Super expression must either be null or a function");
6771 }
6772 subClass.prototype = Object.create(superClass && superClass.prototype, {
6773 constructor: {
6774 value: subClass,
6775 writable: true,
6776 configurable: true
6777 }
6778 });
6779 if (superClass) _set_prototype_of(subClass, superClass);
6780 }
6781 function _instanceof(left, right) {
6782 if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
6783 return !!right[Symbol.hasInstance](left);
6784 } else {
6785 return left instanceof right;
6786 }
6787 }
6788 function _is_native_function(fn) {
6789 return Function.toString.call(fn).indexOf("[native code]") !== -1;
6790 }
6791 function _object_without_properties_loose(source, excluded) {
6792 if (source == null) return {};
6793 var target = {};
6794 var sourceKeys = Object.keys(source);
6795 var key, i;
6796 for(i = 0; i < sourceKeys.length; i++){
6797 key = sourceKeys[i];
6798 if (excluded.indexOf(key) >= 0) continue;
6799 target[key] = source[key];
6800 }
6801 return target;
6802 }
6803 function _set_prototype_of(o, p) {
6804 _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
6805 o.__proto__ = p;
6806 return o;
6807 };
6808 return _set_prototype_of(o, p);
6809 }
6810 function _type_of(obj) {
6811 "@swc/helpers - typeof";
6812 return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
6813 }
6814 function _unsupported_iterable_to_array(o, minLen) {
6815 if (!o) return;
6816 if (typeof o === "string") return _array_like_to_array(o, minLen);
6817 var n = Object.prototype.toString.call(o).slice(8, -1);
6818 if (n === "Object" && o.constructor) n = o.constructor.name;
6819 if (n === "Map" || n === "Set") return Array.from(n);
6820 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
6821 }
6822 function _wrap_native_super(Class) {
6823 var _cache = typeof Map === "function" ? new Map() : undefined;
6824 _wrap_native_super = function wrapNativeSuper(Class) {
6825 if (Class === null || !_is_native_function(Class)) return Class;
6826 if (typeof Class !== "function") {
6827 throw new TypeError("Super expression must either be null or a function");
6828 }
6829 if (typeof _cache !== "undefined") {
6830 if (_cache.has(Class)) return _cache.get(Class);
6831 _cache.set(Class, Wrapper);
6832 }
6833 function Wrapper() {
6834 return _construct(Class, arguments, _get_prototype_of(this).constructor);
6835 }
6836 Wrapper.prototype = Object.create(Class.prototype, {
6837 constructor: {
6838 value: Wrapper,
6839 enumerable: false,
6840 writable: true,
6841 configurable: true
6842 }
6843 });
6844 return _set_prototype_of(Wrapper, Class);
6845 };
6846 return _wrap_native_super(Class);
6847 }
6848 function _is_native_reflect_construct() {
6849 try {
6850 var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
6851 } catch (_) {}
6852 return (_is_native_reflect_construct = function() {
6853 return !!result;
6854 })();
6855 }
6856 function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
6857 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
6858 if (it) return (it = it.call(o)).next.bind(it);
6859 if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike) {
6860 if (it) o = it;
6861 var i = 0;
6862 return function() {
6863 if (i >= o.length) {
6864 return {
6865 done: true
6866 };
6867 }
6868 return {
6869 done: false,
6870 value: o[i++]
6871 };
6872 };
6873 }
6874 throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6875 }
6876 function _ts_generator(thisArg, body) {
6877 var f, y, t, g, _ = {
6878 label: 0,
6879 sent: function() {
6880 if (t[0] & 1) throw t[1];
6881 return t[1];
6882 },
6883 trys: [],
6884 ops: []
6885 };
6886 return g = {
6887 next: verb(0),
6888 "throw": verb(1),
6889 "return": verb(2)
6890 }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
6891 return this;
6892 }), g;
6893 function verb(n) {
6894 return function(v) {
6895 return step([
6896 n,
6897 v
6898 ]);
6899 };
6900 }
6901 function step(op) {
6902 if (f) throw new TypeError("Generator is already executing.");
6903 while(_)try {
6904 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;
6905 if (y = 0, t) op = [
6906 op[0] & 2,
6907 t.value
6908 ];
6909 switch(op[0]){
6910 case 0:
6911 case 1:
6912 t = op;
6913 break;
6914 case 4:
6915 _.label++;
6916 return {
6917 value: op[1],
6918 done: false
6919 };
6920 case 5:
6921 _.label++;
6922 y = op[1];
6923 op = [
6924 0
6925 ];
6926 continue;
6927 case 7:
6928 op = _.ops.pop();
6929 _.trys.pop();
6930 continue;
6931 default:
6932 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
6933 _ = 0;
6934 continue;
6935 }
6936 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
6937 _.label = op[1];
6938 break;
6939 }
6940 if (op[0] === 6 && _.label < t[1]) {
6941 _.label = t[1];
6942 t = op;
6943 break;
6944 }
6945 if (t && _.label < t[2]) {
6946 _.label = t[2];
6947 _.ops.push(op);
6948 break;
6949 }
6950 if (t[2]) _.ops.pop();
6951 _.trys.pop();
6952 continue;
6953 }
6954 op = body.call(thisArg, _);
6955 } catch (e) {
6956 op = [
6957 6,
6958 e
6959 ];
6960 y = 0;
6961 } finally{
6962 f = t = 0;
6963 }
6964 if (op[0] & 5) throw op[1];
6965 return {
6966 value: op[0] ? op[1] : void 0,
6967 done: true
6968 };
6969 }
6970 }
6971 function _ts_values(o) {
6972 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
6973 if (m) return m.call(o);
6974 if (o && typeof o.length === "number") return {
6975 next: function() {
6976 if (o && i >= o.length) o = void 0;
6977 return {
6978 value: o && o[i++],
6979 done: !o
6980 };
6981 }
6982 };
6983 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
6984 }
6985 var __defProp = Object.defineProperty;
6986 var __defNormalProp = function(obj, key, value) {
6987 return key in obj ? __defProp(obj, key, {
6988 enumerable: true,
6989 configurable: true,
6990 writable: true,
6991 value: value
6992 }) : obj[key] = value;
6993 };
6994 var __publicField = function(obj, key, value) {
6995 return __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
6996 };
6997 var _a;
6998 var __defProp$1 = Object.defineProperty;
6999 var __defNormalProp$1 = function(obj, key, value) {
7000 return key in obj ? __defProp$1(obj, key, {
7001 enumerable: true,
7002 configurable: true,
7003 writable: true,
7004 value: value
7005 }) : obj[key] = value;
7006 };
7007 var __publicField$1 = function(obj, key, value) {
7008 return __defNormalProp$1(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
7009 };
7010 var NodeType$3 = /* @__PURE__ */ function(NodeType2) {
7011 NodeType2[NodeType2["Document"] = 0] = "Document";
7012 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
7013 NodeType2[NodeType2["Element"] = 2] = "Element";
7014 NodeType2[NodeType2["Text"] = 3] = "Text";
7015 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
7016 NodeType2[NodeType2["Comment"] = 5] = "Comment";
7017 return NodeType2;
7018 }(NodeType$3 || {});
7019 var testableAccessors$1 = {
7020 Node: [
7021 "childNodes",
7022 "parentNode",
7023 "parentElement",
7024 "textContent"
7025 ],
7026 ShadowRoot: [
7027 "host",
7028 "styleSheets"
7029 ],
7030 Element: [
7031 "shadowRoot",
7032 "querySelector",
7033 "querySelectorAll"
7034 ],
7035 MutationObserver: []
7036 };
7037 var testableMethods$1 = {
7038 Node: [
7039 "contains",
7040 "getRootNode"
7041 ],
7042 ShadowRoot: [
7043 "getSelection"
7044 ],
7045 Element: [],
7046 MutationObserver: [
7047 "constructor"
7048 ]
7049 };
7050 var untaintedBasePrototype$1 = {};
7051 var isAngularZonePresent$1 = function() {
7052 return !!globalThis.Zone;
7053 };
7054 function getUntaintedPrototype$1(key) {
7055 if (untaintedBasePrototype$1[key]) return untaintedBasePrototype$1[key];
7056 var defaultObj = globalThis[key];
7057 var defaultPrototype = defaultObj.prototype;
7058 var accessorNames = key in testableAccessors$1 ? testableAccessors$1[key] : void 0;
7059 var isUntaintedAccessors = Boolean(accessorNames && // @ts-expect-error 2345
7060 accessorNames.every(function(accessor) {
7061 var _a2, _b;
7062 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
7063 }));
7064 var methodNames = key in testableMethods$1 ? testableMethods$1[key] : void 0;
7065 var isUntaintedMethods = Boolean(methodNames && methodNames.every(// @ts-expect-error 2345
7066 function(method) {
7067 var _a2;
7068 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
7069 }));
7070 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent$1()) {
7071 untaintedBasePrototype$1[key] = defaultObj.prototype;
7072 return defaultObj.prototype;
7073 }
7074 try {
7075 var iframeEl = document.createElement("iframe");
7076 document.body.appendChild(iframeEl);
7077 var win = iframeEl.contentWindow;
7078 if (!win) return defaultObj.prototype;
7079 var untaintedObject = win[key].prototype;
7080 document.body.removeChild(iframeEl);
7081 if (!untaintedObject) return defaultPrototype;
7082 return untaintedBasePrototype$1[key] = untaintedObject;
7083 } catch (e) {
7084 return defaultPrototype;
7085 }
7086 }
7087 var untaintedAccessorCache$1 = {};
7088 function getUntaintedAccessor$1(key, instance, accessor) {
7089 var _a2;
7090 var cacheKey = key + "." + String(accessor);
7091 if (untaintedAccessorCache$1[cacheKey]) return untaintedAccessorCache$1[cacheKey].call(instance);
7092 var untaintedPrototype = getUntaintedPrototype$1(key);
7093 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
7094 if (!untaintedAccessor) return instance[accessor];
7095 untaintedAccessorCache$1[cacheKey] = untaintedAccessor;
7096 return untaintedAccessor.call(instance);
7097 }
7098 var untaintedMethodCache$1 = {};
7099 function getUntaintedMethod$1(key, instance, method) {
7100 var cacheKey = key + "." + String(method);
7101 if (untaintedMethodCache$1[cacheKey]) return untaintedMethodCache$1[cacheKey].bind(instance);
7102 var untaintedPrototype = getUntaintedPrototype$1(key);
7103 var untaintedMethod = untaintedPrototype[method];
7104 if (typeof untaintedMethod !== "function") return instance[method];
7105 untaintedMethodCache$1[cacheKey] = untaintedMethod;
7106 return untaintedMethod.bind(instance);
7107 }
7108 function childNodes$1(n2) {
7109 return getUntaintedAccessor$1("Node", n2, "childNodes");
7110 }
7111 function parentNode$1(n2) {
7112 return getUntaintedAccessor$1("Node", n2, "parentNode");
7113 }
7114 function parentElement$1(n2) {
7115 return getUntaintedAccessor$1("Node", n2, "parentElement");
7116 }
7117 function textContent$1(n2) {
7118 return getUntaintedAccessor$1("Node", n2, "textContent");
7119 }
7120 function contains$1(n2, other) {
7121 return getUntaintedMethod$1("Node", n2, "contains")(other);
7122 }
7123 function getRootNode$1(n2) {
7124 return getUntaintedMethod$1("Node", n2, "getRootNode")();
7125 }
7126 function host$1(n2) {
7127 if (!n2 || !("host" in n2)) return null;
7128 return getUntaintedAccessor$1("ShadowRoot", n2, "host");
7129 }
7130 function styleSheets$1(n2) {
7131 return n2.styleSheets;
7132 }
7133 function shadowRoot$1(n2) {
7134 if (!n2 || !("shadowRoot" in n2)) return null;
7135 return getUntaintedAccessor$1("Element", n2, "shadowRoot");
7136 }
7137 function querySelector$1(n2, selectors) {
7138 return getUntaintedAccessor$1("Element", n2, "querySelector")(selectors);
7139 }
7140 function querySelectorAll$1(n2, selectors) {
7141 return getUntaintedAccessor$1("Element", n2, "querySelectorAll")(selectors);
7142 }
7143 function mutationObserverCtor$1() {
7144 return getUntaintedPrototype$1("MutationObserver").constructor;
7145 }
7146 function patch$1(source, name, replacement) {
7147 try {
7148 if (!(name in source)) {
7149 return function() {};
7150 }
7151 var original = source[name];
7152 var wrapped = replacement(original);
7153 if (typeof wrapped === "function") {
7154 wrapped.prototype = wrapped.prototype || {};
7155 Object.defineProperties(wrapped, {
7156 __rrweb_original__: {
7157 enumerable: false,
7158 value: original
7159 }
7160 });
7161 }
7162 source[name] = wrapped;
7163 return function() {
7164 source[name] = original;
7165 };
7166 } catch (e) {
7167 return function() {};
7168 }
7169 }
7170 var index$1 = {
7171 childNodes: childNodes$1,
7172 parentNode: parentNode$1,
7173 parentElement: parentElement$1,
7174 textContent: textContent$1,
7175 contains: contains$1,
7176 getRootNode: getRootNode$1,
7177 host: host$1,
7178 styleSheets: styleSheets$1,
7179 shadowRoot: shadowRoot$1,
7180 querySelector: querySelector$1,
7181 querySelectorAll: querySelectorAll$1,
7182 mutationObserver: mutationObserverCtor$1,
7183 patch: patch$1
7184 };
7185 function isElement(n2) {
7186 return n2.nodeType === n2.ELEMENT_NODE;
7187 }
7188 function isShadowRoot(n2) {
7189 var hostEl = // anchor and textarea elements also have a `host` property
7190 // but only shadow roots have a `mode` property
7191 n2 && "host" in n2 && "mode" in n2 && index$1.host(n2) || null;
7192 return Boolean(hostEl && "shadowRoot" in hostEl && index$1.shadowRoot(hostEl) === n2);
7193 }
7194 function isNativeShadowDom(shadowRoot2) {
7195 return Object.prototype.toString.call(shadowRoot2) === "[object ShadowRoot]";
7196 }
7197 function fixBrowserCompatibilityIssuesInCSS(cssText) {
7198 if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) {
7199 cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;");
7200 }
7201 return cssText;
7202 }
7203 function escapeImportStatement(rule2) {
7204 var cssText = rule2.cssText;
7205 if (cssText.split('"').length < 3) return cssText;
7206 var statement = [
7207 "@import",
7208 "url(" + JSON.stringify(rule2.href) + ")"
7209 ];
7210 if (rule2.layerName === "") {
7211 statement.push("layer");
7212 } else if (rule2.layerName) {
7213 statement.push("layer(" + rule2.layerName + ")");
7214 }
7215 if (rule2.supportsText) {
7216 statement.push("supports(" + rule2.supportsText + ")");
7217 }
7218 if (rule2.media.length) {
7219 statement.push(rule2.media.mediaText);
7220 }
7221 return statement.join(" ") + ";";
7222 }
7223 function stringifyStylesheet(s2) {
7224 try {
7225 var rules2 = s2.rules || s2.cssRules;
7226 if (!rules2) {
7227 return null;
7228 }
7229 var sheetHref = s2.href;
7230 if (!sheetHref && s2.ownerNode && s2.ownerNode.ownerDocument) {
7231 sheetHref = s2.ownerNode.ownerDocument.location.href;
7232 }
7233 var stringifiedRules = Array.from(rules2, function(rule2) {
7234 return stringifyRule(rule2, sheetHref);
7235 }).join("");
7236 return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);
7237 } catch (error) {
7238 return null;
7239 }
7240 }
7241 function stringifyRule(rule2, sheetHref) {
7242 if (isCSSImportRule(rule2)) {
7243 var importStringified;
7244 try {
7245 importStringified = // we can access the imported stylesheet rules directly
7246 stringifyStylesheet(rule2.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement
7247 escapeImportStatement(rule2);
7248 } catch (error) {
7249 importStringified = rule2.cssText;
7250 }
7251 if (rule2.styleSheet.href) {
7252 return absolutifyURLs(importStringified, rule2.styleSheet.href);
7253 }
7254 return importStringified;
7255 } else {
7256 var ruleStringified = rule2.cssText;
7257 if (isCSSStyleRule(rule2) && rule2.selectorText.includes(":")) {
7258 ruleStringified = fixSafariColons(ruleStringified);
7259 }
7260 if (sheetHref) {
7261 return absolutifyURLs(ruleStringified, sheetHref);
7262 }
7263 return ruleStringified;
7264 }
7265 }
7266 function fixSafariColons(cssStringified) {
7267 var regex = /(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;
7268 return cssStringified.replace(regex, "$1\\$2");
7269 }
7270 function isCSSImportRule(rule2) {
7271 return "styleSheet" in rule2;
7272 }
7273 function isCSSStyleRule(rule2) {
7274 return "selectorText" in rule2;
7275 }
7276 var Mirror = /*#__PURE__*/ function() {
7277 function Mirror() {
7278 __publicField$1(this, "idNodeMap", /* @__PURE__ */ new Map());
7279 __publicField$1(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap());
7280 }
7281 var _proto = Mirror.prototype;
7282 _proto.getId = function getId(n2) {
7283 var _a2;
7284 if (!n2) return -1;
7285 var id = (_a2 = this.getMeta(n2)) == null ? void 0 : _a2.id;
7286 return id != null ? id : -1;
7287 };
7288 _proto.getNode = function getNode(id) {
7289 return this.idNodeMap.get(id) || null;
7290 };
7291 _proto.getIds = function getIds() {
7292 return Array.from(this.idNodeMap.keys());
7293 };
7294 _proto.getMeta = function getMeta(n2) {
7295 return this.nodeMetaMap.get(n2) || null;
7296 };
7297 // removes the node from idNodeMap
7298 // doesn't remove the node from nodeMetaMap
7299 _proto.removeNodeFromMap = function removeNodeFromMap(n2) {
7300 var _this = this;
7301 var id = this.getId(n2);
7302 this.idNodeMap.delete(id);
7303 if (n2.childNodes) {
7304 n2.childNodes.forEach(function(childNode) {
7305 return _this.removeNodeFromMap(childNode);
7306 });
7307 }
7308 };
7309 _proto.has = function has(id) {
7310 return this.idNodeMap.has(id);
7311 };
7312 _proto.hasNode = function hasNode(node2) {
7313 return this.nodeMetaMap.has(node2);
7314 };
7315 _proto.add = function add(n2, meta) {
7316 var id = meta.id;
7317 this.idNodeMap.set(id, n2);
7318 this.nodeMetaMap.set(n2, meta);
7319 };
7320 _proto.replace = function replace(id, n2) {
7321 var oldNode = this.getNode(id);
7322 if (oldNode) {
7323 var meta = this.nodeMetaMap.get(oldNode);
7324 if (meta) this.nodeMetaMap.set(n2, meta);
7325 }
7326 this.idNodeMap.set(id, n2);
7327 };
7328 _proto.reset = function reset() {
7329 this.idNodeMap = /* @__PURE__ */ new Map();
7330 this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
7331 };
7332 return Mirror;
7333 }();
7334 function createMirror$2() {
7335 return new Mirror();
7336 }
7337 function maskInputValue(param) {
7338 var element = param.element, maskInputOptions = param.maskInputOptions, tagName = param.tagName, type = param.type, value = param.value, maskInputFn = param.maskInputFn;
7339 var text = value || "";
7340 var actualType = type && toLowerCase(type);
7341 if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {
7342 if (maskInputFn) {
7343 text = maskInputFn(text, element);
7344 } else {
7345 text = "*".repeat(text.length);
7346 }
7347 }
7348 return text;
7349 }
7350 function toLowerCase(str) {
7351 return str.toLowerCase();
7352 }
7353 var ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
7354 function is2DCanvasBlank(canvas) {
7355 var ctx = canvas.getContext("2d");
7356 if (!ctx) return true;
7357 var chunkSize = 50;
7358 for(var x2 = 0; x2 < canvas.width; x2 += chunkSize){
7359 for(var y = 0; y < canvas.height; y += chunkSize){
7360 var getImageData = ctx.getImageData;
7361 var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
7362 var pixelBuffer = new Uint32Array(// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
7363 originalGetImageData.call(ctx, x2, y, Math.min(chunkSize, canvas.width - x2), Math.min(chunkSize, canvas.height - y)).data.buffer);
7364 if (pixelBuffer.some(function(pixel) {
7365 return pixel !== 0;
7366 })) return false;
7367 }
7368 }
7369 return true;
7370 }
7371 function getInputType(element) {
7372 var type = element.type;
7373 return element.hasAttribute("data-rr-is-password") ? "password" : type ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
7374 toLowerCase(type) : null;
7375 }
7376 function extractFileExtension(path, baseURL) {
7377 var url;
7378 try {
7379 url = new URL(path, baseURL != null ? baseURL : window.location.href);
7380 } catch (err) {
7381 return null;
7382 }
7383 var regex = /\.([0-9a-z]+)(?:$)/i;
7384 var match = url.pathname.match(regex);
7385 var _ref;
7386 return (_ref = match == null ? void 0 : match[1]) != null ? _ref : null;
7387 }
7388 function extractOrigin(url) {
7389 var origin = "";
7390 if (url.indexOf("//") > -1) {
7391 origin = url.split("/").slice(0, 3).join("/");
7392 } else {
7393 origin = url.split("/")[0];
7394 }
7395 origin = origin.split("?")[0];
7396 return origin;
7397 }
7398 var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
7399 var URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
7400 var URL_WWW_MATCH = /^www\..*/i;
7401 var DATA_URI = /^(data:)([^,]*),(.*)/i;
7402 function absolutifyURLs(cssText, href) {
7403 return (cssText || "").replace(URL_IN_CSS_REF, function(origin, quote1, path1, quote2, path2, path3) {
7404 var filePath = path1 || path2 || path3;
7405 var maybeQuote = quote1 || quote2 || "";
7406 if (!filePath) {
7407 return origin;
7408 }
7409 if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {
7410 return "url(" + maybeQuote + filePath + maybeQuote + ")";
7411 }
7412 if (DATA_URI.test(filePath)) {
7413 return "url(" + maybeQuote + filePath + maybeQuote + ")";
7414 }
7415 if (filePath[0] === "/") {
7416 return "url(" + maybeQuote + (extractOrigin(href) + filePath) + maybeQuote + ")";
7417 }
7418 var stack = href.split("/");
7419 var parts = filePath.split("/");
7420 stack.pop();
7421 for(var _iterator = _create_for_of_iterator_helper_loose(parts), _step; !(_step = _iterator()).done;){
7422 var part = _step.value;
7423 if (part === ".") {
7424 continue;
7425 } else if (part === "..") {
7426 stack.pop();
7427 } else {
7428 stack.push(part);
7429 }
7430 }
7431 return "url(" + maybeQuote + stack.join("/") + maybeQuote + ")";
7432 });
7433 }
7434 function normalizeCssString(cssText, _testNoPxNorm) {
7435 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
7436 if (_testNoPxNorm) {
7437 return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "");
7438 } else {
7439 return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "").replace(/0px/g, "0");
7440 }
7441 }
7442 function splitCssText(cssText, style, _testNoPxNorm) {
7443 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
7444 var childNodes2 = Array.from(style.childNodes);
7445 var splits = [];
7446 var iterCount = 0;
7447 if (childNodes2.length > 1 && cssText && typeof cssText === "string") {
7448 var cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);
7449 var normFactor = cssTextNorm.length / cssText.length;
7450 for(var i2 = 1; i2 < childNodes2.length; i2++){
7451 if (childNodes2[i2].textContent && typeof childNodes2[i2].textContent === "string") {
7452 var textContentNorm = normalizeCssString(childNodes2[i2].textContent, _testNoPxNorm);
7453 var jLimit = 100;
7454 var j = 3;
7455 for(; j < textContentNorm.length; j++){
7456 if (// keep consuming css identifiers (to get a decent chunk more quickly)
7457 textContentNorm[j].match(/[a-zA-Z0-9]/) || // substring needs to be unique to this section
7458 textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1) {
7459 continue;
7460 }
7461 break;
7462 }
7463 for(; j < textContentNorm.length; j++){
7464 var startSubstring = textContentNorm.substring(0, j);
7465 var cssNormSplits = cssTextNorm.split(startSubstring);
7466 var splitNorm = -1;
7467 if (cssNormSplits.length === 2) {
7468 splitNorm = cssNormSplits[0].length;
7469 } else if (cssNormSplits.length > 2 && cssNormSplits[0] === "" && childNodes2[i2 - 1].textContent !== "") {
7470 splitNorm = cssTextNorm.indexOf(startSubstring, 1);
7471 } else if (cssNormSplits.length === 1) {
7472 startSubstring = startSubstring.substring(0, startSubstring.length - 1);
7473 cssNormSplits = cssTextNorm.split(startSubstring);
7474 if (cssNormSplits.length <= 1) {
7475 splits.push(cssText);
7476 return splits;
7477 }
7478 j = jLimit + 1;
7479 } else if (j === textContentNorm.length - 1) {
7480 splitNorm = cssTextNorm.indexOf(startSubstring);
7481 }
7482 if (cssNormSplits.length >= 2 && j > jLimit) {
7483 var prevTextContent = childNodes2[i2 - 1].textContent;
7484 if (prevTextContent && typeof prevTextContent === "string") {
7485 var prevMinLength = normalizeCssString(prevTextContent).length;
7486 splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);
7487 }
7488 if (splitNorm === -1) {
7489 splitNorm = cssNormSplits[0].length;
7490 }
7491 }
7492 if (splitNorm !== -1) {
7493 var k = Math.floor(splitNorm / normFactor);
7494 for(; k > 0 && k < cssText.length;){
7495 iterCount += 1;
7496 if (iterCount > 50 * childNodes2.length) {
7497 splits.push(cssText);
7498 return splits;
7499 }
7500 var normPart = normalizeCssString(cssText.substring(0, k), _testNoPxNorm);
7501 if (normPart.length === splitNorm) {
7502 splits.push(cssText.substring(0, k));
7503 cssText = cssText.substring(k);
7504 cssTextNorm = cssTextNorm.substring(splitNorm);
7505 break;
7506 } else if (normPart.length < splitNorm) {
7507 k += Math.max(1, Math.floor((splitNorm - normPart.length) / normFactor));
7508 } else {
7509 k -= Math.max(1, Math.floor((normPart.length - splitNorm) * normFactor));
7510 }
7511 }
7512 break;
7513 }
7514 }
7515 }
7516 }
7517 }
7518 splits.push(cssText);
7519 return splits;
7520 }
7521 function markCssSplits(cssText, style) {
7522 return splitCssText(cssText, style).join("/* rr_split */");
7523 }
7524 var _id = 1;
7525 var tagNameRegex = new RegExp("[^a-z0-9-_:]");
7526 var IGNORED_NODE = -2;
7527 function genId() {
7528 return _id++;
7529 }
7530 function getValidTagName$1(element) {
7531 if (_instanceof(element, HTMLFormElement)) {
7532 return "form";
7533 }
7534 var processedTagName = toLowerCase(element.tagName);
7535 if (tagNameRegex.test(processedTagName)) {
7536 return "div";
7537 }
7538 return processedTagName;
7539 }
7540 var canvasService;
7541 var canvasCtx;
7542 var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
7543 var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
7544 function getAbsoluteSrcsetString(doc, attributeValue) {
7545 if (attributeValue.trim() === "") {
7546 return attributeValue;
7547 }
7548 var pos = 0;
7549 function collectCharacters(regEx) {
7550 var chars2;
7551 var match = regEx.exec(attributeValue.substring(pos));
7552 if (match) {
7553 chars2 = match[0];
7554 pos += chars2.length;
7555 return chars2;
7556 }
7557 return "";
7558 }
7559 var output = [];
7560 while(true){
7561 collectCharacters(SRCSET_COMMAS_OR_SPACES);
7562 if (pos >= attributeValue.length) {
7563 break;
7564 }
7565 var url = collectCharacters(SRCSET_NOT_SPACES);
7566 if (url.slice(-1) === ",") {
7567 url = absoluteToDoc(doc, url.substring(0, url.length - 1));
7568 output.push(url);
7569 } else {
7570 var descriptorsStr = "";
7571 url = absoluteToDoc(doc, url);
7572 var inParens = false;
7573 while(true){
7574 var c2 = attributeValue.charAt(pos);
7575 if (c2 === "") {
7576 output.push((url + descriptorsStr).trim());
7577 break;
7578 } else if (!inParens) {
7579 if (c2 === ",") {
7580 pos += 1;
7581 output.push((url + descriptorsStr).trim());
7582 break;
7583 } else if (c2 === "(") {
7584 inParens = true;
7585 }
7586 } else {
7587 if (c2 === ")") {
7588 inParens = false;
7589 }
7590 }
7591 descriptorsStr += c2;
7592 pos += 1;
7593 }
7594 }
7595 }
7596 return output.join(", ");
7597 }
7598 var cachedDocument = /* @__PURE__ */ new WeakMap();
7599 function absoluteToDoc(doc, attributeValue) {
7600 if (!attributeValue || attributeValue.trim() === "") {
7601 return attributeValue;
7602 }
7603 return getHref(doc, attributeValue);
7604 }
7605 function isSVGElement(el) {
7606 return Boolean(el.tagName === "svg" || el.ownerSVGElement);
7607 }
7608 function getHref(doc, customHref) {
7609 var a2 = cachedDocument.get(doc);
7610 if (!a2) {
7611 a2 = doc.createElement("a");
7612 cachedDocument.set(doc, a2);
7613 }
7614 if (!customHref) {
7615 customHref = "";
7616 } else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) {
7617 return customHref;
7618 }
7619 a2.setAttribute("href", customHref);
7620 return a2.href;
7621 }
7622 function transformAttribute(doc, tagName, name, value) {
7623 if (!value) {
7624 return value;
7625 }
7626 if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) {
7627 return absoluteToDoc(doc, value);
7628 } else if (name === "xlink:href" && value[0] !== "#") {
7629 return absoluteToDoc(doc, value);
7630 } else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) {
7631 return absoluteToDoc(doc, value);
7632 } else if (name === "srcset") {
7633 return getAbsoluteSrcsetString(doc, value);
7634 } else if (name === "style") {
7635 return absolutifyURLs(value, getHref(doc));
7636 } else if (tagName === "object" && name === "data") {
7637 return absoluteToDoc(doc, value);
7638 }
7639 return value;
7640 }
7641 function ignoreAttribute(tagName, name, _value) {
7642 return (tagName === "video" || tagName === "audio") && name === "autoplay";
7643 }
7644 function _isBlockedElement(element, blockClass, blockSelector) {
7645 try {
7646 if (typeof blockClass === "string") {
7647 if (element.classList.contains(blockClass)) {
7648 return true;
7649 }
7650 } else {
7651 for(var eIndex = element.classList.length; eIndex--;){
7652 var className = element.classList[eIndex];
7653 if (blockClass.test(className)) {
7654 return true;
7655 }
7656 }
7657 }
7658 if (blockSelector) {
7659 return element.matches(blockSelector);
7660 }
7661 } catch (e2) {}
7662 return false;
7663 }
7664 function classMatchesRegex(node2, regex, checkAncestors) {
7665 if (!node2) return false;
7666 if (node2.nodeType !== node2.ELEMENT_NODE) {
7667 if (!checkAncestors) return false;
7668 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
7669 }
7670 for(var eIndex = node2.classList.length; eIndex--;){
7671 var className = node2.classList[eIndex];
7672 if (regex.test(className)) {
7673 return true;
7674 }
7675 }
7676 if (!checkAncestors) return false;
7677 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
7678 }
7679 function needMaskingText(node2, maskTextClass, maskTextSelector, checkAncestors) {
7680 var el;
7681 if (isElement(node2)) {
7682 el = node2;
7683 if (!index$1.childNodes(el).length) {
7684 return false;
7685 }
7686 } else if (index$1.parentElement(node2) === null) {
7687 return false;
7688 } else {
7689 el = index$1.parentElement(node2);
7690 }
7691 try {
7692 if (typeof maskTextClass === "string") {
7693 if (checkAncestors) {
7694 if (el.closest("." + maskTextClass)) return true;
7695 } else {
7696 if (el.classList.contains(maskTextClass)) return true;
7697 }
7698 } else {
7699 if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;
7700 }
7701 if (maskTextSelector) {
7702 if (checkAncestors) {
7703 if (el.closest(maskTextSelector)) return true;
7704 } else {
7705 if (el.matches(maskTextSelector)) return true;
7706 }
7707 }
7708 } catch (e2) {}
7709 return false;
7710 }
7711 function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
7712 var win = iframeEl.contentWindow;
7713 if (!win) {
7714 return;
7715 }
7716 var fired = false;
7717 var readyState;
7718 try {
7719 readyState = win.document.readyState;
7720 } catch (error) {
7721 return;
7722 }
7723 if (readyState !== "complete") {
7724 var timer = setTimeout(function() {
7725 if (!fired) {
7726 listener();
7727 fired = true;
7728 }
7729 }, iframeLoadTimeout);
7730 iframeEl.addEventListener("load", function() {
7731 clearTimeout(timer);
7732 fired = true;
7733 listener();
7734 });
7735 return;
7736 }
7737 var blankUrl = "about:blank";
7738 if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
7739 setTimeout(listener, 0);
7740 return iframeEl.addEventListener("load", listener);
7741 }
7742 iframeEl.addEventListener("load", listener);
7743 }
7744 function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
7745 var fired = false;
7746 var styleSheetLoaded;
7747 try {
7748 styleSheetLoaded = link.sheet;
7749 } catch (error) {
7750 return;
7751 }
7752 if (styleSheetLoaded) return;
7753 var timer = setTimeout(function() {
7754 if (!fired) {
7755 listener();
7756 fired = true;
7757 }
7758 }, styleSheetLoadTimeout);
7759 link.addEventListener("load", function() {
7760 clearTimeout(timer);
7761 fired = true;
7762 listener();
7763 });
7764 }
7765 function serializeNode(n2, options) {
7766 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;
7767 var rootId = getRootId(doc, mirror2);
7768 switch(n2.nodeType){
7769 case n2.DOCUMENT_NODE:
7770 if (n2.compatMode !== "CSS1Compat") {
7771 return {
7772 type: NodeType$3.Document,
7773 childNodes: [],
7774 compatMode: n2.compatMode
7775 };
7776 } else {
7777 return {
7778 type: NodeType$3.Document,
7779 childNodes: []
7780 };
7781 }
7782 case n2.DOCUMENT_TYPE_NODE:
7783 return {
7784 type: NodeType$3.DocumentType,
7785 name: n2.name,
7786 publicId: n2.publicId,
7787 systemId: n2.systemId,
7788 rootId: rootId
7789 };
7790 case n2.ELEMENT_NODE:
7791 return serializeElementNode(n2, {
7792 doc: doc,
7793 blockClass: blockClass,
7794 blockSelector: blockSelector,
7795 inlineStylesheet: inlineStylesheet,
7796 maskInputOptions: maskInputOptions,
7797 maskInputFn: maskInputFn,
7798 dataURLOptions: dataURLOptions,
7799 inlineImages: inlineImages,
7800 recordCanvas: recordCanvas,
7801 keepIframeSrcFn: keepIframeSrcFn,
7802 newlyAddedElement: newlyAddedElement,
7803 rootId: rootId
7804 });
7805 case n2.TEXT_NODE:
7806 return serializeTextNode(n2, {
7807 doc: doc,
7808 needsMask: needsMask,
7809 maskTextFn: maskTextFn,
7810 rootId: rootId,
7811 cssCaptured: cssCaptured
7812 });
7813 case n2.CDATA_SECTION_NODE:
7814 return {
7815 type: NodeType$3.CDATA,
7816 textContent: "",
7817 rootId: rootId
7818 };
7819 case n2.COMMENT_NODE:
7820 return {
7821 type: NodeType$3.Comment,
7822 textContent: index$1.textContent(n2) || "",
7823 rootId: rootId
7824 };
7825 default:
7826 return false;
7827 }
7828 }
7829 function getRootId(doc, mirror2) {
7830 if (!mirror2.hasNode(doc)) return void 0;
7831 var docId = mirror2.getId(doc);
7832 return docId === 1 ? void 0 : docId;
7833 }
7834 function serializeTextNode(n2, options) {
7835 var needsMask = options.needsMask, maskTextFn = options.maskTextFn, rootId = options.rootId, cssCaptured = options.cssCaptured;
7836 var parent = index$1.parentNode(n2);
7837 var parentTagName = parent && parent.tagName;
7838 var textContent2 = "";
7839 var isStyle = parentTagName === "STYLE" ? true : void 0;
7840 var isScript = parentTagName === "SCRIPT" ? true : void 0;
7841 if (isScript) {
7842 textContent2 = "SCRIPT_PLACEHOLDER";
7843 } else if (!cssCaptured) {
7844 textContent2 = index$1.textContent(n2);
7845 if (isStyle && textContent2) {
7846 textContent2 = absolutifyURLs(textContent2, getHref(options.doc));
7847 }
7848 }
7849 if (!isStyle && !isScript && textContent2 && needsMask) {
7850 textContent2 = maskTextFn ? maskTextFn(textContent2, index$1.parentElement(n2)) : textContent2.replace(/[\S]/g, "*");
7851 }
7852 return {
7853 type: NodeType$3.Text,
7854 textContent: textContent2 || "",
7855 rootId: rootId
7856 };
7857 }
7858 function serializeElementNode(n2, options) {
7859 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;
7860 var needBlock = _isBlockedElement(n2, blockClass, blockSelector);
7861 var tagName = getValidTagName$1(n2);
7862 var attributes = {};
7863 var len = n2.attributes.length;
7864 for(var i2 = 0; i2 < len; i2++){
7865 var attr = n2.attributes[i2];
7866 if (!ignoreAttribute(tagName, attr.name, attr.value)) {
7867 attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value);
7868 }
7869 }
7870 if (tagName === "link" && inlineStylesheet) {
7871 var stylesheet = Array.from(doc.styleSheets).find(function(s2) {
7872 return s2.href === n2.href;
7873 });
7874 var cssText = null;
7875 if (stylesheet) {
7876 cssText = stringifyStylesheet(stylesheet);
7877 }
7878 if (cssText) {
7879 delete attributes.rel;
7880 delete attributes.href;
7881 attributes._cssText = cssText;
7882 }
7883 }
7884 if (tagName === "style" && n2.sheet) {
7885 var cssText1 = stringifyStylesheet(n2.sheet);
7886 if (cssText1) {
7887 if (n2.childNodes.length > 1) {
7888 cssText1 = markCssSplits(cssText1, n2);
7889 }
7890 attributes._cssText = cssText1;
7891 }
7892 }
7893 if (tagName === "input" || tagName === "textarea" || tagName === "select") {
7894 var value = n2.value;
7895 var checked = n2.checked;
7896 if (attributes.type !== "radio" && attributes.type !== "checkbox" && attributes.type !== "submit" && attributes.type !== "button" && value) {
7897 attributes.value = maskInputValue({
7898 element: n2,
7899 type: getInputType(n2),
7900 tagName: tagName,
7901 value: value,
7902 maskInputOptions: maskInputOptions,
7903 maskInputFn: maskInputFn
7904 });
7905 } else if (checked) {
7906 attributes.checked = checked;
7907 }
7908 }
7909 if (tagName === "option") {
7910 if (n2.selected && !maskInputOptions["select"]) {
7911 attributes.selected = true;
7912 } else {
7913 delete attributes.selected;
7914 }
7915 }
7916 if (tagName === "dialog" && n2.open) {
7917 attributes.rr_open_mode = n2.matches("dialog:modal") ? "modal" : "non-modal";
7918 }
7919 if (tagName === "canvas" && recordCanvas) {
7920 if (n2.__context === "2d") {
7921 if (!is2DCanvasBlank(n2)) {
7922 attributes.rr_dataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7923 }
7924 } else if (!("__context" in n2)) {
7925 var canvasDataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7926 var blankCanvas = doc.createElement("canvas");
7927 blankCanvas.width = n2.width;
7928 blankCanvas.height = n2.height;
7929 var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7930 if (canvasDataURL !== blankCanvasDataURL) {
7931 attributes.rr_dataURL = canvasDataURL;
7932 }
7933 }
7934 }
7935 if (tagName === "img" && inlineImages) {
7936 if (!canvasService) {
7937 canvasService = doc.createElement("canvas");
7938 canvasCtx = canvasService.getContext("2d");
7939 }
7940 var image = n2;
7941 var imageSrc = image.currentSrc || image.getAttribute("src") || "<unknown-src>";
7942 var priorCrossOrigin = image.crossOrigin;
7943 var recordInlineImage = function() {
7944 image.removeEventListener("load", recordInlineImage);
7945 try {
7946 canvasService.width = image.naturalWidth;
7947 canvasService.height = image.naturalHeight;
7948 canvasCtx.drawImage(image, 0, 0);
7949 attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
7950 } catch (err) {
7951 if (image.crossOrigin !== "anonymous") {
7952 image.crossOrigin = "anonymous";
7953 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
7954 else image.addEventListener("load", recordInlineImage);
7955 return;
7956 } else {
7957 console.warn("Cannot inline img src=" + imageSrc + "! Error: " + err);
7958 }
7959 }
7960 if (image.crossOrigin === "anonymous") {
7961 priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute("crossorigin");
7962 }
7963 };
7964 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
7965 else image.addEventListener("load", recordInlineImage);
7966 }
7967 if (tagName === "audio" || tagName === "video") {
7968 var mediaAttributes = attributes;
7969 mediaAttributes.rr_mediaState = n2.paused ? "paused" : "played";
7970 mediaAttributes.rr_mediaCurrentTime = n2.currentTime;
7971 mediaAttributes.rr_mediaPlaybackRate = n2.playbackRate;
7972 mediaAttributes.rr_mediaMuted = n2.muted;
7973 mediaAttributes.rr_mediaLoop = n2.loop;
7974 mediaAttributes.rr_mediaVolume = n2.volume;
7975 }
7976 if (!newlyAddedElement) {
7977 if (n2.scrollLeft) {
7978 attributes.rr_scrollLeft = n2.scrollLeft;
7979 }
7980 if (n2.scrollTop) {
7981 attributes.rr_scrollTop = n2.scrollTop;
7982 }
7983 }
7984 if (needBlock) {
7985 var _n2_getBoundingClientRect = n2.getBoundingClientRect(), width = _n2_getBoundingClientRect.width, height = _n2_getBoundingClientRect.height;
7986 attributes = {
7987 class: attributes.class,
7988 rr_width: "" + width + "px",
7989 rr_height: "" + height + "px"
7990 };
7991 }
7992 if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
7993 if (!n2.contentDocument) {
7994 attributes.rr_src = attributes.src;
7995 }
7996 delete attributes.src;
7997 }
7998 var isCustomElement;
7999 try {
8000 if (customElements.get(tagName)) isCustomElement = true;
8001 } catch (e2) {}
8002 return {
8003 type: NodeType$3.Element,
8004 tagName: tagName,
8005 attributes: attributes,
8006 childNodes: [],
8007 isSVG: isSVGElement(n2) || void 0,
8008 needBlock: needBlock,
8009 rootId: rootId,
8010 isCustom: isCustomElement
8011 };
8012 }
8013 function lowerIfExists(maybeAttr) {
8014 if (maybeAttr === void 0 || maybeAttr === null) {
8015 return "";
8016 } else {
8017 return maybeAttr.toLowerCase();
8018 }
8019 }
8020 function slimDOMExcluded(sn, slimDOMOptions) {
8021 if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) {
8022 return true;
8023 } else if (sn.type === NodeType$3.Element) {
8024 if (slimDOMOptions.script && // script tag
8025 (sn.tagName === "script" || // (module)preload link
8026 sn.tagName === "link" && (sn.attributes.rel === "preload" && sn.attributes.as === "script" || sn.attributes.rel === "modulepreload") || // prefetch link
8027 sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) {
8028 return true;
8029 } 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"))) {
8030 return true;
8031 } else if (sn.tagName === "meta") {
8032 if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
8033 return true;
8034 } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)
8035 lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) {
8036 return true;
8037 } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) {
8038 return true;
8039 } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) {
8040 return true;
8041 } 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:/))) {
8042 return true;
8043 } 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")) {
8044 return true;
8045 }
8046 }
8047 }
8048 return false;
8049 }
8050 function serializeNodeWithId(n2, options) {
8051 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() {
8052 return false;
8053 } : _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;
8054 var needsMask = options.needsMask;
8055 var _options_preserveWhiteSpace = options.preserveWhiteSpace, preserveWhiteSpace = _options_preserveWhiteSpace === void 0 ? true : _options_preserveWhiteSpace;
8056 if (!needsMask) {
8057 var checkAncestors = needsMask === void 0;
8058 needsMask = needMaskingText(n2, maskTextClass, maskTextSelector, checkAncestors);
8059 }
8060 var _serializedNode = serializeNode(n2, {
8061 doc: doc,
8062 mirror: mirror2,
8063 blockClass: blockClass,
8064 blockSelector: blockSelector,
8065 needsMask: needsMask,
8066 inlineStylesheet: inlineStylesheet,
8067 maskInputOptions: maskInputOptions,
8068 maskTextFn: maskTextFn,
8069 maskInputFn: maskInputFn,
8070 dataURLOptions: dataURLOptions,
8071 inlineImages: inlineImages,
8072 recordCanvas: recordCanvas,
8073 keepIframeSrcFn: keepIframeSrcFn,
8074 newlyAddedElement: newlyAddedElement,
8075 cssCaptured: cssCaptured
8076 });
8077 if (!_serializedNode) {
8078 console.warn(n2, "not serialized");
8079 return null;
8080 }
8081 var id;
8082 if (mirror2.hasNode(n2)) {
8083 id = mirror2.getId(n2);
8084 } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$3.Text && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) {
8085 id = IGNORED_NODE;
8086 } else {
8087 id = genId();
8088 }
8089 var serializedNode = Object.assign(_serializedNode, {
8090 id: id
8091 });
8092 mirror2.add(n2, serializedNode);
8093 if (id === IGNORED_NODE) {
8094 return null;
8095 }
8096 if (onSerialize) {
8097 onSerialize(n2);
8098 }
8099 var recordChild = !skipChild;
8100 if (serializedNode.type === NodeType$3.Element) {
8101 recordChild = recordChild && !serializedNode.needBlock;
8102 delete serializedNode.needBlock;
8103 var shadowRootEl = index$1.shadowRoot(n2);
8104 if (shadowRootEl && isNativeShadowDom(shadowRootEl)) serializedNode.isShadowHost = true;
8105 }
8106 if ((serializedNode.type === NodeType$3.Document || serializedNode.type === NodeType$3.Element) && recordChild) {
8107 if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType$3.Element && serializedNode.tagName === "head") {
8108 preserveWhiteSpace = false;
8109 }
8110 var bypassOptions = {
8111 doc: doc,
8112 mirror: mirror2,
8113 blockClass: blockClass,
8114 blockSelector: blockSelector,
8115 needsMask: needsMask,
8116 maskTextClass: maskTextClass,
8117 maskTextSelector: maskTextSelector,
8118 skipChild: skipChild,
8119 inlineStylesheet: inlineStylesheet,
8120 maskInputOptions: maskInputOptions,
8121 maskTextFn: maskTextFn,
8122 maskInputFn: maskInputFn,
8123 slimDOMOptions: slimDOMOptions,
8124 dataURLOptions: dataURLOptions,
8125 inlineImages: inlineImages,
8126 recordCanvas: recordCanvas,
8127 preserveWhiteSpace: preserveWhiteSpace,
8128 onSerialize: onSerialize,
8129 onIframeLoad: onIframeLoad,
8130 iframeLoadTimeout: iframeLoadTimeout,
8131 onStylesheetLoad: onStylesheetLoad,
8132 stylesheetLoadTimeout: stylesheetLoadTimeout,
8133 keepIframeSrcFn: keepIframeSrcFn,
8134 cssCaptured: false
8135 };
8136 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "textarea" && serializedNode.attributes.value !== void 0) ;
8137 else {
8138 if (serializedNode.type === NodeType$3.Element && serializedNode.attributes._cssText !== void 0 && typeof serializedNode.attributes._cssText === "string") {
8139 bypassOptions.cssCaptured = true;
8140 }
8141 for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(n2))), _step; !(_step = _iterator()).done;){
8142 var childN = _step.value;
8143 var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
8144 if (serializedChildNode) {
8145 serializedNode.childNodes.push(serializedChildNode);
8146 }
8147 }
8148 }
8149 var shadowRootEl1 = null;
8150 if (isElement(n2) && (shadowRootEl1 = index$1.shadowRoot(n2))) {
8151 for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(shadowRootEl1))), _step1; !(_step1 = _iterator1()).done;){
8152 var childN1 = _step1.value;
8153 var serializedChildNode1 = serializeNodeWithId(childN1, bypassOptions);
8154 if (serializedChildNode1) {
8155 isNativeShadowDom(shadowRootEl1) && (serializedChildNode1.isShadow = true);
8156 serializedNode.childNodes.push(serializedChildNode1);
8157 }
8158 }
8159 }
8160 }
8161 var parent = index$1.parentNode(n2);
8162 if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {
8163 serializedNode.isShadow = true;
8164 }
8165 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "iframe") {
8166 onceIframeLoaded(n2, function() {
8167 var iframeDoc = n2.contentDocument;
8168 if (iframeDoc && onIframeLoad) {
8169 var serializedIframeNode = serializeNodeWithId(iframeDoc, {
8170 doc: iframeDoc,
8171 mirror: mirror2,
8172 blockClass: blockClass,
8173 blockSelector: blockSelector,
8174 needsMask: needsMask,
8175 maskTextClass: maskTextClass,
8176 maskTextSelector: maskTextSelector,
8177 skipChild: false,
8178 inlineStylesheet: inlineStylesheet,
8179 maskInputOptions: maskInputOptions,
8180 maskTextFn: maskTextFn,
8181 maskInputFn: maskInputFn,
8182 slimDOMOptions: slimDOMOptions,
8183 dataURLOptions: dataURLOptions,
8184 inlineImages: inlineImages,
8185 recordCanvas: recordCanvas,
8186 preserveWhiteSpace: preserveWhiteSpace,
8187 onSerialize: onSerialize,
8188 onIframeLoad: onIframeLoad,
8189 iframeLoadTimeout: iframeLoadTimeout,
8190 onStylesheetLoad: onStylesheetLoad,
8191 stylesheetLoadTimeout: stylesheetLoadTimeout,
8192 keepIframeSrcFn: keepIframeSrcFn
8193 });
8194 if (serializedIframeNode) {
8195 onIframeLoad(n2, serializedIframeNode);
8196 }
8197 }
8198 }, iframeLoadTimeout);
8199 }
8200 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")) {
8201 onceStylesheetLoaded(n2, function() {
8202 if (onStylesheetLoad) {
8203 var serializedLinkNode = serializeNodeWithId(n2, {
8204 doc: doc,
8205 mirror: mirror2,
8206 blockClass: blockClass,
8207 blockSelector: blockSelector,
8208 needsMask: needsMask,
8209 maskTextClass: maskTextClass,
8210 maskTextSelector: maskTextSelector,
8211 skipChild: false,
8212 inlineStylesheet: inlineStylesheet,
8213 maskInputOptions: maskInputOptions,
8214 maskTextFn: maskTextFn,
8215 maskInputFn: maskInputFn,
8216 slimDOMOptions: slimDOMOptions,
8217 dataURLOptions: dataURLOptions,
8218 inlineImages: inlineImages,
8219 recordCanvas: recordCanvas,
8220 preserveWhiteSpace: preserveWhiteSpace,
8221 onSerialize: onSerialize,
8222 onIframeLoad: onIframeLoad,
8223 iframeLoadTimeout: iframeLoadTimeout,
8224 onStylesheetLoad: onStylesheetLoad,
8225 stylesheetLoadTimeout: stylesheetLoadTimeout,
8226 keepIframeSrcFn: keepIframeSrcFn
8227 });
8228 if (serializedLinkNode) {
8229 onStylesheetLoad(n2, serializedLinkNode);
8230 }
8231 }
8232 }, stylesheetLoadTimeout);
8233 }
8234 return serializedNode;
8235 }
8236 function snapshot(n2, options) {
8237 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() {
8238 return false;
8239 } : _ref_keepIframeSrcFn;
8240 var maskInputOptions = maskAllInputs === true ? {
8241 color: true,
8242 date: true,
8243 "datetime-local": true,
8244 email: true,
8245 month: true,
8246 number: true,
8247 range: true,
8248 search: true,
8249 tel: true,
8250 text: true,
8251 time: true,
8252 url: true,
8253 week: true,
8254 textarea: true,
8255 select: true,
8256 password: true,
8257 hidden: true
8258 } : maskAllInputs === false ? {
8259 password: true
8260 } : maskAllInputs;
8261 var slimDOMOptions = slimDOM === true || slimDOM === "all" ? // if true: set of sensible options that should not throw away any information
8262 {
8263 script: true,
8264 comment: true,
8265 headFavicon: true,
8266 headWhitespace: true,
8267 headMetaDescKeywords: slimDOM === "all",
8268 // destructive
8269 headMetaSocial: true,
8270 headMetaRobots: true,
8271 headMetaHttpEquiv: true,
8272 headMetaAuthorship: true,
8273 headMetaVerification: true
8274 } : slimDOM === false ? {} : slimDOM;
8275 return serializeNodeWithId(n2, {
8276 doc: n2,
8277 mirror: mirror2,
8278 blockClass: blockClass,
8279 blockSelector: blockSelector,
8280 maskTextClass: maskTextClass,
8281 maskTextSelector: maskTextSelector,
8282 skipChild: false,
8283 inlineStylesheet: inlineStylesheet,
8284 maskInputOptions: maskInputOptions,
8285 maskTextFn: maskTextFn,
8286 maskInputFn: maskInputFn,
8287 slimDOMOptions: slimDOMOptions,
8288 dataURLOptions: dataURLOptions,
8289 inlineImages: inlineImages,
8290 recordCanvas: recordCanvas,
8291 preserveWhiteSpace: preserveWhiteSpace,
8292 onSerialize: onSerialize,
8293 onIframeLoad: onIframeLoad,
8294 iframeLoadTimeout: iframeLoadTimeout,
8295 onStylesheetLoad: onStylesheetLoad,
8296 stylesheetLoadTimeout: stylesheetLoadTimeout,
8297 keepIframeSrcFn: keepIframeSrcFn,
8298 newlyAddedElement: false
8299 });
8300 }
8301 function getDefaultExportFromCjs$1(x2) {
8302 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
8303 }
8304 function getAugmentedNamespace$1(n2) {
8305 if (n2.__esModule) return n2;
8306 var f2 = n2.default;
8307 if (typeof f2 == "function") {
8308 var a2 = function a22() {
8309 if (_instanceof(this, a22)) {
8310 return Reflect.construct(f2, arguments, this.constructor);
8311 }
8312 return f2.apply(this, arguments);
8313 };
8314 a2.prototype = f2.prototype;
8315 } else a2 = {};
8316 Object.defineProperty(a2, "__esModule", {
8317 value: true
8318 });
8319 Object.keys(n2).forEach(function(k) {
8320 var d = Object.getOwnPropertyDescriptor(n2, k);
8321 Object.defineProperty(a2, k, d.get ? d : {
8322 enumerable: true,
8323 get: function get() {
8324 return n2[k];
8325 }
8326 });
8327 });
8328 return a2;
8329 }
8330 var picocolors_browser$1 = {
8331 exports: {}
8332 };
8333 var x$1 = String;
8334 var create$1 = function create$1() {
8335 return {
8336 isColorSupported: false,
8337 reset: x$1,
8338 bold: x$1,
8339 dim: x$1,
8340 italic: x$1,
8341 underline: x$1,
8342 inverse: x$1,
8343 hidden: x$1,
8344 strikethrough: x$1,
8345 black: x$1,
8346 red: x$1,
8347 green: x$1,
8348 yellow: x$1,
8349 blue: x$1,
8350 magenta: x$1,
8351 cyan: x$1,
8352 white: x$1,
8353 gray: x$1,
8354 bgBlack: x$1,
8355 bgRed: x$1,
8356 bgGreen: x$1,
8357 bgYellow: x$1,
8358 bgBlue: x$1,
8359 bgMagenta: x$1,
8360 bgCyan: x$1,
8361 bgWhite: x$1
8362 };
8363 };
8364 picocolors_browser$1.exports = create$1();
8365 picocolors_browser$1.exports.createColors = create$1;
8366 var picocolors_browserExports$1 = picocolors_browser$1.exports;
8367 var __viteBrowserExternal$2 = {};
8368 var __viteBrowserExternal$1$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
8369 __proto__: null,
8370 default: __viteBrowserExternal$2
8371 }, Symbol.toStringTag, {
8372 value: "Module"
8373 }));
8374 var require$$2$1 = /* @__PURE__ */ getAugmentedNamespace$1(__viteBrowserExternal$1$1);
8375 var pico$1 = picocolors_browserExports$1;
8376 var terminalHighlight$1$1 = require$$2$1;
8377 var CssSyntaxError$3$1 = /*#__PURE__*/ function(Error1) {
8378 _inherits(CssSyntaxError, Error1);
8379 function CssSyntaxError(message, line, column, source, file, plugin22) {
8380 var _this;
8381 _this = Error1.call(this, message) || this;
8382 _this.name = "CssSyntaxError";
8383 _this.reason = message;
8384 if (file) {
8385 _this.file = file;
8386 }
8387 if (source) {
8388 _this.source = source;
8389 }
8390 if (plugin22) {
8391 _this.plugin = plugin22;
8392 }
8393 if (typeof line !== "undefined" && typeof column !== "undefined") {
8394 if (typeof line === "number") {
8395 _this.line = line;
8396 _this.column = column;
8397 } else {
8398 _this.line = line.line;
8399 _this.column = line.column;
8400 _this.endLine = column.line;
8401 _this.endColumn = column.column;
8402 }
8403 }
8404 _this.setMessage();
8405 if (Error.captureStackTrace) {
8406 Error.captureStackTrace(_this, CssSyntaxError);
8407 }
8408 return _this;
8409 }
8410 var _proto = CssSyntaxError.prototype;
8411 _proto.setMessage = function setMessage() {
8412 this.message = this.plugin ? this.plugin + ": " : "";
8413 this.message += this.file ? this.file : "<css input>";
8414 if (typeof this.line !== "undefined") {
8415 this.message += ":" + this.line + ":" + this.column;
8416 }
8417 this.message += ": " + this.reason;
8418 };
8419 _proto.showSourceCode = function showSourceCode(color) {
8420 var _this = this;
8421 if (!this.source) return "";
8422 var css = this.source;
8423 if (color == null) color = pico$1.isColorSupported;
8424 if (terminalHighlight$1$1) {
8425 if (color) css = terminalHighlight$1$1(css);
8426 }
8427 var lines = css.split(/\r?\n/);
8428 var start = Math.max(this.line - 3, 0);
8429 var end = Math.min(this.line + 2, lines.length);
8430 var maxWidth = String(end).length;
8431 var mark, aside;
8432 if (color) {
8433 var _pico$1_createColors = pico$1.createColors(true), bold = _pico$1_createColors.bold, gray = _pico$1_createColors.gray, red = _pico$1_createColors.red;
8434 mark = function(text) {
8435 return bold(red(text));
8436 };
8437 aside = function(text) {
8438 return gray(text);
8439 };
8440 } else {
8441 mark = aside = function(str) {
8442 return str;
8443 };
8444 }
8445 return lines.slice(start, end).map(function(line, index2) {
8446 var number = start + 1 + index2;
8447 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
8448 if (number === _this.line) {
8449 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
8450 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
8451 }
8452 return " " + aside(gutter) + line;
8453 }).join("\n");
8454 };
8455 _proto.toString = function toString() {
8456 var code = this.showSourceCode();
8457 if (code) {
8458 code = "\n\n" + code + "\n";
8459 }
8460 return this.name + ": " + this.message + code;
8461 };
8462 return CssSyntaxError;
8463 }(_wrap_native_super(Error));
8464 var cssSyntaxError$1 = CssSyntaxError$3$1;
8465 CssSyntaxError$3$1.default = CssSyntaxError$3$1;
8466 var symbols$1 = {};
8467 symbols$1.isClean = Symbol("isClean");
8468 symbols$1.my = Symbol("my");
8469 var DEFAULT_RAW$1 = {
8470 after: "\n",
8471 beforeClose: "\n",
8472 beforeComment: "\n",
8473 beforeDecl: "\n",
8474 beforeOpen: " ",
8475 beforeRule: "\n",
8476 colon: ": ",
8477 commentLeft: " ",
8478 commentRight: " ",
8479 emptyBody: "",
8480 indent: " ",
8481 semicolon: false
8482 };
8483 function capitalize$1(str) {
8484 return str[0].toUpperCase() + str.slice(1);
8485 }
8486 var Stringifier$2$1 = /*#__PURE__*/ function() {
8487 function Stringifier(builder) {
8488 this.builder = builder;
8489 }
8490 var _proto = Stringifier.prototype;
8491 _proto.atrule = function atrule(node2, semicolon) {
8492 var name = "@" + node2.name;
8493 var params = node2.params ? this.rawValue(node2, "params") : "";
8494 if (typeof node2.raws.afterName !== "undefined") {
8495 name += node2.raws.afterName;
8496 } else if (params) {
8497 name += " ";
8498 }
8499 if (node2.nodes) {
8500 this.block(node2, name + params);
8501 } else {
8502 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
8503 this.builder(name + params + end, node2);
8504 }
8505 };
8506 _proto.beforeAfter = function beforeAfter(node2, detect) {
8507 var value;
8508 if (node2.type === "decl") {
8509 value = this.raw(node2, null, "beforeDecl");
8510 } else if (node2.type === "comment") {
8511 value = this.raw(node2, null, "beforeComment");
8512 } else if (detect === "before") {
8513 value = this.raw(node2, null, "beforeRule");
8514 } else {
8515 value = this.raw(node2, null, "beforeClose");
8516 }
8517 var buf = node2.parent;
8518 var depth = 0;
8519 while(buf && buf.type !== "root"){
8520 depth += 1;
8521 buf = buf.parent;
8522 }
8523 if (value.includes("\n")) {
8524 var indent = this.raw(node2, null, "indent");
8525 if (indent.length) {
8526 for(var step = 0; step < depth; step++)value += indent;
8527 }
8528 }
8529 return value;
8530 };
8531 _proto.block = function block(node2, start) {
8532 var between = this.raw(node2, "between", "beforeOpen");
8533 this.builder(start + between + "{", node2, "start");
8534 var after;
8535 if (node2.nodes && node2.nodes.length) {
8536 this.body(node2);
8537 after = this.raw(node2, "after");
8538 } else {
8539 after = this.raw(node2, "after", "emptyBody");
8540 }
8541 if (after) this.builder(after);
8542 this.builder("}", node2, "end");
8543 };
8544 _proto.body = function body(node2) {
8545 var last = node2.nodes.length - 1;
8546 while(last > 0){
8547 if (node2.nodes[last].type !== "comment") break;
8548 last -= 1;
8549 }
8550 var semicolon = this.raw(node2, "semicolon");
8551 for(var i2 = 0; i2 < node2.nodes.length; i2++){
8552 var child = node2.nodes[i2];
8553 var before = this.raw(child, "before");
8554 if (before) this.builder(before);
8555 this.stringify(child, last !== i2 || semicolon);
8556 }
8557 };
8558 _proto.comment = function comment(node2) {
8559 var left = this.raw(node2, "left", "commentLeft");
8560 var right = this.raw(node2, "right", "commentRight");
8561 this.builder("/*" + left + node2.text + right + "*/", node2);
8562 };
8563 _proto.decl = function decl(node2, semicolon) {
8564 var between = this.raw(node2, "between", "colon");
8565 var string = node2.prop + between + this.rawValue(node2, "value");
8566 if (node2.important) {
8567 string += node2.raws.important || " !important";
8568 }
8569 if (semicolon) string += ";";
8570 this.builder(string, node2);
8571 };
8572 _proto.document = function document1(node2) {
8573 this.body(node2);
8574 };
8575 _proto.raw = function raw(node2, own, detect) {
8576 var value;
8577 if (!detect) detect = own;
8578 if (own) {
8579 value = node2.raws[own];
8580 if (typeof value !== "undefined") return value;
8581 }
8582 var parent = node2.parent;
8583 if (detect === "before") {
8584 if (!parent || parent.type === "root" && parent.first === node2) {
8585 return "";
8586 }
8587 if (parent && parent.type === "document") {
8588 return "";
8589 }
8590 }
8591 if (!parent) return DEFAULT_RAW$1[detect];
8592 var root2 = node2.root();
8593 if (!root2.rawCache) root2.rawCache = {};
8594 if (typeof root2.rawCache[detect] !== "undefined") {
8595 return root2.rawCache[detect];
8596 }
8597 if (detect === "before" || detect === "after") {
8598 return this.beforeAfter(node2, detect);
8599 } else {
8600 var method = "raw" + capitalize$1(detect);
8601 if (this[method]) {
8602 value = this[method](root2, node2);
8603 } else {
8604 root2.walk(function(i2) {
8605 value = i2.raws[own];
8606 if (typeof value !== "undefined") return false;
8607 });
8608 }
8609 }
8610 if (typeof value === "undefined") value = DEFAULT_RAW$1[detect];
8611 root2.rawCache[detect] = value;
8612 return value;
8613 };
8614 _proto.rawBeforeClose = function rawBeforeClose(root2) {
8615 var value;
8616 root2.walk(function(i2) {
8617 if (i2.nodes && i2.nodes.length > 0) {
8618 if (typeof i2.raws.after !== "undefined") {
8619 value = i2.raws.after;
8620 if (value.includes("\n")) {
8621 value = value.replace(/[^\n]+$/, "");
8622 }
8623 return false;
8624 }
8625 }
8626 });
8627 if (value) value = value.replace(/\S/g, "");
8628 return value;
8629 };
8630 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
8631 var value;
8632 root2.walkComments(function(i2) {
8633 if (typeof i2.raws.before !== "undefined") {
8634 value = i2.raws.before;
8635 if (value.includes("\n")) {
8636 value = value.replace(/[^\n]+$/, "");
8637 }
8638 return false;
8639 }
8640 });
8641 if (typeof value === "undefined") {
8642 value = this.raw(node2, null, "beforeDecl");
8643 } else if (value) {
8644 value = value.replace(/\S/g, "");
8645 }
8646 return value;
8647 };
8648 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
8649 var value;
8650 root2.walkDecls(function(i2) {
8651 if (typeof i2.raws.before !== "undefined") {
8652 value = i2.raws.before;
8653 if (value.includes("\n")) {
8654 value = value.replace(/[^\n]+$/, "");
8655 }
8656 return false;
8657 }
8658 });
8659 if (typeof value === "undefined") {
8660 value = this.raw(node2, null, "beforeRule");
8661 } else if (value) {
8662 value = value.replace(/\S/g, "");
8663 }
8664 return value;
8665 };
8666 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
8667 var value;
8668 root2.walk(function(i2) {
8669 if (i2.type !== "decl") {
8670 value = i2.raws.between;
8671 if (typeof value !== "undefined") return false;
8672 }
8673 });
8674 return value;
8675 };
8676 _proto.rawBeforeRule = function rawBeforeRule(root2) {
8677 var value;
8678 root2.walk(function(i2) {
8679 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
8680 if (typeof i2.raws.before !== "undefined") {
8681 value = i2.raws.before;
8682 if (value.includes("\n")) {
8683 value = value.replace(/[^\n]+$/, "");
8684 }
8685 return false;
8686 }
8687 }
8688 });
8689 if (value) value = value.replace(/\S/g, "");
8690 return value;
8691 };
8692 _proto.rawColon = function rawColon(root2) {
8693 var value;
8694 root2.walkDecls(function(i2) {
8695 if (typeof i2.raws.between !== "undefined") {
8696 value = i2.raws.between.replace(/[^\s:]/g, "");
8697 return false;
8698 }
8699 });
8700 return value;
8701 };
8702 _proto.rawEmptyBody = function rawEmptyBody(root2) {
8703 var value;
8704 root2.walk(function(i2) {
8705 if (i2.nodes && i2.nodes.length === 0) {
8706 value = i2.raws.after;
8707 if (typeof value !== "undefined") return false;
8708 }
8709 });
8710 return value;
8711 };
8712 _proto.rawIndent = function rawIndent(root2) {
8713 if (root2.raws.indent) return root2.raws.indent;
8714 var value;
8715 root2.walk(function(i2) {
8716 var p = i2.parent;
8717 if (p && p !== root2 && p.parent && p.parent === root2) {
8718 if (typeof i2.raws.before !== "undefined") {
8719 var parts = i2.raws.before.split("\n");
8720 value = parts[parts.length - 1];
8721 value = value.replace(/\S/g, "");
8722 return false;
8723 }
8724 }
8725 });
8726 return value;
8727 };
8728 _proto.rawSemicolon = function rawSemicolon(root2) {
8729 var value;
8730 root2.walk(function(i2) {
8731 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
8732 value = i2.raws.semicolon;
8733 if (typeof value !== "undefined") return false;
8734 }
8735 });
8736 return value;
8737 };
8738 _proto.rawValue = function rawValue(node2, prop) {
8739 var value = node2[prop];
8740 var raw = node2.raws[prop];
8741 if (raw && raw.value === value) {
8742 return raw.raw;
8743 }
8744 return value;
8745 };
8746 _proto.root = function root(node2) {
8747 this.body(node2);
8748 if (node2.raws.after) this.builder(node2.raws.after);
8749 };
8750 _proto.rule = function rule(node2) {
8751 this.block(node2, this.rawValue(node2, "selector"));
8752 if (node2.raws.ownSemicolon) {
8753 this.builder(node2.raws.ownSemicolon, node2, "end");
8754 }
8755 };
8756 _proto.stringify = function stringify(node2, semicolon) {
8757 if (!this[node2.type]) {
8758 throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
8759 }
8760 this[node2.type](node2, semicolon);
8761 };
8762 return Stringifier;
8763 }();
8764 var stringifier$1 = Stringifier$2$1;
8765 Stringifier$2$1.default = Stringifier$2$1;
8766 var Stringifier$1$1 = stringifier$1;
8767 function stringify$4$1(node2, builder) {
8768 var str = new Stringifier$1$1(builder);
8769 str.stringify(node2);
8770 }
8771 var stringify_1$1 = stringify$4$1;
8772 stringify$4$1.default = stringify$4$1;
8773 var isClean$2$1 = symbols$1.isClean, my$2$1 = symbols$1.my;
8774 var CssSyntaxError$2$1 = cssSyntaxError$1;
8775 var Stringifier2$1 = stringifier$1;
8776 var stringify$3$1 = stringify_1$1;
8777 function cloneNode$1(obj, parent) {
8778 var cloned = new obj.constructor();
8779 for(var i2 in obj){
8780 if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
8781 continue;
8782 }
8783 if (i2 === "proxyCache") continue;
8784 var value = obj[i2];
8785 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
8786 if (i2 === "parent" && type === "object") {
8787 if (parent) cloned[i2] = parent;
8788 } else if (i2 === "source") {
8789 cloned[i2] = value;
8790 } else if (Array.isArray(value)) {
8791 cloned[i2] = value.map(function(j) {
8792 return cloneNode$1(j, cloned);
8793 });
8794 } else {
8795 if (type === "object" && value !== null) value = cloneNode$1(value);
8796 cloned[i2] = value;
8797 }
8798 }
8799 return cloned;
8800 }
8801 var Node$4$1 = /*#__PURE__*/ function() {
8802 function Node2(defaults) {
8803 if (defaults === void 0) defaults = {};
8804 this.raws = {};
8805 this[isClean$2$1] = false;
8806 this[my$2$1] = true;
8807 for(var name in defaults){
8808 if (name === "nodes") {
8809 this.nodes = [];
8810 for(var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;){
8811 var node2 = _step.value;
8812 if (typeof node2.clone === "function") {
8813 this.append(node2.clone());
8814 } else {
8815 this.append(node2);
8816 }
8817 }
8818 } else {
8819 this[name] = defaults[name];
8820 }
8821 }
8822 }
8823 var _proto = Node2.prototype;
8824 _proto.addToError = function addToError(error) {
8825 error.postcssNode = this;
8826 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
8827 var s2 = this.source;
8828 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
8829 }
8830 return error;
8831 };
8832 _proto.after = function after(add) {
8833 this.parent.insertAfter(this, add);
8834 return this;
8835 };
8836 _proto.assign = function assign(overrides) {
8837 if (overrides === void 0) overrides = {};
8838 for(var name in overrides){
8839 this[name] = overrides[name];
8840 }
8841 return this;
8842 };
8843 _proto.before = function before(add) {
8844 this.parent.insertBefore(this, add);
8845 return this;
8846 };
8847 _proto.cleanRaws = function cleanRaws(keepBetween) {
8848 delete this.raws.before;
8849 delete this.raws.after;
8850 if (!keepBetween) delete this.raws.between;
8851 };
8852 _proto.clone = function clone(overrides) {
8853 if (overrides === void 0) overrides = {};
8854 var cloned = cloneNode$1(this);
8855 for(var name in overrides){
8856 cloned[name] = overrides[name];
8857 }
8858 return cloned;
8859 };
8860 _proto.cloneAfter = function cloneAfter(overrides) {
8861 if (overrides === void 0) overrides = {};
8862 var cloned = this.clone(overrides);
8863 this.parent.insertAfter(this, cloned);
8864 return cloned;
8865 };
8866 _proto.cloneBefore = function cloneBefore(overrides) {
8867 if (overrides === void 0) overrides = {};
8868 var cloned = this.clone(overrides);
8869 this.parent.insertBefore(this, cloned);
8870 return cloned;
8871 };
8872 _proto.error = function error(message, opts) {
8873 if (opts === void 0) opts = {};
8874 if (this.source) {
8875 var _this_rangeBy = this.rangeBy(opts), end = _this_rangeBy.end, start = _this_rangeBy.start;
8876 return this.source.input.error(message, {
8877 column: start.column,
8878 line: start.line
8879 }, {
8880 column: end.column,
8881 line: end.line
8882 }, opts);
8883 }
8884 return new CssSyntaxError$2$1(message);
8885 };
8886 _proto.getProxyProcessor = function getProxyProcessor() {
8887 return {
8888 get: function get(node2, prop) {
8889 if (prop === "proxyOf") {
8890 return node2;
8891 } else if (prop === "root") {
8892 return function() {
8893 return node2.root().toProxy();
8894 };
8895 } else {
8896 return node2[prop];
8897 }
8898 },
8899 set: function set(node2, prop, value) {
8900 if (node2[prop] === value) return true;
8901 node2[prop] = value;
8902 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */ prop === "text") {
8903 node2.markDirty();
8904 }
8905 return true;
8906 }
8907 };
8908 };
8909 _proto.markDirty = function markDirty() {
8910 if (this[isClean$2$1]) {
8911 this[isClean$2$1] = false;
8912 var next = this;
8913 while(next = next.parent){
8914 next[isClean$2$1] = false;
8915 }
8916 }
8917 };
8918 _proto.next = function next() {
8919 if (!this.parent) return void 0;
8920 var index2 = this.parent.index(this);
8921 return this.parent.nodes[index2 + 1];
8922 };
8923 _proto.positionBy = function positionBy(opts, stringRepresentation) {
8924 var pos = this.source.start;
8925 if (opts.index) {
8926 pos = this.positionInside(opts.index, stringRepresentation);
8927 } else if (opts.word) {
8928 stringRepresentation = this.toString();
8929 var index2 = stringRepresentation.indexOf(opts.word);
8930 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
8931 }
8932 return pos;
8933 };
8934 _proto.positionInside = function positionInside(index2, stringRepresentation) {
8935 var string = stringRepresentation || this.toString();
8936 var column = this.source.start.column;
8937 var line = this.source.start.line;
8938 for(var i2 = 0; i2 < index2; i2++){
8939 if (string[i2] === "\n") {
8940 column = 1;
8941 line += 1;
8942 } else {
8943 column += 1;
8944 }
8945 }
8946 return {
8947 column: column,
8948 line: line
8949 };
8950 };
8951 _proto.prev = function prev() {
8952 if (!this.parent) return void 0;
8953 var index2 = this.parent.index(this);
8954 return this.parent.nodes[index2 - 1];
8955 };
8956 _proto.rangeBy = function rangeBy(opts) {
8957 var start = {
8958 column: this.source.start.column,
8959 line: this.source.start.line
8960 };
8961 var end = this.source.end ? {
8962 column: this.source.end.column + 1,
8963 line: this.source.end.line
8964 } : {
8965 column: start.column + 1,
8966 line: start.line
8967 };
8968 if (opts.word) {
8969 var stringRepresentation = this.toString();
8970 var index2 = stringRepresentation.indexOf(opts.word);
8971 if (index2 !== -1) {
8972 start = this.positionInside(index2, stringRepresentation);
8973 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
8974 }
8975 } else {
8976 if (opts.start) {
8977 start = {
8978 column: opts.start.column,
8979 line: opts.start.line
8980 };
8981 } else if (opts.index) {
8982 start = this.positionInside(opts.index);
8983 }
8984 if (opts.end) {
8985 end = {
8986 column: opts.end.column,
8987 line: opts.end.line
8988 };
8989 } else if (typeof opts.endIndex === "number") {
8990 end = this.positionInside(opts.endIndex);
8991 } else if (opts.index) {
8992 end = this.positionInside(opts.index + 1);
8993 }
8994 }
8995 if (end.line < start.line || end.line === start.line && end.column <= start.column) {
8996 end = {
8997 column: start.column + 1,
8998 line: start.line
8999 };
9000 }
9001 return {
9002 end: end,
9003 start: start
9004 };
9005 };
9006 _proto.raw = function raw(prop, defaultType) {
9007 var str = new Stringifier2$1();
9008 return str.raw(this, prop, defaultType);
9009 };
9010 _proto.remove = function remove() {
9011 if (this.parent) {
9012 this.parent.removeChild(this);
9013 }
9014 this.parent = void 0;
9015 return this;
9016 };
9017 _proto.replaceWith = function replaceWith() {
9018 for(var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++){
9019 nodes[_key] = arguments[_key];
9020 }
9021 if (this.parent) {
9022 var bookmark = this;
9023 var foundSelf = false;
9024 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
9025 var node2 = _step.value;
9026 if (node2 === this) {
9027 foundSelf = true;
9028 } else if (foundSelf) {
9029 this.parent.insertAfter(bookmark, node2);
9030 bookmark = node2;
9031 } else {
9032 this.parent.insertBefore(bookmark, node2);
9033 }
9034 }
9035 if (!foundSelf) {
9036 this.remove();
9037 }
9038 }
9039 return this;
9040 };
9041 _proto.root = function root() {
9042 var result2 = this;
9043 while(result2.parent && result2.parent.type !== "document"){
9044 result2 = result2.parent;
9045 }
9046 return result2;
9047 };
9048 _proto.toJSON = function toJSON(_, inputs) {
9049 var fixed = {};
9050 var emitInputs = inputs == null;
9051 inputs = inputs || /* @__PURE__ */ new Map();
9052 var inputsNextIndex = 0;
9053 for(var name in this){
9054 if (!Object.prototype.hasOwnProperty.call(this, name)) {
9055 continue;
9056 }
9057 if (name === "parent" || name === "proxyCache") continue;
9058 var value = this[name];
9059 if (Array.isArray(value)) {
9060 fixed[name] = value.map(function(i2) {
9061 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) {
9062 return i2.toJSON(null, inputs);
9063 } else {
9064 return i2;
9065 }
9066 });
9067 } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) {
9068 fixed[name] = value.toJSON(null, inputs);
9069 } else if (name === "source") {
9070 var inputId = inputs.get(value.input);
9071 if (inputId == null) {
9072 inputId = inputsNextIndex;
9073 inputs.set(value.input, inputsNextIndex);
9074 inputsNextIndex++;
9075 }
9076 fixed[name] = {
9077 end: value.end,
9078 inputId: inputId,
9079 start: value.start
9080 };
9081 } else {
9082 fixed[name] = value;
9083 }
9084 }
9085 if (emitInputs) {
9086 fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
9087 return input2.toJSON();
9088 });
9089 }
9090 return fixed;
9091 };
9092 _proto.toProxy = function toProxy() {
9093 if (!this.proxyCache) {
9094 this.proxyCache = new Proxy(this, this.getProxyProcessor());
9095 }
9096 return this.proxyCache;
9097 };
9098 _proto.toString = function toString(stringifier2) {
9099 if (stringifier2 === void 0) stringifier2 = stringify$3$1;
9100 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
9101 var result2 = "";
9102 stringifier2(this, function(i2) {
9103 result2 += i2;
9104 });
9105 return result2;
9106 };
9107 _proto.warn = function warn(result2, text, opts) {
9108 var data = {
9109 node: this
9110 };
9111 for(var i2 in opts)data[i2] = opts[i2];
9112 return result2.warn(text, data);
9113 };
9114 _create_class(Node2, [
9115 {
9116 key: "proxyOf",
9117 get: function get() {
9118 return this;
9119 }
9120 }
9121 ]);
9122 return Node2;
9123 }();
9124 var node$1 = Node$4$1;
9125 Node$4$1.default = Node$4$1;
9126 var Node$3$1 = node$1;
9127 var Declaration$4$1 = /*#__PURE__*/ function(Node$3$1) {
9128 _inherits(Declaration, Node$3$1);
9129 function Declaration(defaults) {
9130 var _this;
9131 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
9132 defaults = _extends({}, defaults, {
9133 value: String(defaults.value)
9134 });
9135 }
9136 _this = Node$3$1.call(this, defaults) || this;
9137 _this.type = "decl";
9138 return _this;
9139 }
9140 _create_class(Declaration, [
9141 {
9142 key: "variable",
9143 get: function get() {
9144 return this.prop.startsWith("--") || this.prop[0] === "$";
9145 }
9146 }
9147 ]);
9148 return Declaration;
9149 }(Node$3$1);
9150 var declaration$1 = Declaration$4$1;
9151 Declaration$4$1.default = Declaration$4$1;
9152 var urlAlphabet$1 = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
9153 var nanoid$1$1 = function(size) {
9154 if (size === void 0) size = 21;
9155 var id = "";
9156 var i2 = size;
9157 while(i2--){
9158 id += urlAlphabet$1[Math.random() * 64 | 0];
9159 }
9160 return id;
9161 };
9162 var nonSecure$1 = {
9163 nanoid: nanoid$1$1};
9164 var SourceMapConsumer$2$1 = require$$2$1.SourceMapConsumer, SourceMapGenerator$2$1 = require$$2$1.SourceMapGenerator;
9165 var existsSync$1 = require$$2$1.existsSync, readFileSync$1 = require$$2$1.readFileSync;
9166 var dirname$1$1 = require$$2$1.dirname, join$1 = require$$2$1.join;
9167 function fromBase64$1(str) {
9168 if (Buffer) {
9169 return Buffer.from(str, "base64").toString();
9170 } else {
9171 return window.atob(str);
9172 }
9173 }
9174 var PreviousMap$2$1 = /*#__PURE__*/ function() {
9175 function PreviousMap(css, opts) {
9176 if (opts.map === false) return;
9177 this.loadAnnotation(css);
9178 this.inline = this.startWith(this.annotation, "data:");
9179 var prev = opts.map ? opts.map.prev : void 0;
9180 var text = this.loadMap(opts.from, prev);
9181 if (!this.mapFile && opts.from) {
9182 this.mapFile = opts.from;
9183 }
9184 if (this.mapFile) this.root = dirname$1$1(this.mapFile);
9185 if (text) this.text = text;
9186 }
9187 var _proto = PreviousMap.prototype;
9188 _proto.consumer = function consumer() {
9189 if (!this.consumerCache) {
9190 this.consumerCache = new SourceMapConsumer$2$1(this.text);
9191 }
9192 return this.consumerCache;
9193 };
9194 _proto.decodeInline = function decodeInline(text) {
9195 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
9196 var baseUri = /^data:application\/json;base64,/;
9197 var charsetUri = /^data:application\/json;charset=utf-?8,/;
9198 var uri = /^data:application\/json,/;
9199 if (charsetUri.test(text) || uri.test(text)) {
9200 return decodeURIComponent(text.substr(RegExp.lastMatch.length));
9201 }
9202 if (baseCharsetUri.test(text) || baseUri.test(text)) {
9203 return fromBase64$1(text.substr(RegExp.lastMatch.length));
9204 }
9205 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
9206 throw new Error("Unsupported source map encoding " + encoding);
9207 };
9208 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
9209 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
9210 };
9211 _proto.isMap = function isMap(map) {
9212 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
9213 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
9214 };
9215 _proto.loadAnnotation = function loadAnnotation(css) {
9216 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
9217 if (!comments) return;
9218 var start = css.lastIndexOf(comments.pop());
9219 var end = css.indexOf("*/", start);
9220 if (start > -1 && end > -1) {
9221 this.annotation = this.getAnnotationURL(css.substring(start, end));
9222 }
9223 };
9224 _proto.loadFile = function loadFile(path) {
9225 this.root = dirname$1$1(path);
9226 if (existsSync$1(path)) {
9227 this.mapFile = path;
9228 return readFileSync$1(path, "utf-8").toString().trim();
9229 }
9230 };
9231 _proto.loadMap = function loadMap(file, prev) {
9232 if (prev === false) return false;
9233 if (prev) {
9234 if (typeof prev === "string") {
9235 return prev;
9236 } else if (typeof prev === "function") {
9237 var prevPath = prev(file);
9238 if (prevPath) {
9239 var map = this.loadFile(prevPath);
9240 if (!map) {
9241 throw new Error("Unable to load previous source map: " + prevPath.toString());
9242 }
9243 return map;
9244 }
9245 } else if (_instanceof(prev, SourceMapConsumer$2$1)) {
9246 return SourceMapGenerator$2$1.fromSourceMap(prev).toString();
9247 } else if (_instanceof(prev, SourceMapGenerator$2$1)) {
9248 return prev.toString();
9249 } else if (this.isMap(prev)) {
9250 return JSON.stringify(prev);
9251 } else {
9252 throw new Error("Unsupported previous source map format: " + prev.toString());
9253 }
9254 } else if (this.inline) {
9255 return this.decodeInline(this.annotation);
9256 } else if (this.annotation) {
9257 var map1 = this.annotation;
9258 if (file) map1 = join$1(dirname$1$1(file), map1);
9259 return this.loadFile(map1);
9260 }
9261 };
9262 _proto.startWith = function startWith(string, start) {
9263 if (!string) return false;
9264 return string.substr(0, start.length) === start;
9265 };
9266 _proto.withContent = function withContent() {
9267 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
9268 };
9269 return PreviousMap;
9270 }();
9271 var previousMap$1 = PreviousMap$2$1;
9272 PreviousMap$2$1.default = PreviousMap$2$1;
9273 var SourceMapConsumer$1$1 = require$$2$1.SourceMapConsumer, SourceMapGenerator$1$1 = require$$2$1.SourceMapGenerator;
9274 var fileURLToPath$1 = require$$2$1.fileURLToPath, pathToFileURL$1$1 = require$$2$1.pathToFileURL;
9275 var isAbsolute$1 = require$$2$1.isAbsolute, resolve$1$1 = require$$2$1.resolve;
9276 var nanoid$2 = nonSecure$1.nanoid;
9277 var terminalHighlight$2 = require$$2$1;
9278 var CssSyntaxError$1$1 = cssSyntaxError$1;
9279 var PreviousMap$1$1 = previousMap$1;
9280 var fromOffsetCache$1 = Symbol("fromOffsetCache");
9281 var sourceMapAvailable$1$1 = Boolean(SourceMapConsumer$1$1 && SourceMapGenerator$1$1);
9282 var pathAvailable$1$1 = Boolean(resolve$1$1 && isAbsolute$1);
9283 var Input$4$1 = /*#__PURE__*/ function() {
9284 function Input(css, opts) {
9285 if (opts === void 0) opts = {};
9286 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) {
9287 throw new Error("PostCSS received " + css + " instead of CSS string");
9288 }
9289 this.css = css.toString();
9290 if (this.css[0] === "\uFEFF" || this.css[0] === "￾") {
9291 this.hasBOM = true;
9292 this.css = this.css.slice(1);
9293 } else {
9294 this.hasBOM = false;
9295 }
9296 if (opts.from) {
9297 if (!pathAvailable$1$1 || /^\w+:\/\//.test(opts.from) || isAbsolute$1(opts.from)) {
9298 this.file = opts.from;
9299 } else {
9300 this.file = resolve$1$1(opts.from);
9301 }
9302 }
9303 if (pathAvailable$1$1 && sourceMapAvailable$1$1) {
9304 var map = new PreviousMap$1$1(this.css, opts);
9305 if (map.text) {
9306 this.map = map;
9307 var file = map.consumer().file;
9308 if (!this.file && file) this.file = this.mapResolve(file);
9309 }
9310 }
9311 if (!this.file) {
9312 this.id = "<input css " + nanoid$2(6) + ">";
9313 }
9314 if (this.map) this.map.file = this.from;
9315 }
9316 var _proto = Input.prototype;
9317 _proto.error = function error(message, line, column, opts) {
9318 if (opts === void 0) opts = {};
9319 var result2, endLine, endColumn;
9320 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
9321 var start = line;
9322 var end = column;
9323 if (typeof start.offset === "number") {
9324 var pos = this.fromOffset(start.offset);
9325 line = pos.line;
9326 column = pos.col;
9327 } else {
9328 line = start.line;
9329 column = start.column;
9330 }
9331 if (typeof end.offset === "number") {
9332 var pos1 = this.fromOffset(end.offset);
9333 endLine = pos1.line;
9334 endColumn = pos1.col;
9335 } else {
9336 endLine = end.line;
9337 endColumn = end.column;
9338 }
9339 } else if (!column) {
9340 var pos2 = this.fromOffset(line);
9341 line = pos2.line;
9342 column = pos2.col;
9343 }
9344 var origin = this.origin(line, column, endLine, endColumn);
9345 if (origin) {
9346 result2 = new CssSyntaxError$1$1(message, origin.endLine === void 0 ? origin.line : {
9347 column: origin.column,
9348 line: origin.line
9349 }, origin.endLine === void 0 ? origin.column : {
9350 column: origin.endColumn,
9351 line: origin.endLine
9352 }, origin.source, origin.file, opts.plugin);
9353 } else {
9354 result2 = new CssSyntaxError$1$1(message, endLine === void 0 ? line : {
9355 column: column,
9356 line: line
9357 }, endLine === void 0 ? column : {
9358 column: endColumn,
9359 line: endLine
9360 }, this.css, this.file, opts.plugin);
9361 }
9362 result2.input = {
9363 column: column,
9364 endColumn: endColumn,
9365 endLine: endLine,
9366 line: line,
9367 source: this.css
9368 };
9369 if (this.file) {
9370 if (pathToFileURL$1$1) {
9371 result2.input.url = pathToFileURL$1$1(this.file).toString();
9372 }
9373 result2.input.file = this.file;
9374 }
9375 return result2;
9376 };
9377 _proto.fromOffset = function fromOffset(offset) {
9378 var lastLine, lineToIndex;
9379 if (!this[fromOffsetCache$1]) {
9380 var lines = this.css.split("\n");
9381 lineToIndex = new Array(lines.length);
9382 var prevIndex = 0;
9383 for(var i2 = 0, l2 = lines.length; i2 < l2; i2++){
9384 lineToIndex[i2] = prevIndex;
9385 prevIndex += lines[i2].length + 1;
9386 }
9387 this[fromOffsetCache$1] = lineToIndex;
9388 } else {
9389 lineToIndex = this[fromOffsetCache$1];
9390 }
9391 lastLine = lineToIndex[lineToIndex.length - 1];
9392 var min = 0;
9393 if (offset >= lastLine) {
9394 min = lineToIndex.length - 1;
9395 } else {
9396 var max = lineToIndex.length - 2;
9397 var mid;
9398 while(min < max){
9399 mid = min + (max - min >> 1);
9400 if (offset < lineToIndex[mid]) {
9401 max = mid - 1;
9402 } else if (offset >= lineToIndex[mid + 1]) {
9403 min = mid + 1;
9404 } else {
9405 min = mid;
9406 break;
9407 }
9408 }
9409 }
9410 return {
9411 col: offset - lineToIndex[min] + 1,
9412 line: min + 1
9413 };
9414 };
9415 _proto.mapResolve = function mapResolve(file) {
9416 if (/^\w+:\/\//.test(file)) {
9417 return file;
9418 }
9419 return resolve$1$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
9420 };
9421 _proto.origin = function origin(line, column, endLine, endColumn) {
9422 if (!this.map) return false;
9423 var consumer = this.map.consumer();
9424 var from = consumer.originalPositionFor({
9425 column: column,
9426 line: line
9427 });
9428 if (!from.source) return false;
9429 var to;
9430 if (typeof endLine === "number") {
9431 to = consumer.originalPositionFor({
9432 column: endColumn,
9433 line: endLine
9434 });
9435 }
9436 var fromUrl;
9437 if (isAbsolute$1(from.source)) {
9438 fromUrl = pathToFileURL$1$1(from.source);
9439 } else {
9440 fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1$1(this.map.mapFile));
9441 }
9442 var result2 = {
9443 column: from.column,
9444 endColumn: to && to.column,
9445 endLine: to && to.line,
9446 line: from.line,
9447 url: fromUrl.toString()
9448 };
9449 if (fromUrl.protocol === "file:") {
9450 if (fileURLToPath$1) {
9451 result2.file = fileURLToPath$1(fromUrl);
9452 } else {
9453 throw new Error("file: protocol is not available in this PostCSS build");
9454 }
9455 }
9456 var source = consumer.sourceContentFor(from.source);
9457 if (source) result2.source = source;
9458 return result2;
9459 };
9460 _proto.toJSON = function toJSON() {
9461 var json = {};
9462 for(var _i = 0, _iter = [
9463 "hasBOM",
9464 "css",
9465 "file",
9466 "id"
9467 ]; _i < _iter.length; _i++){
9468 var name = _iter[_i];
9469 if (this[name] != null) {
9470 json[name] = this[name];
9471 }
9472 }
9473 if (this.map) {
9474 json.map = _extends({}, this.map);
9475 if (json.map.consumerCache) {
9476 json.map.consumerCache = void 0;
9477 }
9478 }
9479 return json;
9480 };
9481 _create_class(Input, [
9482 {
9483 key: "from",
9484 get: function get() {
9485 return this.file || this.id;
9486 }
9487 }
9488 ]);
9489 return Input;
9490 }();
9491 var input$1 = Input$4$1;
9492 Input$4$1.default = Input$4$1;
9493 if (terminalHighlight$2 && terminalHighlight$2.registerInput) {
9494 terminalHighlight$2.registerInput(Input$4$1);
9495 }
9496 var SourceMapConsumer$3 = require$$2$1.SourceMapConsumer, SourceMapGenerator$3 = require$$2$1.SourceMapGenerator;
9497 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;
9498 var pathToFileURL$2 = require$$2$1.pathToFileURL;
9499 var Input$3$1 = input$1;
9500 var sourceMapAvailable$2 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$3);
9501 var pathAvailable$2 = Boolean(dirname$2 && resolve$2 && relative$1 && sep$1);
9502 var MapGenerator$2$1 = /*#__PURE__*/ function() {
9503 function MapGenerator(stringify2, root2, opts, cssString) {
9504 this.stringify = stringify2;
9505 this.mapOpts = opts.map || {};
9506 this.root = root2;
9507 this.opts = opts;
9508 this.css = cssString;
9509 this.originalCSS = cssString;
9510 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
9511 this.memoizedFileURLs = /* @__PURE__ */ new Map();
9512 this.memoizedPaths = /* @__PURE__ */ new Map();
9513 this.memoizedURLs = /* @__PURE__ */ new Map();
9514 }
9515 var _proto = MapGenerator.prototype;
9516 _proto.addAnnotation = function addAnnotation() {
9517 var content;
9518 if (this.isInline()) {
9519 content = "data:application/json;base64," + this.toBase64(this.map.toString());
9520 } else if (typeof this.mapOpts.annotation === "string") {
9521 content = this.mapOpts.annotation;
9522 } else if (typeof this.mapOpts.annotation === "function") {
9523 content = this.mapOpts.annotation(this.opts.to, this.root);
9524 } else {
9525 content = this.outputFile() + ".map";
9526 }
9527 var eol = "\n";
9528 if (this.css.includes("\r\n")) eol = "\r\n";
9529 this.css += eol + "/*# sourceMappingURL=" + content + " */";
9530 };
9531 _proto.applyPrevMaps = function applyPrevMaps() {
9532 for(var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;){
9533 var prev = _step.value;
9534 var from = this.toUrl(this.path(prev.file));
9535 var root2 = prev.root || dirname$2(prev.file);
9536 var map = void 0;
9537 if (this.mapOpts.sourcesContent === false) {
9538 map = new SourceMapConsumer$3(prev.text);
9539 if (map.sourcesContent) {
9540 map.sourcesContent = null;
9541 }
9542 } else {
9543 map = prev.consumer();
9544 }
9545 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
9546 }
9547 };
9548 _proto.clearAnnotation = function clearAnnotation() {
9549 if (this.mapOpts.annotation === false) return;
9550 if (this.root) {
9551 var node2;
9552 for(var i2 = this.root.nodes.length - 1; i2 >= 0; i2--){
9553 node2 = this.root.nodes[i2];
9554 if (node2.type !== "comment") continue;
9555 if (node2.text.indexOf("# sourceMappingURL=") === 0) {
9556 this.root.removeChild(i2);
9557 }
9558 }
9559 } else if (this.css) {
9560 this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
9561 }
9562 };
9563 _proto.generate = function generate() {
9564 this.clearAnnotation();
9565 if (pathAvailable$2 && sourceMapAvailable$2 && this.isMap()) {
9566 return this.generateMap();
9567 } else {
9568 var result2 = "";
9569 this.stringify(this.root, function(i2) {
9570 result2 += i2;
9571 });
9572 return [
9573 result2
9574 ];
9575 }
9576 };
9577 _proto.generateMap = function generateMap() {
9578 if (this.root) {
9579 this.generateString();
9580 } else if (this.previous().length === 1) {
9581 var prev = this.previous()[0].consumer();
9582 prev.file = this.outputFile();
9583 this.map = SourceMapGenerator$3.fromSourceMap(prev, {
9584 ignoreInvalidMapping: true
9585 });
9586 } else {
9587 this.map = new SourceMapGenerator$3({
9588 file: this.outputFile(),
9589 ignoreInvalidMapping: true
9590 });
9591 this.map.addMapping({
9592 generated: {
9593 column: 0,
9594 line: 1
9595 },
9596 original: {
9597 column: 0,
9598 line: 1
9599 },
9600 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
9601 });
9602 }
9603 if (this.isSourcesContent()) this.setSourcesContent();
9604 if (this.root && this.previous().length > 0) this.applyPrevMaps();
9605 if (this.isAnnotation()) this.addAnnotation();
9606 if (this.isInline()) {
9607 return [
9608 this.css
9609 ];
9610 } else {
9611 return [
9612 this.css,
9613 this.map
9614 ];
9615 }
9616 };
9617 _proto.generateString = function generateString() {
9618 var _this = this;
9619 this.css = "";
9620 this.map = new SourceMapGenerator$3({
9621 file: this.outputFile(),
9622 ignoreInvalidMapping: true
9623 });
9624 var line = 1;
9625 var column = 1;
9626 var noSource = "<no source>";
9627 var mapping = {
9628 generated: {
9629 column: 0,
9630 line: 0
9631 },
9632 original: {
9633 column: 0,
9634 line: 0
9635 },
9636 source: ""
9637 };
9638 var lines, last;
9639 this.stringify(this.root, function(str, node2, type) {
9640 _this.css += str;
9641 if (node2 && type !== "end") {
9642 mapping.generated.line = line;
9643 mapping.generated.column = column - 1;
9644 if (node2.source && node2.source.start) {
9645 mapping.source = _this.sourcePath(node2);
9646 mapping.original.line = node2.source.start.line;
9647 mapping.original.column = node2.source.start.column - 1;
9648 _this.map.addMapping(mapping);
9649 } else {
9650 mapping.source = noSource;
9651 mapping.original.line = 1;
9652 mapping.original.column = 0;
9653 _this.map.addMapping(mapping);
9654 }
9655 }
9656 lines = str.match(/\n/g);
9657 if (lines) {
9658 line += lines.length;
9659 last = str.lastIndexOf("\n");
9660 column = str.length - last;
9661 } else {
9662 column += str.length;
9663 }
9664 if (node2 && type !== "start") {
9665 var p = node2.parent || {
9666 raws: {}
9667 };
9668 var childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
9669 if (!childless || node2 !== p.last || p.raws.semicolon) {
9670 if (node2.source && node2.source.end) {
9671 mapping.source = _this.sourcePath(node2);
9672 mapping.original.line = node2.source.end.line;
9673 mapping.original.column = node2.source.end.column - 1;
9674 mapping.generated.line = line;
9675 mapping.generated.column = column - 2;
9676 _this.map.addMapping(mapping);
9677 } else {
9678 mapping.source = noSource;
9679 mapping.original.line = 1;
9680 mapping.original.column = 0;
9681 mapping.generated.line = line;
9682 mapping.generated.column = column - 1;
9683 _this.map.addMapping(mapping);
9684 }
9685 }
9686 }
9687 });
9688 };
9689 _proto.isAnnotation = function isAnnotation() {
9690 if (this.isInline()) {
9691 return true;
9692 }
9693 if (typeof this.mapOpts.annotation !== "undefined") {
9694 return this.mapOpts.annotation;
9695 }
9696 if (this.previous().length) {
9697 return this.previous().some(function(i2) {
9698 return i2.annotation;
9699 });
9700 }
9701 return true;
9702 };
9703 _proto.isInline = function isInline() {
9704 if (typeof this.mapOpts.inline !== "undefined") {
9705 return this.mapOpts.inline;
9706 }
9707 var annotation = this.mapOpts.annotation;
9708 if (typeof annotation !== "undefined" && annotation !== true) {
9709 return false;
9710 }
9711 if (this.previous().length) {
9712 return this.previous().some(function(i2) {
9713 return i2.inline;
9714 });
9715 }
9716 return true;
9717 };
9718 _proto.isMap = function isMap() {
9719 if (typeof this.opts.map !== "undefined") {
9720 return !!this.opts.map;
9721 }
9722 return this.previous().length > 0;
9723 };
9724 _proto.isSourcesContent = function isSourcesContent() {
9725 if (typeof this.mapOpts.sourcesContent !== "undefined") {
9726 return this.mapOpts.sourcesContent;
9727 }
9728 if (this.previous().length) {
9729 return this.previous().some(function(i2) {
9730 return i2.withContent();
9731 });
9732 }
9733 return true;
9734 };
9735 _proto.outputFile = function outputFile() {
9736 if (this.opts.to) {
9737 return this.path(this.opts.to);
9738 } else if (this.opts.from) {
9739 return this.path(this.opts.from);
9740 } else {
9741 return "to.css";
9742 }
9743 };
9744 _proto.path = function path(file) {
9745 if (this.mapOpts.absolute) return file;
9746 if (file.charCodeAt(0) === 60) return file;
9747 if (/^\w+:\/\//.test(file)) return file;
9748 var cached = this.memoizedPaths.get(file);
9749 if (cached) return cached;
9750 var from = this.opts.to ? dirname$2(this.opts.to) : ".";
9751 if (typeof this.mapOpts.annotation === "string") {
9752 from = dirname$2(resolve$2(from, this.mapOpts.annotation));
9753 }
9754 var path = relative$1(from, file);
9755 this.memoizedPaths.set(file, path);
9756 return path;
9757 };
9758 _proto.previous = function previous() {
9759 var _this = this;
9760 if (!this.previousMaps) {
9761 this.previousMaps = [];
9762 if (this.root) {
9763 this.root.walk(function(node2) {
9764 if (node2.source && node2.source.input.map) {
9765 var map = node2.source.input.map;
9766 if (!_this.previousMaps.includes(map)) {
9767 _this.previousMaps.push(map);
9768 }
9769 }
9770 });
9771 } else {
9772 var input2 = new Input$3$1(this.originalCSS, this.opts);
9773 if (input2.map) this.previousMaps.push(input2.map);
9774 }
9775 }
9776 return this.previousMaps;
9777 };
9778 _proto.setSourcesContent = function setSourcesContent() {
9779 var _this = this;
9780 var already = {};
9781 if (this.root) {
9782 this.root.walk(function(node2) {
9783 if (node2.source) {
9784 var from = node2.source.input.from;
9785 if (from && !already[from]) {
9786 already[from] = true;
9787 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
9788 _this.map.setSourceContent(fromUrl, node2.source.input.css);
9789 }
9790 }
9791 });
9792 } else if (this.css) {
9793 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
9794 this.map.setSourceContent(from, this.css);
9795 }
9796 };
9797 _proto.sourcePath = function sourcePath(node2) {
9798 if (this.mapOpts.from) {
9799 return this.toUrl(this.mapOpts.from);
9800 } else if (this.usesFileUrls) {
9801 return this.toFileUrl(node2.source.input.from);
9802 } else {
9803 return this.toUrl(this.path(node2.source.input.from));
9804 }
9805 };
9806 _proto.toBase64 = function toBase64(str) {
9807 if (Buffer) {
9808 return Buffer.from(str).toString("base64");
9809 } else {
9810 return window.btoa(unescape(encodeURIComponent(str)));
9811 }
9812 };
9813 _proto.toFileUrl = function toFileUrl(path) {
9814 var cached = this.memoizedFileURLs.get(path);
9815 if (cached) return cached;
9816 if (pathToFileURL$2) {
9817 var fileURL = pathToFileURL$2(path).toString();
9818 this.memoizedFileURLs.set(path, fileURL);
9819 return fileURL;
9820 } else {
9821 throw new Error("`map.absolute` option is not available in this PostCSS build");
9822 }
9823 };
9824 _proto.toUrl = function toUrl(path) {
9825 var cached = this.memoizedURLs.get(path);
9826 if (cached) return cached;
9827 if (sep$1 === "\\") {
9828 path = path.replace(/\\/g, "/");
9829 }
9830 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
9831 this.memoizedURLs.set(path, url);
9832 return url;
9833 };
9834 return MapGenerator;
9835 }();
9836 var mapGenerator$1 = MapGenerator$2$1;
9837 var Node$2$1 = node$1;
9838 var Comment$4$1 = /*#__PURE__*/ function(Node$2$1) {
9839 _inherits(Comment, Node$2$1);
9840 function Comment(defaults) {
9841 var _this;
9842 _this = Node$2$1.call(this, defaults) || this;
9843 _this.type = "comment";
9844 return _this;
9845 }
9846 return Comment;
9847 }(Node$2$1);
9848 var comment$1 = Comment$4$1;
9849 Comment$4$1.default = Comment$4$1;
9850 var isClean$1$1 = symbols$1.isClean, my$1$1 = symbols$1.my;
9851 var Declaration$3$1 = declaration$1;
9852 var Comment$3$1 = comment$1;
9853 var Node$1$1 = node$1;
9854 var parse$4$1, Rule$4$1, AtRule$4$1, Root$6$1;
9855 function cleanSource$1(nodes) {
9856 return nodes.map(function(i2) {
9857 if (i2.nodes) i2.nodes = cleanSource$1(i2.nodes);
9858 delete i2.source;
9859 return i2;
9860 });
9861 }
9862 function markDirtyUp$1(node2) {
9863 node2[isClean$1$1] = false;
9864 if (node2.proxyOf.nodes) {
9865 for(var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;){
9866 var i2 = _step.value;
9867 markDirtyUp$1(i2);
9868 }
9869 }
9870 }
9871 var Container$7$1 = /*#__PURE__*/ function(Node$1$1) {
9872 _inherits(Container, Node$1$1);
9873 function Container() {
9874 return Node$1$1.apply(this, arguments) || this;
9875 }
9876 var _proto = Container.prototype;
9877 _proto.append = function append() {
9878 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
9879 children[_key] = arguments[_key];
9880 }
9881 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
9882 var child = _step.value;
9883 var nodes = this.normalize(child, this.last);
9884 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
9885 var node2 = _step1.value;
9886 this.proxyOf.nodes.push(node2);
9887 }
9888 }
9889 this.markDirty();
9890 return this;
9891 };
9892 _proto.cleanRaws = function cleanRaws(keepBetween) {
9893 Node$1$1.prototype.cleanRaws.call(this, keepBetween);
9894 if (this.nodes) {
9895 for(var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;){
9896 var node2 = _step.value;
9897 node2.cleanRaws(keepBetween);
9898 }
9899 }
9900 };
9901 _proto.each = function each(callback) {
9902 if (!this.proxyOf.nodes) return void 0;
9903 var iterator = this.getIterator();
9904 var index2, result2;
9905 while(this.indexes[iterator] < this.proxyOf.nodes.length){
9906 index2 = this.indexes[iterator];
9907 result2 = callback(this.proxyOf.nodes[index2], index2);
9908 if (result2 === false) break;
9909 this.indexes[iterator] += 1;
9910 }
9911 delete this.indexes[iterator];
9912 return result2;
9913 };
9914 _proto.every = function every(condition) {
9915 return this.nodes.every(condition);
9916 };
9917 _proto.getIterator = function getIterator() {
9918 if (!this.lastEach) this.lastEach = 0;
9919 if (!this.indexes) this.indexes = {};
9920 this.lastEach += 1;
9921 var iterator = this.lastEach;
9922 this.indexes[iterator] = 0;
9923 return iterator;
9924 };
9925 _proto.getProxyProcessor = function getProxyProcessor() {
9926 return {
9927 get: function get(node2, prop) {
9928 if (prop === "proxyOf") {
9929 return node2;
9930 } else if (!node2[prop]) {
9931 return node2[prop];
9932 } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
9933 return function() {
9934 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
9935 args[_key] = arguments[_key];
9936 }
9937 var _node2;
9938 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
9939 if (typeof i2 === "function") {
9940 return function(child, index2) {
9941 return i2(child.toProxy(), index2);
9942 };
9943 } else {
9944 return i2;
9945 }
9946 })));
9947 };
9948 } else if (prop === "every" || prop === "some") {
9949 return function(cb) {
9950 return node2[prop](function(child) {
9951 for(var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
9952 other[_key - 1] = arguments[_key];
9953 }
9954 return cb.apply(void 0, [].concat([
9955 child.toProxy()
9956 ], other));
9957 });
9958 };
9959 } else if (prop === "root") {
9960 return function() {
9961 return node2.root().toProxy();
9962 };
9963 } else if (prop === "nodes") {
9964 return node2.nodes.map(function(i2) {
9965 return i2.toProxy();
9966 });
9967 } else if (prop === "first" || prop === "last") {
9968 return node2[prop].toProxy();
9969 } else {
9970 return node2[prop];
9971 }
9972 },
9973 set: function set(node2, prop, value) {
9974 if (node2[prop] === value) return true;
9975 node2[prop] = value;
9976 if (prop === "name" || prop === "params" || prop === "selector") {
9977 node2.markDirty();
9978 }
9979 return true;
9980 }
9981 };
9982 };
9983 _proto.index = function index(child) {
9984 if (typeof child === "number") return child;
9985 if (child.proxyOf) child = child.proxyOf;
9986 return this.proxyOf.nodes.indexOf(child);
9987 };
9988 _proto.insertAfter = function insertAfter(exist, add) {
9989 var existIndex = this.index(exist);
9990 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
9991 existIndex = this.index(exist);
9992 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
9993 var node2 = _step.value;
9994 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
9995 }
9996 var index2;
9997 for(var id in this.indexes){
9998 index2 = this.indexes[id];
9999 if (existIndex < index2) {
10000 this.indexes[id] = index2 + nodes.length;
10001 }
10002 }
10003 this.markDirty();
10004 return this;
10005 };
10006 _proto.insertBefore = function insertBefore(exist, add) {
10007 var existIndex = this.index(exist);
10008 var type = existIndex === 0 ? "prepend" : false;
10009 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
10010 existIndex = this.index(exist);
10011 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
10012 var node2 = _step.value;
10013 this.proxyOf.nodes.splice(existIndex, 0, node2);
10014 }
10015 var index2;
10016 for(var id in this.indexes){
10017 index2 = this.indexes[id];
10018 if (existIndex <= index2) {
10019 this.indexes[id] = index2 + nodes.length;
10020 }
10021 }
10022 this.markDirty();
10023 return this;
10024 };
10025 _proto.normalize = function normalize(nodes, sample) {
10026 var _this = this;
10027 if (typeof nodes === "string") {
10028 nodes = cleanSource$1(parse$4$1(nodes).nodes);
10029 } else if (typeof nodes === "undefined") {
10030 nodes = [];
10031 } else if (Array.isArray(nodes)) {
10032 nodes = nodes.slice(0);
10033 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
10034 var i2 = _step.value;
10035 if (i2.parent) i2.parent.removeChild(i2, "ignore");
10036 }
10037 } else if (nodes.type === "root" && this.type !== "document") {
10038 nodes = nodes.nodes.slice(0);
10039 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
10040 var i21 = _step1.value;
10041 if (i21.parent) i21.parent.removeChild(i21, "ignore");
10042 }
10043 } else if (nodes.type) {
10044 nodes = [
10045 nodes
10046 ];
10047 } else if (nodes.prop) {
10048 if (typeof nodes.value === "undefined") {
10049 throw new Error("Value field is missed in node creation");
10050 } else if (typeof nodes.value !== "string") {
10051 nodes.value = String(nodes.value);
10052 }
10053 nodes = [
10054 new Declaration$3$1(nodes)
10055 ];
10056 } else if (nodes.selector) {
10057 nodes = [
10058 new Rule$4$1(nodes)
10059 ];
10060 } else if (nodes.name) {
10061 nodes = [
10062 new AtRule$4$1(nodes)
10063 ];
10064 } else if (nodes.text) {
10065 nodes = [
10066 new Comment$3$1(nodes)
10067 ];
10068 } else {
10069 throw new Error("Unknown node type in node creation");
10070 }
10071 var processed = nodes.map(function(i2) {
10072 if (!i2[my$1$1]) Container.rebuild(i2);
10073 i2 = i2.proxyOf;
10074 if (i2.parent) i2.parent.removeChild(i2);
10075 if (i2[isClean$1$1]) markDirtyUp$1(i2);
10076 if (typeof i2.raws.before === "undefined") {
10077 if (sample && typeof sample.raws.before !== "undefined") {
10078 i2.raws.before = sample.raws.before.replace(/\S/g, "");
10079 }
10080 }
10081 i2.parent = _this.proxyOf;
10082 return i2;
10083 });
10084 return processed;
10085 };
10086 _proto.prepend = function prepend() {
10087 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
10088 children[_key] = arguments[_key];
10089 }
10090 children = children.reverse();
10091 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
10092 var child = _step.value;
10093 var nodes = this.normalize(child, this.first, "prepend").reverse();
10094 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
10095 var node2 = _step1.value;
10096 this.proxyOf.nodes.unshift(node2);
10097 }
10098 for(var id in this.indexes){
10099 this.indexes[id] = this.indexes[id] + nodes.length;
10100 }
10101 }
10102 this.markDirty();
10103 return this;
10104 };
10105 _proto.push = function push(child) {
10106 child.parent = this;
10107 this.proxyOf.nodes.push(child);
10108 return this;
10109 };
10110 _proto.removeAll = function removeAll() {
10111 for(var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;){
10112 var node2 = _step.value;
10113 node2.parent = void 0;
10114 }
10115 this.proxyOf.nodes = [];
10116 this.markDirty();
10117 return this;
10118 };
10119 _proto.removeChild = function removeChild(child) {
10120 child = this.index(child);
10121 this.proxyOf.nodes[child].parent = void 0;
10122 this.proxyOf.nodes.splice(child, 1);
10123 var index2;
10124 for(var id in this.indexes){
10125 index2 = this.indexes[id];
10126 if (index2 >= child) {
10127 this.indexes[id] = index2 - 1;
10128 }
10129 }
10130 this.markDirty();
10131 return this;
10132 };
10133 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
10134 if (!callback) {
10135 callback = opts;
10136 opts = {};
10137 }
10138 this.walkDecls(function(decl) {
10139 if (opts.props && !opts.props.includes(decl.prop)) return;
10140 if (opts.fast && !decl.value.includes(opts.fast)) return;
10141 decl.value = decl.value.replace(pattern, callback);
10142 });
10143 this.markDirty();
10144 return this;
10145 };
10146 _proto.some = function some(condition) {
10147 return this.nodes.some(condition);
10148 };
10149 _proto.walk = function walk(callback) {
10150 return this.each(function(child, i2) {
10151 var result2;
10152 try {
10153 result2 = callback(child, i2);
10154 } catch (e2) {
10155 throw child.addToError(e2);
10156 }
10157 if (result2 !== false && child.walk) {
10158 result2 = child.walk(callback);
10159 }
10160 return result2;
10161 });
10162 };
10163 _proto.walkAtRules = function walkAtRules(name, callback) {
10164 if (!callback) {
10165 callback = name;
10166 return this.walk(function(child, i2) {
10167 if (child.type === "atrule") {
10168 return callback(child, i2);
10169 }
10170 });
10171 }
10172 if (_instanceof(name, RegExp)) {
10173 return this.walk(function(child, i2) {
10174 if (child.type === "atrule" && name.test(child.name)) {
10175 return callback(child, i2);
10176 }
10177 });
10178 }
10179 return this.walk(function(child, i2) {
10180 if (child.type === "atrule" && child.name === name) {
10181 return callback(child, i2);
10182 }
10183 });
10184 };
10185 _proto.walkComments = function walkComments(callback) {
10186 return this.walk(function(child, i2) {
10187 if (child.type === "comment") {
10188 return callback(child, i2);
10189 }
10190 });
10191 };
10192 _proto.walkDecls = function walkDecls(prop, callback) {
10193 if (!callback) {
10194 callback = prop;
10195 return this.walk(function(child, i2) {
10196 if (child.type === "decl") {
10197 return callback(child, i2);
10198 }
10199 });
10200 }
10201 if (_instanceof(prop, RegExp)) {
10202 return this.walk(function(child, i2) {
10203 if (child.type === "decl" && prop.test(child.prop)) {
10204 return callback(child, i2);
10205 }
10206 });
10207 }
10208 return this.walk(function(child, i2) {
10209 if (child.type === "decl" && child.prop === prop) {
10210 return callback(child, i2);
10211 }
10212 });
10213 };
10214 _proto.walkRules = function walkRules(selector, callback) {
10215 if (!callback) {
10216 callback = selector;
10217 return this.walk(function(child, i2) {
10218 if (child.type === "rule") {
10219 return callback(child, i2);
10220 }
10221 });
10222 }
10223 if (_instanceof(selector, RegExp)) {
10224 return this.walk(function(child, i2) {
10225 if (child.type === "rule" && selector.test(child.selector)) {
10226 return callback(child, i2);
10227 }
10228 });
10229 }
10230 return this.walk(function(child, i2) {
10231 if (child.type === "rule" && child.selector === selector) {
10232 return callback(child, i2);
10233 }
10234 });
10235 };
10236 _create_class(Container, [
10237 {
10238 key: "first",
10239 get: function get() {
10240 if (!this.proxyOf.nodes) return void 0;
10241 return this.proxyOf.nodes[0];
10242 }
10243 },
10244 {
10245 key: "last",
10246 get: function get() {
10247 if (!this.proxyOf.nodes) return void 0;
10248 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
10249 }
10250 }
10251 ]);
10252 return Container;
10253 }(Node$1$1);
10254 Container$7$1.registerParse = function(dependant) {
10255 parse$4$1 = dependant;
10256 };
10257 Container$7$1.registerRule = function(dependant) {
10258 Rule$4$1 = dependant;
10259 };
10260 Container$7$1.registerAtRule = function(dependant) {
10261 AtRule$4$1 = dependant;
10262 };
10263 Container$7$1.registerRoot = function(dependant) {
10264 Root$6$1 = dependant;
10265 };
10266 var container$1 = Container$7$1;
10267 Container$7$1.default = Container$7$1;
10268 Container$7$1.rebuild = function(node2) {
10269 if (node2.type === "atrule") {
10270 Object.setPrototypeOf(node2, AtRule$4$1.prototype);
10271 } else if (node2.type === "rule") {
10272 Object.setPrototypeOf(node2, Rule$4$1.prototype);
10273 } else if (node2.type === "decl") {
10274 Object.setPrototypeOf(node2, Declaration$3$1.prototype);
10275 } else if (node2.type === "comment") {
10276 Object.setPrototypeOf(node2, Comment$3$1.prototype);
10277 } else if (node2.type === "root") {
10278 Object.setPrototypeOf(node2, Root$6$1.prototype);
10279 }
10280 node2[my$1$1] = true;
10281 if (node2.nodes) {
10282 node2.nodes.forEach(function(child) {
10283 Container$7$1.rebuild(child);
10284 });
10285 }
10286 };
10287 var Container$6$1 = container$1;
10288 var LazyResult$4$1, Processor$3$1;
10289 var Document$3$1 = /*#__PURE__*/ function(Container$6$1) {
10290 _inherits(Document2, Container$6$1);
10291 function Document2(defaults) {
10292 var _this;
10293 _this = Container$6$1.call(this, _extends({
10294 type: "document"
10295 }, defaults)) || this;
10296 if (!_this.nodes) {
10297 _this.nodes = [];
10298 }
10299 return _this;
10300 }
10301 var _proto = Document2.prototype;
10302 _proto.toResult = function toResult(opts) {
10303 if (opts === void 0) opts = {};
10304 var lazy = new LazyResult$4$1(new Processor$3$1(), this, opts);
10305 return lazy.stringify();
10306 };
10307 return Document2;
10308 }(Container$6$1);
10309 Document$3$1.registerLazyResult = function(dependant) {
10310 LazyResult$4$1 = dependant;
10311 };
10312 Document$3$1.registerProcessor = function(dependant) {
10313 Processor$3$1 = dependant;
10314 };
10315 var document$1$1 = Document$3$1;
10316 Document$3$1.default = Document$3$1;
10317 var printed$1 = {};
10318 var warnOnce$2$1 = function warnOnce(message) {
10319 if (printed$1[message]) return;
10320 printed$1[message] = true;
10321 if (typeof console !== "undefined" && console.warn) {
10322 console.warn(message);
10323 }
10324 };
10325 var Warning$2$1 = /*#__PURE__*/ function() {
10326 function Warning(text, opts) {
10327 if (opts === void 0) opts = {};
10328 this.type = "warning";
10329 this.text = text;
10330 if (opts.node && opts.node.source) {
10331 var range = opts.node.rangeBy(opts);
10332 this.line = range.start.line;
10333 this.column = range.start.column;
10334 this.endLine = range.end.line;
10335 this.endColumn = range.end.column;
10336 }
10337 for(var opt in opts)this[opt] = opts[opt];
10338 }
10339 var _proto = Warning.prototype;
10340 _proto.toString = function toString() {
10341 if (this.node) {
10342 return this.node.error(this.text, {
10343 index: this.index,
10344 plugin: this.plugin,
10345 word: this.word
10346 }).message;
10347 }
10348 if (this.plugin) {
10349 return this.plugin + ": " + this.text;
10350 }
10351 return this.text;
10352 };
10353 return Warning;
10354 }();
10355 var warning$1 = Warning$2$1;
10356 Warning$2$1.default = Warning$2$1;
10357 var Warning$1$1 = warning$1;
10358 var Result$3$1 = /*#__PURE__*/ function() {
10359 function Result(processor2, root2, opts) {
10360 this.processor = processor2;
10361 this.messages = [];
10362 this.root = root2;
10363 this.opts = opts;
10364 this.css = void 0;
10365 this.map = void 0;
10366 }
10367 var _proto = Result.prototype;
10368 _proto.toString = function toString() {
10369 return this.css;
10370 };
10371 _proto.warn = function warn(text, opts) {
10372 if (opts === void 0) opts = {};
10373 if (!opts.plugin) {
10374 if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
10375 opts.plugin = this.lastPlugin.postcssPlugin;
10376 }
10377 }
10378 var warning2 = new Warning$1$1(text, opts);
10379 this.messages.push(warning2);
10380 return warning2;
10381 };
10382 _proto.warnings = function warnings() {
10383 return this.messages.filter(function(i2) {
10384 return i2.type === "warning";
10385 });
10386 };
10387 _create_class(Result, [
10388 {
10389 key: "content",
10390 get: function get() {
10391 return this.css;
10392 }
10393 }
10394 ]);
10395 return Result;
10396 }();
10397 var result$1 = Result$3$1;
10398 Result$3$1.default = Result$3$1;
10399 var SINGLE_QUOTE$1 = "'".charCodeAt(0);
10400 var DOUBLE_QUOTE$1 = '"'.charCodeAt(0);
10401 var BACKSLASH$1 = "\\".charCodeAt(0);
10402 var SLASH$1 = "/".charCodeAt(0);
10403 var NEWLINE$1 = "\n".charCodeAt(0);
10404 var SPACE$1 = " ".charCodeAt(0);
10405 var FEED$1 = "\f".charCodeAt(0);
10406 var TAB$1 = " ".charCodeAt(0);
10407 var CR$1 = "\r".charCodeAt(0);
10408 var OPEN_SQUARE$1 = "[".charCodeAt(0);
10409 var CLOSE_SQUARE$1 = "]".charCodeAt(0);
10410 var OPEN_PARENTHESES$1 = "(".charCodeAt(0);
10411 var CLOSE_PARENTHESES$1 = ")".charCodeAt(0);
10412 var OPEN_CURLY$1 = "{".charCodeAt(0);
10413 var CLOSE_CURLY$1 = "}".charCodeAt(0);
10414 var SEMICOLON$1 = ";".charCodeAt(0);
10415 var ASTERISK$1 = "*".charCodeAt(0);
10416 var COLON$1 = ":".charCodeAt(0);
10417 var AT$1 = "@".charCodeAt(0);
10418 var RE_AT_END$1 = /[\t\n\f\r "#'()/;[\\\]{}]/g;
10419 var RE_WORD_END$1 = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
10420 var RE_BAD_BRACKET$1 = /.[\r\n"'(/\\]/;
10421 var RE_HEX_ESCAPE$1 = /[\da-f]/i;
10422 var tokenize$1 = function tokenizer(input2, options) {
10423 if (options === void 0) options = {};
10424 var css = input2.css.valueOf();
10425 var ignore = options.ignoreErrors;
10426 var code, next, quote, content, escape;
10427 var escaped, escapePos, prev, n2, currentToken;
10428 var length = css.length;
10429 var pos = 0;
10430 var buffer = [];
10431 var returned = [];
10432 function position() {
10433 return pos;
10434 }
10435 function unclosed(what) {
10436 throw input2.error("Unclosed " + what, pos);
10437 }
10438 function endOfFile() {
10439 return returned.length === 0 && pos >= length;
10440 }
10441 function nextToken(opts) {
10442 if (returned.length) return returned.pop();
10443 if (pos >= length) return;
10444 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
10445 code = css.charCodeAt(pos);
10446 switch(code){
10447 case NEWLINE$1:
10448 case SPACE$1:
10449 case TAB$1:
10450 case CR$1:
10451 case FEED$1:
10452 {
10453 next = pos;
10454 do {
10455 next += 1;
10456 code = css.charCodeAt(next);
10457 }while (code === SPACE$1 || code === NEWLINE$1 || code === TAB$1 || code === CR$1 || code === FEED$1);
10458 currentToken = [
10459 "space",
10460 css.slice(pos, next)
10461 ];
10462 pos = next - 1;
10463 break;
10464 }
10465 case OPEN_SQUARE$1:
10466 case CLOSE_SQUARE$1:
10467 case OPEN_CURLY$1:
10468 case CLOSE_CURLY$1:
10469 case COLON$1:
10470 case SEMICOLON$1:
10471 case CLOSE_PARENTHESES$1:
10472 {
10473 var controlChar = String.fromCharCode(code);
10474 currentToken = [
10475 controlChar,
10476 controlChar,
10477 pos
10478 ];
10479 break;
10480 }
10481 case OPEN_PARENTHESES$1:
10482 {
10483 prev = buffer.length ? buffer.pop()[1] : "";
10484 n2 = css.charCodeAt(pos + 1);
10485 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) {
10486 next = pos;
10487 do {
10488 escaped = false;
10489 next = css.indexOf(")", next + 1);
10490 if (next === -1) {
10491 if (ignore || ignoreUnclosed) {
10492 next = pos;
10493 break;
10494 } else {
10495 unclosed("bracket");
10496 }
10497 }
10498 escapePos = next;
10499 while(css.charCodeAt(escapePos - 1) === BACKSLASH$1){
10500 escapePos -= 1;
10501 escaped = !escaped;
10502 }
10503 }while (escaped);
10504 currentToken = [
10505 "brackets",
10506 css.slice(pos, next + 1),
10507 pos,
10508 next
10509 ];
10510 pos = next;
10511 } else {
10512 next = css.indexOf(")", pos + 1);
10513 content = css.slice(pos, next + 1);
10514 if (next === -1 || RE_BAD_BRACKET$1.test(content)) {
10515 currentToken = [
10516 "(",
10517 "(",
10518 pos
10519 ];
10520 } else {
10521 currentToken = [
10522 "brackets",
10523 content,
10524 pos,
10525 next
10526 ];
10527 pos = next;
10528 }
10529 }
10530 break;
10531 }
10532 case SINGLE_QUOTE$1:
10533 case DOUBLE_QUOTE$1:
10534 {
10535 quote = code === SINGLE_QUOTE$1 ? "'" : '"';
10536 next = pos;
10537 do {
10538 escaped = false;
10539 next = css.indexOf(quote, next + 1);
10540 if (next === -1) {
10541 if (ignore || ignoreUnclosed) {
10542 next = pos + 1;
10543 break;
10544 } else {
10545 unclosed("string");
10546 }
10547 }
10548 escapePos = next;
10549 while(css.charCodeAt(escapePos - 1) === BACKSLASH$1){
10550 escapePos -= 1;
10551 escaped = !escaped;
10552 }
10553 }while (escaped);
10554 currentToken = [
10555 "string",
10556 css.slice(pos, next + 1),
10557 pos,
10558 next
10559 ];
10560 pos = next;
10561 break;
10562 }
10563 case AT$1:
10564 {
10565 RE_AT_END$1.lastIndex = pos + 1;
10566 RE_AT_END$1.test(css);
10567 if (RE_AT_END$1.lastIndex === 0) {
10568 next = css.length - 1;
10569 } else {
10570 next = RE_AT_END$1.lastIndex - 2;
10571 }
10572 currentToken = [
10573 "at-word",
10574 css.slice(pos, next + 1),
10575 pos,
10576 next
10577 ];
10578 pos = next;
10579 break;
10580 }
10581 case BACKSLASH$1:
10582 {
10583 next = pos;
10584 escape = true;
10585 while(css.charCodeAt(next + 1) === BACKSLASH$1){
10586 next += 1;
10587 escape = !escape;
10588 }
10589 code = css.charCodeAt(next + 1);
10590 if (escape && code !== SLASH$1 && code !== SPACE$1 && code !== NEWLINE$1 && code !== TAB$1 && code !== CR$1 && code !== FEED$1) {
10591 next += 1;
10592 if (RE_HEX_ESCAPE$1.test(css.charAt(next))) {
10593 while(RE_HEX_ESCAPE$1.test(css.charAt(next + 1))){
10594 next += 1;
10595 }
10596 if (css.charCodeAt(next + 1) === SPACE$1) {
10597 next += 1;
10598 }
10599 }
10600 }
10601 currentToken = [
10602 "word",
10603 css.slice(pos, next + 1),
10604 pos,
10605 next
10606 ];
10607 pos = next;
10608 break;
10609 }
10610 default:
10611 {
10612 if (code === SLASH$1 && css.charCodeAt(pos + 1) === ASTERISK$1) {
10613 next = css.indexOf("*/", pos + 2) + 1;
10614 if (next === 0) {
10615 if (ignore || ignoreUnclosed) {
10616 next = css.length;
10617 } else {
10618 unclosed("comment");
10619 }
10620 }
10621 currentToken = [
10622 "comment",
10623 css.slice(pos, next + 1),
10624 pos,
10625 next
10626 ];
10627 pos = next;
10628 } else {
10629 RE_WORD_END$1.lastIndex = pos + 1;
10630 RE_WORD_END$1.test(css);
10631 if (RE_WORD_END$1.lastIndex === 0) {
10632 next = css.length - 1;
10633 } else {
10634 next = RE_WORD_END$1.lastIndex - 2;
10635 }
10636 currentToken = [
10637 "word",
10638 css.slice(pos, next + 1),
10639 pos,
10640 next
10641 ];
10642 buffer.push(currentToken);
10643 pos = next;
10644 }
10645 break;
10646 }
10647 }
10648 pos++;
10649 return currentToken;
10650 }
10651 function back(token) {
10652 returned.push(token);
10653 }
10654 return {
10655 back: back,
10656 endOfFile: endOfFile,
10657 nextToken: nextToken,
10658 position: position
10659 };
10660 };
10661 var Container$5$1 = container$1;
10662 var AtRule$3$1 = /*#__PURE__*/ function(Container$5$1) {
10663 _inherits(AtRule, Container$5$1);
10664 function AtRule(defaults) {
10665 var _this;
10666 _this = Container$5$1.call(this, defaults) || this;
10667 _this.type = "atrule";
10668 return _this;
10669 }
10670 var _proto = AtRule.prototype;
10671 _proto.append = function append() {
10672 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
10673 children[_key] = arguments[_key];
10674 }
10675 var _Container$5$1_prototype_append;
10676 if (!this.proxyOf.nodes) this.nodes = [];
10677 return (_Container$5$1_prototype_append = Container$5$1.prototype.append).call.apply(_Container$5$1_prototype_append, [].concat([
10678 this
10679 ], children));
10680 };
10681 _proto.prepend = function prepend() {
10682 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
10683 children[_key] = arguments[_key];
10684 }
10685 var _Container$5$1_prototype_prepend;
10686 if (!this.proxyOf.nodes) this.nodes = [];
10687 return (_Container$5$1_prototype_prepend = Container$5$1.prototype.prepend).call.apply(_Container$5$1_prototype_prepend, [].concat([
10688 this
10689 ], children));
10690 };
10691 return AtRule;
10692 }(Container$5$1);
10693 var atRule$1 = AtRule$3$1;
10694 AtRule$3$1.default = AtRule$3$1;
10695 Container$5$1.registerAtRule(AtRule$3$1);
10696 var Container$4$1 = container$1;
10697 var LazyResult$3$1, Processor$2$1;
10698 var Root$5$1 = /*#__PURE__*/ function(Container$4$1) {
10699 _inherits(Root, Container$4$1);
10700 function Root(defaults) {
10701 var _this;
10702 _this = Container$4$1.call(this, defaults) || this;
10703 _this.type = "root";
10704 if (!_this.nodes) _this.nodes = [];
10705 return _this;
10706 }
10707 var _proto = Root.prototype;
10708 _proto.normalize = function normalize(child, sample, type) {
10709 var nodes = Container$4$1.prototype.normalize.call(this, child);
10710 if (sample) {
10711 if (type === "prepend") {
10712 if (this.nodes.length > 1) {
10713 sample.raws.before = this.nodes[1].raws.before;
10714 } else {
10715 delete sample.raws.before;
10716 }
10717 } else if (this.first !== sample) {
10718 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
10719 var node2 = _step.value;
10720 node2.raws.before = sample.raws.before;
10721 }
10722 }
10723 }
10724 return nodes;
10725 };
10726 _proto.removeChild = function removeChild(child, ignore) {
10727 var index2 = this.index(child);
10728 if (!ignore && index2 === 0 && this.nodes.length > 1) {
10729 this.nodes[1].raws.before = this.nodes[index2].raws.before;
10730 }
10731 return Container$4$1.prototype.removeChild.call(this, child);
10732 };
10733 _proto.toResult = function toResult(opts) {
10734 if (opts === void 0) opts = {};
10735 var lazy = new LazyResult$3$1(new Processor$2$1(), this, opts);
10736 return lazy.stringify();
10737 };
10738 return Root;
10739 }(Container$4$1);
10740 Root$5$1.registerLazyResult = function(dependant) {
10741 LazyResult$3$1 = dependant;
10742 };
10743 Root$5$1.registerProcessor = function(dependant) {
10744 Processor$2$1 = dependant;
10745 };
10746 var root$1 = Root$5$1;
10747 Root$5$1.default = Root$5$1;
10748 Container$4$1.registerRoot(Root$5$1);
10749 var list$2$1 = {
10750 comma: function comma(string) {
10751 return list$2$1.split(string, [
10752 ","
10753 ], true);
10754 },
10755 space: function space(string) {
10756 var spaces = [
10757 " ",
10758 "\n",
10759 " "
10760 ];
10761 return list$2$1.split(string, spaces);
10762 },
10763 split: function split(string, separators, last) {
10764 var array = [];
10765 var current = "";
10766 var split = false;
10767 var func = 0;
10768 var inQuote = false;
10769 var prevQuote = "";
10770 var escape = false;
10771 for(var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;){
10772 var letter = _step.value;
10773 if (escape) {
10774 escape = false;
10775 } else if (letter === "\\") {
10776 escape = true;
10777 } else if (inQuote) {
10778 if (letter === prevQuote) {
10779 inQuote = false;
10780 }
10781 } else if (letter === '"' || letter === "'") {
10782 inQuote = true;
10783 prevQuote = letter;
10784 } else if (letter === "(") {
10785 func += 1;
10786 } else if (letter === ")") {
10787 if (func > 0) func -= 1;
10788 } else if (func === 0) {
10789 if (separators.includes(letter)) split = true;
10790 }
10791 if (split) {
10792 if (current !== "") array.push(current.trim());
10793 current = "";
10794 split = false;
10795 } else {
10796 current += letter;
10797 }
10798 }
10799 if (last || current !== "") array.push(current.trim());
10800 return array;
10801 }
10802 };
10803 var list_1$1 = list$2$1;
10804 list$2$1.default = list$2$1;
10805 var Container$3$1 = container$1;
10806 var list$1$1 = list_1$1;
10807 var Rule$3$1 = /*#__PURE__*/ function(Container$3$1) {
10808 _inherits(Rule, Container$3$1);
10809 function Rule(defaults) {
10810 var _this;
10811 _this = Container$3$1.call(this, defaults) || this;
10812 _this.type = "rule";
10813 if (!_this.nodes) _this.nodes = [];
10814 return _this;
10815 }
10816 _create_class(Rule, [
10817 {
10818 key: "selectors",
10819 get: function get() {
10820 return list$1$1.comma(this.selector);
10821 },
10822 set: function set(values) {
10823 var match = this.selector ? this.selector.match(/,\s*/) : null;
10824 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
10825 this.selector = values.join(sep2);
10826 }
10827 }
10828 ]);
10829 return Rule;
10830 }(Container$3$1);
10831 var rule$1 = Rule$3$1;
10832 Rule$3$1.default = Rule$3$1;
10833 Container$3$1.registerRule(Rule$3$1);
10834 var Declaration$2$1 = declaration$1;
10835 var tokenizer2$1 = tokenize$1;
10836 var Comment$2$1 = comment$1;
10837 var AtRule$2$1 = atRule$1;
10838 var Root$4$1 = root$1;
10839 var Rule$2$1 = rule$1;
10840 var SAFE_COMMENT_NEIGHBOR$1 = {
10841 empty: true,
10842 space: true
10843 };
10844 function findLastWithPosition$1(tokens) {
10845 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
10846 var token = tokens[i2];
10847 var pos = token[3] || token[2];
10848 if (pos) return pos;
10849 }
10850 }
10851 var Parser$1$1 = /*#__PURE__*/ function() {
10852 function Parser(input2) {
10853 this.input = input2;
10854 this.root = new Root$4$1();
10855 this.current = this.root;
10856 this.spaces = "";
10857 this.semicolon = false;
10858 this.createTokenizer();
10859 this.root.source = {
10860 input: input2,
10861 start: {
10862 column: 1,
10863 line: 1,
10864 offset: 0
10865 }
10866 };
10867 }
10868 var _proto = Parser.prototype;
10869 _proto.atrule = function atrule(token) {
10870 var node2 = new AtRule$2$1();
10871 node2.name = token[1].slice(1);
10872 if (node2.name === "") {
10873 this.unnamedAtrule(node2, token);
10874 }
10875 this.init(node2, token[2]);
10876 var type;
10877 var prev;
10878 var shift;
10879 var last = false;
10880 var open = false;
10881 var params = [];
10882 var brackets = [];
10883 while(!this.tokenizer.endOfFile()){
10884 token = this.tokenizer.nextToken();
10885 type = token[0];
10886 if (type === "(" || type === "[") {
10887 brackets.push(type === "(" ? ")" : "]");
10888 } else if (type === "{" && brackets.length > 0) {
10889 brackets.push("}");
10890 } else if (type === brackets[brackets.length - 1]) {
10891 brackets.pop();
10892 }
10893 if (brackets.length === 0) {
10894 if (type === ";") {
10895 node2.source.end = this.getPosition(token[2]);
10896 node2.source.end.offset++;
10897 this.semicolon = true;
10898 break;
10899 } else if (type === "{") {
10900 open = true;
10901 break;
10902 } else if (type === "}") {
10903 if (params.length > 0) {
10904 shift = params.length - 1;
10905 prev = params[shift];
10906 while(prev && prev[0] === "space"){
10907 prev = params[--shift];
10908 }
10909 if (prev) {
10910 node2.source.end = this.getPosition(prev[3] || prev[2]);
10911 node2.source.end.offset++;
10912 }
10913 }
10914 this.end(token);
10915 break;
10916 } else {
10917 params.push(token);
10918 }
10919 } else {
10920 params.push(token);
10921 }
10922 if (this.tokenizer.endOfFile()) {
10923 last = true;
10924 break;
10925 }
10926 }
10927 node2.raws.between = this.spacesAndCommentsFromEnd(params);
10928 if (params.length) {
10929 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
10930 this.raw(node2, "params", params);
10931 if (last) {
10932 token = params[params.length - 1];
10933 node2.source.end = this.getPosition(token[3] || token[2]);
10934 node2.source.end.offset++;
10935 this.spaces = node2.raws.between;
10936 node2.raws.between = "";
10937 }
10938 } else {
10939 node2.raws.afterName = "";
10940 node2.params = "";
10941 }
10942 if (open) {
10943 node2.nodes = [];
10944 this.current = node2;
10945 }
10946 };
10947 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
10948 var colon = this.colon(tokens);
10949 if (colon === false) return;
10950 var founded = 0;
10951 var token;
10952 for(var j = colon - 1; j >= 0; j--){
10953 token = tokens[j];
10954 if (token[0] !== "space") {
10955 founded += 1;
10956 if (founded === 2) break;
10957 }
10958 }
10959 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
10960 };
10961 _proto.colon = function colon(tokens) {
10962 var brackets = 0;
10963 var token, type, prev;
10964 for(var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;){
10965 var _step_value = _step.value, i2 = _step_value[0], element = _step_value[1];
10966 token = element;
10967 type = token[0];
10968 if (type === "(") {
10969 brackets += 1;
10970 }
10971 if (type === ")") {
10972 brackets -= 1;
10973 }
10974 if (brackets === 0 && type === ":") {
10975 if (!prev) {
10976 this.doubleColon(token);
10977 } else if (prev[0] === "word" && prev[1] === "progid") {
10978 continue;
10979 } else {
10980 return i2;
10981 }
10982 }
10983 prev = token;
10984 }
10985 return false;
10986 };
10987 _proto.comment = function comment(token) {
10988 var node2 = new Comment$2$1();
10989 this.init(node2, token[2]);
10990 node2.source.end = this.getPosition(token[3] || token[2]);
10991 node2.source.end.offset++;
10992 var text = token[1].slice(2, -2);
10993 if (/^\s*$/.test(text)) {
10994 node2.text = "";
10995 node2.raws.left = text;
10996 node2.raws.right = "";
10997 } else {
10998 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
10999 node2.text = match[2];
11000 node2.raws.left = match[1];
11001 node2.raws.right = match[3];
11002 }
11003 };
11004 _proto.createTokenizer = function createTokenizer() {
11005 this.tokenizer = tokenizer2$1(this.input);
11006 };
11007 _proto.decl = function decl(tokens, customProperty) {
11008 var node2 = new Declaration$2$1();
11009 this.init(node2, tokens[0][2]);
11010 var last = tokens[tokens.length - 1];
11011 if (last[0] === ";") {
11012 this.semicolon = true;
11013 tokens.pop();
11014 }
11015 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition$1(tokens));
11016 node2.source.end.offset++;
11017 while(tokens[0][0] !== "word"){
11018 if (tokens.length === 1) this.unknownWord(tokens);
11019 node2.raws.before += tokens.shift()[1];
11020 }
11021 node2.source.start = this.getPosition(tokens[0][2]);
11022 node2.prop = "";
11023 while(tokens.length){
11024 var type = tokens[0][0];
11025 if (type === ":" || type === "space" || type === "comment") {
11026 break;
11027 }
11028 node2.prop += tokens.shift()[1];
11029 }
11030 node2.raws.between = "";
11031 var token;
11032 while(tokens.length){
11033 token = tokens.shift();
11034 if (token[0] === ":") {
11035 node2.raws.between += token[1];
11036 break;
11037 } else {
11038 if (token[0] === "word" && /\w/.test(token[1])) {
11039 this.unknownWord([
11040 token
11041 ]);
11042 }
11043 node2.raws.between += token[1];
11044 }
11045 }
11046 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
11047 node2.raws.before += node2.prop[0];
11048 node2.prop = node2.prop.slice(1);
11049 }
11050 var firstSpaces = [];
11051 var next;
11052 while(tokens.length){
11053 next = tokens[0][0];
11054 if (next !== "space" && next !== "comment") break;
11055 firstSpaces.push(tokens.shift());
11056 }
11057 this.precheckMissedSemicolon(tokens);
11058 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
11059 token = tokens[i2];
11060 if (token[1].toLowerCase() === "!important") {
11061 node2.important = true;
11062 var string = this.stringFrom(tokens, i2);
11063 string = this.spacesFromEnd(tokens) + string;
11064 if (string !== " !important") node2.raws.important = string;
11065 break;
11066 } else if (token[1].toLowerCase() === "important") {
11067 var cache = tokens.slice(0);
11068 var str = "";
11069 for(var j = i2; j > 0; j--){
11070 var type1 = cache[j][0];
11071 if (str.trim().indexOf("!") === 0 && type1 !== "space") {
11072 break;
11073 }
11074 str = cache.pop()[1] + str;
11075 }
11076 if (str.trim().indexOf("!") === 0) {
11077 node2.important = true;
11078 node2.raws.important = str;
11079 tokens = cache;
11080 }
11081 }
11082 if (token[0] !== "space" && token[0] !== "comment") {
11083 break;
11084 }
11085 }
11086 var hasWord = tokens.some(function(i2) {
11087 return i2[0] !== "space" && i2[0] !== "comment";
11088 });
11089 if (hasWord) {
11090 node2.raws.between += firstSpaces.map(function(i2) {
11091 return i2[1];
11092 }).join("");
11093 firstSpaces = [];
11094 }
11095 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
11096 if (node2.value.includes(":") && !customProperty) {
11097 this.checkMissedSemicolon(tokens);
11098 }
11099 };
11100 _proto.doubleColon = function doubleColon(token) {
11101 throw this.input.error("Double colon", {
11102 offset: token[2]
11103 }, {
11104 offset: token[2] + token[1].length
11105 });
11106 };
11107 _proto.emptyRule = function emptyRule(token) {
11108 var node2 = new Rule$2$1();
11109 this.init(node2, token[2]);
11110 node2.selector = "";
11111 node2.raws.between = "";
11112 this.current = node2;
11113 };
11114 _proto.end = function end(token) {
11115 if (this.current.nodes && this.current.nodes.length) {
11116 this.current.raws.semicolon = this.semicolon;
11117 }
11118 this.semicolon = false;
11119 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
11120 this.spaces = "";
11121 if (this.current.parent) {
11122 this.current.source.end = this.getPosition(token[2]);
11123 this.current.source.end.offset++;
11124 this.current = this.current.parent;
11125 } else {
11126 this.unexpectedClose(token);
11127 }
11128 };
11129 _proto.endFile = function endFile() {
11130 if (this.current.parent) this.unclosedBlock();
11131 if (this.current.nodes && this.current.nodes.length) {
11132 this.current.raws.semicolon = this.semicolon;
11133 }
11134 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
11135 this.root.source.end = this.getPosition(this.tokenizer.position());
11136 };
11137 _proto.freeSemicolon = function freeSemicolon(token) {
11138 this.spaces += token[1];
11139 if (this.current.nodes) {
11140 var prev = this.current.nodes[this.current.nodes.length - 1];
11141 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
11142 prev.raws.ownSemicolon = this.spaces;
11143 this.spaces = "";
11144 }
11145 }
11146 };
11147 // Helpers
11148 _proto.getPosition = function getPosition(offset) {
11149 var pos = this.input.fromOffset(offset);
11150 return {
11151 column: pos.col,
11152 line: pos.line,
11153 offset: offset
11154 };
11155 };
11156 _proto.init = function init(node2, offset) {
11157 this.current.push(node2);
11158 node2.source = {
11159 input: this.input,
11160 start: this.getPosition(offset)
11161 };
11162 node2.raws.before = this.spaces;
11163 this.spaces = "";
11164 if (node2.type !== "comment") this.semicolon = false;
11165 };
11166 _proto.other = function other(start) {
11167 var end = false;
11168 var type = null;
11169 var colon = false;
11170 var bracket = null;
11171 var brackets = [];
11172 var customProperty = start[1].startsWith("--");
11173 var tokens = [];
11174 var token = start;
11175 while(token){
11176 type = token[0];
11177 tokens.push(token);
11178 if (type === "(" || type === "[") {
11179 if (!bracket) bracket = token;
11180 brackets.push(type === "(" ? ")" : "]");
11181 } else if (customProperty && colon && type === "{") {
11182 if (!bracket) bracket = token;
11183 brackets.push("}");
11184 } else if (brackets.length === 0) {
11185 if (type === ";") {
11186 if (colon) {
11187 this.decl(tokens, customProperty);
11188 return;
11189 } else {
11190 break;
11191 }
11192 } else if (type === "{") {
11193 this.rule(tokens);
11194 return;
11195 } else if (type === "}") {
11196 this.tokenizer.back(tokens.pop());
11197 end = true;
11198 break;
11199 } else if (type === ":") {
11200 colon = true;
11201 }
11202 } else if (type === brackets[brackets.length - 1]) {
11203 brackets.pop();
11204 if (brackets.length === 0) bracket = null;
11205 }
11206 token = this.tokenizer.nextToken();
11207 }
11208 if (this.tokenizer.endOfFile()) end = true;
11209 if (brackets.length > 0) this.unclosedBracket(bracket);
11210 if (end && colon) {
11211 if (!customProperty) {
11212 while(tokens.length){
11213 token = tokens[tokens.length - 1][0];
11214 if (token !== "space" && token !== "comment") break;
11215 this.tokenizer.back(tokens.pop());
11216 }
11217 }
11218 this.decl(tokens, customProperty);
11219 } else {
11220 this.unknownWord(tokens);
11221 }
11222 };
11223 _proto.parse = function parse() {
11224 var token;
11225 while(!this.tokenizer.endOfFile()){
11226 token = this.tokenizer.nextToken();
11227 switch(token[0]){
11228 case "space":
11229 this.spaces += token[1];
11230 break;
11231 case ";":
11232 this.freeSemicolon(token);
11233 break;
11234 case "}":
11235 this.end(token);
11236 break;
11237 case "comment":
11238 this.comment(token);
11239 break;
11240 case "at-word":
11241 this.atrule(token);
11242 break;
11243 case "{":
11244 this.emptyRule(token);
11245 break;
11246 default:
11247 this.other(token);
11248 break;
11249 }
11250 }
11251 this.endFile();
11252 };
11253 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
11254 _proto.raw = function raw(node2, prop, tokens, customProperty) {
11255 var token, type;
11256 var length = tokens.length;
11257 var value = "";
11258 var clean = true;
11259 var next, prev;
11260 for(var i2 = 0; i2 < length; i2 += 1){
11261 token = tokens[i2];
11262 type = token[0];
11263 if (type === "space" && i2 === length - 1 && !customProperty) {
11264 clean = false;
11265 } else if (type === "comment") {
11266 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
11267 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
11268 if (!SAFE_COMMENT_NEIGHBOR$1[prev] && !SAFE_COMMENT_NEIGHBOR$1[next]) {
11269 if (value.slice(-1) === ",") {
11270 clean = false;
11271 } else {
11272 value += token[1];
11273 }
11274 } else {
11275 clean = false;
11276 }
11277 } else {
11278 value += token[1];
11279 }
11280 }
11281 if (!clean) {
11282 var raw = tokens.reduce(function(all, i2) {
11283 return all + i2[1];
11284 }, "");
11285 node2.raws[prop] = {
11286 raw: raw,
11287 value: value
11288 };
11289 }
11290 node2[prop] = value;
11291 };
11292 _proto.rule = function rule(tokens) {
11293 tokens.pop();
11294 var node2 = new Rule$2$1();
11295 this.init(node2, tokens[0][2]);
11296 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
11297 this.raw(node2, "selector", tokens);
11298 this.current = node2;
11299 };
11300 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
11301 var lastTokenType;
11302 var spaces = "";
11303 while(tokens.length){
11304 lastTokenType = tokens[tokens.length - 1][0];
11305 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
11306 spaces = tokens.pop()[1] + spaces;
11307 }
11308 return spaces;
11309 };
11310 // Errors
11311 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
11312 var next;
11313 var spaces = "";
11314 while(tokens.length){
11315 next = tokens[0][0];
11316 if (next !== "space" && next !== "comment") break;
11317 spaces += tokens.shift()[1];
11318 }
11319 return spaces;
11320 };
11321 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
11322 var lastTokenType;
11323 var spaces = "";
11324 while(tokens.length){
11325 lastTokenType = tokens[tokens.length - 1][0];
11326 if (lastTokenType !== "space") break;
11327 spaces = tokens.pop()[1] + spaces;
11328 }
11329 return spaces;
11330 };
11331 _proto.stringFrom = function stringFrom(tokens, from) {
11332 var result2 = "";
11333 for(var i2 = from; i2 < tokens.length; i2++){
11334 result2 += tokens[i2][1];
11335 }
11336 tokens.splice(from, tokens.length - from);
11337 return result2;
11338 };
11339 _proto.unclosedBlock = function unclosedBlock() {
11340 var pos = this.current.source.start;
11341 throw this.input.error("Unclosed block", pos.line, pos.column);
11342 };
11343 _proto.unclosedBracket = function unclosedBracket(bracket) {
11344 throw this.input.error("Unclosed bracket", {
11345 offset: bracket[2]
11346 }, {
11347 offset: bracket[2] + 1
11348 });
11349 };
11350 _proto.unexpectedClose = function unexpectedClose(token) {
11351 throw this.input.error("Unexpected }", {
11352 offset: token[2]
11353 }, {
11354 offset: token[2] + 1
11355 });
11356 };
11357 _proto.unknownWord = function unknownWord(tokens) {
11358 throw this.input.error("Unknown word", {
11359 offset: tokens[0][2]
11360 }, {
11361 offset: tokens[0][2] + tokens[0][1].length
11362 });
11363 };
11364 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
11365 throw this.input.error("At-rule without name", {
11366 offset: token[2]
11367 }, {
11368 offset: token[2] + token[1].length
11369 });
11370 };
11371 return Parser;
11372 }();
11373 var parser$1 = Parser$1$1;
11374 var Container$2$1 = container$1;
11375 var Parser2$1 = parser$1;
11376 var Input$2$1 = input$1;
11377 function parse$3$1(css, opts) {
11378 var input2 = new Input$2$1(css, opts);
11379 var parser2 = new Parser2$1(input2);
11380 try {
11381 parser2.parse();
11382 } catch (e2) {
11383 if (true) {
11384 if (e2.name === "CssSyntaxError" && opts && opts.from) {
11385 if (/\.scss$/i.test(opts.from)) {
11386 e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
11387 } else if (/\.sass/i.test(opts.from)) {
11388 e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
11389 } else if (/\.less$/i.test(opts.from)) {
11390 e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
11391 }
11392 }
11393 }
11394 throw e2;
11395 }
11396 return parser2.root;
11397 }
11398 var parse_1$1 = parse$3$1;
11399 parse$3$1.default = parse$3$1;
11400 Container$2$1.registerParse(parse$3$1);
11401 var isClean$3 = symbols$1.isClean, my$3 = symbols$1.my;
11402 var MapGenerator$1$1 = mapGenerator$1;
11403 var stringify$2$1 = stringify_1$1;
11404 var Container$1$1 = container$1;
11405 var Document$2$1 = document$1$1;
11406 var warnOnce$1$1 = warnOnce$2$1;
11407 var Result$2$1 = result$1;
11408 var parse$2$1 = parse_1$1;
11409 var Root$3$1 = root$1;
11410 var TYPE_TO_CLASS_NAME$1 = {
11411 atrule: "AtRule",
11412 comment: "Comment",
11413 decl: "Declaration",
11414 document: "Document",
11415 root: "Root",
11416 rule: "Rule"
11417 };
11418 var PLUGIN_PROPS$1 = {
11419 AtRule: true,
11420 AtRuleExit: true,
11421 Comment: true,
11422 CommentExit: true,
11423 Declaration: true,
11424 DeclarationExit: true,
11425 Document: true,
11426 DocumentExit: true,
11427 Once: true,
11428 OnceExit: true,
11429 postcssPlugin: true,
11430 prepare: true,
11431 Root: true,
11432 RootExit: true,
11433 Rule: true,
11434 RuleExit: true
11435 };
11436 var NOT_VISITORS$1 = {
11437 Once: true,
11438 postcssPlugin: true,
11439 prepare: true
11440 };
11441 var CHILDREN$1 = 0;
11442 function isPromise$1(obj) {
11443 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
11444 }
11445 function getEvents$1(node2) {
11446 var key = false;
11447 var type = TYPE_TO_CLASS_NAME$1[node2.type];
11448 if (node2.type === "decl") {
11449 key = node2.prop.toLowerCase();
11450 } else if (node2.type === "atrule") {
11451 key = node2.name.toLowerCase();
11452 }
11453 if (key && node2.append) {
11454 return [
11455 type,
11456 type + "-" + key,
11457 CHILDREN$1,
11458 type + "Exit",
11459 type + "Exit-" + key
11460 ];
11461 } else if (key) {
11462 return [
11463 type,
11464 type + "-" + key,
11465 type + "Exit",
11466 type + "Exit-" + key
11467 ];
11468 } else if (node2.append) {
11469 return [
11470 type,
11471 CHILDREN$1,
11472 type + "Exit"
11473 ];
11474 } else {
11475 return [
11476 type,
11477 type + "Exit"
11478 ];
11479 }
11480 }
11481 function toStack$1(node2) {
11482 var events;
11483 if (node2.type === "document") {
11484 events = [
11485 "Document",
11486 CHILDREN$1,
11487 "DocumentExit"
11488 ];
11489 } else if (node2.type === "root") {
11490 events = [
11491 "Root",
11492 CHILDREN$1,
11493 "RootExit"
11494 ];
11495 } else {
11496 events = getEvents$1(node2);
11497 }
11498 return {
11499 eventIndex: 0,
11500 events: events,
11501 iterator: 0,
11502 node: node2,
11503 visitorIndex: 0,
11504 visitors: []
11505 };
11506 }
11507 function cleanMarks$1(node2) {
11508 node2[isClean$3] = false;
11509 if (node2.nodes) node2.nodes.forEach(function(i2) {
11510 return cleanMarks$1(i2);
11511 });
11512 return node2;
11513 }
11514 var postcss$2$1 = {};
11515 var LazyResult$2$1 = /*#__PURE__*/ function() {
11516 function LazyResult(processor2, css, opts) {
11517 var _this = this;
11518 this.stringified = false;
11519 this.processed = false;
11520 var root2;
11521 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) {
11522 root2 = cleanMarks$1(css);
11523 } else if (_instanceof(css, LazyResult) || _instanceof(css, Result$2$1)) {
11524 root2 = cleanMarks$1(css.root);
11525 if (css.map) {
11526 if (typeof opts.map === "undefined") opts.map = {};
11527 if (!opts.map.inline) opts.map.inline = false;
11528 opts.map.prev = css.map;
11529 }
11530 } else {
11531 var parser2 = parse$2$1;
11532 if (opts.syntax) parser2 = opts.syntax.parse;
11533 if (opts.parser) parser2 = opts.parser;
11534 if (parser2.parse) parser2 = parser2.parse;
11535 try {
11536 root2 = parser2(css, opts);
11537 } catch (error) {
11538 this.processed = true;
11539 this.error = error;
11540 }
11541 if (root2 && !root2[my$3]) {
11542 Container$1$1.rebuild(root2);
11543 }
11544 }
11545 this.result = new Result$2$1(processor2, root2, opts);
11546 this.helpers = _extends({}, postcss$2$1, {
11547 postcss: postcss$2$1,
11548 result: this.result
11549 });
11550 this.plugins = this.processor.plugins.map(function(plugin22) {
11551 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) {
11552 return _extends({}, plugin22, plugin22.prepare(_this.result));
11553 } else {
11554 return plugin22;
11555 }
11556 });
11557 }
11558 var _proto = LazyResult.prototype;
11559 _proto.async = function async() {
11560 if (this.error) return Promise.reject(this.error);
11561 if (this.processed) return Promise.resolve(this.result);
11562 if (!this.processing) {
11563 this.processing = this.runAsync();
11564 }
11565 return this.processing;
11566 };
11567 _proto.catch = function _catch(onRejected) {
11568 return this.async().catch(onRejected);
11569 };
11570 _proto.finally = function _finally(onFinally) {
11571 return this.async().then(onFinally, onFinally);
11572 };
11573 _proto.getAsyncError = function getAsyncError() {
11574 throw new Error("Use process(css).then(cb) to work with async plugins");
11575 };
11576 _proto.handleError = function handleError(error, node2) {
11577 var plugin22 = this.result.lastPlugin;
11578 try {
11579 if (node2) node2.addToError(error);
11580 this.error = error;
11581 if (error.name === "CssSyntaxError" && !error.plugin) {
11582 error.plugin = plugin22.postcssPlugin;
11583 error.setMessage();
11584 } else if (plugin22.postcssVersion) {
11585 if (true) {
11586 var pluginName = plugin22.postcssPlugin;
11587 var pluginVer = plugin22.postcssVersion;
11588 var runtimeVer = this.result.processor.version;
11589 var a2 = pluginVer.split(".");
11590 var b = runtimeVer.split(".");
11591 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) {
11592 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.");
11593 }
11594 }
11595 }
11596 } catch (err) {
11597 if (console && console.error) console.error(err);
11598 }
11599 return error;
11600 };
11601 _proto.prepareVisitors = function prepareVisitors() {
11602 var _this = this;
11603 this.listeners = {};
11604 var add = function(plugin22, type, cb) {
11605 if (!_this.listeners[type]) _this.listeners[type] = [];
11606 _this.listeners[type].push([
11607 plugin22,
11608 cb
11609 ]);
11610 };
11611 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
11612 var plugin22 = _step.value;
11613 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") {
11614 for(var event in plugin22){
11615 if (!PLUGIN_PROPS$1[event] && /^[A-Z]/.test(event)) {
11616 throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
11617 }
11618 if (!NOT_VISITORS$1[event]) {
11619 if (_type_of(plugin22[event]) === "object") {
11620 for(var filter in plugin22[event]){
11621 if (filter === "*") {
11622 add(plugin22, event, plugin22[event][filter]);
11623 } else {
11624 add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
11625 }
11626 }
11627 } else if (typeof plugin22[event] === "function") {
11628 add(plugin22, event, plugin22[event]);
11629 }
11630 }
11631 }
11632 }
11633 }
11634 this.hasListener = Object.keys(this.listeners).length > 0;
11635 };
11636 _proto.runAsync = function runAsync() {
11637 var _this = this;
11638 return _async_to_generator(function() {
11639 var i2, plugin22, promise, error, root2, stack, promise1, e2, node2, _loop, _iterator, _step;
11640 return _ts_generator(this, function(_state) {
11641 switch(_state.label){
11642 case 0:
11643 _this.plugin = 0;
11644 i2 = 0;
11645 _state.label = 1;
11646 case 1:
11647 if (!(i2 < _this.plugins.length)) return [
11648 3,
11649 6
11650 ];
11651 plugin22 = _this.plugins[i2];
11652 promise = _this.runOnRoot(plugin22);
11653 if (!isPromise$1(promise)) return [
11654 3,
11655 5
11656 ];
11657 _state.label = 2;
11658 case 2:
11659 _state.trys.push([
11660 2,
11661 4,
11662 ,
11663 5
11664 ]);
11665 return [
11666 4,
11667 promise
11668 ];
11669 case 3:
11670 _state.sent();
11671 return [
11672 3,
11673 5
11674 ];
11675 case 4:
11676 error = _state.sent();
11677 throw _this.handleError(error);
11678 case 5:
11679 i2++;
11680 return [
11681 3,
11682 1
11683 ];
11684 case 6:
11685 _this.prepareVisitors();
11686 if (!_this.hasListener) return [
11687 3,
11688 18
11689 ];
11690 root2 = _this.result.root;
11691 _state.label = 7;
11692 case 7:
11693 if (!!root2[isClean$3]) return [
11694 3,
11695 14
11696 ];
11697 root2[isClean$3] = true;
11698 stack = [
11699 toStack$1(root2)
11700 ];
11701 _state.label = 8;
11702 case 8:
11703 if (!(stack.length > 0)) return [
11704 3,
11705 13
11706 ];
11707 promise1 = _this.visitTick(stack);
11708 if (!isPromise$1(promise1)) return [
11709 3,
11710 12
11711 ];
11712 _state.label = 9;
11713 case 9:
11714 _state.trys.push([
11715 9,
11716 11,
11717 ,
11718 12
11719 ]);
11720 return [
11721 4,
11722 promise1
11723 ];
11724 case 10:
11725 _state.sent();
11726 return [
11727 3,
11728 12
11729 ];
11730 case 11:
11731 e2 = _state.sent();
11732 node2 = stack[stack.length - 1].node;
11733 throw _this.handleError(e2, node2);
11734 case 12:
11735 return [
11736 3,
11737 8
11738 ];
11739 case 13:
11740 return [
11741 3,
11742 7
11743 ];
11744 case 14:
11745 if (!_this.listeners.OnceExit) return [
11746 3,
11747 18
11748 ];
11749 _loop = function() {
11750 var _step_value, plugin22, visitor, roots, e2;
11751 return _ts_generator(this, function(_state) {
11752 switch(_state.label){
11753 case 0:
11754 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
11755 _this.result.lastPlugin = plugin22;
11756 _state.label = 1;
11757 case 1:
11758 _state.trys.push([
11759 1,
11760 6,
11761 ,
11762 7
11763 ]);
11764 if (!(root2.type === "document")) return [
11765 3,
11766 3
11767 ];
11768 roots = root2.nodes.map(function(subRoot) {
11769 return visitor(subRoot, _this.helpers);
11770 });
11771 return [
11772 4,
11773 Promise.all(roots)
11774 ];
11775 case 2:
11776 _state.sent();
11777 return [
11778 3,
11779 5
11780 ];
11781 case 3:
11782 return [
11783 4,
11784 visitor(root2, _this.helpers)
11785 ];
11786 case 4:
11787 _state.sent();
11788 _state.label = 5;
11789 case 5:
11790 return [
11791 3,
11792 7
11793 ];
11794 case 6:
11795 e2 = _state.sent();
11796 throw _this.handleError(e2);
11797 case 7:
11798 return [
11799 2
11800 ];
11801 }
11802 });
11803 };
11804 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
11805 _state.label = 15;
11806 case 15:
11807 if (!!(_step = _iterator()).done) return [
11808 3,
11809 18
11810 ];
11811 return [
11812 5,
11813 _ts_values(_loop())
11814 ];
11815 case 16:
11816 _state.sent();
11817 _state.label = 17;
11818 case 17:
11819 return [
11820 3,
11821 15
11822 ];
11823 case 18:
11824 _this.processed = true;
11825 return [
11826 2,
11827 _this.stringify()
11828 ];
11829 }
11830 });
11831 })();
11832 };
11833 _proto.runOnRoot = function runOnRoot(plugin22) {
11834 var _this = this;
11835 this.result.lastPlugin = plugin22;
11836 try {
11837 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
11838 if (this.result.root.type === "document") {
11839 var roots = this.result.root.nodes.map(function(root2) {
11840 return plugin22.Once(root2, _this.helpers);
11841 });
11842 if (isPromise$1(roots[0])) {
11843 return Promise.all(roots);
11844 }
11845 return roots;
11846 }
11847 return plugin22.Once(this.result.root, this.helpers);
11848 } else if (typeof plugin22 === "function") {
11849 return plugin22(this.result.root, this.result);
11850 }
11851 } catch (error) {
11852 throw this.handleError(error);
11853 }
11854 };
11855 _proto.stringify = function stringify() {
11856 if (this.error) throw this.error;
11857 if (this.stringified) return this.result;
11858 this.stringified = true;
11859 this.sync();
11860 var opts = this.result.opts;
11861 var str = stringify$2$1;
11862 if (opts.syntax) str = opts.syntax.stringify;
11863 if (opts.stringifier) str = opts.stringifier;
11864 if (str.stringify) str = str.stringify;
11865 var map = new MapGenerator$1$1(str, this.result.root, this.result.opts);
11866 var data = map.generate();
11867 this.result.css = data[0];
11868 this.result.map = data[1];
11869 return this.result;
11870 };
11871 _proto.sync = function sync() {
11872 if (this.error) throw this.error;
11873 if (this.processed) return this.result;
11874 this.processed = true;
11875 if (this.processing) {
11876 throw this.getAsyncError();
11877 }
11878 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
11879 var plugin22 = _step.value;
11880 var promise = this.runOnRoot(plugin22);
11881 if (isPromise$1(promise)) {
11882 throw this.getAsyncError();
11883 }
11884 }
11885 this.prepareVisitors();
11886 if (this.hasListener) {
11887 var root2 = this.result.root;
11888 while(!root2[isClean$3]){
11889 root2[isClean$3] = true;
11890 this.walkSync(root2);
11891 }
11892 if (this.listeners.OnceExit) {
11893 if (root2.type === "document") {
11894 for(var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;){
11895 var subRoot = _step1.value;
11896 this.visitSync(this.listeners.OnceExit, subRoot);
11897 }
11898 } else {
11899 this.visitSync(this.listeners.OnceExit, root2);
11900 }
11901 }
11902 }
11903 return this.result;
11904 };
11905 _proto.then = function then(onFulfilled, onRejected) {
11906 if (true) {
11907 if (!("from" in this.opts)) {
11908 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.");
11909 }
11910 }
11911 return this.async().then(onFulfilled, onRejected);
11912 };
11913 _proto.toString = function toString() {
11914 return this.css;
11915 };
11916 _proto.visitSync = function visitSync(visitors, node2) {
11917 for(var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;){
11918 var _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
11919 this.result.lastPlugin = plugin22;
11920 var promise = void 0;
11921 try {
11922 promise = visitor(node2, this.helpers);
11923 } catch (e2) {
11924 throw this.handleError(e2, node2.proxyOf);
11925 }
11926 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
11927 return true;
11928 }
11929 if (isPromise$1(promise)) {
11930 throw this.getAsyncError();
11931 }
11932 }
11933 };
11934 _proto.visitTick = function visitTick(stack) {
11935 var visit2 = stack[stack.length - 1];
11936 var node2 = visit2.node, visitors = visit2.visitors;
11937 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
11938 stack.pop();
11939 return;
11940 }
11941 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
11942 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex], plugin22 = _visitors_visit2_visitorIndex[0], visitor = _visitors_visit2_visitorIndex[1];
11943 visit2.visitorIndex += 1;
11944 if (visit2.visitorIndex === visitors.length) {
11945 visit2.visitors = [];
11946 visit2.visitorIndex = 0;
11947 }
11948 this.result.lastPlugin = plugin22;
11949 try {
11950 return visitor(node2.toProxy(), this.helpers);
11951 } catch (e2) {
11952 throw this.handleError(e2, node2);
11953 }
11954 }
11955 if (visit2.iterator !== 0) {
11956 var iterator = visit2.iterator;
11957 var child;
11958 while(child = node2.nodes[node2.indexes[iterator]]){
11959 node2.indexes[iterator] += 1;
11960 if (!child[isClean$3]) {
11961 child[isClean$3] = true;
11962 stack.push(toStack$1(child));
11963 return;
11964 }
11965 }
11966 visit2.iterator = 0;
11967 delete node2.indexes[iterator];
11968 }
11969 var events = visit2.events;
11970 while(visit2.eventIndex < events.length){
11971 var event = events[visit2.eventIndex];
11972 visit2.eventIndex += 1;
11973 if (event === CHILDREN$1) {
11974 if (node2.nodes && node2.nodes.length) {
11975 node2[isClean$3] = true;
11976 visit2.iterator = node2.getIterator();
11977 }
11978 return;
11979 } else if (this.listeners[event]) {
11980 visit2.visitors = this.listeners[event];
11981 return;
11982 }
11983 }
11984 stack.pop();
11985 };
11986 _proto.walkSync = function walkSync(node2) {
11987 var _this = this;
11988 node2[isClean$3] = true;
11989 var events = getEvents$1(node2);
11990 for(var _iterator = _create_for_of_iterator_helper_loose(events), _step; !(_step = _iterator()).done;){
11991 var event = _step.value;
11992 if (event === CHILDREN$1) {
11993 if (node2.nodes) {
11994 node2.each(function(child) {
11995 if (!child[isClean$3]) _this.walkSync(child);
11996 });
11997 }
11998 } else {
11999 var visitors = this.listeners[event];
12000 if (visitors) {
12001 if (this.visitSync(visitors, node2.toProxy())) return;
12002 }
12003 }
12004 }
12005 };
12006 _proto.warnings = function warnings() {
12007 return this.sync().warnings();
12008 };
12009 _create_class(LazyResult, [
12010 {
12011 key: "content",
12012 get: function get() {
12013 return this.stringify().content;
12014 }
12015 },
12016 {
12017 key: "css",
12018 get: function get() {
12019 return this.stringify().css;
12020 }
12021 },
12022 {
12023 key: "map",
12024 get: function get() {
12025 return this.stringify().map;
12026 }
12027 },
12028 {
12029 key: "messages",
12030 get: function get() {
12031 return this.sync().messages;
12032 }
12033 },
12034 {
12035 key: "opts",
12036 get: function get() {
12037 return this.result.opts;
12038 }
12039 },
12040 {
12041 key: "processor",
12042 get: function get() {
12043 return this.result.processor;
12044 }
12045 },
12046 {
12047 key: "root",
12048 get: function get() {
12049 return this.sync().root;
12050 }
12051 },
12052 {
12053 key: Symbol.toStringTag,
12054 get: function get() {
12055 return "LazyResult";
12056 }
12057 }
12058 ]);
12059 return LazyResult;
12060 }();
12061 LazyResult$2$1.registerPostcss = function(dependant) {
12062 postcss$2$1 = dependant;
12063 };
12064 var lazyResult$1 = LazyResult$2$1;
12065 LazyResult$2$1.default = LazyResult$2$1;
12066 Root$3$1.registerLazyResult(LazyResult$2$1);
12067 Document$2$1.registerLazyResult(LazyResult$2$1);
12068 var MapGenerator2$1 = mapGenerator$1;
12069 var stringify$1$1 = stringify_1$1;
12070 var warnOnce2$1 = warnOnce$2$1;
12071 var parse$1$1 = parse_1$1;
12072 var Result$1$1 = result$1;
12073 var NoWorkResult$1$1 = /*#__PURE__*/ function() {
12074 function NoWorkResult(processor2, css, opts) {
12075 css = css.toString();
12076 this.stringified = false;
12077 this._processor = processor2;
12078 this._css = css;
12079 this._opts = opts;
12080 this._map = void 0;
12081 var root2;
12082 var str = stringify$1$1;
12083 this.result = new Result$1$1(this._processor, root2, this._opts);
12084 this.result.css = css;
12085 var self = this;
12086 Object.defineProperty(this.result, "root", {
12087 get: function get() {
12088 return self.root;
12089 }
12090 });
12091 var map = new MapGenerator2$1(str, root2, this._opts, css);
12092 if (map.isMap()) {
12093 var _map_generate = map.generate(), generatedCSS = _map_generate[0], generatedMap = _map_generate[1];
12094 if (generatedCSS) {
12095 this.result.css = generatedCSS;
12096 }
12097 if (generatedMap) {
12098 this.result.map = generatedMap;
12099 }
12100 } else {
12101 map.clearAnnotation();
12102 this.result.css = map.css;
12103 }
12104 }
12105 var _proto = NoWorkResult.prototype;
12106 _proto.async = function async() {
12107 if (this.error) return Promise.reject(this.error);
12108 return Promise.resolve(this.result);
12109 };
12110 _proto.catch = function _catch(onRejected) {
12111 return this.async().catch(onRejected);
12112 };
12113 _proto.finally = function _finally(onFinally) {
12114 return this.async().then(onFinally, onFinally);
12115 };
12116 _proto.sync = function sync() {
12117 if (this.error) throw this.error;
12118 return this.result;
12119 };
12120 _proto.then = function then(onFulfilled, onRejected) {
12121 if (true) {
12122 if (!("from" in this._opts)) {
12123 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.");
12124 }
12125 }
12126 return this.async().then(onFulfilled, onRejected);
12127 };
12128 _proto.toString = function toString() {
12129 return this._css;
12130 };
12131 _proto.warnings = function warnings() {
12132 return [];
12133 };
12134 _create_class(NoWorkResult, [
12135 {
12136 key: "content",
12137 get: function get() {
12138 return this.result.css;
12139 }
12140 },
12141 {
12142 key: "css",
12143 get: function get() {
12144 return this.result.css;
12145 }
12146 },
12147 {
12148 key: "map",
12149 get: function get() {
12150 return this.result.map;
12151 }
12152 },
12153 {
12154 key: "messages",
12155 get: function get() {
12156 return [];
12157 }
12158 },
12159 {
12160 key: "opts",
12161 get: function get() {
12162 return this.result.opts;
12163 }
12164 },
12165 {
12166 key: "processor",
12167 get: function get() {
12168 return this.result.processor;
12169 }
12170 },
12171 {
12172 key: "root",
12173 get: function get() {
12174 if (this._root) {
12175 return this._root;
12176 }
12177 var root2;
12178 var parser2 = parse$1$1;
12179 try {
12180 root2 = parser2(this._css, this._opts);
12181 } catch (error) {
12182 this.error = error;
12183 }
12184 if (this.error) {
12185 throw this.error;
12186 } else {
12187 this._root = root2;
12188 return root2;
12189 }
12190 }
12191 },
12192 {
12193 key: Symbol.toStringTag,
12194 get: function get() {
12195 return "NoWorkResult";
12196 }
12197 }
12198 ]);
12199 return NoWorkResult;
12200 }();
12201 var noWorkResult$1 = NoWorkResult$1$1;
12202 NoWorkResult$1$1.default = NoWorkResult$1$1;
12203 var NoWorkResult2$1 = noWorkResult$1;
12204 var LazyResult$1$1 = lazyResult$1;
12205 var Document$1$1 = document$1$1;
12206 var Root$2$1 = root$1;
12207 var Processor$1$1 = /*#__PURE__*/ function() {
12208 function Processor(plugins) {
12209 if (plugins === void 0) plugins = [];
12210 this.version = "8.4.38";
12211 this.plugins = this.normalize(plugins);
12212 }
12213 var _proto = Processor.prototype;
12214 _proto.normalize = function normalize(plugins) {
12215 var normalized = [];
12216 for(var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;){
12217 var i2 = _step.value;
12218 if (i2.postcss === true) {
12219 i2 = i2();
12220 } else if (i2.postcss) {
12221 i2 = i2.postcss;
12222 }
12223 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) {
12224 normalized = normalized.concat(i2.plugins);
12225 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) {
12226 normalized.push(i2);
12227 } else if (typeof i2 === "function") {
12228 normalized.push(i2);
12229 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) {
12230 if (true) {
12231 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.");
12232 }
12233 } else {
12234 throw new Error(i2 + " is not a PostCSS plugin");
12235 }
12236 }
12237 return normalized;
12238 };
12239 _proto.process = function process1(css, opts) {
12240 if (opts === void 0) opts = {};
12241 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
12242 return new NoWorkResult2$1(this, css, opts);
12243 } else {
12244 return new LazyResult$1$1(this, css, opts);
12245 }
12246 };
12247 _proto.use = function use(plugin22) {
12248 this.plugins = this.plugins.concat(this.normalize([
12249 plugin22
12250 ]));
12251 return this;
12252 };
12253 return Processor;
12254 }();
12255 var processor$1 = Processor$1$1;
12256 Processor$1$1.default = Processor$1$1;
12257 Root$2$1.registerProcessor(Processor$1$1);
12258 Document$1$1.registerProcessor(Processor$1$1);
12259 var Declaration$1$1 = declaration$1;
12260 var PreviousMap2$1 = previousMap$1;
12261 var Comment$1$1 = comment$1;
12262 var AtRule$1$1 = atRule$1;
12263 var Input$1$1 = input$1;
12264 var Root$1$1 = root$1;
12265 var Rule$1$1 = rule$1;
12266 function fromJSON$1$1(json, inputs) {
12267 if (Array.isArray(json)) return json.map(function(n2) {
12268 return fromJSON$1$1(n2);
12269 });
12270 var ownInputs = json.inputs, defaults = _object_without_properties_loose(json, [
12271 "inputs"
12272 ]);
12273 if (ownInputs) {
12274 inputs = [];
12275 for(var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;){
12276 var input2 = _step.value;
12277 var inputHydrated = _extends({}, input2, {
12278 __proto__: Input$1$1.prototype
12279 });
12280 if (inputHydrated.map) {
12281 inputHydrated.map = _extends({}, inputHydrated.map, {
12282 __proto__: PreviousMap2$1.prototype
12283 });
12284 }
12285 inputs.push(inputHydrated);
12286 }
12287 }
12288 if (defaults.nodes) {
12289 defaults.nodes = json.nodes.map(function(n2) {
12290 return fromJSON$1$1(n2, inputs);
12291 });
12292 }
12293 if (defaults.source) {
12294 var _defaults_source = defaults.source, inputId = _defaults_source.inputId, source = _object_without_properties_loose(_defaults_source, [
12295 "inputId"
12296 ]);
12297 defaults.source = source;
12298 if (inputId != null) {
12299 defaults.source.input = inputs[inputId];
12300 }
12301 }
12302 if (defaults.type === "root") {
12303 return new Root$1$1(defaults);
12304 } else if (defaults.type === "decl") {
12305 return new Declaration$1$1(defaults);
12306 } else if (defaults.type === "rule") {
12307 return new Rule$1$1(defaults);
12308 } else if (defaults.type === "comment") {
12309 return new Comment$1$1(defaults);
12310 } else if (defaults.type === "atrule") {
12311 return new AtRule$1$1(defaults);
12312 } else {
12313 throw new Error("Unknown node type: " + json.type);
12314 }
12315 }
12316 var fromJSON_1$1 = fromJSON$1$1;
12317 fromJSON$1$1.default = fromJSON$1$1;
12318 var CssSyntaxError2$1 = cssSyntaxError$1;
12319 var Declaration2$1 = declaration$1;
12320 var LazyResult2$1 = lazyResult$1;
12321 var Container2$1 = container$1;
12322 var Processor2$1 = processor$1;
12323 var stringify$5 = stringify_1$1;
12324 var fromJSON$2 = fromJSON_1$1;
12325 var Document22 = document$1$1;
12326 var Warning2$1 = warning$1;
12327 var Comment2$1 = comment$1;
12328 var AtRule2$1 = atRule$1;
12329 var Result2$1 = result$1;
12330 var Input2$1 = input$1;
12331 var parse$5 = parse_1$1;
12332 var list$3 = list_1$1;
12333 var Rule2$1 = rule$1;
12334 var Root2$1 = root$1;
12335 var Node2$1 = node$1;
12336 function postcss$3() {
12337 for(var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++){
12338 plugins[_key] = arguments[_key];
12339 }
12340 if (plugins.length === 1 && Array.isArray(plugins[0])) {
12341 plugins = plugins[0];
12342 }
12343 return new Processor2$1(plugins);
12344 }
12345 postcss$3.plugin = function plugin(name, initializer) {
12346 var warningPrinted = false;
12347 function creator() {
12348 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
12349 args[_key] = arguments[_key];
12350 }
12351 if (console && console.warn && !warningPrinted) {
12352 warningPrinted = true;
12353 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
12354 if (process.env.LANG && process.env.LANG.startsWith("cn")) {
12355 console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
12356 }
12357 }
12358 var transformer = initializer.apply(void 0, [].concat(args));
12359 transformer.postcssPlugin = name;
12360 transformer.postcssVersion = new Processor2$1().version;
12361 return transformer;
12362 }
12363 var cache;
12364 Object.defineProperty(creator, "postcss", {
12365 get: function get() {
12366 if (!cache) cache = creator();
12367 return cache;
12368 }
12369 });
12370 creator.process = function(css, processOpts, pluginOpts) {
12371 return postcss$3([
12372 creator(pluginOpts)
12373 ]).process(css, processOpts);
12374 };
12375 return creator;
12376 };
12377 postcss$3.stringify = stringify$5;
12378 postcss$3.parse = parse$5;
12379 postcss$3.fromJSON = fromJSON$2;
12380 postcss$3.list = list$3;
12381 postcss$3.comment = function(defaults) {
12382 return new Comment2$1(defaults);
12383 };
12384 postcss$3.atRule = function(defaults) {
12385 return new AtRule2$1(defaults);
12386 };
12387 postcss$3.decl = function(defaults) {
12388 return new Declaration2$1(defaults);
12389 };
12390 postcss$3.rule = function(defaults) {
12391 return new Rule2$1(defaults);
12392 };
12393 postcss$3.root = function(defaults) {
12394 return new Root2$1(defaults);
12395 };
12396 postcss$3.document = function(defaults) {
12397 return new Document22(defaults);
12398 };
12399 postcss$3.CssSyntaxError = CssSyntaxError2$1;
12400 postcss$3.Declaration = Declaration2$1;
12401 postcss$3.Container = Container2$1;
12402 postcss$3.Processor = Processor2$1;
12403 postcss$3.Document = Document22;
12404 postcss$3.Comment = Comment2$1;
12405 postcss$3.Warning = Warning2$1;
12406 postcss$3.AtRule = AtRule2$1;
12407 postcss$3.Result = Result2$1;
12408 postcss$3.Input = Input2$1;
12409 postcss$3.Rule = Rule2$1;
12410 postcss$3.Root = Root2$1;
12411 postcss$3.Node = Node2$1;
12412 LazyResult2$1.registerPostcss(postcss$3);
12413 var postcss_1$1 = postcss$3;
12414 postcss$3.default = postcss$3;
12415 var postcss$1$1 = /* @__PURE__ */ getDefaultExportFromCjs$1(postcss_1$1);
12416 postcss$1$1.stringify;
12417 postcss$1$1.fromJSON;
12418 postcss$1$1.plugin;
12419 postcss$1$1.parse;
12420 postcss$1$1.list;
12421 postcss$1$1.document;
12422 postcss$1$1.comment;
12423 postcss$1$1.atRule;
12424 postcss$1$1.rule;
12425 postcss$1$1.decl;
12426 postcss$1$1.root;
12427 postcss$1$1.CssSyntaxError;
12428 postcss$1$1.Declaration;
12429 postcss$1$1.Container;
12430 postcss$1$1.Processor;
12431 postcss$1$1.Document;
12432 postcss$1$1.Comment;
12433 postcss$1$1.Warning;
12434 postcss$1$1.AtRule;
12435 postcss$1$1.Result;
12436 postcss$1$1.Input;
12437 postcss$1$1.Rule;
12438 postcss$1$1.Root;
12439 postcss$1$1.Node;
12440 var __defProp2 = Object.defineProperty;
12441 var __defNormalProp2 = function(obj, key, value) {
12442 return key in obj ? __defProp2(obj, key, {
12443 enumerable: true,
12444 configurable: true,
12445 writable: true,
12446 value: value
12447 }) : obj[key] = value;
12448 };
12449 var __publicField2 = function(obj, key, value) {
12450 return __defNormalProp2(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
12451 };
12452 function getDefaultExportFromCjs(x2) {
12453 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
12454 }
12455 function getAugmentedNamespace(n2) {
12456 if (n2.__esModule) return n2;
12457 var f2 = n2.default;
12458 if (typeof f2 == "function") {
12459 var a2 = function a22() {
12460 if (_instanceof(this, a22)) {
12461 return Reflect.construct(f2, arguments, this.constructor);
12462 }
12463 return f2.apply(this, arguments);
12464 };
12465 a2.prototype = f2.prototype;
12466 } else a2 = {};
12467 Object.defineProperty(a2, "__esModule", {
12468 value: true
12469 });
12470 Object.keys(n2).forEach(function(k) {
12471 var d = Object.getOwnPropertyDescriptor(n2, k);
12472 Object.defineProperty(a2, k, d.get ? d : {
12473 enumerable: true,
12474 get: function get() {
12475 return n2[k];
12476 }
12477 });
12478 });
12479 return a2;
12480 }
12481 var picocolors_browser = {
12482 exports: {}
12483 };
12484 var x = String;
12485 var create = function create() {
12486 return {
12487 isColorSupported: false,
12488 reset: x,
12489 bold: x,
12490 dim: x,
12491 italic: x,
12492 underline: x,
12493 inverse: x,
12494 hidden: x,
12495 strikethrough: x,
12496 black: x,
12497 red: x,
12498 green: x,
12499 yellow: x,
12500 blue: x,
12501 magenta: x,
12502 cyan: x,
12503 white: x,
12504 gray: x,
12505 bgBlack: x,
12506 bgRed: x,
12507 bgGreen: x,
12508 bgYellow: x,
12509 bgBlue: x,
12510 bgMagenta: x,
12511 bgCyan: x,
12512 bgWhite: x
12513 };
12514 };
12515 picocolors_browser.exports = create();
12516 picocolors_browser.exports.createColors = create;
12517 var picocolors_browserExports = picocolors_browser.exports;
12518 var __viteBrowserExternal = {};
12519 var __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
12520 __proto__: null,
12521 default: __viteBrowserExternal
12522 }, Symbol.toStringTag, {
12523 value: "Module"
12524 }));
12525 var require$$2 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
12526 var pico = picocolors_browserExports;
12527 var terminalHighlight$1 = require$$2;
12528 var CssSyntaxError$3 = /*#__PURE__*/ function(Error1) {
12529 _inherits(CssSyntaxError2, Error1);
12530 function CssSyntaxError2(message, line, column, source, file, plugin22) {
12531 var _this;
12532 _this = Error1.call(this, message) || this;
12533 _this.name = "CssSyntaxError";
12534 _this.reason = message;
12535 if (file) {
12536 _this.file = file;
12537 }
12538 if (source) {
12539 _this.source = source;
12540 }
12541 if (plugin22) {
12542 _this.plugin = plugin22;
12543 }
12544 if (typeof line !== "undefined" && typeof column !== "undefined") {
12545 if (typeof line === "number") {
12546 _this.line = line;
12547 _this.column = column;
12548 } else {
12549 _this.line = line.line;
12550 _this.column = line.column;
12551 _this.endLine = column.line;
12552 _this.endColumn = column.column;
12553 }
12554 }
12555 _this.setMessage();
12556 if (Error.captureStackTrace) {
12557 Error.captureStackTrace(_this, CssSyntaxError2);
12558 }
12559 return _this;
12560 }
12561 var _proto = CssSyntaxError2.prototype;
12562 _proto.setMessage = function setMessage() {
12563 this.message = this.plugin ? this.plugin + ": " : "";
12564 this.message += this.file ? this.file : "<css input>";
12565 if (typeof this.line !== "undefined") {
12566 this.message += ":" + this.line + ":" + this.column;
12567 }
12568 this.message += ": " + this.reason;
12569 };
12570 _proto.showSourceCode = function showSourceCode(color) {
12571 var _this = this;
12572 if (!this.source) return "";
12573 var css = this.source;
12574 if (color == null) color = pico.isColorSupported;
12575 if (terminalHighlight$1) {
12576 if (color) css = terminalHighlight$1(css);
12577 }
12578 var lines = css.split(/\r?\n/);
12579 var start = Math.max(this.line - 3, 0);
12580 var end = Math.min(this.line + 2, lines.length);
12581 var maxWidth = String(end).length;
12582 var mark, aside;
12583 if (color) {
12584 var _pico_createColors = pico.createColors(true), bold = _pico_createColors.bold, gray = _pico_createColors.gray, red = _pico_createColors.red;
12585 mark = function(text) {
12586 return bold(red(text));
12587 };
12588 aside = function(text) {
12589 return gray(text);
12590 };
12591 } else {
12592 mark = aside = function(str) {
12593 return str;
12594 };
12595 }
12596 return lines.slice(start, end).map(function(line, index2) {
12597 var number = start + 1 + index2;
12598 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
12599 if (number === _this.line) {
12600 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
12601 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
12602 }
12603 return " " + aside(gutter) + line;
12604 }).join("\n");
12605 };
12606 _proto.toString = function toString() {
12607 var code = this.showSourceCode();
12608 if (code) {
12609 code = "\n\n" + code + "\n";
12610 }
12611 return this.name + ": " + this.message + code;
12612 };
12613 return CssSyntaxError2;
12614 }(_wrap_native_super(Error));
12615 var cssSyntaxError = CssSyntaxError$3;
12616 CssSyntaxError$3.default = CssSyntaxError$3;
12617 var symbols = {};
12618 symbols.isClean = Symbol("isClean");
12619 symbols.my = Symbol("my");
12620 var DEFAULT_RAW = {
12621 after: "\n",
12622 beforeClose: "\n",
12623 beforeComment: "\n",
12624 beforeDecl: "\n",
12625 beforeOpen: " ",
12626 beforeRule: "\n",
12627 colon: ": ",
12628 commentLeft: " ",
12629 commentRight: " ",
12630 emptyBody: "",
12631 indent: " ",
12632 semicolon: false
12633 };
12634 function capitalize(str) {
12635 return str[0].toUpperCase() + str.slice(1);
12636 }
12637 var Stringifier$2 = /*#__PURE__*/ function() {
12638 function Stringifier2(builder) {
12639 this.builder = builder;
12640 }
12641 var _proto = Stringifier2.prototype;
12642 _proto.atrule = function atrule(node2, semicolon) {
12643 var name = "@" + node2.name;
12644 var params = node2.params ? this.rawValue(node2, "params") : "";
12645 if (typeof node2.raws.afterName !== "undefined") {
12646 name += node2.raws.afterName;
12647 } else if (params) {
12648 name += " ";
12649 }
12650 if (node2.nodes) {
12651 this.block(node2, name + params);
12652 } else {
12653 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
12654 this.builder(name + params + end, node2);
12655 }
12656 };
12657 _proto.beforeAfter = function beforeAfter(node2, detect) {
12658 var value;
12659 if (node2.type === "decl") {
12660 value = this.raw(node2, null, "beforeDecl");
12661 } else if (node2.type === "comment") {
12662 value = this.raw(node2, null, "beforeComment");
12663 } else if (detect === "before") {
12664 value = this.raw(node2, null, "beforeRule");
12665 } else {
12666 value = this.raw(node2, null, "beforeClose");
12667 }
12668 var buf = node2.parent;
12669 var depth = 0;
12670 while(buf && buf.type !== "root"){
12671 depth += 1;
12672 buf = buf.parent;
12673 }
12674 if (value.includes("\n")) {
12675 var indent = this.raw(node2, null, "indent");
12676 if (indent.length) {
12677 for(var step = 0; step < depth; step++)value += indent;
12678 }
12679 }
12680 return value;
12681 };
12682 _proto.block = function block(node2, start) {
12683 var between = this.raw(node2, "between", "beforeOpen");
12684 this.builder(start + between + "{", node2, "start");
12685 var after;
12686 if (node2.nodes && node2.nodes.length) {
12687 this.body(node2);
12688 after = this.raw(node2, "after");
12689 } else {
12690 after = this.raw(node2, "after", "emptyBody");
12691 }
12692 if (after) this.builder(after);
12693 this.builder("}", node2, "end");
12694 };
12695 _proto.body = function body(node2) {
12696 var last = node2.nodes.length - 1;
12697 while(last > 0){
12698 if (node2.nodes[last].type !== "comment") break;
12699 last -= 1;
12700 }
12701 var semicolon = this.raw(node2, "semicolon");
12702 for(var i2 = 0; i2 < node2.nodes.length; i2++){
12703 var child = node2.nodes[i2];
12704 var before = this.raw(child, "before");
12705 if (before) this.builder(before);
12706 this.stringify(child, last !== i2 || semicolon);
12707 }
12708 };
12709 _proto.comment = function comment(node2) {
12710 var left = this.raw(node2, "left", "commentLeft");
12711 var right = this.raw(node2, "right", "commentRight");
12712 this.builder("/*" + left + node2.text + right + "*/", node2);
12713 };
12714 _proto.decl = function decl(node2, semicolon) {
12715 var between = this.raw(node2, "between", "colon");
12716 var string = node2.prop + between + this.rawValue(node2, "value");
12717 if (node2.important) {
12718 string += node2.raws.important || " !important";
12719 }
12720 if (semicolon) string += ";";
12721 this.builder(string, node2);
12722 };
12723 _proto.document = function document1(node2) {
12724 this.body(node2);
12725 };
12726 _proto.raw = function raw(node2, own, detect) {
12727 var value;
12728 if (!detect) detect = own;
12729 if (own) {
12730 value = node2.raws[own];
12731 if (typeof value !== "undefined") return value;
12732 }
12733 var parent = node2.parent;
12734 if (detect === "before") {
12735 if (!parent || parent.type === "root" && parent.first === node2) {
12736 return "";
12737 }
12738 if (parent && parent.type === "document") {
12739 return "";
12740 }
12741 }
12742 if (!parent) return DEFAULT_RAW[detect];
12743 var root2 = node2.root();
12744 if (!root2.rawCache) root2.rawCache = {};
12745 if (typeof root2.rawCache[detect] !== "undefined") {
12746 return root2.rawCache[detect];
12747 }
12748 if (detect === "before" || detect === "after") {
12749 return this.beforeAfter(node2, detect);
12750 } else {
12751 var method = "raw" + capitalize(detect);
12752 if (this[method]) {
12753 value = this[method](root2, node2);
12754 } else {
12755 root2.walk(function(i2) {
12756 value = i2.raws[own];
12757 if (typeof value !== "undefined") return false;
12758 });
12759 }
12760 }
12761 if (typeof value === "undefined") value = DEFAULT_RAW[detect];
12762 root2.rawCache[detect] = value;
12763 return value;
12764 };
12765 _proto.rawBeforeClose = function rawBeforeClose(root2) {
12766 var value;
12767 root2.walk(function(i2) {
12768 if (i2.nodes && i2.nodes.length > 0) {
12769 if (typeof i2.raws.after !== "undefined") {
12770 value = i2.raws.after;
12771 if (value.includes("\n")) {
12772 value = value.replace(/[^\n]+$/, "");
12773 }
12774 return false;
12775 }
12776 }
12777 });
12778 if (value) value = value.replace(/\S/g, "");
12779 return value;
12780 };
12781 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
12782 var value;
12783 root2.walkComments(function(i2) {
12784 if (typeof i2.raws.before !== "undefined") {
12785 value = i2.raws.before;
12786 if (value.includes("\n")) {
12787 value = value.replace(/[^\n]+$/, "");
12788 }
12789 return false;
12790 }
12791 });
12792 if (typeof value === "undefined") {
12793 value = this.raw(node2, null, "beforeDecl");
12794 } else if (value) {
12795 value = value.replace(/\S/g, "");
12796 }
12797 return value;
12798 };
12799 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
12800 var value;
12801 root2.walkDecls(function(i2) {
12802 if (typeof i2.raws.before !== "undefined") {
12803 value = i2.raws.before;
12804 if (value.includes("\n")) {
12805 value = value.replace(/[^\n]+$/, "");
12806 }
12807 return false;
12808 }
12809 });
12810 if (typeof value === "undefined") {
12811 value = this.raw(node2, null, "beforeRule");
12812 } else if (value) {
12813 value = value.replace(/\S/g, "");
12814 }
12815 return value;
12816 };
12817 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
12818 var value;
12819 root2.walk(function(i2) {
12820 if (i2.type !== "decl") {
12821 value = i2.raws.between;
12822 if (typeof value !== "undefined") return false;
12823 }
12824 });
12825 return value;
12826 };
12827 _proto.rawBeforeRule = function rawBeforeRule(root2) {
12828 var value;
12829 root2.walk(function(i2) {
12830 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
12831 if (typeof i2.raws.before !== "undefined") {
12832 value = i2.raws.before;
12833 if (value.includes("\n")) {
12834 value = value.replace(/[^\n]+$/, "");
12835 }
12836 return false;
12837 }
12838 }
12839 });
12840 if (value) value = value.replace(/\S/g, "");
12841 return value;
12842 };
12843 _proto.rawColon = function rawColon(root2) {
12844 var value;
12845 root2.walkDecls(function(i2) {
12846 if (typeof i2.raws.between !== "undefined") {
12847 value = i2.raws.between.replace(/[^\s:]/g, "");
12848 return false;
12849 }
12850 });
12851 return value;
12852 };
12853 _proto.rawEmptyBody = function rawEmptyBody(root2) {
12854 var value;
12855 root2.walk(function(i2) {
12856 if (i2.nodes && i2.nodes.length === 0) {
12857 value = i2.raws.after;
12858 if (typeof value !== "undefined") return false;
12859 }
12860 });
12861 return value;
12862 };
12863 _proto.rawIndent = function rawIndent(root2) {
12864 if (root2.raws.indent) return root2.raws.indent;
12865 var value;
12866 root2.walk(function(i2) {
12867 var p = i2.parent;
12868 if (p && p !== root2 && p.parent && p.parent === root2) {
12869 if (typeof i2.raws.before !== "undefined") {
12870 var parts = i2.raws.before.split("\n");
12871 value = parts[parts.length - 1];
12872 value = value.replace(/\S/g, "");
12873 return false;
12874 }
12875 }
12876 });
12877 return value;
12878 };
12879 _proto.rawSemicolon = function rawSemicolon(root2) {
12880 var value;
12881 root2.walk(function(i2) {
12882 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
12883 value = i2.raws.semicolon;
12884 if (typeof value !== "undefined") return false;
12885 }
12886 });
12887 return value;
12888 };
12889 _proto.rawValue = function rawValue(node2, prop) {
12890 var value = node2[prop];
12891 var raw = node2.raws[prop];
12892 if (raw && raw.value === value) {
12893 return raw.raw;
12894 }
12895 return value;
12896 };
12897 _proto.root = function root(node2) {
12898 this.body(node2);
12899 if (node2.raws.after) this.builder(node2.raws.after);
12900 };
12901 _proto.rule = function rule(node2) {
12902 this.block(node2, this.rawValue(node2, "selector"));
12903 if (node2.raws.ownSemicolon) {
12904 this.builder(node2.raws.ownSemicolon, node2, "end");
12905 }
12906 };
12907 _proto.stringify = function stringify(node2, semicolon) {
12908 if (!this[node2.type]) {
12909 throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
12910 }
12911 this[node2.type](node2, semicolon);
12912 };
12913 return Stringifier2;
12914 }();
12915 var stringifier = Stringifier$2;
12916 Stringifier$2.default = Stringifier$2;
12917 var Stringifier$1 = stringifier;
12918 function stringify$4(node2, builder) {
12919 var str = new Stringifier$1(builder);
12920 str.stringify(node2);
12921 }
12922 var stringify_1 = stringify$4;
12923 stringify$4.default = stringify$4;
12924 var isClean$2 = symbols.isClean, my$2 = symbols.my;
12925 var CssSyntaxError$2 = cssSyntaxError;
12926 var Stringifier22 = stringifier;
12927 var stringify$3 = stringify_1;
12928 function cloneNode(obj, parent) {
12929 var cloned = new obj.constructor();
12930 for(var i2 in obj){
12931 if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
12932 continue;
12933 }
12934 if (i2 === "proxyCache") continue;
12935 var value = obj[i2];
12936 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
12937 if (i2 === "parent" && type === "object") {
12938 if (parent) cloned[i2] = parent;
12939 } else if (i2 === "source") {
12940 cloned[i2] = value;
12941 } else if (Array.isArray(value)) {
12942 cloned[i2] = value.map(function(j) {
12943 return cloneNode(j, cloned);
12944 });
12945 } else {
12946 if (type === "object" && value !== null) value = cloneNode(value);
12947 cloned[i2] = value;
12948 }
12949 }
12950 return cloned;
12951 }
12952 var Node$4 = /*#__PURE__*/ function() {
12953 function Node3(defaults) {
12954 if (defaults === void 0) defaults = {};
12955 this.raws = {};
12956 this[isClean$2] = false;
12957 this[my$2] = true;
12958 for(var name in defaults){
12959 if (name === "nodes") {
12960 this.nodes = [];
12961 for(var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;){
12962 var node2 = _step.value;
12963 if (typeof node2.clone === "function") {
12964 this.append(node2.clone());
12965 } else {
12966 this.append(node2);
12967 }
12968 }
12969 } else {
12970 this[name] = defaults[name];
12971 }
12972 }
12973 }
12974 var _proto = Node3.prototype;
12975 _proto.addToError = function addToError(error) {
12976 error.postcssNode = this;
12977 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
12978 var s2 = this.source;
12979 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
12980 }
12981 return error;
12982 };
12983 _proto.after = function after(add) {
12984 this.parent.insertAfter(this, add);
12985 return this;
12986 };
12987 _proto.assign = function assign(overrides) {
12988 if (overrides === void 0) overrides = {};
12989 for(var name in overrides){
12990 this[name] = overrides[name];
12991 }
12992 return this;
12993 };
12994 _proto.before = function before(add) {
12995 this.parent.insertBefore(this, add);
12996 return this;
12997 };
12998 _proto.cleanRaws = function cleanRaws(keepBetween) {
12999 delete this.raws.before;
13000 delete this.raws.after;
13001 if (!keepBetween) delete this.raws.between;
13002 };
13003 _proto.clone = function clone(overrides) {
13004 if (overrides === void 0) overrides = {};
13005 var cloned = cloneNode(this);
13006 for(var name in overrides){
13007 cloned[name] = overrides[name];
13008 }
13009 return cloned;
13010 };
13011 _proto.cloneAfter = function cloneAfter(overrides) {
13012 if (overrides === void 0) overrides = {};
13013 var cloned = this.clone(overrides);
13014 this.parent.insertAfter(this, cloned);
13015 return cloned;
13016 };
13017 _proto.cloneBefore = function cloneBefore(overrides) {
13018 if (overrides === void 0) overrides = {};
13019 var cloned = this.clone(overrides);
13020 this.parent.insertBefore(this, cloned);
13021 return cloned;
13022 };
13023 _proto.error = function error(message, opts) {
13024 if (opts === void 0) opts = {};
13025 if (this.source) {
13026 var _this_rangeBy = this.rangeBy(opts), end = _this_rangeBy.end, start = _this_rangeBy.start;
13027 return this.source.input.error(message, {
13028 column: start.column,
13029 line: start.line
13030 }, {
13031 column: end.column,
13032 line: end.line
13033 }, opts);
13034 }
13035 return new CssSyntaxError$2(message);
13036 };
13037 _proto.getProxyProcessor = function getProxyProcessor() {
13038 return {
13039 get: function get(node2, prop) {
13040 if (prop === "proxyOf") {
13041 return node2;
13042 } else if (prop === "root") {
13043 return function() {
13044 return node2.root().toProxy();
13045 };
13046 } else {
13047 return node2[prop];
13048 }
13049 },
13050 set: function set(node2, prop, value) {
13051 if (node2[prop] === value) return true;
13052 node2[prop] = value;
13053 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */ prop === "text") {
13054 node2.markDirty();
13055 }
13056 return true;
13057 }
13058 };
13059 };
13060 _proto.markDirty = function markDirty() {
13061 if (this[isClean$2]) {
13062 this[isClean$2] = false;
13063 var next = this;
13064 while(next = next.parent){
13065 next[isClean$2] = false;
13066 }
13067 }
13068 };
13069 _proto.next = function next() {
13070 if (!this.parent) return void 0;
13071 var index2 = this.parent.index(this);
13072 return this.parent.nodes[index2 + 1];
13073 };
13074 _proto.positionBy = function positionBy(opts, stringRepresentation) {
13075 var pos = this.source.start;
13076 if (opts.index) {
13077 pos = this.positionInside(opts.index, stringRepresentation);
13078 } else if (opts.word) {
13079 stringRepresentation = this.toString();
13080 var index2 = stringRepresentation.indexOf(opts.word);
13081 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
13082 }
13083 return pos;
13084 };
13085 _proto.positionInside = function positionInside(index2, stringRepresentation) {
13086 var string = stringRepresentation || this.toString();
13087 var column = this.source.start.column;
13088 var line = this.source.start.line;
13089 for(var i2 = 0; i2 < index2; i2++){
13090 if (string[i2] === "\n") {
13091 column = 1;
13092 line += 1;
13093 } else {
13094 column += 1;
13095 }
13096 }
13097 return {
13098 column: column,
13099 line: line
13100 };
13101 };
13102 _proto.prev = function prev() {
13103 if (!this.parent) return void 0;
13104 var index2 = this.parent.index(this);
13105 return this.parent.nodes[index2 - 1];
13106 };
13107 _proto.rangeBy = function rangeBy(opts) {
13108 var start = {
13109 column: this.source.start.column,
13110 line: this.source.start.line
13111 };
13112 var end = this.source.end ? {
13113 column: this.source.end.column + 1,
13114 line: this.source.end.line
13115 } : {
13116 column: start.column + 1,
13117 line: start.line
13118 };
13119 if (opts.word) {
13120 var stringRepresentation = this.toString();
13121 var index2 = stringRepresentation.indexOf(opts.word);
13122 if (index2 !== -1) {
13123 start = this.positionInside(index2, stringRepresentation);
13124 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
13125 }
13126 } else {
13127 if (opts.start) {
13128 start = {
13129 column: opts.start.column,
13130 line: opts.start.line
13131 };
13132 } else if (opts.index) {
13133 start = this.positionInside(opts.index);
13134 }
13135 if (opts.end) {
13136 end = {
13137 column: opts.end.column,
13138 line: opts.end.line
13139 };
13140 } else if (typeof opts.endIndex === "number") {
13141 end = this.positionInside(opts.endIndex);
13142 } else if (opts.index) {
13143 end = this.positionInside(opts.index + 1);
13144 }
13145 }
13146 if (end.line < start.line || end.line === start.line && end.column <= start.column) {
13147 end = {
13148 column: start.column + 1,
13149 line: start.line
13150 };
13151 }
13152 return {
13153 end: end,
13154 start: start
13155 };
13156 };
13157 _proto.raw = function raw(prop, defaultType) {
13158 var str = new Stringifier22();
13159 return str.raw(this, prop, defaultType);
13160 };
13161 _proto.remove = function remove() {
13162 if (this.parent) {
13163 this.parent.removeChild(this);
13164 }
13165 this.parent = void 0;
13166 return this;
13167 };
13168 _proto.replaceWith = function replaceWith() {
13169 for(var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++){
13170 nodes[_key] = arguments[_key];
13171 }
13172 if (this.parent) {
13173 var bookmark = this;
13174 var foundSelf = false;
13175 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
13176 var node2 = _step.value;
13177 if (node2 === this) {
13178 foundSelf = true;
13179 } else if (foundSelf) {
13180 this.parent.insertAfter(bookmark, node2);
13181 bookmark = node2;
13182 } else {
13183 this.parent.insertBefore(bookmark, node2);
13184 }
13185 }
13186 if (!foundSelf) {
13187 this.remove();
13188 }
13189 }
13190 return this;
13191 };
13192 _proto.root = function root() {
13193 var result2 = this;
13194 while(result2.parent && result2.parent.type !== "document"){
13195 result2 = result2.parent;
13196 }
13197 return result2;
13198 };
13199 _proto.toJSON = function toJSON(_, inputs) {
13200 var fixed = {};
13201 var emitInputs = inputs == null;
13202 inputs = inputs || /* @__PURE__ */ new Map();
13203 var inputsNextIndex = 0;
13204 for(var name in this){
13205 if (!Object.prototype.hasOwnProperty.call(this, name)) {
13206 continue;
13207 }
13208 if (name === "parent" || name === "proxyCache") continue;
13209 var value = this[name];
13210 if (Array.isArray(value)) {
13211 fixed[name] = value.map(function(i2) {
13212 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) {
13213 return i2.toJSON(null, inputs);
13214 } else {
13215 return i2;
13216 }
13217 });
13218 } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) {
13219 fixed[name] = value.toJSON(null, inputs);
13220 } else if (name === "source") {
13221 var inputId = inputs.get(value.input);
13222 if (inputId == null) {
13223 inputId = inputsNextIndex;
13224 inputs.set(value.input, inputsNextIndex);
13225 inputsNextIndex++;
13226 }
13227 fixed[name] = {
13228 end: value.end,
13229 inputId: inputId,
13230 start: value.start
13231 };
13232 } else {
13233 fixed[name] = value;
13234 }
13235 }
13236 if (emitInputs) {
13237 fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
13238 return input2.toJSON();
13239 });
13240 }
13241 return fixed;
13242 };
13243 _proto.toProxy = function toProxy() {
13244 if (!this.proxyCache) {
13245 this.proxyCache = new Proxy(this, this.getProxyProcessor());
13246 }
13247 return this.proxyCache;
13248 };
13249 _proto.toString = function toString(stringifier2) {
13250 if (stringifier2 === void 0) stringifier2 = stringify$3;
13251 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
13252 var result2 = "";
13253 stringifier2(this, function(i2) {
13254 result2 += i2;
13255 });
13256 return result2;
13257 };
13258 _proto.warn = function warn(result2, text, opts) {
13259 var data = {
13260 node: this
13261 };
13262 for(var i2 in opts)data[i2] = opts[i2];
13263 return result2.warn(text, data);
13264 };
13265 _create_class(Node3, [
13266 {
13267 key: "proxyOf",
13268 get: function get() {
13269 return this;
13270 }
13271 }
13272 ]);
13273 return Node3;
13274 }();
13275 var node = Node$4;
13276 Node$4.default = Node$4;
13277 var Node$3 = node;
13278 var Declaration$4 = /*#__PURE__*/ function(Node$3) {
13279 _inherits(Declaration2, Node$3);
13280 function Declaration2(defaults) {
13281 var _this;
13282 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
13283 defaults = _extends({}, defaults, {
13284 value: String(defaults.value)
13285 });
13286 }
13287 _this = Node$3.call(this, defaults) || this;
13288 _this.type = "decl";
13289 return _this;
13290 }
13291 _create_class(Declaration2, [
13292 {
13293 key: "variable",
13294 get: function get() {
13295 return this.prop.startsWith("--") || this.prop[0] === "$";
13296 }
13297 }
13298 ]);
13299 return Declaration2;
13300 }(Node$3);
13301 var declaration = Declaration$4;
13302 Declaration$4.default = Declaration$4;
13303 var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
13304 var nanoid$1 = function(size) {
13305 if (size === void 0) size = 21;
13306 var id = "";
13307 var i2 = size;
13308 while(i2--){
13309 id += urlAlphabet[Math.random() * 64 | 0];
13310 }
13311 return id;
13312 };
13313 var nonSecure = {
13314 nanoid: nanoid$1};
13315 var SourceMapConsumer$2 = require$$2.SourceMapConsumer, SourceMapGenerator$2 = require$$2.SourceMapGenerator;
13316 var existsSync = require$$2.existsSync, readFileSync = require$$2.readFileSync;
13317 var dirname$1 = require$$2.dirname, join = require$$2.join;
13318 function fromBase64(str) {
13319 if (Buffer) {
13320 return Buffer.from(str, "base64").toString();
13321 } else {
13322 return window.atob(str);
13323 }
13324 }
13325 var PreviousMap$2 = /*#__PURE__*/ function() {
13326 function PreviousMap2(css, opts) {
13327 if (opts.map === false) return;
13328 this.loadAnnotation(css);
13329 this.inline = this.startWith(this.annotation, "data:");
13330 var prev = opts.map ? opts.map.prev : void 0;
13331 var text = this.loadMap(opts.from, prev);
13332 if (!this.mapFile && opts.from) {
13333 this.mapFile = opts.from;
13334 }
13335 if (this.mapFile) this.root = dirname$1(this.mapFile);
13336 if (text) this.text = text;
13337 }
13338 var _proto = PreviousMap2.prototype;
13339 _proto.consumer = function consumer() {
13340 if (!this.consumerCache) {
13341 this.consumerCache = new SourceMapConsumer$2(this.text);
13342 }
13343 return this.consumerCache;
13344 };
13345 _proto.decodeInline = function decodeInline(text) {
13346 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
13347 var baseUri = /^data:application\/json;base64,/;
13348 var charsetUri = /^data:application\/json;charset=utf-?8,/;
13349 var uri = /^data:application\/json,/;
13350 if (charsetUri.test(text) || uri.test(text)) {
13351 return decodeURIComponent(text.substr(RegExp.lastMatch.length));
13352 }
13353 if (baseCharsetUri.test(text) || baseUri.test(text)) {
13354 return fromBase64(text.substr(RegExp.lastMatch.length));
13355 }
13356 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
13357 throw new Error("Unsupported source map encoding " + encoding);
13358 };
13359 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
13360 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
13361 };
13362 _proto.isMap = function isMap(map) {
13363 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
13364 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
13365 };
13366 _proto.loadAnnotation = function loadAnnotation(css) {
13367 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
13368 if (!comments) return;
13369 var start = css.lastIndexOf(comments.pop());
13370 var end = css.indexOf("*/", start);
13371 if (start > -1 && end > -1) {
13372 this.annotation = this.getAnnotationURL(css.substring(start, end));
13373 }
13374 };
13375 _proto.loadFile = function loadFile(path) {
13376 this.root = dirname$1(path);
13377 if (existsSync(path)) {
13378 this.mapFile = path;
13379 return readFileSync(path, "utf-8").toString().trim();
13380 }
13381 };
13382 _proto.loadMap = function loadMap(file, prev) {
13383 if (prev === false) return false;
13384 if (prev) {
13385 if (typeof prev === "string") {
13386 return prev;
13387 } else if (typeof prev === "function") {
13388 var prevPath = prev(file);
13389 if (prevPath) {
13390 var map = this.loadFile(prevPath);
13391 if (!map) {
13392 throw new Error("Unable to load previous source map: " + prevPath.toString());
13393 }
13394 return map;
13395 }
13396 } else if (_instanceof(prev, SourceMapConsumer$2)) {
13397 return SourceMapGenerator$2.fromSourceMap(prev).toString();
13398 } else if (_instanceof(prev, SourceMapGenerator$2)) {
13399 return prev.toString();
13400 } else if (this.isMap(prev)) {
13401 return JSON.stringify(prev);
13402 } else {
13403 throw new Error("Unsupported previous source map format: " + prev.toString());
13404 }
13405 } else if (this.inline) {
13406 return this.decodeInline(this.annotation);
13407 } else if (this.annotation) {
13408 var map1 = this.annotation;
13409 if (file) map1 = join(dirname$1(file), map1);
13410 return this.loadFile(map1);
13411 }
13412 };
13413 _proto.startWith = function startWith(string, start) {
13414 if (!string) return false;
13415 return string.substr(0, start.length) === start;
13416 };
13417 _proto.withContent = function withContent() {
13418 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
13419 };
13420 return PreviousMap2;
13421 }();
13422 var previousMap = PreviousMap$2;
13423 PreviousMap$2.default = PreviousMap$2;
13424 var SourceMapConsumer$1 = require$$2.SourceMapConsumer, SourceMapGenerator$1 = require$$2.SourceMapGenerator;
13425 var fileURLToPath = require$$2.fileURLToPath, pathToFileURL$1 = require$$2.pathToFileURL;
13426 var isAbsolute = require$$2.isAbsolute, resolve$1 = require$$2.resolve;
13427 var nanoid = nonSecure.nanoid;
13428 var terminalHighlight = require$$2;
13429 var CssSyntaxError$1 = cssSyntaxError;
13430 var PreviousMap$1 = previousMap;
13431 var fromOffsetCache = Symbol("fromOffsetCache");
13432 var sourceMapAvailable$1 = Boolean(SourceMapConsumer$1 && SourceMapGenerator$1);
13433 var pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
13434 var Input$4 = /*#__PURE__*/ function() {
13435 function Input2(css, opts) {
13436 if (opts === void 0) opts = {};
13437 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) {
13438 throw new Error("PostCSS received " + css + " instead of CSS string");
13439 }
13440 this.css = css.toString();
13441 if (this.css[0] === "\uFEFF" || this.css[0] === "￾") {
13442 this.hasBOM = true;
13443 this.css = this.css.slice(1);
13444 } else {
13445 this.hasBOM = false;
13446 }
13447 if (opts.from) {
13448 if (!pathAvailable$1 || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from)) {
13449 this.file = opts.from;
13450 } else {
13451 this.file = resolve$1(opts.from);
13452 }
13453 }
13454 if (pathAvailable$1 && sourceMapAvailable$1) {
13455 var map = new PreviousMap$1(this.css, opts);
13456 if (map.text) {
13457 this.map = map;
13458 var file = map.consumer().file;
13459 if (!this.file && file) this.file = this.mapResolve(file);
13460 }
13461 }
13462 if (!this.file) {
13463 this.id = "<input css " + nanoid(6) + ">";
13464 }
13465 if (this.map) this.map.file = this.from;
13466 }
13467 var _proto = Input2.prototype;
13468 _proto.error = function error(message, line, column, opts) {
13469 if (opts === void 0) opts = {};
13470 var result2, endLine, endColumn;
13471 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
13472 var start = line;
13473 var end = column;
13474 if (typeof start.offset === "number") {
13475 var pos = this.fromOffset(start.offset);
13476 line = pos.line;
13477 column = pos.col;
13478 } else {
13479 line = start.line;
13480 column = start.column;
13481 }
13482 if (typeof end.offset === "number") {
13483 var pos1 = this.fromOffset(end.offset);
13484 endLine = pos1.line;
13485 endColumn = pos1.col;
13486 } else {
13487 endLine = end.line;
13488 endColumn = end.column;
13489 }
13490 } else if (!column) {
13491 var pos2 = this.fromOffset(line);
13492 line = pos2.line;
13493 column = pos2.col;
13494 }
13495 var origin = this.origin(line, column, endLine, endColumn);
13496 if (origin) {
13497 result2 = new CssSyntaxError$1(message, origin.endLine === void 0 ? origin.line : {
13498 column: origin.column,
13499 line: origin.line
13500 }, origin.endLine === void 0 ? origin.column : {
13501 column: origin.endColumn,
13502 line: origin.endLine
13503 }, origin.source, origin.file, opts.plugin);
13504 } else {
13505 result2 = new CssSyntaxError$1(message, endLine === void 0 ? line : {
13506 column: column,
13507 line: line
13508 }, endLine === void 0 ? column : {
13509 column: endColumn,
13510 line: endLine
13511 }, this.css, this.file, opts.plugin);
13512 }
13513 result2.input = {
13514 column: column,
13515 endColumn: endColumn,
13516 endLine: endLine,
13517 line: line,
13518 source: this.css
13519 };
13520 if (this.file) {
13521 if (pathToFileURL$1) {
13522 result2.input.url = pathToFileURL$1(this.file).toString();
13523 }
13524 result2.input.file = this.file;
13525 }
13526 return result2;
13527 };
13528 _proto.fromOffset = function fromOffset(offset) {
13529 var lastLine, lineToIndex;
13530 if (!this[fromOffsetCache]) {
13531 var lines = this.css.split("\n");
13532 lineToIndex = new Array(lines.length);
13533 var prevIndex = 0;
13534 for(var i2 = 0, l2 = lines.length; i2 < l2; i2++){
13535 lineToIndex[i2] = prevIndex;
13536 prevIndex += lines[i2].length + 1;
13537 }
13538 this[fromOffsetCache] = lineToIndex;
13539 } else {
13540 lineToIndex = this[fromOffsetCache];
13541 }
13542 lastLine = lineToIndex[lineToIndex.length - 1];
13543 var min = 0;
13544 if (offset >= lastLine) {
13545 min = lineToIndex.length - 1;
13546 } else {
13547 var max = lineToIndex.length - 2;
13548 var mid;
13549 while(min < max){
13550 mid = min + (max - min >> 1);
13551 if (offset < lineToIndex[mid]) {
13552 max = mid - 1;
13553 } else if (offset >= lineToIndex[mid + 1]) {
13554 min = mid + 1;
13555 } else {
13556 min = mid;
13557 break;
13558 }
13559 }
13560 }
13561 return {
13562 col: offset - lineToIndex[min] + 1,
13563 line: min + 1
13564 };
13565 };
13566 _proto.mapResolve = function mapResolve(file) {
13567 if (/^\w+:\/\//.test(file)) {
13568 return file;
13569 }
13570 return resolve$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
13571 };
13572 _proto.origin = function origin(line, column, endLine, endColumn) {
13573 if (!this.map) return false;
13574 var consumer = this.map.consumer();
13575 var from = consumer.originalPositionFor({
13576 column: column,
13577 line: line
13578 });
13579 if (!from.source) return false;
13580 var to;
13581 if (typeof endLine === "number") {
13582 to = consumer.originalPositionFor({
13583 column: endColumn,
13584 line: endLine
13585 });
13586 }
13587 var fromUrl;
13588 if (isAbsolute(from.source)) {
13589 fromUrl = pathToFileURL$1(from.source);
13590 } else {
13591 fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile));
13592 }
13593 var result2 = {
13594 column: from.column,
13595 endColumn: to && to.column,
13596 endLine: to && to.line,
13597 line: from.line,
13598 url: fromUrl.toString()
13599 };
13600 if (fromUrl.protocol === "file:") {
13601 if (fileURLToPath) {
13602 result2.file = fileURLToPath(fromUrl);
13603 } else {
13604 throw new Error("file: protocol is not available in this PostCSS build");
13605 }
13606 }
13607 var source = consumer.sourceContentFor(from.source);
13608 if (source) result2.source = source;
13609 return result2;
13610 };
13611 _proto.toJSON = function toJSON() {
13612 var json = {};
13613 for(var _i = 0, _iter = [
13614 "hasBOM",
13615 "css",
13616 "file",
13617 "id"
13618 ]; _i < _iter.length; _i++){
13619 var name = _iter[_i];
13620 if (this[name] != null) {
13621 json[name] = this[name];
13622 }
13623 }
13624 if (this.map) {
13625 json.map = _extends({}, this.map);
13626 if (json.map.consumerCache) {
13627 json.map.consumerCache = void 0;
13628 }
13629 }
13630 return json;
13631 };
13632 _create_class(Input2, [
13633 {
13634 key: "from",
13635 get: function get() {
13636 return this.file || this.id;
13637 }
13638 }
13639 ]);
13640 return Input2;
13641 }();
13642 var input = Input$4;
13643 Input$4.default = Input$4;
13644 if (terminalHighlight && terminalHighlight.registerInput) {
13645 terminalHighlight.registerInput(Input$4);
13646 }
13647 var SourceMapConsumer = require$$2.SourceMapConsumer, SourceMapGenerator = require$$2.SourceMapGenerator;
13648 var dirname = require$$2.dirname, relative = require$$2.relative, resolve$3 = require$$2.resolve, sep = require$$2.sep;
13649 var pathToFileURL = require$$2.pathToFileURL;
13650 var Input$3 = input;
13651 var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
13652 var pathAvailable = Boolean(dirname && resolve$3 && relative && sep);
13653 var MapGenerator$2 = /*#__PURE__*/ function() {
13654 function MapGenerator2(stringify2, root2, opts, cssString) {
13655 this.stringify = stringify2;
13656 this.mapOpts = opts.map || {};
13657 this.root = root2;
13658 this.opts = opts;
13659 this.css = cssString;
13660 this.originalCSS = cssString;
13661 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
13662 this.memoizedFileURLs = /* @__PURE__ */ new Map();
13663 this.memoizedPaths = /* @__PURE__ */ new Map();
13664 this.memoizedURLs = /* @__PURE__ */ new Map();
13665 }
13666 var _proto = MapGenerator2.prototype;
13667 _proto.addAnnotation = function addAnnotation() {
13668 var content;
13669 if (this.isInline()) {
13670 content = "data:application/json;base64," + this.toBase64(this.map.toString());
13671 } else if (typeof this.mapOpts.annotation === "string") {
13672 content = this.mapOpts.annotation;
13673 } else if (typeof this.mapOpts.annotation === "function") {
13674 content = this.mapOpts.annotation(this.opts.to, this.root);
13675 } else {
13676 content = this.outputFile() + ".map";
13677 }
13678 var eol = "\n";
13679 if (this.css.includes("\r\n")) eol = "\r\n";
13680 this.css += eol + "/*# sourceMappingURL=" + content + " */";
13681 };
13682 _proto.applyPrevMaps = function applyPrevMaps() {
13683 for(var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;){
13684 var prev = _step.value;
13685 var from = this.toUrl(this.path(prev.file));
13686 var root2 = prev.root || dirname(prev.file);
13687 var map = void 0;
13688 if (this.mapOpts.sourcesContent === false) {
13689 map = new SourceMapConsumer(prev.text);
13690 if (map.sourcesContent) {
13691 map.sourcesContent = null;
13692 }
13693 } else {
13694 map = prev.consumer();
13695 }
13696 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
13697 }
13698 };
13699 _proto.clearAnnotation = function clearAnnotation() {
13700 if (this.mapOpts.annotation === false) return;
13701 if (this.root) {
13702 var node2;
13703 for(var i2 = this.root.nodes.length - 1; i2 >= 0; i2--){
13704 node2 = this.root.nodes[i2];
13705 if (node2.type !== "comment") continue;
13706 if (node2.text.indexOf("# sourceMappingURL=") === 0) {
13707 this.root.removeChild(i2);
13708 }
13709 }
13710 } else if (this.css) {
13711 this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
13712 }
13713 };
13714 _proto.generate = function generate() {
13715 this.clearAnnotation();
13716 if (pathAvailable && sourceMapAvailable && this.isMap()) {
13717 return this.generateMap();
13718 } else {
13719 var result2 = "";
13720 this.stringify(this.root, function(i2) {
13721 result2 += i2;
13722 });
13723 return [
13724 result2
13725 ];
13726 }
13727 };
13728 _proto.generateMap = function generateMap() {
13729 if (this.root) {
13730 this.generateString();
13731 } else if (this.previous().length === 1) {
13732 var prev = this.previous()[0].consumer();
13733 prev.file = this.outputFile();
13734 this.map = SourceMapGenerator.fromSourceMap(prev, {
13735 ignoreInvalidMapping: true
13736 });
13737 } else {
13738 this.map = new SourceMapGenerator({
13739 file: this.outputFile(),
13740 ignoreInvalidMapping: true
13741 });
13742 this.map.addMapping({
13743 generated: {
13744 column: 0,
13745 line: 1
13746 },
13747 original: {
13748 column: 0,
13749 line: 1
13750 },
13751 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
13752 });
13753 }
13754 if (this.isSourcesContent()) this.setSourcesContent();
13755 if (this.root && this.previous().length > 0) this.applyPrevMaps();
13756 if (this.isAnnotation()) this.addAnnotation();
13757 if (this.isInline()) {
13758 return [
13759 this.css
13760 ];
13761 } else {
13762 return [
13763 this.css,
13764 this.map
13765 ];
13766 }
13767 };
13768 _proto.generateString = function generateString() {
13769 var _this = this;
13770 this.css = "";
13771 this.map = new SourceMapGenerator({
13772 file: this.outputFile(),
13773 ignoreInvalidMapping: true
13774 });
13775 var line = 1;
13776 var column = 1;
13777 var noSource = "<no source>";
13778 var mapping = {
13779 generated: {
13780 column: 0,
13781 line: 0
13782 },
13783 original: {
13784 column: 0,
13785 line: 0
13786 },
13787 source: ""
13788 };
13789 var lines, last;
13790 this.stringify(this.root, function(str, node2, type) {
13791 _this.css += str;
13792 if (node2 && type !== "end") {
13793 mapping.generated.line = line;
13794 mapping.generated.column = column - 1;
13795 if (node2.source && node2.source.start) {
13796 mapping.source = _this.sourcePath(node2);
13797 mapping.original.line = node2.source.start.line;
13798 mapping.original.column = node2.source.start.column - 1;
13799 _this.map.addMapping(mapping);
13800 } else {
13801 mapping.source = noSource;
13802 mapping.original.line = 1;
13803 mapping.original.column = 0;
13804 _this.map.addMapping(mapping);
13805 }
13806 }
13807 lines = str.match(/\n/g);
13808 if (lines) {
13809 line += lines.length;
13810 last = str.lastIndexOf("\n");
13811 column = str.length - last;
13812 } else {
13813 column += str.length;
13814 }
13815 if (node2 && type !== "start") {
13816 var p = node2.parent || {
13817 raws: {}
13818 };
13819 var childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
13820 if (!childless || node2 !== p.last || p.raws.semicolon) {
13821 if (node2.source && node2.source.end) {
13822 mapping.source = _this.sourcePath(node2);
13823 mapping.original.line = node2.source.end.line;
13824 mapping.original.column = node2.source.end.column - 1;
13825 mapping.generated.line = line;
13826 mapping.generated.column = column - 2;
13827 _this.map.addMapping(mapping);
13828 } else {
13829 mapping.source = noSource;
13830 mapping.original.line = 1;
13831 mapping.original.column = 0;
13832 mapping.generated.line = line;
13833 mapping.generated.column = column - 1;
13834 _this.map.addMapping(mapping);
13835 }
13836 }
13837 }
13838 });
13839 };
13840 _proto.isAnnotation = function isAnnotation() {
13841 if (this.isInline()) {
13842 return true;
13843 }
13844 if (typeof this.mapOpts.annotation !== "undefined") {
13845 return this.mapOpts.annotation;
13846 }
13847 if (this.previous().length) {
13848 return this.previous().some(function(i2) {
13849 return i2.annotation;
13850 });
13851 }
13852 return true;
13853 };
13854 _proto.isInline = function isInline() {
13855 if (typeof this.mapOpts.inline !== "undefined") {
13856 return this.mapOpts.inline;
13857 }
13858 var annotation = this.mapOpts.annotation;
13859 if (typeof annotation !== "undefined" && annotation !== true) {
13860 return false;
13861 }
13862 if (this.previous().length) {
13863 return this.previous().some(function(i2) {
13864 return i2.inline;
13865 });
13866 }
13867 return true;
13868 };
13869 _proto.isMap = function isMap() {
13870 if (typeof this.opts.map !== "undefined") {
13871 return !!this.opts.map;
13872 }
13873 return this.previous().length > 0;
13874 };
13875 _proto.isSourcesContent = function isSourcesContent() {
13876 if (typeof this.mapOpts.sourcesContent !== "undefined") {
13877 return this.mapOpts.sourcesContent;
13878 }
13879 if (this.previous().length) {
13880 return this.previous().some(function(i2) {
13881 return i2.withContent();
13882 });
13883 }
13884 return true;
13885 };
13886 _proto.outputFile = function outputFile() {
13887 if (this.opts.to) {
13888 return this.path(this.opts.to);
13889 } else if (this.opts.from) {
13890 return this.path(this.opts.from);
13891 } else {
13892 return "to.css";
13893 }
13894 };
13895 _proto.path = function path(file) {
13896 if (this.mapOpts.absolute) return file;
13897 if (file.charCodeAt(0) === 60) return file;
13898 if (/^\w+:\/\//.test(file)) return file;
13899 var cached = this.memoizedPaths.get(file);
13900 if (cached) return cached;
13901 var from = this.opts.to ? dirname(this.opts.to) : ".";
13902 if (typeof this.mapOpts.annotation === "string") {
13903 from = dirname(resolve$3(from, this.mapOpts.annotation));
13904 }
13905 var path = relative(from, file);
13906 this.memoizedPaths.set(file, path);
13907 return path;
13908 };
13909 _proto.previous = function previous() {
13910 var _this = this;
13911 if (!this.previousMaps) {
13912 this.previousMaps = [];
13913 if (this.root) {
13914 this.root.walk(function(node2) {
13915 if (node2.source && node2.source.input.map) {
13916 var map = node2.source.input.map;
13917 if (!_this.previousMaps.includes(map)) {
13918 _this.previousMaps.push(map);
13919 }
13920 }
13921 });
13922 } else {
13923 var input2 = new Input$3(this.originalCSS, this.opts);
13924 if (input2.map) this.previousMaps.push(input2.map);
13925 }
13926 }
13927 return this.previousMaps;
13928 };
13929 _proto.setSourcesContent = function setSourcesContent() {
13930 var _this = this;
13931 var already = {};
13932 if (this.root) {
13933 this.root.walk(function(node2) {
13934 if (node2.source) {
13935 var from = node2.source.input.from;
13936 if (from && !already[from]) {
13937 already[from] = true;
13938 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
13939 _this.map.setSourceContent(fromUrl, node2.source.input.css);
13940 }
13941 }
13942 });
13943 } else if (this.css) {
13944 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
13945 this.map.setSourceContent(from, this.css);
13946 }
13947 };
13948 _proto.sourcePath = function sourcePath(node2) {
13949 if (this.mapOpts.from) {
13950 return this.toUrl(this.mapOpts.from);
13951 } else if (this.usesFileUrls) {
13952 return this.toFileUrl(node2.source.input.from);
13953 } else {
13954 return this.toUrl(this.path(node2.source.input.from));
13955 }
13956 };
13957 _proto.toBase64 = function toBase64(str) {
13958 if (Buffer) {
13959 return Buffer.from(str).toString("base64");
13960 } else {
13961 return window.btoa(unescape(encodeURIComponent(str)));
13962 }
13963 };
13964 _proto.toFileUrl = function toFileUrl(path) {
13965 var cached = this.memoizedFileURLs.get(path);
13966 if (cached) return cached;
13967 if (pathToFileURL) {
13968 var fileURL = pathToFileURL(path).toString();
13969 this.memoizedFileURLs.set(path, fileURL);
13970 return fileURL;
13971 } else {
13972 throw new Error("`map.absolute` option is not available in this PostCSS build");
13973 }
13974 };
13975 _proto.toUrl = function toUrl(path) {
13976 var cached = this.memoizedURLs.get(path);
13977 if (cached) return cached;
13978 if (sep === "\\") {
13979 path = path.replace(/\\/g, "/");
13980 }
13981 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
13982 this.memoizedURLs.set(path, url);
13983 return url;
13984 };
13985 return MapGenerator2;
13986 }();
13987 var mapGenerator = MapGenerator$2;
13988 var Node$2 = node;
13989 var Comment$4 = /*#__PURE__*/ function(Node$2) {
13990 _inherits(Comment2, Node$2);
13991 function Comment2(defaults) {
13992 var _this;
13993 _this = Node$2.call(this, defaults) || this;
13994 _this.type = "comment";
13995 return _this;
13996 }
13997 return Comment2;
13998 }(Node$2);
13999 var comment = Comment$4;
14000 Comment$4.default = Comment$4;
14001 var isClean$1 = symbols.isClean, my$1 = symbols.my;
14002 var Declaration$3 = declaration;
14003 var Comment$3 = comment;
14004 var Node$1 = node;
14005 var parse$4, Rule$4, AtRule$4, Root$6;
14006 function cleanSource(nodes) {
14007 return nodes.map(function(i2) {
14008 if (i2.nodes) i2.nodes = cleanSource(i2.nodes);
14009 delete i2.source;
14010 return i2;
14011 });
14012 }
14013 function markDirtyUp(node2) {
14014 node2[isClean$1] = false;
14015 if (node2.proxyOf.nodes) {
14016 for(var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;){
14017 var i2 = _step.value;
14018 markDirtyUp(i2);
14019 }
14020 }
14021 }
14022 var Container$7 = /*#__PURE__*/ function(Node$1) {
14023 _inherits(Container2, Node$1);
14024 function Container2() {
14025 return Node$1.apply(this, arguments) || this;
14026 }
14027 var _proto = Container2.prototype;
14028 _proto.append = function append() {
14029 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
14030 children[_key] = arguments[_key];
14031 }
14032 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
14033 var child = _step.value;
14034 var nodes = this.normalize(child, this.last);
14035 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
14036 var node2 = _step1.value;
14037 this.proxyOf.nodes.push(node2);
14038 }
14039 }
14040 this.markDirty();
14041 return this;
14042 };
14043 _proto.cleanRaws = function cleanRaws(keepBetween) {
14044 Node$1.prototype.cleanRaws.call(this, keepBetween);
14045 if (this.nodes) {
14046 for(var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;){
14047 var node2 = _step.value;
14048 node2.cleanRaws(keepBetween);
14049 }
14050 }
14051 };
14052 _proto.each = function each(callback) {
14053 if (!this.proxyOf.nodes) return void 0;
14054 var iterator = this.getIterator();
14055 var index2, result2;
14056 while(this.indexes[iterator] < this.proxyOf.nodes.length){
14057 index2 = this.indexes[iterator];
14058 result2 = callback(this.proxyOf.nodes[index2], index2);
14059 if (result2 === false) break;
14060 this.indexes[iterator] += 1;
14061 }
14062 delete this.indexes[iterator];
14063 return result2;
14064 };
14065 _proto.every = function every(condition) {
14066 return this.nodes.every(condition);
14067 };
14068 _proto.getIterator = function getIterator() {
14069 if (!this.lastEach) this.lastEach = 0;
14070 if (!this.indexes) this.indexes = {};
14071 this.lastEach += 1;
14072 var iterator = this.lastEach;
14073 this.indexes[iterator] = 0;
14074 return iterator;
14075 };
14076 _proto.getProxyProcessor = function getProxyProcessor() {
14077 return {
14078 get: function get(node2, prop) {
14079 if (prop === "proxyOf") {
14080 return node2;
14081 } else if (!node2[prop]) {
14082 return node2[prop];
14083 } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
14084 return function() {
14085 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
14086 args[_key] = arguments[_key];
14087 }
14088 var _node2;
14089 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
14090 if (typeof i2 === "function") {
14091 return function(child, index2) {
14092 return i2(child.toProxy(), index2);
14093 };
14094 } else {
14095 return i2;
14096 }
14097 })));
14098 };
14099 } else if (prop === "every" || prop === "some") {
14100 return function(cb) {
14101 return node2[prop](function(child) {
14102 for(var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
14103 other[_key - 1] = arguments[_key];
14104 }
14105 return cb.apply(void 0, [].concat([
14106 child.toProxy()
14107 ], other));
14108 });
14109 };
14110 } else if (prop === "root") {
14111 return function() {
14112 return node2.root().toProxy();
14113 };
14114 } else if (prop === "nodes") {
14115 return node2.nodes.map(function(i2) {
14116 return i2.toProxy();
14117 });
14118 } else if (prop === "first" || prop === "last") {
14119 return node2[prop].toProxy();
14120 } else {
14121 return node2[prop];
14122 }
14123 },
14124 set: function set(node2, prop, value) {
14125 if (node2[prop] === value) return true;
14126 node2[prop] = value;
14127 if (prop === "name" || prop === "params" || prop === "selector") {
14128 node2.markDirty();
14129 }
14130 return true;
14131 }
14132 };
14133 };
14134 _proto.index = function index(child) {
14135 if (typeof child === "number") return child;
14136 if (child.proxyOf) child = child.proxyOf;
14137 return this.proxyOf.nodes.indexOf(child);
14138 };
14139 _proto.insertAfter = function insertAfter(exist, add) {
14140 var existIndex = this.index(exist);
14141 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
14142 existIndex = this.index(exist);
14143 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
14144 var node2 = _step.value;
14145 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
14146 }
14147 var index2;
14148 for(var id in this.indexes){
14149 index2 = this.indexes[id];
14150 if (existIndex < index2) {
14151 this.indexes[id] = index2 + nodes.length;
14152 }
14153 }
14154 this.markDirty();
14155 return this;
14156 };
14157 _proto.insertBefore = function insertBefore(exist, add) {
14158 var existIndex = this.index(exist);
14159 var type = existIndex === 0 ? "prepend" : false;
14160 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
14161 existIndex = this.index(exist);
14162 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
14163 var node2 = _step.value;
14164 this.proxyOf.nodes.splice(existIndex, 0, node2);
14165 }
14166 var index2;
14167 for(var id in this.indexes){
14168 index2 = this.indexes[id];
14169 if (existIndex <= index2) {
14170 this.indexes[id] = index2 + nodes.length;
14171 }
14172 }
14173 this.markDirty();
14174 return this;
14175 };
14176 _proto.normalize = function normalize(nodes, sample) {
14177 var _this = this;
14178 if (typeof nodes === "string") {
14179 nodes = cleanSource(parse$4(nodes).nodes);
14180 } else if (typeof nodes === "undefined") {
14181 nodes = [];
14182 } else if (Array.isArray(nodes)) {
14183 nodes = nodes.slice(0);
14184 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
14185 var i2 = _step.value;
14186 if (i2.parent) i2.parent.removeChild(i2, "ignore");
14187 }
14188 } else if (nodes.type === "root" && this.type !== "document") {
14189 nodes = nodes.nodes.slice(0);
14190 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
14191 var i21 = _step1.value;
14192 if (i21.parent) i21.parent.removeChild(i21, "ignore");
14193 }
14194 } else if (nodes.type) {
14195 nodes = [
14196 nodes
14197 ];
14198 } else if (nodes.prop) {
14199 if (typeof nodes.value === "undefined") {
14200 throw new Error("Value field is missed in node creation");
14201 } else if (typeof nodes.value !== "string") {
14202 nodes.value = String(nodes.value);
14203 }
14204 nodes = [
14205 new Declaration$3(nodes)
14206 ];
14207 } else if (nodes.selector) {
14208 nodes = [
14209 new Rule$4(nodes)
14210 ];
14211 } else if (nodes.name) {
14212 nodes = [
14213 new AtRule$4(nodes)
14214 ];
14215 } else if (nodes.text) {
14216 nodes = [
14217 new Comment$3(nodes)
14218 ];
14219 } else {
14220 throw new Error("Unknown node type in node creation");
14221 }
14222 var processed = nodes.map(function(i2) {
14223 if (!i2[my$1]) Container2.rebuild(i2);
14224 i2 = i2.proxyOf;
14225 if (i2.parent) i2.parent.removeChild(i2);
14226 if (i2[isClean$1]) markDirtyUp(i2);
14227 if (typeof i2.raws.before === "undefined") {
14228 if (sample && typeof sample.raws.before !== "undefined") {
14229 i2.raws.before = sample.raws.before.replace(/\S/g, "");
14230 }
14231 }
14232 i2.parent = _this.proxyOf;
14233 return i2;
14234 });
14235 return processed;
14236 };
14237 _proto.prepend = function prepend() {
14238 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
14239 children[_key] = arguments[_key];
14240 }
14241 children = children.reverse();
14242 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
14243 var child = _step.value;
14244 var nodes = this.normalize(child, this.first, "prepend").reverse();
14245 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
14246 var node2 = _step1.value;
14247 this.proxyOf.nodes.unshift(node2);
14248 }
14249 for(var id in this.indexes){
14250 this.indexes[id] = this.indexes[id] + nodes.length;
14251 }
14252 }
14253 this.markDirty();
14254 return this;
14255 };
14256 _proto.push = function push(child) {
14257 child.parent = this;
14258 this.proxyOf.nodes.push(child);
14259 return this;
14260 };
14261 _proto.removeAll = function removeAll() {
14262 for(var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;){
14263 var node2 = _step.value;
14264 node2.parent = void 0;
14265 }
14266 this.proxyOf.nodes = [];
14267 this.markDirty();
14268 return this;
14269 };
14270 _proto.removeChild = function removeChild(child) {
14271 child = this.index(child);
14272 this.proxyOf.nodes[child].parent = void 0;
14273 this.proxyOf.nodes.splice(child, 1);
14274 var index2;
14275 for(var id in this.indexes){
14276 index2 = this.indexes[id];
14277 if (index2 >= child) {
14278 this.indexes[id] = index2 - 1;
14279 }
14280 }
14281 this.markDirty();
14282 return this;
14283 };
14284 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
14285 if (!callback) {
14286 callback = opts;
14287 opts = {};
14288 }
14289 this.walkDecls(function(decl) {
14290 if (opts.props && !opts.props.includes(decl.prop)) return;
14291 if (opts.fast && !decl.value.includes(opts.fast)) return;
14292 decl.value = decl.value.replace(pattern, callback);
14293 });
14294 this.markDirty();
14295 return this;
14296 };
14297 _proto.some = function some(condition) {
14298 return this.nodes.some(condition);
14299 };
14300 _proto.walk = function walk(callback) {
14301 return this.each(function(child, i2) {
14302 var result2;
14303 try {
14304 result2 = callback(child, i2);
14305 } catch (e2) {
14306 throw child.addToError(e2);
14307 }
14308 if (result2 !== false && child.walk) {
14309 result2 = child.walk(callback);
14310 }
14311 return result2;
14312 });
14313 };
14314 _proto.walkAtRules = function walkAtRules(name, callback) {
14315 if (!callback) {
14316 callback = name;
14317 return this.walk(function(child, i2) {
14318 if (child.type === "atrule") {
14319 return callback(child, i2);
14320 }
14321 });
14322 }
14323 if (_instanceof(name, RegExp)) {
14324 return this.walk(function(child, i2) {
14325 if (child.type === "atrule" && name.test(child.name)) {
14326 return callback(child, i2);
14327 }
14328 });
14329 }
14330 return this.walk(function(child, i2) {
14331 if (child.type === "atrule" && child.name === name) {
14332 return callback(child, i2);
14333 }
14334 });
14335 };
14336 _proto.walkComments = function walkComments(callback) {
14337 return this.walk(function(child, i2) {
14338 if (child.type === "comment") {
14339 return callback(child, i2);
14340 }
14341 });
14342 };
14343 _proto.walkDecls = function walkDecls(prop, callback) {
14344 if (!callback) {
14345 callback = prop;
14346 return this.walk(function(child, i2) {
14347 if (child.type === "decl") {
14348 return callback(child, i2);
14349 }
14350 });
14351 }
14352 if (_instanceof(prop, RegExp)) {
14353 return this.walk(function(child, i2) {
14354 if (child.type === "decl" && prop.test(child.prop)) {
14355 return callback(child, i2);
14356 }
14357 });
14358 }
14359 return this.walk(function(child, i2) {
14360 if (child.type === "decl" && child.prop === prop) {
14361 return callback(child, i2);
14362 }
14363 });
14364 };
14365 _proto.walkRules = function walkRules(selector, callback) {
14366 if (!callback) {
14367 callback = selector;
14368 return this.walk(function(child, i2) {
14369 if (child.type === "rule") {
14370 return callback(child, i2);
14371 }
14372 });
14373 }
14374 if (_instanceof(selector, RegExp)) {
14375 return this.walk(function(child, i2) {
14376 if (child.type === "rule" && selector.test(child.selector)) {
14377 return callback(child, i2);
14378 }
14379 });
14380 }
14381 return this.walk(function(child, i2) {
14382 if (child.type === "rule" && child.selector === selector) {
14383 return callback(child, i2);
14384 }
14385 });
14386 };
14387 _create_class(Container2, [
14388 {
14389 key: "first",
14390 get: function get() {
14391 if (!this.proxyOf.nodes) return void 0;
14392 return this.proxyOf.nodes[0];
14393 }
14394 },
14395 {
14396 key: "last",
14397 get: function get() {
14398 if (!this.proxyOf.nodes) return void 0;
14399 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
14400 }
14401 }
14402 ]);
14403 return Container2;
14404 }(Node$1);
14405 Container$7.registerParse = function(dependant) {
14406 parse$4 = dependant;
14407 };
14408 Container$7.registerRule = function(dependant) {
14409 Rule$4 = dependant;
14410 };
14411 Container$7.registerAtRule = function(dependant) {
14412 AtRule$4 = dependant;
14413 };
14414 Container$7.registerRoot = function(dependant) {
14415 Root$6 = dependant;
14416 };
14417 var container = Container$7;
14418 Container$7.default = Container$7;
14419 Container$7.rebuild = function(node2) {
14420 if (node2.type === "atrule") {
14421 Object.setPrototypeOf(node2, AtRule$4.prototype);
14422 } else if (node2.type === "rule") {
14423 Object.setPrototypeOf(node2, Rule$4.prototype);
14424 } else if (node2.type === "decl") {
14425 Object.setPrototypeOf(node2, Declaration$3.prototype);
14426 } else if (node2.type === "comment") {
14427 Object.setPrototypeOf(node2, Comment$3.prototype);
14428 } else if (node2.type === "root") {
14429 Object.setPrototypeOf(node2, Root$6.prototype);
14430 }
14431 node2[my$1] = true;
14432 if (node2.nodes) {
14433 node2.nodes.forEach(function(child) {
14434 Container$7.rebuild(child);
14435 });
14436 }
14437 };
14438 var Container$6 = container;
14439 var LazyResult$4, Processor$3;
14440 var Document$3 = /*#__PURE__*/ function(Container$6) {
14441 _inherits(Document23, Container$6);
14442 function Document23(defaults) {
14443 var _this;
14444 _this = Container$6.call(this, _extends({
14445 type: "document"
14446 }, defaults)) || this;
14447 if (!_this.nodes) {
14448 _this.nodes = [];
14449 }
14450 return _this;
14451 }
14452 var _proto = Document23.prototype;
14453 _proto.toResult = function toResult(opts) {
14454 if (opts === void 0) opts = {};
14455 var lazy = new LazyResult$4(new Processor$3(), this, opts);
14456 return lazy.stringify();
14457 };
14458 return Document23;
14459 }(Container$6);
14460 Document$3.registerLazyResult = function(dependant) {
14461 LazyResult$4 = dependant;
14462 };
14463 Document$3.registerProcessor = function(dependant) {
14464 Processor$3 = dependant;
14465 };
14466 var document$1$2 = Document$3;
14467 Document$3.default = Document$3;
14468 var printed = {};
14469 var warnOnce$2 = function warnOnce2(message) {
14470 if (printed[message]) return;
14471 printed[message] = true;
14472 if (typeof console !== "undefined" && console.warn) {
14473 console.warn(message);
14474 }
14475 };
14476 var Warning$2 = /*#__PURE__*/ function() {
14477 function Warning2(text, opts) {
14478 if (opts === void 0) opts = {};
14479 this.type = "warning";
14480 this.text = text;
14481 if (opts.node && opts.node.source) {
14482 var range = opts.node.rangeBy(opts);
14483 this.line = range.start.line;
14484 this.column = range.start.column;
14485 this.endLine = range.end.line;
14486 this.endColumn = range.end.column;
14487 }
14488 for(var opt in opts)this[opt] = opts[opt];
14489 }
14490 var _proto = Warning2.prototype;
14491 _proto.toString = function toString() {
14492 if (this.node) {
14493 return this.node.error(this.text, {
14494 index: this.index,
14495 plugin: this.plugin,
14496 word: this.word
14497 }).message;
14498 }
14499 if (this.plugin) {
14500 return this.plugin + ": " + this.text;
14501 }
14502 return this.text;
14503 };
14504 return Warning2;
14505 }();
14506 var warning = Warning$2;
14507 Warning$2.default = Warning$2;
14508 var Warning$1 = warning;
14509 var Result$3 = /*#__PURE__*/ function() {
14510 function Result2(processor2, root2, opts) {
14511 this.processor = processor2;
14512 this.messages = [];
14513 this.root = root2;
14514 this.opts = opts;
14515 this.css = void 0;
14516 this.map = void 0;
14517 }
14518 var _proto = Result2.prototype;
14519 _proto.toString = function toString() {
14520 return this.css;
14521 };
14522 _proto.warn = function warn(text, opts) {
14523 if (opts === void 0) opts = {};
14524 if (!opts.plugin) {
14525 if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
14526 opts.plugin = this.lastPlugin.postcssPlugin;
14527 }
14528 }
14529 var warning2 = new Warning$1(text, opts);
14530 this.messages.push(warning2);
14531 return warning2;
14532 };
14533 _proto.warnings = function warnings() {
14534 return this.messages.filter(function(i2) {
14535 return i2.type === "warning";
14536 });
14537 };
14538 _create_class(Result2, [
14539 {
14540 key: "content",
14541 get: function get() {
14542 return this.css;
14543 }
14544 }
14545 ]);
14546 return Result2;
14547 }();
14548 var result = Result$3;
14549 Result$3.default = Result$3;
14550 var SINGLE_QUOTE = "'".charCodeAt(0);
14551 var DOUBLE_QUOTE = '"'.charCodeAt(0);
14552 var BACKSLASH = "\\".charCodeAt(0);
14553 var SLASH = "/".charCodeAt(0);
14554 var NEWLINE = "\n".charCodeAt(0);
14555 var SPACE = " ".charCodeAt(0);
14556 var FEED = "\f".charCodeAt(0);
14557 var TAB = " ".charCodeAt(0);
14558 var CR = "\r".charCodeAt(0);
14559 var OPEN_SQUARE = "[".charCodeAt(0);
14560 var CLOSE_SQUARE = "]".charCodeAt(0);
14561 var OPEN_PARENTHESES = "(".charCodeAt(0);
14562 var CLOSE_PARENTHESES = ")".charCodeAt(0);
14563 var OPEN_CURLY = "{".charCodeAt(0);
14564 var CLOSE_CURLY = "}".charCodeAt(0);
14565 var SEMICOLON = ";".charCodeAt(0);
14566 var ASTERISK = "*".charCodeAt(0);
14567 var COLON = ":".charCodeAt(0);
14568 var AT = "@".charCodeAt(0);
14569 var RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
14570 var RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
14571 var RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
14572 var RE_HEX_ESCAPE = /[\da-f]/i;
14573 var tokenize = function tokenizer2(input2, options) {
14574 if (options === void 0) options = {};
14575 var css = input2.css.valueOf();
14576 var ignore = options.ignoreErrors;
14577 var code, next, quote, content, escape;
14578 var escaped, escapePos, prev, n2, currentToken;
14579 var length = css.length;
14580 var pos = 0;
14581 var buffer = [];
14582 var returned = [];
14583 function position() {
14584 return pos;
14585 }
14586 function unclosed(what) {
14587 throw input2.error("Unclosed " + what, pos);
14588 }
14589 function endOfFile() {
14590 return returned.length === 0 && pos >= length;
14591 }
14592 function nextToken(opts) {
14593 if (returned.length) return returned.pop();
14594 if (pos >= length) return;
14595 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
14596 code = css.charCodeAt(pos);
14597 switch(code){
14598 case NEWLINE:
14599 case SPACE:
14600 case TAB:
14601 case CR:
14602 case FEED:
14603 {
14604 next = pos;
14605 do {
14606 next += 1;
14607 code = css.charCodeAt(next);
14608 }while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
14609 currentToken = [
14610 "space",
14611 css.slice(pos, next)
14612 ];
14613 pos = next - 1;
14614 break;
14615 }
14616 case OPEN_SQUARE:
14617 case CLOSE_SQUARE:
14618 case OPEN_CURLY:
14619 case CLOSE_CURLY:
14620 case COLON:
14621 case SEMICOLON:
14622 case CLOSE_PARENTHESES:
14623 {
14624 var controlChar = String.fromCharCode(code);
14625 currentToken = [
14626 controlChar,
14627 controlChar,
14628 pos
14629 ];
14630 break;
14631 }
14632 case OPEN_PARENTHESES:
14633 {
14634 prev = buffer.length ? buffer.pop()[1] : "";
14635 n2 = css.charCodeAt(pos + 1);
14636 if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE && n2 !== NEWLINE && n2 !== TAB && n2 !== FEED && n2 !== CR) {
14637 next = pos;
14638 do {
14639 escaped = false;
14640 next = css.indexOf(")", next + 1);
14641 if (next === -1) {
14642 if (ignore || ignoreUnclosed) {
14643 next = pos;
14644 break;
14645 } else {
14646 unclosed("bracket");
14647 }
14648 }
14649 escapePos = next;
14650 while(css.charCodeAt(escapePos - 1) === BACKSLASH){
14651 escapePos -= 1;
14652 escaped = !escaped;
14653 }
14654 }while (escaped);
14655 currentToken = [
14656 "brackets",
14657 css.slice(pos, next + 1),
14658 pos,
14659 next
14660 ];
14661 pos = next;
14662 } else {
14663 next = css.indexOf(")", pos + 1);
14664 content = css.slice(pos, next + 1);
14665 if (next === -1 || RE_BAD_BRACKET.test(content)) {
14666 currentToken = [
14667 "(",
14668 "(",
14669 pos
14670 ];
14671 } else {
14672 currentToken = [
14673 "brackets",
14674 content,
14675 pos,
14676 next
14677 ];
14678 pos = next;
14679 }
14680 }
14681 break;
14682 }
14683 case SINGLE_QUOTE:
14684 case DOUBLE_QUOTE:
14685 {
14686 quote = code === SINGLE_QUOTE ? "'" : '"';
14687 next = pos;
14688 do {
14689 escaped = false;
14690 next = css.indexOf(quote, next + 1);
14691 if (next === -1) {
14692 if (ignore || ignoreUnclosed) {
14693 next = pos + 1;
14694 break;
14695 } else {
14696 unclosed("string");
14697 }
14698 }
14699 escapePos = next;
14700 while(css.charCodeAt(escapePos - 1) === BACKSLASH){
14701 escapePos -= 1;
14702 escaped = !escaped;
14703 }
14704 }while (escaped);
14705 currentToken = [
14706 "string",
14707 css.slice(pos, next + 1),
14708 pos,
14709 next
14710 ];
14711 pos = next;
14712 break;
14713 }
14714 case AT:
14715 {
14716 RE_AT_END.lastIndex = pos + 1;
14717 RE_AT_END.test(css);
14718 if (RE_AT_END.lastIndex === 0) {
14719 next = css.length - 1;
14720 } else {
14721 next = RE_AT_END.lastIndex - 2;
14722 }
14723 currentToken = [
14724 "at-word",
14725 css.slice(pos, next + 1),
14726 pos,
14727 next
14728 ];
14729 pos = next;
14730 break;
14731 }
14732 case BACKSLASH:
14733 {
14734 next = pos;
14735 escape = true;
14736 while(css.charCodeAt(next + 1) === BACKSLASH){
14737 next += 1;
14738 escape = !escape;
14739 }
14740 code = css.charCodeAt(next + 1);
14741 if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
14742 next += 1;
14743 if (RE_HEX_ESCAPE.test(css.charAt(next))) {
14744 while(RE_HEX_ESCAPE.test(css.charAt(next + 1))){
14745 next += 1;
14746 }
14747 if (css.charCodeAt(next + 1) === SPACE) {
14748 next += 1;
14749 }
14750 }
14751 }
14752 currentToken = [
14753 "word",
14754 css.slice(pos, next + 1),
14755 pos,
14756 next
14757 ];
14758 pos = next;
14759 break;
14760 }
14761 default:
14762 {
14763 if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
14764 next = css.indexOf("*/", pos + 2) + 1;
14765 if (next === 0) {
14766 if (ignore || ignoreUnclosed) {
14767 next = css.length;
14768 } else {
14769 unclosed("comment");
14770 }
14771 }
14772 currentToken = [
14773 "comment",
14774 css.slice(pos, next + 1),
14775 pos,
14776 next
14777 ];
14778 pos = next;
14779 } else {
14780 RE_WORD_END.lastIndex = pos + 1;
14781 RE_WORD_END.test(css);
14782 if (RE_WORD_END.lastIndex === 0) {
14783 next = css.length - 1;
14784 } else {
14785 next = RE_WORD_END.lastIndex - 2;
14786 }
14787 currentToken = [
14788 "word",
14789 css.slice(pos, next + 1),
14790 pos,
14791 next
14792 ];
14793 buffer.push(currentToken);
14794 pos = next;
14795 }
14796 break;
14797 }
14798 }
14799 pos++;
14800 return currentToken;
14801 }
14802 function back(token) {
14803 returned.push(token);
14804 }
14805 return {
14806 back: back,
14807 endOfFile: endOfFile,
14808 nextToken: nextToken,
14809 position: position
14810 };
14811 };
14812 var Container$5 = container;
14813 var AtRule$3 = /*#__PURE__*/ function(Container$5) {
14814 _inherits(AtRule2, Container$5);
14815 function AtRule2(defaults) {
14816 var _this;
14817 _this = Container$5.call(this, defaults) || this;
14818 _this.type = "atrule";
14819 return _this;
14820 }
14821 var _proto = AtRule2.prototype;
14822 _proto.append = function append() {
14823 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
14824 children[_key] = arguments[_key];
14825 }
14826 var _Container$5_prototype_append;
14827 if (!this.proxyOf.nodes) this.nodes = [];
14828 return (_Container$5_prototype_append = Container$5.prototype.append).call.apply(_Container$5_prototype_append, [].concat([
14829 this
14830 ], children));
14831 };
14832 _proto.prepend = function prepend() {
14833 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
14834 children[_key] = arguments[_key];
14835 }
14836 var _Container$5_prototype_prepend;
14837 if (!this.proxyOf.nodes) this.nodes = [];
14838 return (_Container$5_prototype_prepend = Container$5.prototype.prepend).call.apply(_Container$5_prototype_prepend, [].concat([
14839 this
14840 ], children));
14841 };
14842 return AtRule2;
14843 }(Container$5);
14844 var atRule = AtRule$3;
14845 AtRule$3.default = AtRule$3;
14846 Container$5.registerAtRule(AtRule$3);
14847 var Container$4 = container;
14848 var LazyResult$3, Processor$2;
14849 var Root$5 = /*#__PURE__*/ function(Container$4) {
14850 _inherits(Root2, Container$4);
14851 function Root2(defaults) {
14852 var _this;
14853 _this = Container$4.call(this, defaults) || this;
14854 _this.type = "root";
14855 if (!_this.nodes) _this.nodes = [];
14856 return _this;
14857 }
14858 var _proto = Root2.prototype;
14859 _proto.normalize = function normalize(child, sample, type) {
14860 var nodes = Container$4.prototype.normalize.call(this, child);
14861 if (sample) {
14862 if (type === "prepend") {
14863 if (this.nodes.length > 1) {
14864 sample.raws.before = this.nodes[1].raws.before;
14865 } else {
14866 delete sample.raws.before;
14867 }
14868 } else if (this.first !== sample) {
14869 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
14870 var node2 = _step.value;
14871 node2.raws.before = sample.raws.before;
14872 }
14873 }
14874 }
14875 return nodes;
14876 };
14877 _proto.removeChild = function removeChild(child, ignore) {
14878 var index2 = this.index(child);
14879 if (!ignore && index2 === 0 && this.nodes.length > 1) {
14880 this.nodes[1].raws.before = this.nodes[index2].raws.before;
14881 }
14882 return Container$4.prototype.removeChild.call(this, child);
14883 };
14884 _proto.toResult = function toResult(opts) {
14885 if (opts === void 0) opts = {};
14886 var lazy = new LazyResult$3(new Processor$2(), this, opts);
14887 return lazy.stringify();
14888 };
14889 return Root2;
14890 }(Container$4);
14891 Root$5.registerLazyResult = function(dependant) {
14892 LazyResult$3 = dependant;
14893 };
14894 Root$5.registerProcessor = function(dependant) {
14895 Processor$2 = dependant;
14896 };
14897 var root = Root$5;
14898 Root$5.default = Root$5;
14899 Container$4.registerRoot(Root$5);
14900 var list$2 = {
14901 comma: function comma(string) {
14902 return list$2.split(string, [
14903 ","
14904 ], true);
14905 },
14906 space: function space(string) {
14907 var spaces = [
14908 " ",
14909 "\n",
14910 " "
14911 ];
14912 return list$2.split(string, spaces);
14913 },
14914 split: function split(string, separators, last) {
14915 var array = [];
14916 var current = "";
14917 var split = false;
14918 var func = 0;
14919 var inQuote = false;
14920 var prevQuote = "";
14921 var escape = false;
14922 for(var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;){
14923 var letter = _step.value;
14924 if (escape) {
14925 escape = false;
14926 } else if (letter === "\\") {
14927 escape = true;
14928 } else if (inQuote) {
14929 if (letter === prevQuote) {
14930 inQuote = false;
14931 }
14932 } else if (letter === '"' || letter === "'") {
14933 inQuote = true;
14934 prevQuote = letter;
14935 } else if (letter === "(") {
14936 func += 1;
14937 } else if (letter === ")") {
14938 if (func > 0) func -= 1;
14939 } else if (func === 0) {
14940 if (separators.includes(letter)) split = true;
14941 }
14942 if (split) {
14943 if (current !== "") array.push(current.trim());
14944 current = "";
14945 split = false;
14946 } else {
14947 current += letter;
14948 }
14949 }
14950 if (last || current !== "") array.push(current.trim());
14951 return array;
14952 }
14953 };
14954 var list_1 = list$2;
14955 list$2.default = list$2;
14956 var Container$3 = container;
14957 var list$1 = list_1;
14958 var Rule$3 = /*#__PURE__*/ function(Container$3) {
14959 _inherits(Rule2, Container$3);
14960 function Rule2(defaults) {
14961 var _this;
14962 _this = Container$3.call(this, defaults) || this;
14963 _this.type = "rule";
14964 if (!_this.nodes) _this.nodes = [];
14965 return _this;
14966 }
14967 _create_class(Rule2, [
14968 {
14969 key: "selectors",
14970 get: function get() {
14971 return list$1.comma(this.selector);
14972 },
14973 set: function set(values) {
14974 var match = this.selector ? this.selector.match(/,\s*/) : null;
14975 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
14976 this.selector = values.join(sep2);
14977 }
14978 }
14979 ]);
14980 return Rule2;
14981 }(Container$3);
14982 var rule = Rule$3;
14983 Rule$3.default = Rule$3;
14984 Container$3.registerRule(Rule$3);
14985 var Declaration$2 = declaration;
14986 var tokenizer22 = tokenize;
14987 var Comment$2 = comment;
14988 var AtRule$2 = atRule;
14989 var Root$4 = root;
14990 var Rule$2 = rule;
14991 var SAFE_COMMENT_NEIGHBOR = {
14992 empty: true,
14993 space: true
14994 };
14995 function findLastWithPosition(tokens) {
14996 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
14997 var token = tokens[i2];
14998 var pos = token[3] || token[2];
14999 if (pos) return pos;
15000 }
15001 }
15002 var Parser$1 = /*#__PURE__*/ function() {
15003 function Parser2(input2) {
15004 this.input = input2;
15005 this.root = new Root$4();
15006 this.current = this.root;
15007 this.spaces = "";
15008 this.semicolon = false;
15009 this.createTokenizer();
15010 this.root.source = {
15011 input: input2,
15012 start: {
15013 column: 1,
15014 line: 1,
15015 offset: 0
15016 }
15017 };
15018 }
15019 var _proto = Parser2.prototype;
15020 _proto.atrule = function atrule(token) {
15021 var node2 = new AtRule$2();
15022 node2.name = token[1].slice(1);
15023 if (node2.name === "") {
15024 this.unnamedAtrule(node2, token);
15025 }
15026 this.init(node2, token[2]);
15027 var type;
15028 var prev;
15029 var shift;
15030 var last = false;
15031 var open = false;
15032 var params = [];
15033 var brackets = [];
15034 while(!this.tokenizer.endOfFile()){
15035 token = this.tokenizer.nextToken();
15036 type = token[0];
15037 if (type === "(" || type === "[") {
15038 brackets.push(type === "(" ? ")" : "]");
15039 } else if (type === "{" && brackets.length > 0) {
15040 brackets.push("}");
15041 } else if (type === brackets[brackets.length - 1]) {
15042 brackets.pop();
15043 }
15044 if (brackets.length === 0) {
15045 if (type === ";") {
15046 node2.source.end = this.getPosition(token[2]);
15047 node2.source.end.offset++;
15048 this.semicolon = true;
15049 break;
15050 } else if (type === "{") {
15051 open = true;
15052 break;
15053 } else if (type === "}") {
15054 if (params.length > 0) {
15055 shift = params.length - 1;
15056 prev = params[shift];
15057 while(prev && prev[0] === "space"){
15058 prev = params[--shift];
15059 }
15060 if (prev) {
15061 node2.source.end = this.getPosition(prev[3] || prev[2]);
15062 node2.source.end.offset++;
15063 }
15064 }
15065 this.end(token);
15066 break;
15067 } else {
15068 params.push(token);
15069 }
15070 } else {
15071 params.push(token);
15072 }
15073 if (this.tokenizer.endOfFile()) {
15074 last = true;
15075 break;
15076 }
15077 }
15078 node2.raws.between = this.spacesAndCommentsFromEnd(params);
15079 if (params.length) {
15080 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
15081 this.raw(node2, "params", params);
15082 if (last) {
15083 token = params[params.length - 1];
15084 node2.source.end = this.getPosition(token[3] || token[2]);
15085 node2.source.end.offset++;
15086 this.spaces = node2.raws.between;
15087 node2.raws.between = "";
15088 }
15089 } else {
15090 node2.raws.afterName = "";
15091 node2.params = "";
15092 }
15093 if (open) {
15094 node2.nodes = [];
15095 this.current = node2;
15096 }
15097 };
15098 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
15099 var colon = this.colon(tokens);
15100 if (colon === false) return;
15101 var founded = 0;
15102 var token;
15103 for(var j = colon - 1; j >= 0; j--){
15104 token = tokens[j];
15105 if (token[0] !== "space") {
15106 founded += 1;
15107 if (founded === 2) break;
15108 }
15109 }
15110 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
15111 };
15112 _proto.colon = function colon(tokens) {
15113 var brackets = 0;
15114 var token, type, prev;
15115 for(var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;){
15116 var _step_value = _step.value, i2 = _step_value[0], element = _step_value[1];
15117 token = element;
15118 type = token[0];
15119 if (type === "(") {
15120 brackets += 1;
15121 }
15122 if (type === ")") {
15123 brackets -= 1;
15124 }
15125 if (brackets === 0 && type === ":") {
15126 if (!prev) {
15127 this.doubleColon(token);
15128 } else if (prev[0] === "word" && prev[1] === "progid") {
15129 continue;
15130 } else {
15131 return i2;
15132 }
15133 }
15134 prev = token;
15135 }
15136 return false;
15137 };
15138 _proto.comment = function comment(token) {
15139 var node2 = new Comment$2();
15140 this.init(node2, token[2]);
15141 node2.source.end = this.getPosition(token[3] || token[2]);
15142 node2.source.end.offset++;
15143 var text = token[1].slice(2, -2);
15144 if (/^\s*$/.test(text)) {
15145 node2.text = "";
15146 node2.raws.left = text;
15147 node2.raws.right = "";
15148 } else {
15149 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
15150 node2.text = match[2];
15151 node2.raws.left = match[1];
15152 node2.raws.right = match[3];
15153 }
15154 };
15155 _proto.createTokenizer = function createTokenizer() {
15156 this.tokenizer = tokenizer22(this.input);
15157 };
15158 _proto.decl = function decl(tokens, customProperty) {
15159 var node2 = new Declaration$2();
15160 this.init(node2, tokens[0][2]);
15161 var last = tokens[tokens.length - 1];
15162 if (last[0] === ";") {
15163 this.semicolon = true;
15164 tokens.pop();
15165 }
15166 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition(tokens));
15167 node2.source.end.offset++;
15168 while(tokens[0][0] !== "word"){
15169 if (tokens.length === 1) this.unknownWord(tokens);
15170 node2.raws.before += tokens.shift()[1];
15171 }
15172 node2.source.start = this.getPosition(tokens[0][2]);
15173 node2.prop = "";
15174 while(tokens.length){
15175 var type = tokens[0][0];
15176 if (type === ":" || type === "space" || type === "comment") {
15177 break;
15178 }
15179 node2.prop += tokens.shift()[1];
15180 }
15181 node2.raws.between = "";
15182 var token;
15183 while(tokens.length){
15184 token = tokens.shift();
15185 if (token[0] === ":") {
15186 node2.raws.between += token[1];
15187 break;
15188 } else {
15189 if (token[0] === "word" && /\w/.test(token[1])) {
15190 this.unknownWord([
15191 token
15192 ]);
15193 }
15194 node2.raws.between += token[1];
15195 }
15196 }
15197 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
15198 node2.raws.before += node2.prop[0];
15199 node2.prop = node2.prop.slice(1);
15200 }
15201 var firstSpaces = [];
15202 var next;
15203 while(tokens.length){
15204 next = tokens[0][0];
15205 if (next !== "space" && next !== "comment") break;
15206 firstSpaces.push(tokens.shift());
15207 }
15208 this.precheckMissedSemicolon(tokens);
15209 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
15210 token = tokens[i2];
15211 if (token[1].toLowerCase() === "!important") {
15212 node2.important = true;
15213 var string = this.stringFrom(tokens, i2);
15214 string = this.spacesFromEnd(tokens) + string;
15215 if (string !== " !important") node2.raws.important = string;
15216 break;
15217 } else if (token[1].toLowerCase() === "important") {
15218 var cache = tokens.slice(0);
15219 var str = "";
15220 for(var j = i2; j > 0; j--){
15221 var type1 = cache[j][0];
15222 if (str.trim().indexOf("!") === 0 && type1 !== "space") {
15223 break;
15224 }
15225 str = cache.pop()[1] + str;
15226 }
15227 if (str.trim().indexOf("!") === 0) {
15228 node2.important = true;
15229 node2.raws.important = str;
15230 tokens = cache;
15231 }
15232 }
15233 if (token[0] !== "space" && token[0] !== "comment") {
15234 break;
15235 }
15236 }
15237 var hasWord = tokens.some(function(i2) {
15238 return i2[0] !== "space" && i2[0] !== "comment";
15239 });
15240 if (hasWord) {
15241 node2.raws.between += firstSpaces.map(function(i2) {
15242 return i2[1];
15243 }).join("");
15244 firstSpaces = [];
15245 }
15246 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
15247 if (node2.value.includes(":") && !customProperty) {
15248 this.checkMissedSemicolon(tokens);
15249 }
15250 };
15251 _proto.doubleColon = function doubleColon(token) {
15252 throw this.input.error("Double colon", {
15253 offset: token[2]
15254 }, {
15255 offset: token[2] + token[1].length
15256 });
15257 };
15258 _proto.emptyRule = function emptyRule(token) {
15259 var node2 = new Rule$2();
15260 this.init(node2, token[2]);
15261 node2.selector = "";
15262 node2.raws.between = "";
15263 this.current = node2;
15264 };
15265 _proto.end = function end(token) {
15266 if (this.current.nodes && this.current.nodes.length) {
15267 this.current.raws.semicolon = this.semicolon;
15268 }
15269 this.semicolon = false;
15270 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
15271 this.spaces = "";
15272 if (this.current.parent) {
15273 this.current.source.end = this.getPosition(token[2]);
15274 this.current.source.end.offset++;
15275 this.current = this.current.parent;
15276 } else {
15277 this.unexpectedClose(token);
15278 }
15279 };
15280 _proto.endFile = function endFile() {
15281 if (this.current.parent) this.unclosedBlock();
15282 if (this.current.nodes && this.current.nodes.length) {
15283 this.current.raws.semicolon = this.semicolon;
15284 }
15285 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
15286 this.root.source.end = this.getPosition(this.tokenizer.position());
15287 };
15288 _proto.freeSemicolon = function freeSemicolon(token) {
15289 this.spaces += token[1];
15290 if (this.current.nodes) {
15291 var prev = this.current.nodes[this.current.nodes.length - 1];
15292 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
15293 prev.raws.ownSemicolon = this.spaces;
15294 this.spaces = "";
15295 }
15296 }
15297 };
15298 // Helpers
15299 _proto.getPosition = function getPosition(offset) {
15300 var pos = this.input.fromOffset(offset);
15301 return {
15302 column: pos.col,
15303 line: pos.line,
15304 offset: offset
15305 };
15306 };
15307 _proto.init = function init(node2, offset) {
15308 this.current.push(node2);
15309 node2.source = {
15310 input: this.input,
15311 start: this.getPosition(offset)
15312 };
15313 node2.raws.before = this.spaces;
15314 this.spaces = "";
15315 if (node2.type !== "comment") this.semicolon = false;
15316 };
15317 _proto.other = function other(start) {
15318 var end = false;
15319 var type = null;
15320 var colon = false;
15321 var bracket = null;
15322 var brackets = [];
15323 var customProperty = start[1].startsWith("--");
15324 var tokens = [];
15325 var token = start;
15326 while(token){
15327 type = token[0];
15328 tokens.push(token);
15329 if (type === "(" || type === "[") {
15330 if (!bracket) bracket = token;
15331 brackets.push(type === "(" ? ")" : "]");
15332 } else if (customProperty && colon && type === "{") {
15333 if (!bracket) bracket = token;
15334 brackets.push("}");
15335 } else if (brackets.length === 0) {
15336 if (type === ";") {
15337 if (colon) {
15338 this.decl(tokens, customProperty);
15339 return;
15340 } else {
15341 break;
15342 }
15343 } else if (type === "{") {
15344 this.rule(tokens);
15345 return;
15346 } else if (type === "}") {
15347 this.tokenizer.back(tokens.pop());
15348 end = true;
15349 break;
15350 } else if (type === ":") {
15351 colon = true;
15352 }
15353 } else if (type === brackets[brackets.length - 1]) {
15354 brackets.pop();
15355 if (brackets.length === 0) bracket = null;
15356 }
15357 token = this.tokenizer.nextToken();
15358 }
15359 if (this.tokenizer.endOfFile()) end = true;
15360 if (brackets.length > 0) this.unclosedBracket(bracket);
15361 if (end && colon) {
15362 if (!customProperty) {
15363 while(tokens.length){
15364 token = tokens[tokens.length - 1][0];
15365 if (token !== "space" && token !== "comment") break;
15366 this.tokenizer.back(tokens.pop());
15367 }
15368 }
15369 this.decl(tokens, customProperty);
15370 } else {
15371 this.unknownWord(tokens);
15372 }
15373 };
15374 _proto.parse = function parse() {
15375 var token;
15376 while(!this.tokenizer.endOfFile()){
15377 token = this.tokenizer.nextToken();
15378 switch(token[0]){
15379 case "space":
15380 this.spaces += token[1];
15381 break;
15382 case ";":
15383 this.freeSemicolon(token);
15384 break;
15385 case "}":
15386 this.end(token);
15387 break;
15388 case "comment":
15389 this.comment(token);
15390 break;
15391 case "at-word":
15392 this.atrule(token);
15393 break;
15394 case "{":
15395 this.emptyRule(token);
15396 break;
15397 default:
15398 this.other(token);
15399 break;
15400 }
15401 }
15402 this.endFile();
15403 };
15404 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
15405 _proto.raw = function raw(node2, prop, tokens, customProperty) {
15406 var token, type;
15407 var length = tokens.length;
15408 var value = "";
15409 var clean = true;
15410 var next, prev;
15411 for(var i2 = 0; i2 < length; i2 += 1){
15412 token = tokens[i2];
15413 type = token[0];
15414 if (type === "space" && i2 === length - 1 && !customProperty) {
15415 clean = false;
15416 } else if (type === "comment") {
15417 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
15418 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
15419 if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
15420 if (value.slice(-1) === ",") {
15421 clean = false;
15422 } else {
15423 value += token[1];
15424 }
15425 } else {
15426 clean = false;
15427 }
15428 } else {
15429 value += token[1];
15430 }
15431 }
15432 if (!clean) {
15433 var raw = tokens.reduce(function(all, i2) {
15434 return all + i2[1];
15435 }, "");
15436 node2.raws[prop] = {
15437 raw: raw,
15438 value: value
15439 };
15440 }
15441 node2[prop] = value;
15442 };
15443 _proto.rule = function rule(tokens) {
15444 tokens.pop();
15445 var node2 = new Rule$2();
15446 this.init(node2, tokens[0][2]);
15447 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
15448 this.raw(node2, "selector", tokens);
15449 this.current = node2;
15450 };
15451 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
15452 var lastTokenType;
15453 var spaces = "";
15454 while(tokens.length){
15455 lastTokenType = tokens[tokens.length - 1][0];
15456 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
15457 spaces = tokens.pop()[1] + spaces;
15458 }
15459 return spaces;
15460 };
15461 // Errors
15462 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
15463 var next;
15464 var spaces = "";
15465 while(tokens.length){
15466 next = tokens[0][0];
15467 if (next !== "space" && next !== "comment") break;
15468 spaces += tokens.shift()[1];
15469 }
15470 return spaces;
15471 };
15472 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
15473 var lastTokenType;
15474 var spaces = "";
15475 while(tokens.length){
15476 lastTokenType = tokens[tokens.length - 1][0];
15477 if (lastTokenType !== "space") break;
15478 spaces = tokens.pop()[1] + spaces;
15479 }
15480 return spaces;
15481 };
15482 _proto.stringFrom = function stringFrom(tokens, from) {
15483 var result2 = "";
15484 for(var i2 = from; i2 < tokens.length; i2++){
15485 result2 += tokens[i2][1];
15486 }
15487 tokens.splice(from, tokens.length - from);
15488 return result2;
15489 };
15490 _proto.unclosedBlock = function unclosedBlock() {
15491 var pos = this.current.source.start;
15492 throw this.input.error("Unclosed block", pos.line, pos.column);
15493 };
15494 _proto.unclosedBracket = function unclosedBracket(bracket) {
15495 throw this.input.error("Unclosed bracket", {
15496 offset: bracket[2]
15497 }, {
15498 offset: bracket[2] + 1
15499 });
15500 };
15501 _proto.unexpectedClose = function unexpectedClose(token) {
15502 throw this.input.error("Unexpected }", {
15503 offset: token[2]
15504 }, {
15505 offset: token[2] + 1
15506 });
15507 };
15508 _proto.unknownWord = function unknownWord(tokens) {
15509 throw this.input.error("Unknown word", {
15510 offset: tokens[0][2]
15511 }, {
15512 offset: tokens[0][2] + tokens[0][1].length
15513 });
15514 };
15515 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
15516 throw this.input.error("At-rule without name", {
15517 offset: token[2]
15518 }, {
15519 offset: token[2] + token[1].length
15520 });
15521 };
15522 return Parser2;
15523 }();
15524 var parser = Parser$1;
15525 var Container$2 = container;
15526 var Parser22 = parser;
15527 var Input$2 = input;
15528 function parse$3(css, opts) {
15529 var input2 = new Input$2(css, opts);
15530 var parser2 = new Parser22(input2);
15531 try {
15532 parser2.parse();
15533 } catch (e2) {
15534 if (true) {
15535 if (e2.name === "CssSyntaxError" && opts && opts.from) {
15536 if (/\.scss$/i.test(opts.from)) {
15537 e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
15538 } else if (/\.sass/i.test(opts.from)) {
15539 e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
15540 } else if (/\.less$/i.test(opts.from)) {
15541 e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
15542 }
15543 }
15544 }
15545 throw e2;
15546 }
15547 return parser2.root;
15548 }
15549 var parse_1 = parse$3;
15550 parse$3.default = parse$3;
15551 Container$2.registerParse(parse$3);
15552 var isClean = symbols.isClean, my = symbols.my;
15553 var MapGenerator$1 = mapGenerator;
15554 var stringify$2 = stringify_1;
15555 var Container$1 = container;
15556 var Document$2 = document$1$2;
15557 var warnOnce$1 = warnOnce$2;
15558 var Result$2 = result;
15559 var parse$2 = parse_1;
15560 var Root$3 = root;
15561 var TYPE_TO_CLASS_NAME = {
15562 atrule: "AtRule",
15563 comment: "Comment",
15564 decl: "Declaration",
15565 document: "Document",
15566 root: "Root",
15567 rule: "Rule"
15568 };
15569 var PLUGIN_PROPS = {
15570 AtRule: true,
15571 AtRuleExit: true,
15572 Comment: true,
15573 CommentExit: true,
15574 Declaration: true,
15575 DeclarationExit: true,
15576 Document: true,
15577 DocumentExit: true,
15578 Once: true,
15579 OnceExit: true,
15580 postcssPlugin: true,
15581 prepare: true,
15582 Root: true,
15583 RootExit: true,
15584 Rule: true,
15585 RuleExit: true
15586 };
15587 var NOT_VISITORS = {
15588 Once: true,
15589 postcssPlugin: true,
15590 prepare: true
15591 };
15592 var CHILDREN = 0;
15593 function isPromise(obj) {
15594 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
15595 }
15596 function getEvents(node2) {
15597 var key = false;
15598 var type = TYPE_TO_CLASS_NAME[node2.type];
15599 if (node2.type === "decl") {
15600 key = node2.prop.toLowerCase();
15601 } else if (node2.type === "atrule") {
15602 key = node2.name.toLowerCase();
15603 }
15604 if (key && node2.append) {
15605 return [
15606 type,
15607 type + "-" + key,
15608 CHILDREN,
15609 type + "Exit",
15610 type + "Exit-" + key
15611 ];
15612 } else if (key) {
15613 return [
15614 type,
15615 type + "-" + key,
15616 type + "Exit",
15617 type + "Exit-" + key
15618 ];
15619 } else if (node2.append) {
15620 return [
15621 type,
15622 CHILDREN,
15623 type + "Exit"
15624 ];
15625 } else {
15626 return [
15627 type,
15628 type + "Exit"
15629 ];
15630 }
15631 }
15632 function toStack(node2) {
15633 var events;
15634 if (node2.type === "document") {
15635 events = [
15636 "Document",
15637 CHILDREN,
15638 "DocumentExit"
15639 ];
15640 } else if (node2.type === "root") {
15641 events = [
15642 "Root",
15643 CHILDREN,
15644 "RootExit"
15645 ];
15646 } else {
15647 events = getEvents(node2);
15648 }
15649 return {
15650 eventIndex: 0,
15651 events: events,
15652 iterator: 0,
15653 node: node2,
15654 visitorIndex: 0,
15655 visitors: []
15656 };
15657 }
15658 function cleanMarks(node2) {
15659 node2[isClean] = false;
15660 if (node2.nodes) node2.nodes.forEach(function(i2) {
15661 return cleanMarks(i2);
15662 });
15663 return node2;
15664 }
15665 var postcss$2 = {};
15666 var LazyResult$2 = /*#__PURE__*/ function() {
15667 function LazyResult2(processor2, css, opts) {
15668 var _this = this;
15669 this.stringified = false;
15670 this.processed = false;
15671 var root2;
15672 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) {
15673 root2 = cleanMarks(css);
15674 } else if (_instanceof(css, LazyResult2) || _instanceof(css, Result$2)) {
15675 root2 = cleanMarks(css.root);
15676 if (css.map) {
15677 if (typeof opts.map === "undefined") opts.map = {};
15678 if (!opts.map.inline) opts.map.inline = false;
15679 opts.map.prev = css.map;
15680 }
15681 } else {
15682 var parser2 = parse$2;
15683 if (opts.syntax) parser2 = opts.syntax.parse;
15684 if (opts.parser) parser2 = opts.parser;
15685 if (parser2.parse) parser2 = parser2.parse;
15686 try {
15687 root2 = parser2(css, opts);
15688 } catch (error) {
15689 this.processed = true;
15690 this.error = error;
15691 }
15692 if (root2 && !root2[my]) {
15693 Container$1.rebuild(root2);
15694 }
15695 }
15696 this.result = new Result$2(processor2, root2, opts);
15697 this.helpers = _extends({}, postcss$2, {
15698 postcss: postcss$2,
15699 result: this.result
15700 });
15701 this.plugins = this.processor.plugins.map(function(plugin22) {
15702 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) {
15703 return _extends({}, plugin22, plugin22.prepare(_this.result));
15704 } else {
15705 return plugin22;
15706 }
15707 });
15708 }
15709 var _proto = LazyResult2.prototype;
15710 _proto.async = function async() {
15711 if (this.error) return Promise.reject(this.error);
15712 if (this.processed) return Promise.resolve(this.result);
15713 if (!this.processing) {
15714 this.processing = this.runAsync();
15715 }
15716 return this.processing;
15717 };
15718 _proto.catch = function _catch(onRejected) {
15719 return this.async().catch(onRejected);
15720 };
15721 _proto.finally = function _finally(onFinally) {
15722 return this.async().then(onFinally, onFinally);
15723 };
15724 _proto.getAsyncError = function getAsyncError() {
15725 throw new Error("Use process(css).then(cb) to work with async plugins");
15726 };
15727 _proto.handleError = function handleError(error, node2) {
15728 var plugin22 = this.result.lastPlugin;
15729 try {
15730 if (node2) node2.addToError(error);
15731 this.error = error;
15732 if (error.name === "CssSyntaxError" && !error.plugin) {
15733 error.plugin = plugin22.postcssPlugin;
15734 error.setMessage();
15735 } else if (plugin22.postcssVersion) {
15736 if (true) {
15737 var pluginName = plugin22.postcssPlugin;
15738 var pluginVer = plugin22.postcssVersion;
15739 var runtimeVer = this.result.processor.version;
15740 var a2 = pluginVer.split(".");
15741 var b = runtimeVer.split(".");
15742 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) {
15743 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.");
15744 }
15745 }
15746 }
15747 } catch (err) {
15748 if (console && console.error) console.error(err);
15749 }
15750 return error;
15751 };
15752 _proto.prepareVisitors = function prepareVisitors() {
15753 var _this = this;
15754 this.listeners = {};
15755 var add = function(plugin22, type, cb) {
15756 if (!_this.listeners[type]) _this.listeners[type] = [];
15757 _this.listeners[type].push([
15758 plugin22,
15759 cb
15760 ]);
15761 };
15762 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
15763 var plugin22 = _step.value;
15764 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") {
15765 for(var event in plugin22){
15766 if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
15767 throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
15768 }
15769 if (!NOT_VISITORS[event]) {
15770 if (_type_of(plugin22[event]) === "object") {
15771 for(var filter in plugin22[event]){
15772 if (filter === "*") {
15773 add(plugin22, event, plugin22[event][filter]);
15774 } else {
15775 add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
15776 }
15777 }
15778 } else if (typeof plugin22[event] === "function") {
15779 add(plugin22, event, plugin22[event]);
15780 }
15781 }
15782 }
15783 }
15784 }
15785 this.hasListener = Object.keys(this.listeners).length > 0;
15786 };
15787 _proto.runAsync = function runAsync() {
15788 var _this = this;
15789 return _async_to_generator(function() {
15790 var i2, plugin22, promise, error, root2, stack, promise1, e2, node2, _loop, _iterator, _step;
15791 return _ts_generator(this, function(_state) {
15792 switch(_state.label){
15793 case 0:
15794 _this.plugin = 0;
15795 i2 = 0;
15796 _state.label = 1;
15797 case 1:
15798 if (!(i2 < _this.plugins.length)) return [
15799 3,
15800 6
15801 ];
15802 plugin22 = _this.plugins[i2];
15803 promise = _this.runOnRoot(plugin22);
15804 if (!isPromise(promise)) return [
15805 3,
15806 5
15807 ];
15808 _state.label = 2;
15809 case 2:
15810 _state.trys.push([
15811 2,
15812 4,
15813 ,
15814 5
15815 ]);
15816 return [
15817 4,
15818 promise
15819 ];
15820 case 3:
15821 _state.sent();
15822 return [
15823 3,
15824 5
15825 ];
15826 case 4:
15827 error = _state.sent();
15828 throw _this.handleError(error);
15829 case 5:
15830 i2++;
15831 return [
15832 3,
15833 1
15834 ];
15835 case 6:
15836 _this.prepareVisitors();
15837 if (!_this.hasListener) return [
15838 3,
15839 18
15840 ];
15841 root2 = _this.result.root;
15842 _state.label = 7;
15843 case 7:
15844 if (!!root2[isClean]) return [
15845 3,
15846 14
15847 ];
15848 root2[isClean] = true;
15849 stack = [
15850 toStack(root2)
15851 ];
15852 _state.label = 8;
15853 case 8:
15854 if (!(stack.length > 0)) return [
15855 3,
15856 13
15857 ];
15858 promise1 = _this.visitTick(stack);
15859 if (!isPromise(promise1)) return [
15860 3,
15861 12
15862 ];
15863 _state.label = 9;
15864 case 9:
15865 _state.trys.push([
15866 9,
15867 11,
15868 ,
15869 12
15870 ]);
15871 return [
15872 4,
15873 promise1
15874 ];
15875 case 10:
15876 _state.sent();
15877 return [
15878 3,
15879 12
15880 ];
15881 case 11:
15882 e2 = _state.sent();
15883 node2 = stack[stack.length - 1].node;
15884 throw _this.handleError(e2, node2);
15885 case 12:
15886 return [
15887 3,
15888 8
15889 ];
15890 case 13:
15891 return [
15892 3,
15893 7
15894 ];
15895 case 14:
15896 if (!_this.listeners.OnceExit) return [
15897 3,
15898 18
15899 ];
15900 _loop = function() {
15901 var _step_value, plugin22, visitor, roots, e2;
15902 return _ts_generator(this, function(_state) {
15903 switch(_state.label){
15904 case 0:
15905 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
15906 _this.result.lastPlugin = plugin22;
15907 _state.label = 1;
15908 case 1:
15909 _state.trys.push([
15910 1,
15911 6,
15912 ,
15913 7
15914 ]);
15915 if (!(root2.type === "document")) return [
15916 3,
15917 3
15918 ];
15919 roots = root2.nodes.map(function(subRoot) {
15920 return visitor(subRoot, _this.helpers);
15921 });
15922 return [
15923 4,
15924 Promise.all(roots)
15925 ];
15926 case 2:
15927 _state.sent();
15928 return [
15929 3,
15930 5
15931 ];
15932 case 3:
15933 return [
15934 4,
15935 visitor(root2, _this.helpers)
15936 ];
15937 case 4:
15938 _state.sent();
15939 _state.label = 5;
15940 case 5:
15941 return [
15942 3,
15943 7
15944 ];
15945 case 6:
15946 e2 = _state.sent();
15947 throw _this.handleError(e2);
15948 case 7:
15949 return [
15950 2
15951 ];
15952 }
15953 });
15954 };
15955 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
15956 _state.label = 15;
15957 case 15:
15958 if (!!(_step = _iterator()).done) return [
15959 3,
15960 18
15961 ];
15962 return [
15963 5,
15964 _ts_values(_loop())
15965 ];
15966 case 16:
15967 _state.sent();
15968 _state.label = 17;
15969 case 17:
15970 return [
15971 3,
15972 15
15973 ];
15974 case 18:
15975 _this.processed = true;
15976 return [
15977 2,
15978 _this.stringify()
15979 ];
15980 }
15981 });
15982 })();
15983 };
15984 _proto.runOnRoot = function runOnRoot(plugin22) {
15985 var _this = this;
15986 this.result.lastPlugin = plugin22;
15987 try {
15988 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
15989 if (this.result.root.type === "document") {
15990 var roots = this.result.root.nodes.map(function(root2) {
15991 return plugin22.Once(root2, _this.helpers);
15992 });
15993 if (isPromise(roots[0])) {
15994 return Promise.all(roots);
15995 }
15996 return roots;
15997 }
15998 return plugin22.Once(this.result.root, this.helpers);
15999 } else if (typeof plugin22 === "function") {
16000 return plugin22(this.result.root, this.result);
16001 }
16002 } catch (error) {
16003 throw this.handleError(error);
16004 }
16005 };
16006 _proto.stringify = function stringify() {
16007 if (this.error) throw this.error;
16008 if (this.stringified) return this.result;
16009 this.stringified = true;
16010 this.sync();
16011 var opts = this.result.opts;
16012 var str = stringify$2;
16013 if (opts.syntax) str = opts.syntax.stringify;
16014 if (opts.stringifier) str = opts.stringifier;
16015 if (str.stringify) str = str.stringify;
16016 var map = new MapGenerator$1(str, this.result.root, this.result.opts);
16017 var data = map.generate();
16018 this.result.css = data[0];
16019 this.result.map = data[1];
16020 return this.result;
16021 };
16022 _proto.sync = function sync() {
16023 if (this.error) throw this.error;
16024 if (this.processed) return this.result;
16025 this.processed = true;
16026 if (this.processing) {
16027 throw this.getAsyncError();
16028 }
16029 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
16030 var plugin22 = _step.value;
16031 var promise = this.runOnRoot(plugin22);
16032 if (isPromise(promise)) {
16033 throw this.getAsyncError();
16034 }
16035 }
16036 this.prepareVisitors();
16037 if (this.hasListener) {
16038 var root2 = this.result.root;
16039 while(!root2[isClean]){
16040 root2[isClean] = true;
16041 this.walkSync(root2);
16042 }
16043 if (this.listeners.OnceExit) {
16044 if (root2.type === "document") {
16045 for(var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;){
16046 var subRoot = _step1.value;
16047 this.visitSync(this.listeners.OnceExit, subRoot);
16048 }
16049 } else {
16050 this.visitSync(this.listeners.OnceExit, root2);
16051 }
16052 }
16053 }
16054 return this.result;
16055 };
16056 _proto.then = function then(onFulfilled, onRejected) {
16057 if (true) {
16058 if (!("from" in this.opts)) {
16059 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.");
16060 }
16061 }
16062 return this.async().then(onFulfilled, onRejected);
16063 };
16064 _proto.toString = function toString() {
16065 return this.css;
16066 };
16067 _proto.visitSync = function visitSync(visitors, node2) {
16068 for(var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;){
16069 var _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
16070 this.result.lastPlugin = plugin22;
16071 var promise = void 0;
16072 try {
16073 promise = visitor(node2, this.helpers);
16074 } catch (e2) {
16075 throw this.handleError(e2, node2.proxyOf);
16076 }
16077 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
16078 return true;
16079 }
16080 if (isPromise(promise)) {
16081 throw this.getAsyncError();
16082 }
16083 }
16084 };
16085 _proto.visitTick = function visitTick(stack) {
16086 var visit2 = stack[stack.length - 1];
16087 var node2 = visit2.node, visitors = visit2.visitors;
16088 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
16089 stack.pop();
16090 return;
16091 }
16092 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
16093 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex], plugin22 = _visitors_visit2_visitorIndex[0], visitor = _visitors_visit2_visitorIndex[1];
16094 visit2.visitorIndex += 1;
16095 if (visit2.visitorIndex === visitors.length) {
16096 visit2.visitors = [];
16097 visit2.visitorIndex = 0;
16098 }
16099 this.result.lastPlugin = plugin22;
16100 try {
16101 return visitor(node2.toProxy(), this.helpers);
16102 } catch (e2) {
16103 throw this.handleError(e2, node2);
16104 }
16105 }
16106 if (visit2.iterator !== 0) {
16107 var iterator = visit2.iterator;
16108 var child;
16109 while(child = node2.nodes[node2.indexes[iterator]]){
16110 node2.indexes[iterator] += 1;
16111 if (!child[isClean]) {
16112 child[isClean] = true;
16113 stack.push(toStack(child));
16114 return;
16115 }
16116 }
16117 visit2.iterator = 0;
16118 delete node2.indexes[iterator];
16119 }
16120 var events = visit2.events;
16121 while(visit2.eventIndex < events.length){
16122 var event = events[visit2.eventIndex];
16123 visit2.eventIndex += 1;
16124 if (event === CHILDREN) {
16125 if (node2.nodes && node2.nodes.length) {
16126 node2[isClean] = true;
16127 visit2.iterator = node2.getIterator();
16128 }
16129 return;
16130 } else if (this.listeners[event]) {
16131 visit2.visitors = this.listeners[event];
16132 return;
16133 }
16134 }
16135 stack.pop();
16136 };
16137 _proto.walkSync = function walkSync(node2) {
16138 var _this = this;
16139 node2[isClean] = true;
16140 var events = getEvents(node2);
16141 for(var _iterator = _create_for_of_iterator_helper_loose(events), _step; !(_step = _iterator()).done;){
16142 var event = _step.value;
16143 if (event === CHILDREN) {
16144 if (node2.nodes) {
16145 node2.each(function(child) {
16146 if (!child[isClean]) _this.walkSync(child);
16147 });
16148 }
16149 } else {
16150 var visitors = this.listeners[event];
16151 if (visitors) {
16152 if (this.visitSync(visitors, node2.toProxy())) return;
16153 }
16154 }
16155 }
16156 };
16157 _proto.warnings = function warnings() {
16158 return this.sync().warnings();
16159 };
16160 _create_class(LazyResult2, [
16161 {
16162 key: "content",
16163 get: function get() {
16164 return this.stringify().content;
16165 }
16166 },
16167 {
16168 key: "css",
16169 get: function get() {
16170 return this.stringify().css;
16171 }
16172 },
16173 {
16174 key: "map",
16175 get: function get() {
16176 return this.stringify().map;
16177 }
16178 },
16179 {
16180 key: "messages",
16181 get: function get() {
16182 return this.sync().messages;
16183 }
16184 },
16185 {
16186 key: "opts",
16187 get: function get() {
16188 return this.result.opts;
16189 }
16190 },
16191 {
16192 key: "processor",
16193 get: function get() {
16194 return this.result.processor;
16195 }
16196 },
16197 {
16198 key: "root",
16199 get: function get() {
16200 return this.sync().root;
16201 }
16202 },
16203 {
16204 key: Symbol.toStringTag,
16205 get: function get() {
16206 return "LazyResult";
16207 }
16208 }
16209 ]);
16210 return LazyResult2;
16211 }();
16212 LazyResult$2.registerPostcss = function(dependant) {
16213 postcss$2 = dependant;
16214 };
16215 var lazyResult = LazyResult$2;
16216 LazyResult$2.default = LazyResult$2;
16217 Root$3.registerLazyResult(LazyResult$2);
16218 Document$2.registerLazyResult(LazyResult$2);
16219 var MapGenerator22 = mapGenerator;
16220 var stringify$1 = stringify_1;
16221 var warnOnce22 = warnOnce$2;
16222 var parse$1 = parse_1;
16223 var Result$1 = result;
16224 var NoWorkResult$1 = /*#__PURE__*/ function() {
16225 function NoWorkResult2(processor2, css, opts) {
16226 css = css.toString();
16227 this.stringified = false;
16228 this._processor = processor2;
16229 this._css = css;
16230 this._opts = opts;
16231 this._map = void 0;
16232 var root2;
16233 var str = stringify$1;
16234 this.result = new Result$1(this._processor, root2, this._opts);
16235 this.result.css = css;
16236 var self = this;
16237 Object.defineProperty(this.result, "root", {
16238 get: function get() {
16239 return self.root;
16240 }
16241 });
16242 var map = new MapGenerator22(str, root2, this._opts, css);
16243 if (map.isMap()) {
16244 var _map_generate = map.generate(), generatedCSS = _map_generate[0], generatedMap = _map_generate[1];
16245 if (generatedCSS) {
16246 this.result.css = generatedCSS;
16247 }
16248 if (generatedMap) {
16249 this.result.map = generatedMap;
16250 }
16251 } else {
16252 map.clearAnnotation();
16253 this.result.css = map.css;
16254 }
16255 }
16256 var _proto = NoWorkResult2.prototype;
16257 _proto.async = function async() {
16258 if (this.error) return Promise.reject(this.error);
16259 return Promise.resolve(this.result);
16260 };
16261 _proto.catch = function _catch(onRejected) {
16262 return this.async().catch(onRejected);
16263 };
16264 _proto.finally = function _finally(onFinally) {
16265 return this.async().then(onFinally, onFinally);
16266 };
16267 _proto.sync = function sync() {
16268 if (this.error) throw this.error;
16269 return this.result;
16270 };
16271 _proto.then = function then(onFulfilled, onRejected) {
16272 if (true) {
16273 if (!("from" in this._opts)) {
16274 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.");
16275 }
16276 }
16277 return this.async().then(onFulfilled, onRejected);
16278 };
16279 _proto.toString = function toString() {
16280 return this._css;
16281 };
16282 _proto.warnings = function warnings() {
16283 return [];
16284 };
16285 _create_class(NoWorkResult2, [
16286 {
16287 key: "content",
16288 get: function get() {
16289 return this.result.css;
16290 }
16291 },
16292 {
16293 key: "css",
16294 get: function get() {
16295 return this.result.css;
16296 }
16297 },
16298 {
16299 key: "map",
16300 get: function get() {
16301 return this.result.map;
16302 }
16303 },
16304 {
16305 key: "messages",
16306 get: function get() {
16307 return [];
16308 }
16309 },
16310 {
16311 key: "opts",
16312 get: function get() {
16313 return this.result.opts;
16314 }
16315 },
16316 {
16317 key: "processor",
16318 get: function get() {
16319 return this.result.processor;
16320 }
16321 },
16322 {
16323 key: "root",
16324 get: function get() {
16325 if (this._root) {
16326 return this._root;
16327 }
16328 var root2;
16329 var parser2 = parse$1;
16330 try {
16331 root2 = parser2(this._css, this._opts);
16332 } catch (error) {
16333 this.error = error;
16334 }
16335 if (this.error) {
16336 throw this.error;
16337 } else {
16338 this._root = root2;
16339 return root2;
16340 }
16341 }
16342 },
16343 {
16344 key: Symbol.toStringTag,
16345 get: function get() {
16346 return "NoWorkResult";
16347 }
16348 }
16349 ]);
16350 return NoWorkResult2;
16351 }();
16352 var noWorkResult = NoWorkResult$1;
16353 NoWorkResult$1.default = NoWorkResult$1;
16354 var NoWorkResult22 = noWorkResult;
16355 var LazyResult$1 = lazyResult;
16356 var Document$1 = document$1$2;
16357 var Root$2 = root;
16358 var Processor$1 = /*#__PURE__*/ function() {
16359 function Processor2(plugins) {
16360 if (plugins === void 0) plugins = [];
16361 this.version = "8.4.38";
16362 this.plugins = this.normalize(plugins);
16363 }
16364 var _proto = Processor2.prototype;
16365 _proto.normalize = function normalize(plugins) {
16366 var normalized = [];
16367 for(var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;){
16368 var i2 = _step.value;
16369 if (i2.postcss === true) {
16370 i2 = i2();
16371 } else if (i2.postcss) {
16372 i2 = i2.postcss;
16373 }
16374 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) {
16375 normalized = normalized.concat(i2.plugins);
16376 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) {
16377 normalized.push(i2);
16378 } else if (typeof i2 === "function") {
16379 normalized.push(i2);
16380 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) {
16381 if (true) {
16382 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.");
16383 }
16384 } else {
16385 throw new Error(i2 + " is not a PostCSS plugin");
16386 }
16387 }
16388 return normalized;
16389 };
16390 _proto.process = function process1(css, opts) {
16391 if (opts === void 0) opts = {};
16392 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
16393 return new NoWorkResult22(this, css, opts);
16394 } else {
16395 return new LazyResult$1(this, css, opts);
16396 }
16397 };
16398 _proto.use = function use(plugin22) {
16399 this.plugins = this.plugins.concat(this.normalize([
16400 plugin22
16401 ]));
16402 return this;
16403 };
16404 return Processor2;
16405 }();
16406 var processor = Processor$1;
16407 Processor$1.default = Processor$1;
16408 Root$2.registerProcessor(Processor$1);
16409 Document$1.registerProcessor(Processor$1);
16410 var Declaration$1 = declaration;
16411 var PreviousMap22 = previousMap;
16412 var Comment$1 = comment;
16413 var AtRule$1 = atRule;
16414 var Input$1 = input;
16415 var Root$1 = root;
16416 var Rule$1 = rule;
16417 function fromJSON$1(json, inputs) {
16418 if (Array.isArray(json)) return json.map(function(n2) {
16419 return fromJSON$1(n2);
16420 });
16421 var ownInputs = json.inputs, defaults = _object_without_properties_loose(json, [
16422 "inputs"
16423 ]);
16424 if (ownInputs) {
16425 inputs = [];
16426 for(var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;){
16427 var input2 = _step.value;
16428 var inputHydrated = _extends({}, input2, {
16429 __proto__: Input$1.prototype
16430 });
16431 if (inputHydrated.map) {
16432 inputHydrated.map = _extends({}, inputHydrated.map, {
16433 __proto__: PreviousMap22.prototype
16434 });
16435 }
16436 inputs.push(inputHydrated);
16437 }
16438 }
16439 if (defaults.nodes) {
16440 defaults.nodes = json.nodes.map(function(n2) {
16441 return fromJSON$1(n2, inputs);
16442 });
16443 }
16444 if (defaults.source) {
16445 var _defaults_source = defaults.source, inputId = _defaults_source.inputId, source = _object_without_properties_loose(_defaults_source, [
16446 "inputId"
16447 ]);
16448 defaults.source = source;
16449 if (inputId != null) {
16450 defaults.source.input = inputs[inputId];
16451 }
16452 }
16453 if (defaults.type === "root") {
16454 return new Root$1(defaults);
16455 } else if (defaults.type === "decl") {
16456 return new Declaration$1(defaults);
16457 } else if (defaults.type === "rule") {
16458 return new Rule$1(defaults);
16459 } else if (defaults.type === "comment") {
16460 return new Comment$1(defaults);
16461 } else if (defaults.type === "atrule") {
16462 return new AtRule$1(defaults);
16463 } else {
16464 throw new Error("Unknown node type: " + json.type);
16465 }
16466 }
16467 var fromJSON_1 = fromJSON$1;
16468 fromJSON$1.default = fromJSON$1;
16469 var CssSyntaxError22 = cssSyntaxError;
16470 var Declaration22 = declaration;
16471 var LazyResult22 = lazyResult;
16472 var Container22 = container;
16473 var Processor22 = processor;
16474 var stringify = stringify_1;
16475 var fromJSON = fromJSON_1;
16476 var Document222 = document$1$2;
16477 var Warning22 = warning;
16478 var Comment22 = comment;
16479 var AtRule22 = atRule;
16480 var Result22 = result;
16481 var Input22 = input;
16482 var parse = parse_1;
16483 var list = list_1;
16484 var Rule22 = rule;
16485 var Root22 = root;
16486 var Node22 = node;
16487 function postcss() {
16488 for(var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++){
16489 plugins[_key] = arguments[_key];
16490 }
16491 if (plugins.length === 1 && Array.isArray(plugins[0])) {
16492 plugins = plugins[0];
16493 }
16494 return new Processor22(plugins);
16495 }
16496 postcss.plugin = function plugin2(name, initializer) {
16497 var warningPrinted = false;
16498 function creator() {
16499 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
16500 args[_key] = arguments[_key];
16501 }
16502 if (console && console.warn && !warningPrinted) {
16503 warningPrinted = true;
16504 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
16505 if (process.env.LANG && process.env.LANG.startsWith("cn")) {
16506 console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
16507 }
16508 }
16509 var transformer = initializer.apply(void 0, [].concat(args));
16510 transformer.postcssPlugin = name;
16511 transformer.postcssVersion = new Processor22().version;
16512 return transformer;
16513 }
16514 var cache;
16515 Object.defineProperty(creator, "postcss", {
16516 get: function get() {
16517 if (!cache) cache = creator();
16518 return cache;
16519 }
16520 });
16521 creator.process = function(css, processOpts, pluginOpts) {
16522 return postcss([
16523 creator(pluginOpts)
16524 ]).process(css, processOpts);
16525 };
16526 return creator;
16527 };
16528 postcss.stringify = stringify;
16529 postcss.parse = parse;
16530 postcss.fromJSON = fromJSON;
16531 postcss.list = list;
16532 postcss.comment = function(defaults) {
16533 return new Comment22(defaults);
16534 };
16535 postcss.atRule = function(defaults) {
16536 return new AtRule22(defaults);
16537 };
16538 postcss.decl = function(defaults) {
16539 return new Declaration22(defaults);
16540 };
16541 postcss.rule = function(defaults) {
16542 return new Rule22(defaults);
16543 };
16544 postcss.root = function(defaults) {
16545 return new Root22(defaults);
16546 };
16547 postcss.document = function(defaults) {
16548 return new Document222(defaults);
16549 };
16550 postcss.CssSyntaxError = CssSyntaxError22;
16551 postcss.Declaration = Declaration22;
16552 postcss.Container = Container22;
16553 postcss.Processor = Processor22;
16554 postcss.Document = Document222;
16555 postcss.Comment = Comment22;
16556 postcss.Warning = Warning22;
16557 postcss.AtRule = AtRule22;
16558 postcss.Result = Result22;
16559 postcss.Input = Input22;
16560 postcss.Rule = Rule22;
16561 postcss.Root = Root22;
16562 postcss.Node = Node22;
16563 LazyResult22.registerPostcss(postcss);
16564 var postcss_1 = postcss;
16565 postcss.default = postcss;
16566 var postcss$1 = /* @__PURE__ */ getDefaultExportFromCjs(postcss_1);
16567 postcss$1.stringify;
16568 postcss$1.fromJSON;
16569 postcss$1.plugin;
16570 postcss$1.parse;
16571 postcss$1.list;
16572 postcss$1.document;
16573 postcss$1.comment;
16574 postcss$1.atRule;
16575 postcss$1.rule;
16576 postcss$1.decl;
16577 postcss$1.root;
16578 postcss$1.CssSyntaxError;
16579 postcss$1.Declaration;
16580 postcss$1.Container;
16581 postcss$1.Processor;
16582 postcss$1.Document;
16583 postcss$1.Comment;
16584 postcss$1.Warning;
16585 postcss$1.AtRule;
16586 postcss$1.Result;
16587 postcss$1.Input;
16588 postcss$1.Rule;
16589 postcss$1.Root;
16590 postcss$1.Node;
16591 var BaseRRNode = /*#__PURE__*/ function() {
16592 function BaseRRNode() {
16593 for(var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++){
16594 _args[_key] = arguments[_key];
16595 }
16596 __publicField2(this, "parentElement", null);
16597 __publicField2(this, "parentNode", null);
16598 __publicField2(this, "ownerDocument");
16599 __publicField2(this, "firstChild", null);
16600 __publicField2(this, "lastChild", null);
16601 __publicField2(this, "previousSibling", null);
16602 __publicField2(this, "nextSibling", null);
16603 __publicField2(this, "ELEMENT_NODE", 1);
16604 __publicField2(this, "TEXT_NODE", 3);
16605 __publicField2(this, "nodeType");
16606 __publicField2(this, "nodeName");
16607 __publicField2(this, "RRNodeType");
16608 }
16609 var _proto = BaseRRNode.prototype;
16610 _proto.contains = function contains(node2) {
16611 if (!_instanceof(node2, BaseRRNode)) return false;
16612 else if (node2.ownerDocument !== this.ownerDocument) return false;
16613 else if (node2 === this) return true;
16614 while(node2.parentNode){
16615 if (node2.parentNode === this) return true;
16616 node2 = node2.parentNode;
16617 }
16618 return false;
16619 };
16620 // eslint-disable-next-line @typescript-eslint/no-unused-vars
16621 _proto.appendChild = function appendChild(_newChild) {
16622 throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.");
16623 };
16624 // eslint-disable-next-line @typescript-eslint/no-unused-vars
16625 _proto.insertBefore = function insertBefore(_newChild, _refChild) {
16626 throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.");
16627 };
16628 // eslint-disable-next-line @typescript-eslint/no-unused-vars
16629 _proto.removeChild = function removeChild(_node) {
16630 throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.");
16631 };
16632 _proto.toString = function toString() {
16633 return "RRNode";
16634 };
16635 _create_class(BaseRRNode, [
16636 {
16637 key: "childNodes",
16638 get: function get() {
16639 var childNodes2 = [];
16640 var childIterator = this.firstChild;
16641 while(childIterator){
16642 childNodes2.push(childIterator);
16643 childIterator = childIterator.nextSibling;
16644 }
16645 return childNodes2;
16646 }
16647 }
16648 ]);
16649 return BaseRRNode;
16650 }();
16651 var testableAccessors = {
16652 Node: [
16653 "childNodes",
16654 "parentNode",
16655 "parentElement",
16656 "textContent"
16657 ],
16658 ShadowRoot: [
16659 "host",
16660 "styleSheets"
16661 ],
16662 Element: [
16663 "shadowRoot",
16664 "querySelector",
16665 "querySelectorAll"
16666 ],
16667 MutationObserver: []
16668 };
16669 var testableMethods = {
16670 Node: [
16671 "contains",
16672 "getRootNode"
16673 ],
16674 ShadowRoot: [
16675 "getSelection"
16676 ],
16677 Element: [],
16678 MutationObserver: [
16679 "constructor"
16680 ]
16681 };
16682 var untaintedBasePrototype = {};
16683 var isAngularZonePresent = function() {
16684 return !!globalThis.Zone;
16685 };
16686 function getUntaintedPrototype(key) {
16687 if (untaintedBasePrototype[key]) return untaintedBasePrototype[key];
16688 var defaultObj = globalThis[key];
16689 var defaultPrototype = defaultObj.prototype;
16690 var accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;
16691 var isUntaintedAccessors = Boolean(accessorNames && // @ts-expect-error 2345
16692 accessorNames.every(function(accessor) {
16693 var _a2, _b;
16694 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
16695 }));
16696 var methodNames = key in testableMethods ? testableMethods[key] : void 0;
16697 var isUntaintedMethods = Boolean(methodNames && methodNames.every(// @ts-expect-error 2345
16698 function(method) {
16699 var _a2;
16700 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
16701 }));
16702 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent()) {
16703 untaintedBasePrototype[key] = defaultObj.prototype;
16704 return defaultObj.prototype;
16705 }
16706 try {
16707 var iframeEl = document.createElement("iframe");
16708 document.body.appendChild(iframeEl);
16709 var win = iframeEl.contentWindow;
16710 if (!win) return defaultObj.prototype;
16711 var untaintedObject = win[key].prototype;
16712 document.body.removeChild(iframeEl);
16713 if (!untaintedObject) return defaultPrototype;
16714 return untaintedBasePrototype[key] = untaintedObject;
16715 } catch (e) {
16716 return defaultPrototype;
16717 }
16718 }
16719 var untaintedAccessorCache = {};
16720 function getUntaintedAccessor(key, instance, accessor) {
16721 var _a2;
16722 var cacheKey = key + "." + String(accessor);
16723 if (untaintedAccessorCache[cacheKey]) return untaintedAccessorCache[cacheKey].call(instance);
16724 var untaintedPrototype = getUntaintedPrototype(key);
16725 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
16726 if (!untaintedAccessor) return instance[accessor];
16727 untaintedAccessorCache[cacheKey] = untaintedAccessor;
16728 return untaintedAccessor.call(instance);
16729 }
16730 var untaintedMethodCache = {};
16731 function getUntaintedMethod(key, instance, method) {
16732 var cacheKey = key + "." + String(method);
16733 if (untaintedMethodCache[cacheKey]) return untaintedMethodCache[cacheKey].bind(instance);
16734 var untaintedPrototype = getUntaintedPrototype(key);
16735 var untaintedMethod = untaintedPrototype[method];
16736 if (typeof untaintedMethod !== "function") return instance[method];
16737 untaintedMethodCache[cacheKey] = untaintedMethod;
16738 return untaintedMethod.bind(instance);
16739 }
16740 function childNodes(n2) {
16741 return getUntaintedAccessor("Node", n2, "childNodes");
16742 }
16743 function parentNode(n2) {
16744 return getUntaintedAccessor("Node", n2, "parentNode");
16745 }
16746 function parentElement(n2) {
16747 return getUntaintedAccessor("Node", n2, "parentElement");
16748 }
16749 function textContent(n2) {
16750 return getUntaintedAccessor("Node", n2, "textContent");
16751 }
16752 function contains(n2, other) {
16753 return getUntaintedMethod("Node", n2, "contains")(other);
16754 }
16755 function getRootNode(n2) {
16756 return getUntaintedMethod("Node", n2, "getRootNode")();
16757 }
16758 function host(n2) {
16759 if (!n2 || !("host" in n2)) return null;
16760 return getUntaintedAccessor("ShadowRoot", n2, "host");
16761 }
16762 function styleSheets(n2) {
16763 return n2.styleSheets;
16764 }
16765 function shadowRoot(n2) {
16766 if (!n2 || !("shadowRoot" in n2)) return null;
16767 return getUntaintedAccessor("Element", n2, "shadowRoot");
16768 }
16769 function querySelector(n2, selectors) {
16770 return getUntaintedAccessor("Element", n2, "querySelector")(selectors);
16771 }
16772 function querySelectorAll(n2, selectors) {
16773 return getUntaintedAccessor("Element", n2, "querySelectorAll")(selectors);
16774 }
16775 function mutationObserverCtor() {
16776 return getUntaintedPrototype("MutationObserver").constructor;
16777 }
16778 function patch(source, name, replacement) {
16779 try {
16780 if (!(name in source)) {
16781 return function() {};
16782 }
16783 var original = source[name];
16784 var wrapped = replacement(original);
16785 if (typeof wrapped === "function") {
16786 wrapped.prototype = wrapped.prototype || {};
16787 Object.defineProperties(wrapped, {
16788 __rrweb_original__: {
16789 enumerable: false,
16790 value: original
16791 }
16792 });
16793 }
16794 source[name] = wrapped;
16795 return function() {
16796 source[name] = original;
16797 };
16798 } catch (e) {
16799 return function() {};
16800 }
16801 }
16802 var index = {
16803 childNodes: childNodes,
16804 parentNode: parentNode,
16805 parentElement: parentElement,
16806 textContent: textContent,
16807 contains: contains,
16808 getRootNode: getRootNode,
16809 host: host,
16810 styleSheets: styleSheets,
16811 shadowRoot: shadowRoot,
16812 querySelector: querySelector,
16813 querySelectorAll: querySelectorAll,
16814 mutationObserver: mutationObserverCtor,
16815 patch: patch
16816 };
16817 function on(type, fn, target) {
16818 if (target === void 0) target = document;
16819 var options = {
16820 capture: true,
16821 passive: true
16822 };
16823 target.addEventListener(type, fn, options);
16824 return function() {
16825 return target.removeEventListener(type, fn, options);
16826 };
16827 }
16828 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.";
16829 var _mirror = {
16830 map: {},
16831 getId: function getId() {
16832 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16833 return -1;
16834 },
16835 getNode: function getNode() {
16836 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16837 return null;
16838 },
16839 removeNodeFromMap: function removeNodeFromMap() {
16840 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16841 },
16842 has: function has() {
16843 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16844 return false;
16845 },
16846 reset: function reset() {
16847 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16848 }
16849 };
16850 if (typeof window !== "undefined" && window.Proxy && window.Reflect) {
16851 _mirror = new Proxy(_mirror, {
16852 get: function get(target, prop, receiver) {
16853 if (prop === "map") {
16854 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
16855 }
16856 return Reflect.get(target, prop, receiver);
16857 }
16858 });
16859 }
16860 function throttle(func, wait, options) {
16861 if (options === void 0) options = {};
16862 var timeout = null;
16863 var previous = 0;
16864 return function() {
16865 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
16866 args[_key] = arguments[_key];
16867 }
16868 var now = Date.now();
16869 if (!previous && options.leading === false) {
16870 previous = now;
16871 }
16872 var remaining = wait - (now - previous);
16873 var context = this;
16874 if (remaining <= 0 || remaining > wait) {
16875 if (timeout) {
16876 clearTimeout(timeout);
16877 timeout = null;
16878 }
16879 previous = now;
16880 func.apply(context, args);
16881 } else if (!timeout && options.trailing !== false) {
16882 timeout = setTimeout(function() {
16883 previous = options.leading === false ? 0 : Date.now();
16884 timeout = null;
16885 func.apply(context, args);
16886 }, remaining);
16887 }
16888 };
16889 }
16890 function hookSetter(target, key, d, isRevoked, win) {
16891 if (win === void 0) win = window;
16892 var original = win.Object.getOwnPropertyDescriptor(target, key);
16893 win.Object.defineProperty(target, key, isRevoked ? d : {
16894 set: function set(value) {
16895 var _this = this;
16896 setTimeout(function() {
16897 d.set.call(_this, value);
16898 }, 0);
16899 if (original && original.set) {
16900 original.set.call(this, value);
16901 }
16902 }
16903 });
16904 return function() {
16905 return hookSetter(target, key, original || {}, true);
16906 };
16907 }
16908 var nowTimestamp = Date.now;
16909 if (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {
16910 nowTimestamp = function() {
16911 return /* @__PURE__ */ new Date().getTime();
16912 };
16913 }
16914 function getWindowScroll(win) {
16915 var _a2, _b, _c, _d;
16916 var doc = win.document;
16917 return {
16918 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,
16919 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
16920 };
16921 }
16922 function getWindowHeight() {
16923 return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
16924 }
16925 function getWindowWidth() {
16926 return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
16927 }
16928 function closestElementOfNode(node2) {
16929 if (!node2) {
16930 return null;
16931 }
16932 var el = node2.nodeType === node2.ELEMENT_NODE ? node2 : index.parentElement(node2);
16933 return el;
16934 }
16935 function isBlocked(node2, blockClass, blockSelector, checkAncestors) {
16936 if (!node2) {
16937 return false;
16938 }
16939 var el = closestElementOfNode(node2);
16940 if (!el) {
16941 return false;
16942 }
16943 try {
16944 if (typeof blockClass === "string") {
16945 if (el.classList.contains(blockClass)) return true;
16946 if (checkAncestors && el.closest("." + blockClass) !== null) return true;
16947 } else {
16948 if (classMatchesRegex(el, blockClass, checkAncestors)) return true;
16949 }
16950 } catch (e2) {}
16951 if (blockSelector) {
16952 if (el.matches(blockSelector)) return true;
16953 if (checkAncestors && el.closest(blockSelector) !== null) return true;
16954 }
16955 return false;
16956 }
16957 function isSerialized(n2, mirror2) {
16958 return mirror2.getId(n2) !== -1;
16959 }
16960 function isIgnored(n2, mirror2, slimDOMOptions) {
16961 if (n2.tagName === "TITLE" && slimDOMOptions.headTitleMutations) {
16962 return true;
16963 }
16964 return mirror2.getId(n2) === IGNORED_NODE;
16965 }
16966 function isAncestorRemoved(target, mirror2) {
16967 if (isShadowRoot(target)) {
16968 return false;
16969 }
16970 var id = mirror2.getId(target);
16971 if (!mirror2.has(id)) {
16972 return true;
16973 }
16974 var parent = index.parentNode(target);
16975 if (parent && parent.nodeType === target.DOCUMENT_NODE) {
16976 return false;
16977 }
16978 if (!parent) {
16979 return true;
16980 }
16981 return isAncestorRemoved(parent, mirror2);
16982 }
16983 function legacy_isTouchEvent(event) {
16984 return Boolean(event.changedTouches);
16985 }
16986 function polyfill$1(win) {
16987 if (win === void 0) win = window;
16988 if ("NodeList" in win && !win.NodeList.prototype.forEach) {
16989 win.NodeList.prototype.forEach = Array.prototype.forEach;
16990 }
16991 if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) {
16992 win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
16993 }
16994 }
16995 function isSerializedIframe(n2, mirror2) {
16996 return Boolean(n2.nodeName === "IFRAME" && mirror2.getMeta(n2));
16997 }
16998 function isSerializedStylesheet(n2, mirror2) {
16999 return Boolean(n2.nodeName === "LINK" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute("rel") === "stylesheet" && mirror2.getMeta(n2));
17000 }
17001 function hasShadowRoot(n2) {
17002 if (!n2) return false;
17003 if (_instanceof(n2, BaseRRNode) && "shadowRoot" in n2) {
17004 return Boolean(n2.shadowRoot);
17005 }
17006 return Boolean(index.shadowRoot(n2));
17007 }
17008 var StyleSheetMirror = /*#__PURE__*/ function() {
17009 function StyleSheetMirror() {
17010 __publicField(this, "id", 1);
17011 __publicField(this, "styleIDMap", /* @__PURE__ */ new WeakMap());
17012 __publicField(this, "idStyleMap", /* @__PURE__ */ new Map());
17013 }
17014 var _proto = StyleSheetMirror.prototype;
17015 _proto.getId = function getId(stylesheet) {
17016 var _this_styleIDMap_get;
17017 return (_this_styleIDMap_get = this.styleIDMap.get(stylesheet)) != null ? _this_styleIDMap_get : -1;
17018 };
17019 _proto.has = function has(stylesheet) {
17020 return this.styleIDMap.has(stylesheet);
17021 };
17022 /**
17023 * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.
17024 */ _proto.add = function add(stylesheet, id) {
17025 if (this.has(stylesheet)) return this.getId(stylesheet);
17026 var newId;
17027 if (id === void 0) {
17028 newId = this.id++;
17029 } else newId = id;
17030 this.styleIDMap.set(stylesheet, newId);
17031 this.idStyleMap.set(newId, stylesheet);
17032 return newId;
17033 };
17034 _proto.getStyle = function getStyle(id) {
17035 return this.idStyleMap.get(id) || null;
17036 };
17037 _proto.reset = function reset() {
17038 this.styleIDMap = /* @__PURE__ */ new WeakMap();
17039 this.idStyleMap = /* @__PURE__ */ new Map();
17040 this.id = 1;
17041 };
17042 _proto.generateId = function generateId() {
17043 return this.id++;
17044 };
17045 return StyleSheetMirror;
17046 }();
17047 function getShadowHost(n2) {
17048 var _a2;
17049 var shadowHost = null;
17050 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));
17051 return shadowHost;
17052 }
17053 function getRootShadowHost(n2) {
17054 var rootShadowHost = n2;
17055 var shadowHost;
17056 while(shadowHost = getShadowHost(rootShadowHost))rootShadowHost = shadowHost;
17057 return rootShadowHost;
17058 }
17059 function shadowHostInDom(n2) {
17060 var doc = n2.ownerDocument;
17061 if (!doc) return false;
17062 var shadowHost = getRootShadowHost(n2);
17063 return index.contains(doc, shadowHost);
17064 }
17065 function inDom(n2) {
17066 var doc = n2.ownerDocument;
17067 if (!doc) return false;
17068 return index.contains(doc, n2) || shadowHostInDom(n2);
17069 }
17070 var EventType = /* @__PURE__ */ function(EventType2) {
17071 EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
17072 EventType2[EventType2["Load"] = 1] = "Load";
17073 EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
17074 EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
17075 EventType2[EventType2["Meta"] = 4] = "Meta";
17076 EventType2[EventType2["Custom"] = 5] = "Custom";
17077 EventType2[EventType2["Plugin"] = 6] = "Plugin";
17078 return EventType2;
17079 }(EventType || {});
17080 var IncrementalSource = /* @__PURE__ */ function(IncrementalSource2) {
17081 IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
17082 IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
17083 IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
17084 IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
17085 IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
17086 IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
17087 IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
17088 IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
17089 IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
17090 IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
17091 IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
17092 IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
17093 IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
17094 IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
17095 IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
17096 IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
17097 IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement";
17098 return IncrementalSource2;
17099 }(IncrementalSource || {});
17100 var MouseInteractions = /* @__PURE__ */ function(MouseInteractions2) {
17101 MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
17102 MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
17103 MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
17104 MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
17105 MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
17106 MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
17107 MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
17108 MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
17109 MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
17110 MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
17111 MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
17112 return MouseInteractions2;
17113 }(MouseInteractions || {});
17114 var PointerTypes = /* @__PURE__ */ function(PointerTypes2) {
17115 PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse";
17116 PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen";
17117 PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch";
17118 return PointerTypes2;
17119 }(PointerTypes || {});
17120 var CanvasContext = /* @__PURE__ */ function(CanvasContext2) {
17121 CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
17122 CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
17123 CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
17124 return CanvasContext2;
17125 }(CanvasContext || {});
17126 var MediaInteractions = /* @__PURE__ */ function(MediaInteractions2) {
17127 MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play";
17128 MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause";
17129 MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked";
17130 MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange";
17131 MediaInteractions2[MediaInteractions2["RateChange"] = 4] = "RateChange";
17132 return MediaInteractions2;
17133 }(MediaInteractions || {});
17134 var NodeType = /* @__PURE__ */ function(NodeType2) {
17135 NodeType2[NodeType2["Document"] = 0] = "Document";
17136 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
17137 NodeType2[NodeType2["Element"] = 2] = "Element";
17138 NodeType2[NodeType2["Text"] = 3] = "Text";
17139 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
17140 NodeType2[NodeType2["Comment"] = 5] = "Comment";
17141 return NodeType2;
17142 }(NodeType || {});
17143 function isNodeInLinkedList(n2) {
17144 return "__ln" in n2;
17145 }
17146 var DoubleLinkedList = /*#__PURE__*/ function() {
17147 function DoubleLinkedList() {
17148 __publicField(this, "length", 0);
17149 __publicField(this, "head", null);
17150 __publicField(this, "tail", null);
17151 }
17152 var _proto = DoubleLinkedList.prototype;
17153 _proto.get = function get(position) {
17154 if (position >= this.length) {
17155 throw new Error("Position outside of list range");
17156 }
17157 var current = this.head;
17158 for(var index2 = 0; index2 < position; index2++){
17159 current = (current == null ? void 0 : current.next) || null;
17160 }
17161 return current;
17162 };
17163 _proto.addNode = function addNode(n2) {
17164 var node2 = {
17165 value: n2,
17166 previous: null,
17167 next: null
17168 };
17169 n2.__ln = node2;
17170 if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {
17171 var current = n2.previousSibling.__ln.next;
17172 node2.next = current;
17173 node2.previous = n2.previousSibling.__ln;
17174 n2.previousSibling.__ln.next = node2;
17175 if (current) {
17176 current.previous = node2;
17177 }
17178 } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {
17179 var current1 = n2.nextSibling.__ln.previous;
17180 node2.previous = current1;
17181 node2.next = n2.nextSibling.__ln;
17182 n2.nextSibling.__ln.previous = node2;
17183 if (current1) {
17184 current1.next = node2;
17185 }
17186 } else {
17187 if (this.head) {
17188 this.head.previous = node2;
17189 }
17190 node2.next = this.head;
17191 this.head = node2;
17192 }
17193 if (node2.next === null) {
17194 this.tail = node2;
17195 }
17196 this.length++;
17197 };
17198 _proto.removeNode = function removeNode(n2) {
17199 var current = n2.__ln;
17200 if (!this.head) {
17201 return;
17202 }
17203 if (!current.previous) {
17204 this.head = current.next;
17205 if (this.head) {
17206 this.head.previous = null;
17207 } else {
17208 this.tail = null;
17209 }
17210 } else {
17211 current.previous.next = current.next;
17212 if (current.next) {
17213 current.next.previous = current.previous;
17214 } else {
17215 this.tail = current.previous;
17216 }
17217 }
17218 if (n2.__ln) {
17219 delete n2.__ln;
17220 }
17221 this.length--;
17222 };
17223 return DoubleLinkedList;
17224 }();
17225 var moveKey = function(id, parentId) {
17226 return id + "@" + parentId;
17227 };
17228 var MutationBuffer = /*#__PURE__*/ function() {
17229 function MutationBuffer() {
17230 var _this = this;
17231 __publicField(this, "frozen", false);
17232 __publicField(this, "locked", false);
17233 __publicField(this, "texts", []);
17234 __publicField(this, "attributes", []);
17235 __publicField(this, "attributeMap", /* @__PURE__ */ new WeakMap());
17236 __publicField(this, "removes", []);
17237 __publicField(this, "mapRemoves", []);
17238 __publicField(this, "movedMap", {});
17239 /**
17240 * the browser MutationObserver emits multiple mutations after
17241 * a delay for performance reasons, making tracing added nodes hard
17242 * in our `processMutations` callback function.
17243 * For example, if we append an element el_1 into body, and then append
17244 * another element el_2 into el_1, these two mutations may be passed to the
17245 * callback function together when the two operations were done.
17246 * Generally we need to trace child nodes of newly added nodes, but in this
17247 * case if we count el_2 as el_1's child node in the first mutation record,
17248 * then we will count el_2 again in the second mutation record which was
17249 * duplicated.
17250 * To avoid of duplicate counting added nodes, we use a Set to store
17251 * added nodes and its child nodes during iterate mutation records. Then
17252 * collect added nodes from the Set which have no duplicate copy. But
17253 * this also causes newly added nodes will not be serialized with id ASAP,
17254 * which means all the id related calculation should be lazy too.
17255 */ __publicField(this, "addedSet", /* @__PURE__ */ new Set());
17256 __publicField(this, "movedSet", /* @__PURE__ */ new Set());
17257 __publicField(this, "droppedSet", /* @__PURE__ */ new Set());
17258 __publicField(this, "removesSubTreeCache", /* @__PURE__ */ new Set());
17259 __publicField(this, "mutationCb");
17260 __publicField(this, "blockClass");
17261 __publicField(this, "blockSelector");
17262 __publicField(this, "maskTextClass");
17263 __publicField(this, "maskTextSelector");
17264 __publicField(this, "inlineStylesheet");
17265 __publicField(this, "maskInputOptions");
17266 __publicField(this, "maskTextFn");
17267 __publicField(this, "maskInputFn");
17268 __publicField(this, "keepIframeSrcFn");
17269 __publicField(this, "recordCanvas");
17270 __publicField(this, "inlineImages");
17271 __publicField(this, "slimDOMOptions");
17272 __publicField(this, "dataURLOptions");
17273 __publicField(this, "doc");
17274 __publicField(this, "mirror");
17275 __publicField(this, "iframeManager");
17276 __publicField(this, "stylesheetManager");
17277 __publicField(this, "shadowDomManager");
17278 __publicField(this, "canvasManager");
17279 __publicField(this, "processedNodeManager");
17280 __publicField(this, "unattachedDoc");
17281 __publicField(this, "processMutations", function(mutations) {
17282 mutations.forEach(_this.processMutation);
17283 _this.emit();
17284 });
17285 __publicField(this, "emit", function() {
17286 if (_this.frozen || _this.locked) {
17287 return;
17288 }
17289 var adds = [];
17290 var addedIds = /* @__PURE__ */ new Set();
17291 var addList = new DoubleLinkedList();
17292 var getNextId = function(n2) {
17293 var ns = n2;
17294 var nextId = IGNORED_NODE;
17295 while(nextId === IGNORED_NODE){
17296 ns = ns && ns.nextSibling;
17297 nextId = ns && _this.mirror.getId(ns);
17298 }
17299 return nextId;
17300 };
17301 var pushAdd = function(n2) {
17302 var parent = index.parentNode(n2);
17303 if (!parent || !inDom(n2)) {
17304 return;
17305 }
17306 var cssCaptured = false;
17307 if (n2.nodeType === Node.TEXT_NODE) {
17308 var parentTag = parent.tagName;
17309 if (parentTag === "TEXTAREA") {
17310 return;
17311 } else if (parentTag === "STYLE" && _this.addedSet.has(parent)) {
17312 cssCaptured = true;
17313 }
17314 }
17315 var parentId = isShadowRoot(parent) ? _this.mirror.getId(getShadowHost(n2)) : _this.mirror.getId(parent);
17316 var nextId = getNextId(n2);
17317 if (parentId === -1 || nextId === -1) {
17318 return addList.addNode(n2);
17319 }
17320 var sn = serializeNodeWithId(n2, {
17321 doc: _this.doc,
17322 mirror: _this.mirror,
17323 blockClass: _this.blockClass,
17324 blockSelector: _this.blockSelector,
17325 maskTextClass: _this.maskTextClass,
17326 maskTextSelector: _this.maskTextSelector,
17327 skipChild: true,
17328 newlyAddedElement: true,
17329 inlineStylesheet: _this.inlineStylesheet,
17330 maskInputOptions: _this.maskInputOptions,
17331 maskTextFn: _this.maskTextFn,
17332 maskInputFn: _this.maskInputFn,
17333 slimDOMOptions: _this.slimDOMOptions,
17334 dataURLOptions: _this.dataURLOptions,
17335 recordCanvas: _this.recordCanvas,
17336 inlineImages: _this.inlineImages,
17337 onSerialize: function(currentN) {
17338 if (isSerializedIframe(currentN, _this.mirror)) {
17339 _this.iframeManager.addIframe(currentN);
17340 }
17341 if (isSerializedStylesheet(currentN, _this.mirror)) {
17342 _this.stylesheetManager.trackLinkElement(currentN);
17343 }
17344 if (hasShadowRoot(n2)) {
17345 _this.shadowDomManager.addShadowRoot(index.shadowRoot(n2), _this.doc);
17346 }
17347 },
17348 onIframeLoad: function(iframe, childSn) {
17349 _this.iframeManager.attachIframe(iframe, childSn);
17350 _this.shadowDomManager.observeAttachShadow(iframe);
17351 },
17352 onStylesheetLoad: function(link, childSn) {
17353 _this.stylesheetManager.attachLinkElement(link, childSn);
17354 },
17355 cssCaptured: cssCaptured
17356 });
17357 if (sn) {
17358 adds.push({
17359 parentId: parentId,
17360 nextId: nextId,
17361 node: sn
17362 });
17363 addedIds.add(sn.id);
17364 }
17365 };
17366 while(_this.mapRemoves.length){
17367 _this.mirror.removeNodeFromMap(_this.mapRemoves.shift());
17368 }
17369 for(var _iterator = _create_for_of_iterator_helper_loose(_this.movedSet), _step; !(_step = _iterator()).done;){
17370 var n2 = _step.value;
17371 if (isParentRemoved(_this.removesSubTreeCache, n2, _this.mirror) && !_this.movedSet.has(index.parentNode(n2))) {
17372 continue;
17373 }
17374 pushAdd(n2);
17375 }
17376 for(var _iterator1 = _create_for_of_iterator_helper_loose(_this.addedSet), _step1; !(_step1 = _iterator1()).done;){
17377 var n21 = _step1.value;
17378 if (!isAncestorInSet(_this.droppedSet, n21) && !isParentRemoved(_this.removesSubTreeCache, n21, _this.mirror)) {
17379 pushAdd(n21);
17380 } else if (isAncestorInSet(_this.movedSet, n21)) {
17381 pushAdd(n21);
17382 } else {
17383 _this.droppedSet.add(n21);
17384 }
17385 }
17386 var candidate = null;
17387 while(addList.length){
17388 var node2 = null;
17389 if (candidate) {
17390 var parentId = _this.mirror.getId(index.parentNode(candidate.value));
17391 var nextId = getNextId(candidate.value);
17392 if (parentId !== -1 && nextId !== -1) {
17393 node2 = candidate;
17394 }
17395 }
17396 if (!node2) {
17397 var tailNode = addList.tail;
17398 while(tailNode){
17399 var _node = tailNode;
17400 tailNode = tailNode.previous;
17401 if (_node) {
17402 var parentId1 = _this.mirror.getId(index.parentNode(_node.value));
17403 var nextId1 = getNextId(_node.value);
17404 if (nextId1 === -1) continue;
17405 else if (parentId1 !== -1) {
17406 node2 = _node;
17407 break;
17408 } else {
17409 var unhandledNode = _node.value;
17410 var parent = index.parentNode(unhandledNode);
17411 if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
17412 var shadowHost = index.host(parent);
17413 var parentId2 = _this.mirror.getId(shadowHost);
17414 if (parentId2 !== -1) {
17415 node2 = _node;
17416 break;
17417 }
17418 }
17419 }
17420 }
17421 }
17422 }
17423 if (!node2) {
17424 while(addList.head){
17425 addList.removeNode(addList.head.value);
17426 }
17427 break;
17428 }
17429 candidate = node2.previous;
17430 addList.removeNode(node2.value);
17431 pushAdd(node2.value);
17432 }
17433 var payload = {
17434 texts: _this.texts.map(function(text) {
17435 var n2 = text.node;
17436 var parent = index.parentNode(n2);
17437 if (parent && parent.tagName === "TEXTAREA") {
17438 _this.genTextAreaValueMutation(parent);
17439 }
17440 return {
17441 id: _this.mirror.getId(n2),
17442 value: text.value
17443 };
17444 }).filter(function(text) {
17445 return !addedIds.has(text.id);
17446 }).filter(function(text) {
17447 return _this.mirror.has(text.id);
17448 }),
17449 attributes: _this.attributes.map(function(attribute) {
17450 var attributes = attribute.attributes;
17451 if (typeof attributes.style === "string") {
17452 var diffAsStr = JSON.stringify(attribute.styleDiff);
17453 var unchangedAsStr = JSON.stringify(attribute._unchangedStyles);
17454 if (diffAsStr.length < attributes.style.length) {
17455 if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) {
17456 attributes.style = attribute.styleDiff;
17457 }
17458 }
17459 }
17460 return {
17461 id: _this.mirror.getId(attribute.node),
17462 attributes: attributes
17463 };
17464 }).filter(function(attribute) {
17465 return !addedIds.has(attribute.id);
17466 }).filter(function(attribute) {
17467 return _this.mirror.has(attribute.id);
17468 }),
17469 removes: _this.removes,
17470 adds: adds
17471 };
17472 if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {
17473 return;
17474 }
17475 _this.texts = [];
17476 _this.attributes = [];
17477 _this.attributeMap = /* @__PURE__ */ new WeakMap();
17478 _this.removes = [];
17479 _this.addedSet = /* @__PURE__ */ new Set();
17480 _this.movedSet = /* @__PURE__ */ new Set();
17481 _this.droppedSet = /* @__PURE__ */ new Set();
17482 _this.removesSubTreeCache = /* @__PURE__ */ new Set();
17483 _this.movedMap = {};
17484 _this.mutationCb(payload);
17485 });
17486 __publicField(this, "genTextAreaValueMutation", function(textarea) {
17487 var item = _this.attributeMap.get(textarea);
17488 if (!item) {
17489 item = {
17490 node: textarea,
17491 attributes: {},
17492 styleDiff: {},
17493 _unchangedStyles: {}
17494 };
17495 _this.attributes.push(item);
17496 _this.attributeMap.set(textarea, item);
17497 }
17498 var value = Array.from(index.childNodes(textarea), function(cn) {
17499 return index.textContent(cn) || "";
17500 }).join("");
17501 item.attributes.value = maskInputValue({
17502 element: textarea,
17503 maskInputOptions: _this.maskInputOptions,
17504 tagName: textarea.tagName,
17505 type: getInputType(textarea),
17506 value: value,
17507 maskInputFn: _this.maskInputFn
17508 });
17509 });
17510 __publicField(this, "processMutation", function(m) {
17511 if (isIgnored(m.target, _this.mirror, _this.slimDOMOptions)) {
17512 return;
17513 }
17514 switch(m.type){
17515 case "characterData":
17516 {
17517 var value = index.textContent(m.target);
17518 if (!isBlocked(m.target, _this.blockClass, _this.blockSelector, false) && value !== m.oldValue) {
17519 _this.texts.push({
17520 value: needMaskingText(m.target, _this.maskTextClass, _this.maskTextSelector, true) && value ? _this.maskTextFn ? _this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\S]/g, "*") : value,
17521 node: m.target
17522 });
17523 }
17524 break;
17525 }
17526 case "attributes":
17527 {
17528 var target = m.target;
17529 var attributeName = m.attributeName;
17530 var value1 = m.target.getAttribute(attributeName);
17531 if (attributeName === "value") {
17532 var type = getInputType(target);
17533 value1 = maskInputValue({
17534 element: target,
17535 maskInputOptions: _this.maskInputOptions,
17536 tagName: target.tagName,
17537 type: type,
17538 value: value1,
17539 maskInputFn: _this.maskInputFn
17540 });
17541 }
17542 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || value1 === m.oldValue) {
17543 return;
17544 }
17545 var item = _this.attributeMap.get(m.target);
17546 if (target.tagName === "IFRAME" && attributeName === "src" && !_this.keepIframeSrcFn(value1)) {
17547 if (!target.contentDocument) {
17548 attributeName = "rr_src";
17549 } else {
17550 return;
17551 }
17552 }
17553 if (!item) {
17554 item = {
17555 node: m.target,
17556 attributes: {},
17557 styleDiff: {},
17558 _unchangedStyles: {}
17559 };
17560 _this.attributes.push(item);
17561 _this.attributeMap.set(m.target, item);
17562 }
17563 if (attributeName === "type" && target.tagName === "INPUT" && (m.oldValue || "").toLowerCase() === "password") {
17564 target.setAttribute("data-rr-is-password", "true");
17565 }
17566 if (!ignoreAttribute(target.tagName, attributeName)) {
17567 item.attributes[attributeName] = transformAttribute(_this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value1);
17568 if (attributeName === "style") {
17569 if (!_this.unattachedDoc) {
17570 try {
17571 _this.unattachedDoc = document.implementation.createHTMLDocument();
17572 } catch (e2) {
17573 _this.unattachedDoc = _this.doc;
17574 }
17575 }
17576 var old = _this.unattachedDoc.createElement("span");
17577 if (m.oldValue) {
17578 old.setAttribute("style", m.oldValue);
17579 }
17580 for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(target.style)), _step; !(_step = _iterator()).done;){
17581 var pname = _step.value;
17582 var newValue = target.style.getPropertyValue(pname);
17583 var newPriority = target.style.getPropertyPriority(pname);
17584 if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {
17585 if (newPriority === "") {
17586 item.styleDiff[pname] = newValue;
17587 } else {
17588 item.styleDiff[pname] = [
17589 newValue,
17590 newPriority
17591 ];
17592 }
17593 } else {
17594 item._unchangedStyles[pname] = [
17595 newValue,
17596 newPriority
17597 ];
17598 }
17599 }
17600 for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(old.style)), _step1; !(_step1 = _iterator1()).done;){
17601 var pname1 = _step1.value;
17602 if (target.style.getPropertyValue(pname1) === "") {
17603 item.styleDiff[pname1] = false;
17604 }
17605 }
17606 } else if (attributeName === "open" && target.tagName === "DIALOG") {
17607 if (target.matches("dialog:modal")) {
17608 item.attributes["rr_open_mode"] = "modal";
17609 } else {
17610 item.attributes["rr_open_mode"] = "non-modal";
17611 }
17612 }
17613 }
17614 break;
17615 }
17616 case "childList":
17617 {
17618 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, true)) return;
17619 if (m.target.tagName === "TEXTAREA") {
17620 _this.genTextAreaValueMutation(m.target);
17621 return;
17622 }
17623 m.addedNodes.forEach(function(n2) {
17624 return _this.genAdds(n2, m.target);
17625 });
17626 m.removedNodes.forEach(function(n2) {
17627 var nodeId = _this.mirror.getId(n2);
17628 var parentId = isShadowRoot(m.target) ? _this.mirror.getId(index.host(m.target)) : _this.mirror.getId(m.target);
17629 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || isIgnored(n2, _this.mirror, _this.slimDOMOptions) || !isSerialized(n2, _this.mirror)) {
17630 return;
17631 }
17632 if (_this.addedSet.has(n2)) {
17633 deepDelete(_this.addedSet, n2);
17634 _this.droppedSet.add(n2);
17635 } else if (_this.addedSet.has(m.target) && nodeId === -1) ;
17636 else if (isAncestorRemoved(m.target, _this.mirror)) ;
17637 else if (_this.movedSet.has(n2) && _this.movedMap[moveKey(nodeId, parentId)]) {
17638 deepDelete(_this.movedSet, n2);
17639 } else {
17640 _this.removes.push({
17641 parentId: parentId,
17642 id: nodeId,
17643 isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0
17644 });
17645 processRemoves(n2, _this.removesSubTreeCache);
17646 }
17647 _this.mapRemoves.push(n2);
17648 });
17649 break;
17650 }
17651 }
17652 });
17653 /**
17654 * Make sure you check if `n`'s parent is blocked before calling this function
17655 * */ __publicField(this, "genAdds", function(n2, target) {
17656 if (_this.processedNodeManager.inOtherBuffer(n2, _this)) return;
17657 if (_this.addedSet.has(n2) || _this.movedSet.has(n2)) return;
17658 if (_this.mirror.hasNode(n2)) {
17659 if (isIgnored(n2, _this.mirror, _this.slimDOMOptions)) {
17660 return;
17661 }
17662 _this.movedSet.add(n2);
17663 var targetId = null;
17664 if (target && _this.mirror.hasNode(target)) {
17665 targetId = _this.mirror.getId(target);
17666 }
17667 if (targetId && targetId !== -1) {
17668 _this.movedMap[moveKey(_this.mirror.getId(n2), targetId)] = true;
17669 }
17670 } else {
17671 _this.addedSet.add(n2);
17672 _this.droppedSet.delete(n2);
17673 }
17674 if (!isBlocked(n2, _this.blockClass, _this.blockSelector, false)) {
17675 index.childNodes(n2).forEach(function(childN) {
17676 return _this.genAdds(childN);
17677 });
17678 if (hasShadowRoot(n2)) {
17679 index.childNodes(index.shadowRoot(n2)).forEach(function(childN) {
17680 _this.processedNodeManager.add(childN, _this);
17681 _this.genAdds(childN, n2);
17682 });
17683 }
17684 }
17685 });
17686 }
17687 var _proto = MutationBuffer.prototype;
17688 _proto.init = function init(options) {
17689 var _this = this;
17690 [
17691 "mutationCb",
17692 "blockClass",
17693 "blockSelector",
17694 "maskTextClass",
17695 "maskTextSelector",
17696 "inlineStylesheet",
17697 "maskInputOptions",
17698 "maskTextFn",
17699 "maskInputFn",
17700 "keepIframeSrcFn",
17701 "recordCanvas",
17702 "inlineImages",
17703 "slimDOMOptions",
17704 "dataURLOptions",
17705 "doc",
17706 "mirror",
17707 "iframeManager",
17708 "stylesheetManager",
17709 "shadowDomManager",
17710 "canvasManager",
17711 "processedNodeManager"
17712 ].forEach(function(key) {
17713 _this[key] = options[key];
17714 });
17715 };
17716 _proto.freeze = function freeze() {
17717 this.frozen = true;
17718 this.canvasManager.freeze();
17719 };
17720 _proto.unfreeze = function unfreeze() {
17721 this.frozen = false;
17722 this.canvasManager.unfreeze();
17723 this.emit();
17724 };
17725 _proto.isFrozen = function isFrozen() {
17726 return this.frozen;
17727 };
17728 _proto.lock = function lock() {
17729 this.locked = true;
17730 this.canvasManager.lock();
17731 };
17732 _proto.unlock = function unlock() {
17733 this.locked = false;
17734 this.canvasManager.unlock();
17735 this.emit();
17736 };
17737 _proto.reset = function reset() {
17738 this.shadowDomManager.reset();
17739 this.canvasManager.reset();
17740 };
17741 return MutationBuffer;
17742 }();
17743 function deepDelete(addsSet, n2) {
17744 addsSet.delete(n2);
17745 index.childNodes(n2).forEach(function(childN) {
17746 return deepDelete(addsSet, childN);
17747 });
17748 }
17749 function processRemoves(n2, cache) {
17750 var queue = [
17751 n2
17752 ];
17753 while(queue.length){
17754 var next = queue.pop();
17755 if (cache.has(next)) continue;
17756 cache.add(next);
17757 index.childNodes(next).forEach(function(n22) {
17758 return queue.push(n22);
17759 });
17760 }
17761 return;
17762 }
17763 function isParentRemoved(removes, n2, mirror2) {
17764 if (removes.size === 0) return false;
17765 return _isParentRemoved(removes, n2);
17766 }
17767 function _isParentRemoved(removes, n2, _mirror2) {
17768 var node2 = index.parentNode(n2);
17769 if (!node2) return false;
17770 return removes.has(node2);
17771 }
17772 function isAncestorInSet(set, n2) {
17773 if (set.size === 0) return false;
17774 return _isAncestorInSet(set, n2);
17775 }
17776 function _isAncestorInSet(set, n2) {
17777 var parent = index.parentNode(n2);
17778 if (!parent) {
17779 return false;
17780 }
17781 if (set.has(parent)) {
17782 return true;
17783 }
17784 return _isAncestorInSet(set, parent);
17785 }
17786 var errorHandler;
17787 function registerErrorHandler(handler) {
17788 errorHandler = handler;
17789 }
17790 function unregisterErrorHandler() {
17791 errorHandler = void 0;
17792 }
17793 var callbackWrapper = function(cb) {
17794 if (!errorHandler) {
17795 return cb;
17796 }
17797 var rrwebWrapped = function() {
17798 for(var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++){
17799 rest[_key] = arguments[_key];
17800 }
17801 try {
17802 return cb.apply(void 0, [].concat(rest));
17803 } catch (error) {
17804 if (errorHandler && errorHandler(error) === true) {
17805 return;
17806 }
17807 throw error;
17808 }
17809 };
17810 return rrwebWrapped;
17811 };
17812 var mutationBuffers = [];
17813 function getEventTarget(event) {
17814 try {
17815 if ("composedPath" in event) {
17816 var path = event.composedPath();
17817 if (path.length) {
17818 return path[0];
17819 }
17820 } else if ("path" in event && event.path.length) {
17821 return event.path[0];
17822 }
17823 } catch (e) {}
17824 return event && event.target;
17825 }
17826 function initMutationObserver(options, rootEl) {
17827 var mutationBuffer = new MutationBuffer();
17828 mutationBuffers.push(mutationBuffer);
17829 mutationBuffer.init(options);
17830 var observer = new (mutationObserverCtor())(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));
17831 observer.observe(rootEl, {
17832 attributes: true,
17833 attributeOldValue: true,
17834 characterData: true,
17835 characterDataOldValue: true,
17836 childList: true,
17837 subtree: true
17838 });
17839 return observer;
17840 }
17841 function initMoveObserver(param) {
17842 var mousemoveCb = param.mousemoveCb, sampling = param.sampling, doc = param.doc, mirror2 = param.mirror;
17843 if (sampling.mousemove === false) {
17844 return function() {};
17845 }
17846 var threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50;
17847 var callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500;
17848 var positions = [];
17849 var timeBaseline;
17850 var wrappedCb = throttle(callbackWrapper(function(source) {
17851 var totalOffset = Date.now() - timeBaseline;
17852 mousemoveCb(positions.map(function(p) {
17853 p.timeOffset -= totalOffset;
17854 return p;
17855 }), source);
17856 positions = [];
17857 timeBaseline = null;
17858 }), callbackThreshold);
17859 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
17860 var target = getEventTarget(evt);
17861 var _ref = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt, clientX = _ref.clientX, clientY = _ref.clientY;
17862 if (!timeBaseline) {
17863 timeBaseline = nowTimestamp();
17864 }
17865 positions.push({
17866 x: clientX,
17867 y: clientY,
17868 id: mirror2.getId(target),
17869 timeOffset: nowTimestamp() - timeBaseline
17870 });
17871 wrappedCb(typeof DragEvent !== "undefined" && _instanceof(evt, DragEvent) ? IncrementalSource.Drag : _instanceof(evt, MouseEvent) ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
17872 }), threshold, {
17873 trailing: false
17874 }));
17875 var handlers = [
17876 on("mousemove", updatePosition, doc),
17877 on("touchmove", updatePosition, doc),
17878 on("drag", updatePosition, doc)
17879 ];
17880 return callbackWrapper(function() {
17881 handlers.forEach(function(h) {
17882 return h();
17883 });
17884 });
17885 }
17886 function initMouseInteractionObserver(param) {
17887 var mouseInteractionCb = param.mouseInteractionCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, sampling = param.sampling;
17888 if (sampling.mouseInteraction === false) {
17889 return function() {};
17890 }
17891 var disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;
17892 var handlers = [];
17893 var currentPointerType = null;
17894 var getHandler = function(eventKey) {
17895 return function(event) {
17896 var target = getEventTarget(event);
17897 if (isBlocked(target, blockClass, blockSelector, true)) {
17898 return;
17899 }
17900 var pointerType = null;
17901 var thisEventKey = eventKey;
17902 if ("pointerType" in event) {
17903 switch(event.pointerType){
17904 case "mouse":
17905 pointerType = PointerTypes.Mouse;
17906 break;
17907 case "touch":
17908 pointerType = PointerTypes.Touch;
17909 break;
17910 case "pen":
17911 pointerType = PointerTypes.Pen;
17912 break;
17913 }
17914 if (pointerType === PointerTypes.Touch) {
17915 if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {
17916 thisEventKey = "TouchStart";
17917 } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {
17918 thisEventKey = "TouchEnd";
17919 }
17920 } else if (pointerType === PointerTypes.Pen) ;
17921 } else if (legacy_isTouchEvent(event)) {
17922 pointerType = PointerTypes.Touch;
17923 }
17924 if (pointerType !== null) {
17925 currentPointerType = pointerType;
17926 if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) {
17927 pointerType = null;
17928 }
17929 } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {
17930 pointerType = currentPointerType;
17931 currentPointerType = null;
17932 }
17933 var e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;
17934 if (!e2) {
17935 return;
17936 }
17937 var id = mirror2.getId(target);
17938 var clientX = e2.clientX, clientY = e2.clientY;
17939 callbackWrapper(mouseInteractionCb)(_extends({
17940 type: MouseInteractions[thisEventKey],
17941 id: id,
17942 x: clientX,
17943 y: clientY
17944 }, pointerType !== null && {
17945 pointerType: pointerType
17946 }));
17947 };
17948 };
17949 Object.keys(MouseInteractions).filter(function(key) {
17950 return Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false;
17951 }).forEach(function(eventKey) {
17952 var eventName = toLowerCase(eventKey);
17953 var handler = getHandler(eventKey);
17954 if (window.PointerEvent) {
17955 switch(MouseInteractions[eventKey]){
17956 case MouseInteractions.MouseDown:
17957 case MouseInteractions.MouseUp:
17958 eventName = eventName.replace("mouse", "pointer");
17959 break;
17960 case MouseInteractions.TouchStart:
17961 case MouseInteractions.TouchEnd:
17962 return;
17963 }
17964 }
17965 handlers.push(on(eventName, handler, doc));
17966 });
17967 return callbackWrapper(function() {
17968 handlers.forEach(function(h) {
17969 return h();
17970 });
17971 });
17972 }
17973 function initScrollObserver(param) {
17974 var scrollCb = param.scrollCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, sampling = param.sampling;
17975 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
17976 var target = getEventTarget(evt);
17977 if (!target || isBlocked(target, blockClass, blockSelector, true)) {
17978 return;
17979 }
17980 var id = mirror2.getId(target);
17981 if (target === doc && doc.defaultView) {
17982 var scrollLeftTop = getWindowScroll(doc.defaultView);
17983 scrollCb({
17984 id: id,
17985 x: scrollLeftTop.left,
17986 y: scrollLeftTop.top
17987 });
17988 } else {
17989 scrollCb({
17990 id: id,
17991 x: target.scrollLeft,
17992 y: target.scrollTop
17993 });
17994 }
17995 }), sampling.scroll || 100));
17996 return on("scroll", updatePosition, doc);
17997 }
17998 function initViewportResizeObserver(param, param1) {
17999 var viewportResizeCb = param.viewportResizeCb;
18000 var win = param1.win;
18001 var lastH = -1;
18002 var lastW = -1;
18003 var updateDimension = callbackWrapper(throttle(callbackWrapper(function() {
18004 var height = getWindowHeight();
18005 var width = getWindowWidth();
18006 if (lastH !== height || lastW !== width) {
18007 viewportResizeCb({
18008 width: Number(width),
18009 height: Number(height)
18010 });
18011 lastH = height;
18012 lastW = width;
18013 }
18014 }), 200));
18015 return on("resize", updateDimension, win);
18016 }
18017 var INPUT_TAGS = [
18018 "INPUT",
18019 "TEXTAREA",
18020 "SELECT"
18021 ];
18022 var lastInputValueMap = /* @__PURE__ */ new WeakMap();
18023 function initInputObserver(param) {
18024 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;
18025 function eventHandler(event) {
18026 var target = getEventTarget(event);
18027 var userTriggered = event.isTrusted;
18028 var tagName = target && target.tagName;
18029 if (target && tagName === "OPTION") {
18030 target = index.parentElement(target);
18031 }
18032 if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {
18033 return;
18034 }
18035 if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) {
18036 return;
18037 }
18038 var text = target.value;
18039 var isChecked = false;
18040 var type = getInputType(target) || "";
18041 if (type === "radio" || type === "checkbox") {
18042 isChecked = target.checked;
18043 } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {
18044 text = maskInputValue({
18045 element: target,
18046 maskInputOptions: maskInputOptions,
18047 tagName: tagName,
18048 type: type,
18049 value: text,
18050 maskInputFn: maskInputFn
18051 });
18052 }
18053 cbWithDedup(target, userTriggeredOnInput ? {
18054 text: text,
18055 isChecked: isChecked,
18056 userTriggered: userTriggered
18057 } : {
18058 text: text,
18059 isChecked: isChecked
18060 });
18061 var name = target.name;
18062 if (type === "radio" && name && isChecked) {
18063 doc.querySelectorAll('input[type="radio"][name="' + name + '"]').forEach(function(el) {
18064 if (el !== target) {
18065 var text2 = el.value;
18066 cbWithDedup(el, userTriggeredOnInput ? {
18067 text: text2,
18068 isChecked: !isChecked,
18069 userTriggered: false
18070 } : {
18071 text: text2,
18072 isChecked: !isChecked
18073 });
18074 }
18075 });
18076 }
18077 }
18078 function cbWithDedup(target, v2) {
18079 var lastInputValue = lastInputValueMap.get(target);
18080 if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {
18081 lastInputValueMap.set(target, v2);
18082 var id = mirror2.getId(target);
18083 callbackWrapper(inputCb)(_extends({}, v2, {
18084 id: id
18085 }));
18086 }
18087 }
18088 var events = sampling.input === "last" ? [
18089 "change"
18090 ] : [
18091 "input",
18092 "change"
18093 ];
18094 var handlers = events.map(function(eventName) {
18095 return on(eventName, callbackWrapper(eventHandler), doc);
18096 });
18097 var currentWindow = doc.defaultView;
18098 if (!currentWindow) {
18099 return function() {
18100 handlers.forEach(function(h) {
18101 return h();
18102 });
18103 };
18104 }
18105 var propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value");
18106 var hookProperties = [
18107 [
18108 currentWindow.HTMLInputElement.prototype,
18109 "value"
18110 ],
18111 [
18112 currentWindow.HTMLInputElement.prototype,
18113 "checked"
18114 ],
18115 [
18116 currentWindow.HTMLSelectElement.prototype,
18117 "value"
18118 ],
18119 [
18120 currentWindow.HTMLTextAreaElement.prototype,
18121 "value"
18122 ],
18123 // Some UI library use selectedIndex to set select value
18124 [
18125 currentWindow.HTMLSelectElement.prototype,
18126 "selectedIndex"
18127 ],
18128 [
18129 currentWindow.HTMLOptionElement.prototype,
18130 "selected"
18131 ]
18132 ];
18133 if (propertyDescriptor && propertyDescriptor.set) {
18134 var _handlers;
18135 (_handlers = handlers).push.apply(_handlers, [].concat(hookProperties.map(function(p) {
18136 return hookSetter(p[0], p[1], {
18137 set: function set() {
18138 callbackWrapper(eventHandler)({
18139 target: this,
18140 isTrusted: false
18141 });
18142 }
18143 }, false, currentWindow);
18144 })));
18145 }
18146 return callbackWrapper(function() {
18147 handlers.forEach(function(h) {
18148 return h();
18149 });
18150 });
18151 }
18152 function getNestedCSSRulePositions(rule2) {
18153 var positions = [];
18154 function recurse(childRule, pos) {
18155 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)) {
18156 var rules2 = Array.from(childRule.parentRule.cssRules);
18157 var index2 = rules2.indexOf(childRule);
18158 pos.unshift(index2);
18159 } else if (childRule.parentStyleSheet) {
18160 var rules21 = Array.from(childRule.parentStyleSheet.cssRules);
18161 var index21 = rules21.indexOf(childRule);
18162 pos.unshift(index21);
18163 }
18164 return pos;
18165 }
18166 return recurse(rule2, positions);
18167 }
18168 function getIdAndStyleId(sheet, mirror2, styleMirror) {
18169 var id, styleId;
18170 if (!sheet) return {};
18171 if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);
18172 else styleId = styleMirror.getId(sheet);
18173 return {
18174 styleId: styleId,
18175 id: id
18176 };
18177 }
18178 function initStyleSheetObserver(param, param1) {
18179 var styleSheetRuleCb = param.styleSheetRuleCb, mirror2 = param.mirror, stylesheetManager = param.stylesheetManager;
18180 var win = param1.win;
18181 if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {
18182 return function() {};
18183 }
18184 var insertRule = win.CSSStyleSheet.prototype.insertRule;
18185 win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {
18186 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18187 var rule2 = argumentsList[0], index2 = argumentsList[1];
18188 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18189 if (id && id !== -1 || styleId && styleId !== -1) {
18190 styleSheetRuleCb({
18191 id: id,
18192 styleId: styleId,
18193 adds: [
18194 {
18195 rule: rule2,
18196 index: index2
18197 }
18198 ]
18199 });
18200 }
18201 return target.apply(thisArg, argumentsList);
18202 })
18203 });
18204 win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2) {
18205 if (index2 === void 0) index2 = this.cssRules.length;
18206 var rule2 = selector + " { " + styleBlock + " }";
18207 return win.CSSStyleSheet.prototype.insertRule.apply(this, [
18208 rule2,
18209 index2
18210 ]);
18211 };
18212 var deleteRule = win.CSSStyleSheet.prototype.deleteRule;
18213 win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {
18214 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18215 var index2 = argumentsList[0];
18216 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18217 if (id && id !== -1 || styleId && styleId !== -1) {
18218 styleSheetRuleCb({
18219 id: id,
18220 styleId: styleId,
18221 removes: [
18222 {
18223 index: index2
18224 }
18225 ]
18226 });
18227 }
18228 return target.apply(thisArg, argumentsList);
18229 })
18230 });
18231 win.CSSStyleSheet.prototype.removeRule = function(index2) {
18232 return win.CSSStyleSheet.prototype.deleteRule.apply(this, [
18233 index2
18234 ]);
18235 };
18236 var replace;
18237 if (win.CSSStyleSheet.prototype.replace) {
18238 replace = win.CSSStyleSheet.prototype.replace;
18239 win.CSSStyleSheet.prototype.replace = new Proxy(replace, {
18240 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18241 var text = argumentsList[0];
18242 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18243 if (id && id !== -1 || styleId && styleId !== -1) {
18244 styleSheetRuleCb({
18245 id: id,
18246 styleId: styleId,
18247 replace: text
18248 });
18249 }
18250 return target.apply(thisArg, argumentsList);
18251 })
18252 });
18253 }
18254 var replaceSync;
18255 if (win.CSSStyleSheet.prototype.replaceSync) {
18256 replaceSync = win.CSSStyleSheet.prototype.replaceSync;
18257 win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {
18258 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18259 var text = argumentsList[0];
18260 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18261 if (id && id !== -1 || styleId && styleId !== -1) {
18262 styleSheetRuleCb({
18263 id: id,
18264 styleId: styleId,
18265 replaceSync: text
18266 });
18267 }
18268 return target.apply(thisArg, argumentsList);
18269 })
18270 });
18271 }
18272 var supportedNestedCSSRuleTypes = {};
18273 if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) {
18274 supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
18275 } else {
18276 if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) {
18277 supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
18278 }
18279 if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) {
18280 supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
18281 }
18282 if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) {
18283 supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
18284 }
18285 }
18286 var unmodifiedFunctions = {};
18287 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
18288 var typeKey = param[0], type = param[1];
18289 unmodifiedFunctions[typeKey] = {
18290 // eslint-disable-next-line @typescript-eslint/unbound-method
18291 insertRule: type.prototype.insertRule,
18292 // eslint-disable-next-line @typescript-eslint/unbound-method
18293 deleteRule: type.prototype.deleteRule
18294 };
18295 type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {
18296 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18297 var rule2 = argumentsList[0], index2 = argumentsList[1];
18298 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18299 if (id && id !== -1 || styleId && styleId !== -1) {
18300 styleSheetRuleCb({
18301 id: id,
18302 styleId: styleId,
18303 adds: [
18304 {
18305 rule: rule2,
18306 index: [].concat(getNestedCSSRulePositions(thisArg), [
18307 index2 || 0
18308 ])
18309 }
18310 ]
18311 });
18312 }
18313 return target.apply(thisArg, argumentsList);
18314 })
18315 });
18316 type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {
18317 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18318 var index2 = argumentsList[0];
18319 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18320 if (id && id !== -1 || styleId && styleId !== -1) {
18321 styleSheetRuleCb({
18322 id: id,
18323 styleId: styleId,
18324 removes: [
18325 {
18326 index: [].concat(getNestedCSSRulePositions(thisArg), [
18327 index2
18328 ])
18329 }
18330 ]
18331 });
18332 }
18333 return target.apply(thisArg, argumentsList);
18334 })
18335 });
18336 });
18337 return callbackWrapper(function() {
18338 win.CSSStyleSheet.prototype.insertRule = insertRule;
18339 win.CSSStyleSheet.prototype.deleteRule = deleteRule;
18340 replace && (win.CSSStyleSheet.prototype.replace = replace);
18341 replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
18342 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
18343 var typeKey = param[0], type = param[1];
18344 type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
18345 type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
18346 });
18347 });
18348 }
18349 function initAdoptedStyleSheetObserver(param, host2) {
18350 var mirror2 = param.mirror, stylesheetManager = param.stylesheetManager;
18351 var _a2, _b, _c;
18352 var hostId = null;
18353 if (host2.nodeName === "#document") hostId = mirror2.getId(host2);
18354 else hostId = mirror2.getId(index.host(host2));
18355 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;
18356 var originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(patchTarget == null ? void 0 : patchTarget.prototype, "adoptedStyleSheets") : void 0;
18357 if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return function() {};
18358 Object.defineProperty(host2, "adoptedStyleSheets", {
18359 configurable: originalPropertyDescriptor.configurable,
18360 enumerable: originalPropertyDescriptor.enumerable,
18361 get: function get() {
18362 var _a3;
18363 return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);
18364 },
18365 set: function set(sheets) {
18366 var _a3;
18367 var result2 = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);
18368 if (hostId !== null && hostId !== -1) {
18369 try {
18370 stylesheetManager.adoptStyleSheets(sheets, hostId);
18371 } catch (e2) {}
18372 }
18373 return result2;
18374 }
18375 });
18376 return callbackWrapper(function() {
18377 Object.defineProperty(host2, "adoptedStyleSheets", {
18378 configurable: originalPropertyDescriptor.configurable,
18379 enumerable: originalPropertyDescriptor.enumerable,
18380 // eslint-disable-next-line @typescript-eslint/unbound-method
18381 get: originalPropertyDescriptor.get,
18382 // eslint-disable-next-line @typescript-eslint/unbound-method
18383 set: originalPropertyDescriptor.set
18384 });
18385 });
18386 }
18387 function initStyleDeclarationObserver(param, param1) {
18388 var styleDeclarationCb = param.styleDeclarationCb, mirror2 = param.mirror, ignoreCSSAttributes = param.ignoreCSSAttributes, stylesheetManager = param.stylesheetManager;
18389 var win = param1.win;
18390 var setProperty = win.CSSStyleDeclaration.prototype.setProperty;
18391 win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {
18392 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18393 var _a2;
18394 var property = argumentsList[0], value = argumentsList[1], priority = argumentsList[2];
18395 if (ignoreCSSAttributes.has(property)) {
18396 return setProperty.apply(thisArg, [
18397 property,
18398 value,
18399 priority
18400 ]);
18401 }
18402 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18403 if (id && id !== -1 || styleId && styleId !== -1) {
18404 styleDeclarationCb({
18405 id: id,
18406 styleId: styleId,
18407 set: {
18408 property: property,
18409 value: value,
18410 priority: priority
18411 },
18412 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
18413 index: getNestedCSSRulePositions(thisArg.parentRule)
18414 });
18415 }
18416 return target.apply(thisArg, argumentsList);
18417 })
18418 });
18419 var removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
18420 win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {
18421 apply: callbackWrapper(function(target, thisArg, argumentsList) {
18422 var _a2;
18423 var property = argumentsList[0];
18424 if (ignoreCSSAttributes.has(property)) {
18425 return removeProperty.apply(thisArg, [
18426 property
18427 ]);
18428 }
18429 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
18430 if (id && id !== -1 || styleId && styleId !== -1) {
18431 styleDeclarationCb({
18432 id: id,
18433 styleId: styleId,
18434 remove: {
18435 property: property
18436 },
18437 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
18438 index: getNestedCSSRulePositions(thisArg.parentRule)
18439 });
18440 }
18441 return target.apply(thisArg, argumentsList);
18442 })
18443 });
18444 return callbackWrapper(function() {
18445 win.CSSStyleDeclaration.prototype.setProperty = setProperty;
18446 win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
18447 });
18448 }
18449 function initMediaInteractionObserver(param) {
18450 var mediaInteractionCb = param.mediaInteractionCb, blockClass = param.blockClass, blockSelector = param.blockSelector, mirror2 = param.mirror, sampling = param.sampling, doc = param.doc;
18451 var handler = callbackWrapper(function(type) {
18452 return throttle(callbackWrapper(function(event) {
18453 var target = getEventTarget(event);
18454 if (!target || isBlocked(target, blockClass, blockSelector, true)) {
18455 return;
18456 }
18457 var currentTime = target.currentTime, volume = target.volume, muted = target.muted, playbackRate = target.playbackRate, loop = target.loop;
18458 mediaInteractionCb({
18459 type: type,
18460 id: mirror2.getId(target),
18461 currentTime: currentTime,
18462 volume: volume,
18463 muted: muted,
18464 playbackRate: playbackRate,
18465 loop: loop
18466 });
18467 }), sampling.media || 500);
18468 });
18469 var handlers = [
18470 on("play", handler(MediaInteractions.Play), doc),
18471 on("pause", handler(MediaInteractions.Pause), doc),
18472 on("seeked", handler(MediaInteractions.Seeked), doc),
18473 on("volumechange", handler(MediaInteractions.VolumeChange), doc),
18474 on("ratechange", handler(MediaInteractions.RateChange), doc)
18475 ];
18476 return callbackWrapper(function() {
18477 handlers.forEach(function(h) {
18478 return h();
18479 });
18480 });
18481 }
18482 function initFontObserver(param) {
18483 var fontCb = param.fontCb, doc = param.doc;
18484 var win = doc.defaultView;
18485 if (!win) {
18486 return function() {};
18487 }
18488 var handlers = [];
18489 var fontMap = /* @__PURE__ */ new WeakMap();
18490 var originalFontFace = win.FontFace;
18491 win.FontFace = function FontFace2(family, source, descriptors) {
18492 var fontFace = new originalFontFace(family, source, descriptors);
18493 fontMap.set(fontFace, {
18494 family: family,
18495 buffer: typeof source !== "string",
18496 descriptors: descriptors,
18497 fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source)))
18498 });
18499 return fontFace;
18500 };
18501 var restoreHandler = patch(doc.fonts, "add", function(original) {
18502 return function(fontFace) {
18503 setTimeout(callbackWrapper(function() {
18504 var p = fontMap.get(fontFace);
18505 if (p) {
18506 fontCb(p);
18507 fontMap.delete(fontFace);
18508 }
18509 }), 0);
18510 return original.apply(this, [
18511 fontFace
18512 ]);
18513 };
18514 });
18515 handlers.push(function() {
18516 win.FontFace = originalFontFace;
18517 });
18518 handlers.push(restoreHandler);
18519 return callbackWrapper(function() {
18520 handlers.forEach(function(h) {
18521 return h();
18522 });
18523 });
18524 }
18525 function initSelectionObserver(param) {
18526 var doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, selectionCb = param.selectionCb;
18527 var collapsed = true;
18528 var updateSelection = callbackWrapper(function() {
18529 var selection = doc.getSelection();
18530 if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;
18531 collapsed = selection.isCollapsed || false;
18532 var ranges = [];
18533 var count = selection.rangeCount || 0;
18534 for(var i2 = 0; i2 < count; i2++){
18535 var range = selection.getRangeAt(i2);
18536 var startContainer = range.startContainer, startOffset = range.startOffset, endContainer = range.endContainer, endOffset = range.endOffset;
18537 var blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);
18538 if (blocked) continue;
18539 ranges.push({
18540 start: mirror2.getId(startContainer),
18541 startOffset: startOffset,
18542 end: mirror2.getId(endContainer),
18543 endOffset: endOffset
18544 });
18545 }
18546 selectionCb({
18547 ranges: ranges
18548 });
18549 });
18550 updateSelection();
18551 return on("selectionchange", updateSelection);
18552 }
18553 function initCustomElementObserver(param) {
18554 var doc = param.doc, customElementCb = param.customElementCb;
18555 var win = doc.defaultView;
18556 if (!win || !win.customElements) return function() {};
18557 var restoreHandler = patch(win.customElements, "define", function(original) {
18558 return function(name, constructor, options) {
18559 try {
18560 customElementCb({
18561 define: {
18562 name: name
18563 }
18564 });
18565 } catch (e2) {
18566 console.warn("Custom element callback failed for " + name);
18567 }
18568 return original.apply(this, [
18569 name,
18570 constructor,
18571 options
18572 ]);
18573 };
18574 });
18575 return restoreHandler;
18576 }
18577 function mergeHooks(o2, hooks) {
18578 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;
18579 o2.mutationCb = function() {
18580 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18581 p[_key] = arguments[_key];
18582 }
18583 if (hooks.mutation) {
18584 var _hooks;
18585 (_hooks = hooks).mutation.apply(_hooks, [].concat(p));
18586 }
18587 mutationCb.apply(void 0, [].concat(p));
18588 };
18589 o2.mousemoveCb = function() {
18590 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18591 p[_key] = arguments[_key];
18592 }
18593 if (hooks.mousemove) {
18594 var _hooks;
18595 (_hooks = hooks).mousemove.apply(_hooks, [].concat(p));
18596 }
18597 mousemoveCb.apply(void 0, [].concat(p));
18598 };
18599 o2.mouseInteractionCb = function() {
18600 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18601 p[_key] = arguments[_key];
18602 }
18603 if (hooks.mouseInteraction) {
18604 var _hooks;
18605 (_hooks = hooks).mouseInteraction.apply(_hooks, [].concat(p));
18606 }
18607 mouseInteractionCb.apply(void 0, [].concat(p));
18608 };
18609 o2.scrollCb = function() {
18610 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18611 p[_key] = arguments[_key];
18612 }
18613 if (hooks.scroll) {
18614 var _hooks;
18615 (_hooks = hooks).scroll.apply(_hooks, [].concat(p));
18616 }
18617 scrollCb.apply(void 0, [].concat(p));
18618 };
18619 o2.viewportResizeCb = function() {
18620 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18621 p[_key] = arguments[_key];
18622 }
18623 if (hooks.viewportResize) {
18624 var _hooks;
18625 (_hooks = hooks).viewportResize.apply(_hooks, [].concat(p));
18626 }
18627 viewportResizeCb.apply(void 0, [].concat(p));
18628 };
18629 o2.inputCb = function() {
18630 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18631 p[_key] = arguments[_key];
18632 }
18633 if (hooks.input) {
18634 var _hooks;
18635 (_hooks = hooks).input.apply(_hooks, [].concat(p));
18636 }
18637 inputCb.apply(void 0, [].concat(p));
18638 };
18639 o2.mediaInteractionCb = function() {
18640 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18641 p[_key] = arguments[_key];
18642 }
18643 if (hooks.mediaInteaction) {
18644 var _hooks;
18645 (_hooks = hooks).mediaInteaction.apply(_hooks, [].concat(p));
18646 }
18647 mediaInteractionCb.apply(void 0, [].concat(p));
18648 };
18649 o2.styleSheetRuleCb = function() {
18650 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18651 p[_key] = arguments[_key];
18652 }
18653 if (hooks.styleSheetRule) {
18654 var _hooks;
18655 (_hooks = hooks).styleSheetRule.apply(_hooks, [].concat(p));
18656 }
18657 styleSheetRuleCb.apply(void 0, [].concat(p));
18658 };
18659 o2.styleDeclarationCb = function() {
18660 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18661 p[_key] = arguments[_key];
18662 }
18663 if (hooks.styleDeclaration) {
18664 var _hooks;
18665 (_hooks = hooks).styleDeclaration.apply(_hooks, [].concat(p));
18666 }
18667 styleDeclarationCb.apply(void 0, [].concat(p));
18668 };
18669 o2.canvasMutationCb = function() {
18670 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18671 p[_key] = arguments[_key];
18672 }
18673 if (hooks.canvasMutation) {
18674 var _hooks;
18675 (_hooks = hooks).canvasMutation.apply(_hooks, [].concat(p));
18676 }
18677 canvasMutationCb.apply(void 0, [].concat(p));
18678 };
18679 o2.fontCb = function() {
18680 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18681 p[_key] = arguments[_key];
18682 }
18683 if (hooks.font) {
18684 var _hooks;
18685 (_hooks = hooks).font.apply(_hooks, [].concat(p));
18686 }
18687 fontCb.apply(void 0, [].concat(p));
18688 };
18689 o2.selectionCb = function() {
18690 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
18691 p[_key] = arguments[_key];
18692 }
18693 if (hooks.selection) {
18694 var _hooks;
18695 (_hooks = hooks).selection.apply(_hooks, [].concat(p));
18696 }
18697 selectionCb.apply(void 0, [].concat(p));
18698 };
18699 o2.customElementCb = function() {
18700 for(var _len = arguments.length, c2 = new Array(_len), _key = 0; _key < _len; _key++){
18701 c2[_key] = arguments[_key];
18702 }
18703 if (hooks.customElement) {
18704 var _hooks;
18705 (_hooks = hooks).customElement.apply(_hooks, [].concat(c2));
18706 }
18707 customElementCb.apply(void 0, [].concat(c2));
18708 };
18709 }
18710 function initObservers(o2, hooks) {
18711 if (hooks === void 0) hooks = {};
18712 var currentWindow = o2.doc.defaultView;
18713 if (!currentWindow) {
18714 return function() {};
18715 }
18716 mergeHooks(o2, hooks);
18717 var mutationObserver;
18718 if (o2.recordDOM) {
18719 mutationObserver = initMutationObserver(o2, o2.doc);
18720 }
18721 var mousemoveHandler = initMoveObserver(o2);
18722 var mouseInteractionHandler = initMouseInteractionObserver(o2);
18723 var scrollHandler = initScrollObserver(o2);
18724 var viewportResizeHandler = initViewportResizeObserver(o2, {
18725 win: currentWindow
18726 });
18727 var inputHandler = initInputObserver(o2);
18728 var mediaInteractionHandler = initMediaInteractionObserver(o2);
18729 var styleSheetObserver = function() {};
18730 var adoptedStyleSheetObserver = function() {};
18731 var styleDeclarationObserver = function() {};
18732 var fontObserver = function() {};
18733 if (o2.recordDOM) {
18734 styleSheetObserver = initStyleSheetObserver(o2, {
18735 win: currentWindow
18736 });
18737 adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);
18738 styleDeclarationObserver = initStyleDeclarationObserver(o2, {
18739 win: currentWindow
18740 });
18741 if (o2.collectFonts) {
18742 fontObserver = initFontObserver(o2);
18743 }
18744 }
18745 var selectionObserver = initSelectionObserver(o2);
18746 var customElementObserver = initCustomElementObserver(o2);
18747 var pluginHandlers = [];
18748 for(var _iterator = _create_for_of_iterator_helper_loose(o2.plugins), _step; !(_step = _iterator()).done;){
18749 var plugin3 = _step.value;
18750 pluginHandlers.push(plugin3.observer(plugin3.callback, currentWindow, plugin3.options));
18751 }
18752 return callbackWrapper(function() {
18753 mutationBuffers.forEach(function(b) {
18754 return b.reset();
18755 });
18756 mutationObserver == null ? void 0 : mutationObserver.disconnect();
18757 mousemoveHandler();
18758 mouseInteractionHandler();
18759 scrollHandler();
18760 viewportResizeHandler();
18761 inputHandler();
18762 mediaInteractionHandler();
18763 styleSheetObserver();
18764 adoptedStyleSheetObserver();
18765 styleDeclarationObserver();
18766 fontObserver();
18767 selectionObserver();
18768 customElementObserver();
18769 pluginHandlers.forEach(function(h) {
18770 return h();
18771 });
18772 });
18773 }
18774 function hasNestedCSSRule(prop) {
18775 return typeof window[prop] !== "undefined";
18776 }
18777 function canMonkeyPatchNestedCSSRule(prop) {
18778 return Boolean(typeof window[prop] !== "undefined" && // Note: Generally, this check _shouldn't_ be necessary
18779 // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here
18780 window[prop].prototype && "insertRule" in window[prop].prototype && "deleteRule" in window[prop].prototype);
18781 }
18782 var CrossOriginIframeMirror = /*#__PURE__*/ function() {
18783 function CrossOriginIframeMirror(generateIdFn) {
18784 __publicField(this, "iframeIdToRemoteIdMap", /* @__PURE__ */ new WeakMap());
18785 __publicField(this, "iframeRemoteIdToIdMap", /* @__PURE__ */ new WeakMap());
18786 this.generateIdFn = generateIdFn;
18787 }
18788 var _proto = CrossOriginIframeMirror.prototype;
18789 _proto.getId = function getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
18790 var idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
18791 var remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
18792 var id = idToRemoteIdMap.get(remoteId);
18793 if (!id) {
18794 id = this.generateIdFn();
18795 idToRemoteIdMap.set(remoteId, id);
18796 remoteIdToIdMap.set(id, remoteId);
18797 }
18798 return id;
18799 };
18800 _proto.getIds = function getIds(iframe, remoteId) {
18801 var _this = this;
18802 var idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
18803 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
18804 return remoteId.map(function(id) {
18805 return _this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap);
18806 });
18807 };
18808 _proto.getRemoteId = function getRemoteId(iframe, id, map) {
18809 var remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
18810 if (typeof id !== "number") return id;
18811 var remoteId = remoteIdToIdMap.get(id);
18812 if (!remoteId) return -1;
18813 return remoteId;
18814 };
18815 _proto.getRemoteIds = function getRemoteIds(iframe, ids) {
18816 var _this = this;
18817 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
18818 return ids.map(function(id) {
18819 return _this.getRemoteId(iframe, id, remoteIdToIdMap);
18820 });
18821 };
18822 _proto.reset = function reset(iframe) {
18823 if (!iframe) {
18824 this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
18825 this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
18826 return;
18827 }
18828 this.iframeIdToRemoteIdMap.delete(iframe);
18829 this.iframeRemoteIdToIdMap.delete(iframe);
18830 };
18831 _proto.getIdToRemoteIdMap = function getIdToRemoteIdMap(iframe) {
18832 var idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
18833 if (!idToRemoteIdMap) {
18834 idToRemoteIdMap = /* @__PURE__ */ new Map();
18835 this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
18836 }
18837 return idToRemoteIdMap;
18838 };
18839 _proto.getRemoteIdToIdMap = function getRemoteIdToIdMap(iframe) {
18840 var remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
18841 if (!remoteIdToIdMap) {
18842 remoteIdToIdMap = /* @__PURE__ */ new Map();
18843 this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
18844 }
18845 return remoteIdToIdMap;
18846 };
18847 return CrossOriginIframeMirror;
18848 }();
18849 var IframeManager = /*#__PURE__*/ function() {
18850 function IframeManager(options) {
18851 __publicField(this, "iframes", /* @__PURE__ */ new WeakMap());
18852 __publicField(this, "crossOriginIframeMap", /* @__PURE__ */ new WeakMap());
18853 __publicField(this, "crossOriginIframeMirror", new CrossOriginIframeMirror(genId));
18854 __publicField(this, "crossOriginIframeStyleMirror");
18855 __publicField(this, "crossOriginIframeRootIdMap", /* @__PURE__ */ new WeakMap());
18856 __publicField(this, "mirror");
18857 __publicField(this, "mutationCb");
18858 __publicField(this, "wrappedEmit");
18859 __publicField(this, "loadListener");
18860 __publicField(this, "stylesheetManager");
18861 __publicField(this, "recordCrossOriginIframes");
18862 this.mutationCb = options.mutationCb;
18863 this.wrappedEmit = options.wrappedEmit;
18864 this.stylesheetManager = options.stylesheetManager;
18865 this.recordCrossOriginIframes = options.recordCrossOriginIframes;
18866 this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
18867 this.mirror = options.mirror;
18868 if (this.recordCrossOriginIframes) {
18869 window.addEventListener("message", this.handleMessage.bind(this));
18870 }
18871 }
18872 var _proto = IframeManager.prototype;
18873 _proto.addIframe = function addIframe(iframeEl) {
18874 this.iframes.set(iframeEl, true);
18875 if (iframeEl.contentWindow) this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
18876 };
18877 _proto.addLoadListener = function addLoadListener(cb) {
18878 this.loadListener = cb;
18879 };
18880 _proto.attachIframe = function attachIframe(iframeEl, childSn) {
18881 var _a2, _b;
18882 this.mutationCb({
18883 adds: [
18884 {
18885 parentId: this.mirror.getId(iframeEl),
18886 nextId: null,
18887 node: childSn
18888 }
18889 ],
18890 removes: [],
18891 texts: [],
18892 attributes: [],
18893 isAttachIframe: true
18894 });
18895 if (this.recordCrossOriginIframes) (_a2 = iframeEl.contentWindow) == null ? void 0 : _a2.addEventListener("message", this.handleMessage.bind(this));
18896 (_b = this.loadListener) == null ? void 0 : _b.call(this, iframeEl);
18897 if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
18898 };
18899 _proto.handleMessage = function handleMessage(message) {
18900 var crossOriginMessageEvent = message;
18901 if (crossOriginMessageEvent.data.type !== "rrweb" || // To filter out the rrweb messages which are forwarded by some sites.
18902 crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return;
18903 var iframeSourceWindow = message.source;
18904 if (!iframeSourceWindow) return;
18905 var iframeEl = this.crossOriginIframeMap.get(message.source);
18906 if (!iframeEl) return;
18907 var transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
18908 if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
18909 };
18910 _proto.transformCrossOriginEvent = function transformCrossOriginEvent(iframeEl, e2) {
18911 var _this = this;
18912 var _a2;
18913 switch(e2.type){
18914 case EventType.FullSnapshot:
18915 {
18916 this.crossOriginIframeMirror.reset(iframeEl);
18917 this.crossOriginIframeStyleMirror.reset(iframeEl);
18918 this.replaceIdOnNode(e2.data.node, iframeEl);
18919 var rootId = e2.data.node.id;
18920 this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
18921 this.patchRootIdOnNode(e2.data.node, rootId);
18922 return {
18923 timestamp: e2.timestamp,
18924 type: EventType.IncrementalSnapshot,
18925 data: {
18926 source: IncrementalSource.Mutation,
18927 adds: [
18928 {
18929 parentId: this.mirror.getId(iframeEl),
18930 nextId: null,
18931 node: e2.data.node
18932 }
18933 ],
18934 removes: [],
18935 texts: [],
18936 attributes: [],
18937 isAttachIframe: true
18938 }
18939 };
18940 }
18941 case EventType.Meta:
18942 case EventType.Load:
18943 case EventType.DomContentLoaded:
18944 {
18945 return false;
18946 }
18947 case EventType.Plugin:
18948 {
18949 return e2;
18950 }
18951 case EventType.Custom:
18952 {
18953 this.replaceIds(e2.data.payload, iframeEl, [
18954 "id",
18955 "parentId",
18956 "previousId",
18957 "nextId"
18958 ]);
18959 return e2;
18960 }
18961 case EventType.IncrementalSnapshot:
18962 {
18963 switch(e2.data.source){
18964 case IncrementalSource.Mutation:
18965 {
18966 e2.data.adds.forEach(function(n2) {
18967 _this.replaceIds(n2, iframeEl, [
18968 "parentId",
18969 "nextId",
18970 "previousId"
18971 ]);
18972 _this.replaceIdOnNode(n2.node, iframeEl);
18973 var rootId = _this.crossOriginIframeRootIdMap.get(iframeEl);
18974 rootId && _this.patchRootIdOnNode(n2.node, rootId);
18975 });
18976 e2.data.removes.forEach(function(n2) {
18977 _this.replaceIds(n2, iframeEl, [
18978 "parentId",
18979 "id"
18980 ]);
18981 });
18982 e2.data.attributes.forEach(function(n2) {
18983 _this.replaceIds(n2, iframeEl, [
18984 "id"
18985 ]);
18986 });
18987 e2.data.texts.forEach(function(n2) {
18988 _this.replaceIds(n2, iframeEl, [
18989 "id"
18990 ]);
18991 });
18992 return e2;
18993 }
18994 case IncrementalSource.Drag:
18995 case IncrementalSource.TouchMove:
18996 case IncrementalSource.MouseMove:
18997 {
18998 e2.data.positions.forEach(function(p) {
18999 _this.replaceIds(p, iframeEl, [
19000 "id"
19001 ]);
19002 });
19003 return e2;
19004 }
19005 case IncrementalSource.ViewportResize:
19006 {
19007 return false;
19008 }
19009 case IncrementalSource.MediaInteraction:
19010 case IncrementalSource.MouseInteraction:
19011 case IncrementalSource.Scroll:
19012 case IncrementalSource.CanvasMutation:
19013 case IncrementalSource.Input:
19014 {
19015 this.replaceIds(e2.data, iframeEl, [
19016 "id"
19017 ]);
19018 return e2;
19019 }
19020 case IncrementalSource.StyleSheetRule:
19021 case IncrementalSource.StyleDeclaration:
19022 {
19023 this.replaceIds(e2.data, iframeEl, [
19024 "id"
19025 ]);
19026 this.replaceStyleIds(e2.data, iframeEl, [
19027 "styleId"
19028 ]);
19029 return e2;
19030 }
19031 case IncrementalSource.Font:
19032 {
19033 return e2;
19034 }
19035 case IncrementalSource.Selection:
19036 {
19037 e2.data.ranges.forEach(function(range) {
19038 _this.replaceIds(range, iframeEl, [
19039 "start",
19040 "end"
19041 ]);
19042 });
19043 return e2;
19044 }
19045 case IncrementalSource.AdoptedStyleSheet:
19046 {
19047 this.replaceIds(e2.data, iframeEl, [
19048 "id"
19049 ]);
19050 this.replaceStyleIds(e2.data, iframeEl, [
19051 "styleIds"
19052 ]);
19053 (_a2 = e2.data.styles) == null ? void 0 : _a2.forEach(function(style) {
19054 _this.replaceStyleIds(style, iframeEl, [
19055 "styleId"
19056 ]);
19057 });
19058 return e2;
19059 }
19060 }
19061 }
19062 }
19063 return false;
19064 };
19065 _proto.replace = function replace(iframeMirror, obj, iframeEl, keys) {
19066 for(var _iterator = _create_for_of_iterator_helper_loose(keys), _step; !(_step = _iterator()).done;){
19067 var key = _step.value;
19068 if (!Array.isArray(obj[key]) && typeof obj[key] !== "number") continue;
19069 if (Array.isArray(obj[key])) {
19070 obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
19071 } else {
19072 obj[key] = iframeMirror.getId(iframeEl, obj[key]);
19073 }
19074 }
19075 return obj;
19076 };
19077 _proto.replaceIds = function replaceIds(obj, iframeEl, keys) {
19078 return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
19079 };
19080 _proto.replaceStyleIds = function replaceStyleIds(obj, iframeEl, keys) {
19081 return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
19082 };
19083 _proto.replaceIdOnNode = function replaceIdOnNode(node2, iframeEl) {
19084 var _this = this;
19085 this.replaceIds(node2, iframeEl, [
19086 "id",
19087 "rootId"
19088 ]);
19089 if ("childNodes" in node2) {
19090 node2.childNodes.forEach(function(child) {
19091 _this.replaceIdOnNode(child, iframeEl);
19092 });
19093 }
19094 };
19095 _proto.patchRootIdOnNode = function patchRootIdOnNode(node2, rootId) {
19096 var _this = this;
19097 if (node2.type !== NodeType.Document && !node2.rootId) node2.rootId = rootId;
19098 if ("childNodes" in node2) {
19099 node2.childNodes.forEach(function(child) {
19100 _this.patchRootIdOnNode(child, rootId);
19101 });
19102 }
19103 };
19104 return IframeManager;
19105 }();
19106 var ShadowDomManager = /*#__PURE__*/ function() {
19107 function ShadowDomManager(options) {
19108 __publicField(this, "shadowDoms", /* @__PURE__ */ new WeakSet());
19109 __publicField(this, "mutationCb");
19110 __publicField(this, "scrollCb");
19111 __publicField(this, "bypassOptions");
19112 __publicField(this, "mirror");
19113 __publicField(this, "restoreHandlers", []);
19114 this.mutationCb = options.mutationCb;
19115 this.scrollCb = options.scrollCb;
19116 this.bypassOptions = options.bypassOptions;
19117 this.mirror = options.mirror;
19118 this.init();
19119 }
19120 var _proto = ShadowDomManager.prototype;
19121 _proto.init = function init() {
19122 this.reset();
19123 this.patchAttachShadow(Element, document);
19124 };
19125 _proto.addShadowRoot = function addShadowRoot(shadowRoot2, doc) {
19126 var _this = this;
19127 if (!isNativeShadowDom(shadowRoot2)) return;
19128 if (this.shadowDoms.has(shadowRoot2)) return;
19129 this.shadowDoms.add(shadowRoot2);
19130 var observer = initMutationObserver(_extends({}, this.bypassOptions, {
19131 doc: doc,
19132 mutationCb: this.mutationCb,
19133 mirror: this.mirror,
19134 shadowDomManager: this
19135 }), shadowRoot2);
19136 this.restoreHandlers.push(function() {
19137 return observer.disconnect();
19138 });
19139 this.restoreHandlers.push(initScrollObserver(_extends({}, this.bypassOptions, {
19140 scrollCb: this.scrollCb,
19141 // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813
19142 // scroll is not allowed to pass the boundary, so we need to listen the shadow document
19143 doc: shadowRoot2,
19144 mirror: this.mirror
19145 })));
19146 setTimeout(function() {
19147 if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0) _this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot2.adoptedStyleSheets, _this.mirror.getId(index.host(shadowRoot2)));
19148 _this.restoreHandlers.push(initAdoptedStyleSheetObserver({
19149 mirror: _this.mirror,
19150 stylesheetManager: _this.bypassOptions.stylesheetManager
19151 }, shadowRoot2));
19152 }, 0);
19153 };
19154 /**
19155 * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.
19156 */ _proto.observeAttachShadow = function observeAttachShadow(iframeElement) {
19157 if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;
19158 this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);
19159 };
19160 /**
19161 * Patch 'attachShadow' to observe newly added shadow doms.
19162 */ _proto.patchAttachShadow = function patchAttachShadow(element, doc) {
19163 var manager = this;
19164 this.restoreHandlers.push(patch(element.prototype, "attachShadow", function(original) {
19165 return function(option) {
19166 var sRoot = original.call(this, option);
19167 var shadowRootEl = index.shadowRoot(this);
19168 if (shadowRootEl && inDom(this)) manager.addShadowRoot(shadowRootEl, doc);
19169 return sRoot;
19170 };
19171 }));
19172 };
19173 _proto.reset = function reset() {
19174 this.restoreHandlers.forEach(function(handler) {
19175 try {
19176 handler();
19177 } catch (e2) {}
19178 });
19179 this.restoreHandlers = [];
19180 this.shadowDoms = /* @__PURE__ */ new WeakSet();
19181 };
19182 return ShadowDomManager;
19183 }();
19184 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
19185 var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
19186 for(var i$1 = 0; i$1 < chars.length; i$1++){
19187 lookup[chars.charCodeAt(i$1)] = i$1;
19188 }
19189 var encode = function encode(arraybuffer) {
19190 var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";
19191 for(i2 = 0; i2 < len; i2 += 3){
19192 base64 += chars[bytes[i2] >> 2];
19193 base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
19194 base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
19195 base64 += chars[bytes[i2 + 2] & 63];
19196 }
19197 if (len % 3 === 2) {
19198 base64 = base64.substring(0, base64.length - 1) + "=";
19199 } else if (len % 3 === 1) {
19200 base64 = base64.substring(0, base64.length - 2) + "==";
19201 }
19202 return base64;
19203 };
19204 var canvasVarMap = /* @__PURE__ */ new Map();
19205 function variableListFor$1(ctx, ctor) {
19206 var contextMap = canvasVarMap.get(ctx);
19207 if (!contextMap) {
19208 contextMap = /* @__PURE__ */ new Map();
19209 canvasVarMap.set(ctx, contextMap);
19210 }
19211 if (!contextMap.has(ctor)) {
19212 contextMap.set(ctor, []);
19213 }
19214 return contextMap.get(ctor);
19215 }
19216 var saveWebGLVar = function(value, win, ctx) {
19217 if (!value || !(isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object")) return;
19218 var name = value.constructor.name;
19219 var list2 = variableListFor$1(ctx, name);
19220 var index2 = list2.indexOf(value);
19221 if (index2 === -1) {
19222 index2 = list2.length;
19223 list2.push(value);
19224 }
19225 return index2;
19226 };
19227 function serializeArg(value, win, ctx) {
19228 if (_instanceof(value, Array)) {
19229 return value.map(function(arg) {
19230 return serializeArg(arg, win, ctx);
19231 });
19232 } else if (value === null) {
19233 return value;
19234 } 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)) {
19235 var name = value.constructor.name;
19236 return {
19237 rr_type: name,
19238 args: [
19239 Object.values(value)
19240 ]
19241 };
19242 } else if (// SharedArrayBuffer disabled on most browsers due to spectre.
19243 // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer
19244 // value instanceof SharedArrayBuffer ||
19245 _instanceof(value, ArrayBuffer)) {
19246 var name1 = value.constructor.name;
19247 var base64 = encode(value);
19248 return {
19249 rr_type: name1,
19250 base64: base64
19251 };
19252 } else if (_instanceof(value, DataView)) {
19253 var name2 = value.constructor.name;
19254 return {
19255 rr_type: name2,
19256 args: [
19257 serializeArg(value.buffer, win, ctx),
19258 value.byteOffset,
19259 value.byteLength
19260 ]
19261 };
19262 } else if (_instanceof(value, HTMLImageElement)) {
19263 var name3 = value.constructor.name;
19264 var src = value.src;
19265 return {
19266 rr_type: name3,
19267 src: src
19268 };
19269 } else if (_instanceof(value, HTMLCanvasElement)) {
19270 var name4 = "HTMLImageElement";
19271 var src1 = value.toDataURL();
19272 return {
19273 rr_type: name4,
19274 src: src1
19275 };
19276 } else if (_instanceof(value, ImageData)) {
19277 var name5 = value.constructor.name;
19278 return {
19279 rr_type: name5,
19280 args: [
19281 serializeArg(value.data, win, ctx),
19282 value.width,
19283 value.height
19284 ]
19285 };
19286 } else if (isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") {
19287 var name6 = value.constructor.name;
19288 var index2 = saveWebGLVar(value, win, ctx);
19289 return {
19290 rr_type: name6,
19291 index: index2
19292 };
19293 }
19294 return value;
19295 }
19296 var serializeArgs = function(args, win, ctx) {
19297 return args.map(function(arg) {
19298 return serializeArg(arg, win, ctx);
19299 });
19300 };
19301 var isInstanceOfWebGLObject = function(value, win) {
19302 var webGLConstructorNames = [
19303 "WebGLActiveInfo",
19304 "WebGLBuffer",
19305 "WebGLFramebuffer",
19306 "WebGLProgram",
19307 "WebGLRenderbuffer",
19308 "WebGLShader",
19309 "WebGLShaderPrecisionFormat",
19310 "WebGLTexture",
19311 "WebGLUniformLocation",
19312 "WebGLVertexArrayObject",
19313 // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.
19314 "WebGLVertexArrayObjectOES"
19315 ];
19316 var supportedWebGLConstructorNames = webGLConstructorNames.filter(function(name) {
19317 return typeof win[name] === "function";
19318 });
19319 return Boolean(supportedWebGLConstructorNames.find(function(name) {
19320 return _instanceof(value, win[name]);
19321 }));
19322 };
19323 function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
19324 var _loop = function() {
19325 var prop = _step.value;
19326 try {
19327 if (typeof win.CanvasRenderingContext2D.prototype[prop] !== "function") {
19328 return "continue";
19329 }
19330 var restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function(original) {
19331 return function() {
19332 var _this = this;
19333 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
19334 args[_key] = arguments[_key];
19335 }
19336 if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
19337 setTimeout(function() {
19338 var recordArgs = serializeArgs(args, win, _this);
19339 cb(_this.canvas, {
19340 type: CanvasContext["2D"],
19341 property: prop,
19342 args: recordArgs
19343 });
19344 }, 0);
19345 }
19346 return original.apply(this, args);
19347 };
19348 });
19349 handlers.push(restoreHandler);
19350 } catch (e) {
19351 var hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
19352 set: function set(v2) {
19353 cb(this.canvas, {
19354 type: CanvasContext["2D"],
19355 property: prop,
19356 args: [
19357 v2
19358 ],
19359 setter: true
19360 });
19361 }
19362 });
19363 handlers.push(hookHandler);
19364 }
19365 };
19366 var handlers = [];
19367 var props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
19368 for(var _iterator = _create_for_of_iterator_helper_loose(props2D), _step; !(_step = _iterator()).done;)_loop();
19369 return function() {
19370 handlers.forEach(function(h) {
19371 return h();
19372 });
19373 };
19374 }
19375 function getNormalizedContextName(contextType) {
19376 return contextType === "experimental-webgl" ? "webgl" : contextType;
19377 }
19378 function initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {
19379 var handlers = [];
19380 try {
19381 var restoreHandler = patch(win.HTMLCanvasElement.prototype, "getContext", function(original) {
19382 return function(contextType) {
19383 for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
19384 args[_key - 1] = arguments[_key];
19385 }
19386 if (!isBlocked(this, blockClass, blockSelector, true)) {
19387 var ctxName = getNormalizedContextName(contextType);
19388 if (!("__context" in this)) this.__context = ctxName;
19389 if (setPreserveDrawingBufferToTrue && [
19390 "webgl",
19391 "webgl2"
19392 ].includes(ctxName)) {
19393 if (args[0] && _type_of(args[0]) === "object") {
19394 var contextAttributes = args[0];
19395 if (!contextAttributes.preserveDrawingBuffer) {
19396 contextAttributes.preserveDrawingBuffer = true;
19397 }
19398 } else {
19399 args.splice(0, 1, {
19400 preserveDrawingBuffer: true
19401 });
19402 }
19403 }
19404 }
19405 return original.apply(this, [].concat([
19406 contextType
19407 ], args));
19408 };
19409 });
19410 handlers.push(restoreHandler);
19411 } catch (e) {
19412 console.error("failed to patch HTMLCanvasElement.prototype.getContext");
19413 }
19414 return function() {
19415 handlers.forEach(function(h) {
19416 return h();
19417 });
19418 };
19419 }
19420 function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win) {
19421 var _loop = function() {
19422 var prop = _step.value;
19423 if (//prop.startsWith('get') || // e.g. getProgramParameter, but too risky
19424 [
19425 "isContextLost",
19426 "canvas",
19427 "drawingBufferWidth",
19428 "drawingBufferHeight"
19429 ].includes(prop)) {
19430 return "continue";
19431 }
19432 try {
19433 if (typeof prototype[prop] !== "function") {
19434 return "continue";
19435 }
19436 var restoreHandler = patch(prototype, prop, function(original) {
19437 return function() {
19438 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
19439 args[_key] = arguments[_key];
19440 }
19441 var result2 = original.apply(this, args);
19442 saveWebGLVar(result2, win, this);
19443 if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {
19444 var recordArgs = serializeArgs(args, win, this);
19445 var mutation = {
19446 type: type,
19447 property: prop,
19448 args: recordArgs
19449 };
19450 cb(this.canvas, mutation);
19451 }
19452 return result2;
19453 };
19454 });
19455 handlers.push(restoreHandler);
19456 } catch (e) {
19457 var hookHandler = hookSetter(prototype, prop, {
19458 set: function set(v2) {
19459 cb(this.canvas, {
19460 type: type,
19461 property: prop,
19462 args: [
19463 v2
19464 ],
19465 setter: true
19466 });
19467 }
19468 });
19469 handlers.push(hookHandler);
19470 }
19471 };
19472 var handlers = [];
19473 var props = Object.getOwnPropertyNames(prototype);
19474 for(var _iterator = _create_for_of_iterator_helper_loose(props), _step; !(_step = _iterator()).done;)_loop();
19475 return handlers;
19476 }
19477 function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector) {
19478 var _handlers;
19479 var handlers = [];
19480 (_handlers = handlers).push.apply(_handlers, [].concat(patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, win)));
19481 if (typeof win.WebGL2RenderingContext !== "undefined") {
19482 var _handlers1;
19483 (_handlers1 = handlers).push.apply(_handlers1, [].concat(patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, win)));
19484 }
19485 return function() {
19486 handlers.forEach(function(h) {
19487 return h();
19488 });
19489 };
19490 }
19491 var encodedJs = "KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=";
19492 var decodeBase64 = function(base64) {
19493 return Uint8Array.from(atob(base64), function(c2) {
19494 return c2.charCodeAt(0);
19495 });
19496 };
19497 var blob = typeof window !== "undefined" && window.Blob && new Blob([
19498 decodeBase64(encodedJs)
19499 ], {
19500 type: "text/javascript;charset=utf-8"
19501 });
19502 function WorkerWrapper(options) {
19503 var objURL;
19504 try {
19505 objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
19506 if (!objURL) throw "";
19507 var worker = new Worker(objURL, {
19508 name: options == null ? void 0 : options.name
19509 });
19510 worker.addEventListener("error", function() {
19511 (window.URL || window.webkitURL).revokeObjectURL(objURL);
19512 });
19513 return worker;
19514 } catch (e2) {
19515 return new Worker("data:text/javascript;base64," + encodedJs, {
19516 name: options == null ? void 0 : options.name
19517 });
19518 } finally{
19519 objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
19520 }
19521 }
19522 var CanvasManager = /*#__PURE__*/ function() {
19523 function CanvasManager(options) {
19524 var _this = this;
19525 __publicField(this, "pendingCanvasMutations", /* @__PURE__ */ new Map());
19526 __publicField(this, "rafStamps", {
19527 latestId: 0,
19528 invokeId: null
19529 });
19530 __publicField(this, "mirror");
19531 __publicField(this, "mutationCb");
19532 __publicField(this, "resetObservers");
19533 __publicField(this, "frozen", false);
19534 __publicField(this, "locked", false);
19535 __publicField(this, "processMutation", function(target, mutation) {
19536 var newFrame = _this.rafStamps.invokeId && _this.rafStamps.latestId !== _this.rafStamps.invokeId;
19537 if (newFrame || !_this.rafStamps.invokeId) _this.rafStamps.invokeId = _this.rafStamps.latestId;
19538 if (!_this.pendingCanvasMutations.has(target)) {
19539 _this.pendingCanvasMutations.set(target, []);
19540 }
19541 _this.pendingCanvasMutations.get(target).push(mutation);
19542 });
19543 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;
19544 this.mutationCb = options.mutationCb;
19545 this.mirror = options.mirror;
19546 if (recordCanvas && sampling === "all") this.initCanvasMutationObserver(win, blockClass, blockSelector);
19547 if (recordCanvas && typeof sampling === "number") this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
19548 dataURLOptions: dataURLOptions
19549 });
19550 }
19551 var _proto = CanvasManager.prototype;
19552 _proto.reset = function reset() {
19553 this.pendingCanvasMutations.clear();
19554 this.resetObservers && this.resetObservers();
19555 };
19556 _proto.freeze = function freeze() {
19557 this.frozen = true;
19558 };
19559 _proto.unfreeze = function unfreeze() {
19560 this.frozen = false;
19561 };
19562 _proto.lock = function lock() {
19563 this.locked = true;
19564 };
19565 _proto.unlock = function unlock() {
19566 this.locked = false;
19567 };
19568 _proto.initCanvasFPSObserver = function initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
19569 var _this = this;
19570 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, true);
19571 var snapshotInProgressMap = /* @__PURE__ */ new Map();
19572 var worker = new WorkerWrapper();
19573 worker.onmessage = function(e2) {
19574 var id = e2.data.id;
19575 snapshotInProgressMap.set(id, false);
19576 if (!("base64" in e2.data)) return;
19577 var _e2_data = e2.data, base64 = _e2_data.base64, type = _e2_data.type, width = _e2_data.width, height = _e2_data.height;
19578 _this.mutationCb({
19579 id: id,
19580 type: CanvasContext["2D"],
19581 commands: [
19582 {
19583 property: "clearRect",
19584 // wipe canvas
19585 args: [
19586 0,
19587 0,
19588 width,
19589 height
19590 ]
19591 },
19592 {
19593 property: "drawImage",
19594 // draws (semi-transparent) image
19595 args: [
19596 {
19597 rr_type: "ImageBitmap",
19598 args: [
19599 {
19600 rr_type: "Blob",
19601 data: [
19602 {
19603 rr_type: "ArrayBuffer",
19604 base64: base64
19605 }
19606 ],
19607 type: type
19608 }
19609 ]
19610 },
19611 0,
19612 0
19613 ]
19614 }
19615 ]
19616 });
19617 };
19618 var timeBetweenSnapshots = 1e3 / fps;
19619 var lastSnapshotTime = 0;
19620 var rafId;
19621 var getCanvas = function() {
19622 var matchedCanvas = [];
19623 win.document.querySelectorAll("canvas").forEach(function(canvas) {
19624 if (!isBlocked(canvas, blockClass, blockSelector, true)) {
19625 matchedCanvas.push(canvas);
19626 }
19627 });
19628 return matchedCanvas;
19629 };
19630 var takeCanvasSnapshots = function(timestamp) {
19631 if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {
19632 rafId = requestAnimationFrame(takeCanvasSnapshots);
19633 return;
19634 }
19635 lastSnapshotTime = timestamp;
19636 var _this1 = _this;
19637 getCanvas().forEach(/*#__PURE__*/ _async_to_generator(function(canvas) {
19638 var _a2, id, context, bitmap;
19639 return _ts_generator(this, function(_state) {
19640 switch(_state.label){
19641 case 0:
19642 id = _this1.mirror.getId(canvas);
19643 if (snapshotInProgressMap.get(id)) return [
19644 2
19645 ];
19646 if (canvas.width === 0 || canvas.height === 0) return [
19647 2
19648 ];
19649 snapshotInProgressMap.set(id, true);
19650 if ([
19651 "webgl",
19652 "webgl2"
19653 ].includes(canvas.__context)) {
19654 context = canvas.getContext(canvas.__context);
19655 if (((_a2 = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _a2.preserveDrawingBuffer) === false) {
19656 context.clear(context.COLOR_BUFFER_BIT);
19657 }
19658 }
19659 return [
19660 4,
19661 createImageBitmap(canvas)
19662 ];
19663 case 1:
19664 bitmap = _state.sent();
19665 worker.postMessage({
19666 id: id,
19667 bitmap: bitmap,
19668 width: canvas.width,
19669 height: canvas.height,
19670 dataURLOptions: options.dataURLOptions
19671 }, [
19672 bitmap
19673 ]);
19674 return [
19675 2
19676 ];
19677 }
19678 });
19679 }));
19680 rafId = requestAnimationFrame(takeCanvasSnapshots);
19681 };
19682 rafId = requestAnimationFrame(takeCanvasSnapshots);
19683 this.resetObservers = function() {
19684 canvasContextReset();
19685 cancelAnimationFrame(rafId);
19686 };
19687 };
19688 _proto.initCanvasMutationObserver = function initCanvasMutationObserver(win, blockClass, blockSelector) {
19689 this.startRAFTimestamping();
19690 this.startPendingCanvasMutationFlusher();
19691 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, false);
19692 var canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
19693 var canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
19694 this.resetObservers = function() {
19695 canvasContextReset();
19696 canvas2DReset();
19697 canvasWebGL1and2Reset();
19698 };
19699 };
19700 _proto.startPendingCanvasMutationFlusher = function startPendingCanvasMutationFlusher() {
19701 var _this = this;
19702 requestAnimationFrame(function() {
19703 return _this.flushPendingCanvasMutations();
19704 });
19705 };
19706 _proto.startRAFTimestamping = function startRAFTimestamping() {
19707 var _this = this;
19708 var setLatestRAFTimestamp = function(timestamp) {
19709 _this.rafStamps.latestId = timestamp;
19710 requestAnimationFrame(setLatestRAFTimestamp);
19711 };
19712 requestAnimationFrame(setLatestRAFTimestamp);
19713 };
19714 _proto.flushPendingCanvasMutations = function flushPendingCanvasMutations() {
19715 var _this = this;
19716 this.pendingCanvasMutations.forEach(function(_values, canvas) {
19717 var id = _this.mirror.getId(canvas);
19718 _this.flushPendingCanvasMutationFor(canvas, id);
19719 });
19720 requestAnimationFrame(function() {
19721 return _this.flushPendingCanvasMutations();
19722 });
19723 };
19724 _proto.flushPendingCanvasMutationFor = function flushPendingCanvasMutationFor(canvas, id) {
19725 if (this.frozen || this.locked) {
19726 return;
19727 }
19728 var valuesWithType = this.pendingCanvasMutations.get(canvas);
19729 if (!valuesWithType || id === -1) return;
19730 var values = valuesWithType.map(function(value) {
19731 value.type; var rest = _object_without_properties_loose(value, [
19732 "type"
19733 ]);
19734 return rest;
19735 });
19736 var type = valuesWithType[0].type;
19737 this.mutationCb({
19738 id: id,
19739 type: type,
19740 commands: values
19741 });
19742 this.pendingCanvasMutations.delete(canvas);
19743 };
19744 return CanvasManager;
19745 }();
19746 var StylesheetManager = /*#__PURE__*/ function() {
19747 function StylesheetManager(options) {
19748 __publicField(this, "trackedLinkElements", /* @__PURE__ */ new WeakSet());
19749 __publicField(this, "mutationCb");
19750 __publicField(this, "adoptedStyleSheetCb");
19751 __publicField(this, "styleMirror", new StyleSheetMirror());
19752 this.mutationCb = options.mutationCb;
19753 this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
19754 }
19755 var _proto = StylesheetManager.prototype;
19756 _proto.attachLinkElement = function attachLinkElement(linkEl, childSn) {
19757 if ("_cssText" in childSn.attributes) this.mutationCb({
19758 adds: [],
19759 removes: [],
19760 texts: [],
19761 attributes: [
19762 {
19763 id: childSn.id,
19764 attributes: childSn.attributes
19765 }
19766 ]
19767 });
19768 this.trackLinkElement(linkEl);
19769 };
19770 _proto.trackLinkElement = function trackLinkElement(linkEl) {
19771 if (this.trackedLinkElements.has(linkEl)) return;
19772 this.trackedLinkElements.add(linkEl);
19773 this.trackStylesheetInLinkElement(linkEl);
19774 };
19775 _proto.adoptStyleSheets = function adoptStyleSheets(sheets, hostId) {
19776 var _this, _loop = function() {
19777 var sheet = _step.value;
19778 var styleId = void 0;
19779 if (!_this.styleMirror.has(sheet)) {
19780 styleId = _this.styleMirror.add(sheet);
19781 styles.push({
19782 styleId: styleId,
19783 rules: Array.from(sheet.rules || CSSRule, function(r2, index2) {
19784 return {
19785 rule: stringifyRule(r2, sheet.href),
19786 index: index2
19787 };
19788 })
19789 });
19790 } else styleId = _this.styleMirror.getId(sheet);
19791 adoptedStyleSheetData.styleIds.push(styleId);
19792 };
19793 if (sheets.length === 0) return;
19794 var adoptedStyleSheetData = {
19795 id: hostId,
19796 styleIds: []
19797 };
19798 var styles = [];
19799 for(var _iterator = _create_for_of_iterator_helper_loose(sheets), _step; !(_step = _iterator()).done;)_this = this, _loop();
19800 if (styles.length > 0) adoptedStyleSheetData.styles = styles;
19801 this.adoptedStyleSheetCb(adoptedStyleSheetData);
19802 };
19803 _proto.reset = function reset() {
19804 this.styleMirror.reset();
19805 this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
19806 };
19807 // TODO: take snapshot on stylesheet reload by applying event listener
19808 _proto.trackStylesheetInLinkElement = function trackStylesheetInLinkElement(_linkEl) {};
19809 return StylesheetManager;
19810 }();
19811 var ProcessedNodeManager = /*#__PURE__*/ function() {
19812 function ProcessedNodeManager() {
19813 __publicField(this, "nodeMap", /* @__PURE__ */ new WeakMap());
19814 __publicField(this, "active", false);
19815 }
19816 var _proto = ProcessedNodeManager.prototype;
19817 _proto.inOtherBuffer = function inOtherBuffer(node2, thisBuffer) {
19818 var buffers = this.nodeMap.get(node2);
19819 return buffers && Array.from(buffers).some(function(buffer) {
19820 return buffer !== thisBuffer;
19821 });
19822 };
19823 _proto.add = function add(node2, buffer) {
19824 var _this = this;
19825 if (!this.active) {
19826 this.active = true;
19827 requestAnimationFrame(function() {
19828 _this.nodeMap = /* @__PURE__ */ new WeakMap();
19829 _this.active = false;
19830 });
19831 }
19832 this.nodeMap.set(node2, (this.nodeMap.get(node2) || /* @__PURE__ */ new Set()).add(buffer));
19833 };
19834 _proto.destroy = function destroy() {};
19835 return ProcessedNodeManager;
19836 }();
19837 var wrappedEmit;
19838 var takeFullSnapshot$1;
19839 var canvasManager;
19840 var recording = false;
19841 try {
19842 if (Array.from([
19843 1
19844 ], function(x2) {
19845 return x2 * 2;
19846 })[0] !== 2) {
19847 var cleanFrame = document.createElement("iframe");
19848 document.body.appendChild(cleanFrame);
19849 Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;
19850 document.body.removeChild(cleanFrame);
19851 }
19852 } catch (err) {
19853 console.debug("Unable to override Array.from", err);
19854 }
19855 var mirror = createMirror$2();
19856 function record(options) {
19857 if (options === void 0) options = {};
19858 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() {
19859 return false;
19860 } : _options_keepIframeSrcFn, _options_ignoreCSSAttributes = options.ignoreCSSAttributes, ignoreCSSAttributes = _options_ignoreCSSAttributes === void 0 ? /* @__PURE__ */ new Set([]) : _options_ignoreCSSAttributes, errorHandler2 = options.errorHandler;
19861 registerErrorHandler(errorHandler2);
19862 var inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
19863 var passEmitsToParent = false;
19864 if (!inEmittingFrame) {
19865 try {
19866 if (window.parent.document) {
19867 passEmitsToParent = false;
19868 }
19869 } catch (e2) {
19870 passEmitsToParent = true;
19871 }
19872 }
19873 if (inEmittingFrame && !emit) {
19874 throw new Error("emit function is required");
19875 }
19876 if (!inEmittingFrame && !passEmitsToParent) {
19877 return function() {};
19878 }
19879 if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {
19880 sampling.mousemove = mousemoveWait;
19881 }
19882 mirror.reset();
19883 var maskInputOptions = maskAllInputs === true ? {
19884 color: true,
19885 date: true,
19886 "datetime-local": true,
19887 email: true,
19888 month: true,
19889 number: true,
19890 range: true,
19891 search: true,
19892 tel: true,
19893 text: true,
19894 time: true,
19895 url: true,
19896 week: true,
19897 textarea: true,
19898 select: true,
19899 password: true,
19900 hidden: true
19901 } : _maskInputOptions !== void 0 ? _maskInputOptions : {
19902 password: true
19903 };
19904 var slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? {
19905 script: true,
19906 comment: true,
19907 headFavicon: true,
19908 headWhitespace: true,
19909 headMetaSocial: true,
19910 headMetaRobots: true,
19911 headMetaHttpEquiv: true,
19912 headMetaVerification: true,
19913 // the following are off for slimDOMOptions === true,
19914 // as they destroy some (hidden) info:
19915 headMetaAuthorship: _slimDOMOptions === "all",
19916 headMetaDescKeywords: _slimDOMOptions === "all",
19917 headTitleMutations: _slimDOMOptions === "all"
19918 } : _slimDOMOptions ? _slimDOMOptions : {};
19919 polyfill$1();
19920 var lastFullSnapshotEvent;
19921 var incrementalSnapshotCount = 0;
19922 var eventProcessor = function(e2) {
19923 for(var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;){
19924 var plugin3 = _step.value;
19925 if (plugin3.eventProcessor) {
19926 e2 = plugin3.eventProcessor(e2);
19927 }
19928 }
19929 if (packFn && // Disable packing events which will be emitted to parent frames.
19930 !passEmitsToParent) {
19931 e2 = packFn(e2);
19932 }
19933 return e2;
19934 };
19935 wrappedEmit = function(r2, isCheckout) {
19936 var _a2;
19937 var e2 = r2;
19938 e2.timestamp = nowTimestamp();
19939 if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) {
19940 mutationBuffers.forEach(function(buf) {
19941 return buf.unfreeze();
19942 });
19943 }
19944 if (inEmittingFrame) {
19945 emit == null ? void 0 : emit(eventProcessor(e2), isCheckout);
19946 } else if (passEmitsToParent) {
19947 var message = {
19948 type: "rrweb",
19949 event: eventProcessor(e2),
19950 origin: window.location.origin,
19951 isCheckout: isCheckout
19952 };
19953 window.parent.postMessage(message, "*");
19954 }
19955 if (e2.type === EventType.FullSnapshot) {
19956 lastFullSnapshotEvent = e2;
19957 incrementalSnapshotCount = 0;
19958 } else if (e2.type === EventType.IncrementalSnapshot) {
19959 if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) {
19960 return;
19961 }
19962 incrementalSnapshotCount++;
19963 var exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
19964 var exceedTime = checkoutEveryNms && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
19965 if (exceedCount || exceedTime) {
19966 takeFullSnapshot$1(true);
19967 }
19968 }
19969 };
19970 var wrappedMutationEmit = function(m) {
19971 wrappedEmit({
19972 type: EventType.IncrementalSnapshot,
19973 data: _extends({
19974 source: IncrementalSource.Mutation
19975 }, m)
19976 });
19977 };
19978 var wrappedScrollEmit = function(p) {
19979 return wrappedEmit({
19980 type: EventType.IncrementalSnapshot,
19981 data: _extends({
19982 source: IncrementalSource.Scroll
19983 }, p)
19984 });
19985 };
19986 var wrappedCanvasMutationEmit = function(p) {
19987 return wrappedEmit({
19988 type: EventType.IncrementalSnapshot,
19989 data: _extends({
19990 source: IncrementalSource.CanvasMutation
19991 }, p)
19992 });
19993 };
19994 var wrappedAdoptedStyleSheetEmit = function(a2) {
19995 return wrappedEmit({
19996 type: EventType.IncrementalSnapshot,
19997 data: _extends({
19998 source: IncrementalSource.AdoptedStyleSheet
19999 }, a2)
20000 });
20001 };
20002 var stylesheetManager = new StylesheetManager({
20003 mutationCb: wrappedMutationEmit,
20004 adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
20005 });
20006 var iframeManager = new IframeManager({
20007 mirror: mirror,
20008 mutationCb: wrappedMutationEmit,
20009 stylesheetManager: stylesheetManager,
20010 recordCrossOriginIframes: recordCrossOriginIframes,
20011 wrappedEmit: wrappedEmit
20012 });
20013 for(var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;){
20014 var plugin3 = _step.value;
20015 if (plugin3.getMirror) plugin3.getMirror({
20016 nodeMirror: mirror,
20017 crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
20018 crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
20019 });
20020 }
20021 var processedNodeManager = new ProcessedNodeManager();
20022 canvasManager = new CanvasManager({
20023 recordCanvas: recordCanvas,
20024 mutationCb: wrappedCanvasMutationEmit,
20025 win: window,
20026 blockClass: blockClass,
20027 blockSelector: blockSelector,
20028 mirror: mirror,
20029 sampling: sampling.canvas,
20030 dataURLOptions: dataURLOptions
20031 });
20032 var shadowDomManager = new ShadowDomManager({
20033 mutationCb: wrappedMutationEmit,
20034 scrollCb: wrappedScrollEmit,
20035 bypassOptions: {
20036 blockClass: blockClass,
20037 blockSelector: blockSelector,
20038 maskTextClass: maskTextClass,
20039 maskTextSelector: maskTextSelector,
20040 inlineStylesheet: inlineStylesheet,
20041 maskInputOptions: maskInputOptions,
20042 dataURLOptions: dataURLOptions,
20043 maskTextFn: maskTextFn,
20044 maskInputFn: maskInputFn,
20045 recordCanvas: recordCanvas,
20046 inlineImages: inlineImages,
20047 sampling: sampling,
20048 slimDOMOptions: slimDOMOptions,
20049 iframeManager: iframeManager,
20050 stylesheetManager: stylesheetManager,
20051 canvasManager: canvasManager,
20052 keepIframeSrcFn: keepIframeSrcFn,
20053 processedNodeManager: processedNodeManager
20054 },
20055 mirror: mirror
20056 });
20057 takeFullSnapshot$1 = function(isCheckout) {
20058 if (isCheckout === void 0) isCheckout = false;
20059 if (!recordDOM) {
20060 return;
20061 }
20062 wrappedEmit({
20063 type: EventType.Meta,
20064 data: {
20065 href: window.location.href,
20066 width: getWindowWidth(),
20067 height: getWindowHeight()
20068 }
20069 }, isCheckout);
20070 stylesheetManager.reset();
20071 shadowDomManager.init();
20072 mutationBuffers.forEach(function(buf) {
20073 return buf.lock();
20074 });
20075 var node2 = snapshot(document, {
20076 mirror: mirror,
20077 blockClass: blockClass,
20078 blockSelector: blockSelector,
20079 maskTextClass: maskTextClass,
20080 maskTextSelector: maskTextSelector,
20081 inlineStylesheet: inlineStylesheet,
20082 maskAllInputs: maskInputOptions,
20083 maskTextFn: maskTextFn,
20084 maskInputFn: maskInputFn,
20085 slimDOM: slimDOMOptions,
20086 dataURLOptions: dataURLOptions,
20087 recordCanvas: recordCanvas,
20088 inlineImages: inlineImages,
20089 onSerialize: function(n2) {
20090 if (isSerializedIframe(n2, mirror)) {
20091 iframeManager.addIframe(n2);
20092 }
20093 if (isSerializedStylesheet(n2, mirror)) {
20094 stylesheetManager.trackLinkElement(n2);
20095 }
20096 if (hasShadowRoot(n2)) {
20097 shadowDomManager.addShadowRoot(index.shadowRoot(n2), document);
20098 }
20099 },
20100 onIframeLoad: function(iframe, childSn) {
20101 iframeManager.attachIframe(iframe, childSn);
20102 shadowDomManager.observeAttachShadow(iframe);
20103 },
20104 onStylesheetLoad: function(linkEl, childSn) {
20105 stylesheetManager.attachLinkElement(linkEl, childSn);
20106 },
20107 keepIframeSrcFn: keepIframeSrcFn
20108 });
20109 if (!node2) {
20110 return console.warn("Failed to snapshot the document");
20111 }
20112 wrappedEmit({
20113 type: EventType.FullSnapshot,
20114 data: {
20115 node: node2,
20116 initialOffset: getWindowScroll(window)
20117 }
20118 }, isCheckout);
20119 mutationBuffers.forEach(function(buf) {
20120 return buf.unlock();
20121 });
20122 if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
20123 };
20124 try {
20125 var handlers = [];
20126 var observe = function(doc) {
20127 var _a2;
20128 return callbackWrapper(initObservers)({
20129 mutationCb: wrappedMutationEmit,
20130 mousemoveCb: function(positions, source) {
20131 return wrappedEmit({
20132 type: EventType.IncrementalSnapshot,
20133 data: {
20134 source: source,
20135 positions: positions
20136 }
20137 });
20138 },
20139 mouseInteractionCb: function(d) {
20140 return wrappedEmit({
20141 type: EventType.IncrementalSnapshot,
20142 data: _extends({
20143 source: IncrementalSource.MouseInteraction
20144 }, d)
20145 });
20146 },
20147 scrollCb: wrappedScrollEmit,
20148 viewportResizeCb: function(d) {
20149 return wrappedEmit({
20150 type: EventType.IncrementalSnapshot,
20151 data: _extends({
20152 source: IncrementalSource.ViewportResize
20153 }, d)
20154 });
20155 },
20156 inputCb: function(v2) {
20157 return wrappedEmit({
20158 type: EventType.IncrementalSnapshot,
20159 data: _extends({
20160 source: IncrementalSource.Input
20161 }, v2)
20162 });
20163 },
20164 mediaInteractionCb: function(p) {
20165 return wrappedEmit({
20166 type: EventType.IncrementalSnapshot,
20167 data: _extends({
20168 source: IncrementalSource.MediaInteraction
20169 }, p)
20170 });
20171 },
20172 styleSheetRuleCb: function(r2) {
20173 return wrappedEmit({
20174 type: EventType.IncrementalSnapshot,
20175 data: _extends({
20176 source: IncrementalSource.StyleSheetRule
20177 }, r2)
20178 });
20179 },
20180 styleDeclarationCb: function(r2) {
20181 return wrappedEmit({
20182 type: EventType.IncrementalSnapshot,
20183 data: _extends({
20184 source: IncrementalSource.StyleDeclaration
20185 }, r2)
20186 });
20187 },
20188 canvasMutationCb: wrappedCanvasMutationEmit,
20189 fontCb: function(p) {
20190 return wrappedEmit({
20191 type: EventType.IncrementalSnapshot,
20192 data: _extends({
20193 source: IncrementalSource.Font
20194 }, p)
20195 });
20196 },
20197 selectionCb: function(p) {
20198 wrappedEmit({
20199 type: EventType.IncrementalSnapshot,
20200 data: _extends({
20201 source: IncrementalSource.Selection
20202 }, p)
20203 });
20204 },
20205 customElementCb: function(c2) {
20206 wrappedEmit({
20207 type: EventType.IncrementalSnapshot,
20208 data: _extends({
20209 source: IncrementalSource.CustomElement
20210 }, c2)
20211 });
20212 },
20213 blockClass: blockClass,
20214 ignoreClass: ignoreClass,
20215 ignoreSelector: ignoreSelector,
20216 maskTextClass: maskTextClass,
20217 maskTextSelector: maskTextSelector,
20218 maskInputOptions: maskInputOptions,
20219 inlineStylesheet: inlineStylesheet,
20220 sampling: sampling,
20221 recordDOM: recordDOM,
20222 recordCanvas: recordCanvas,
20223 inlineImages: inlineImages,
20224 userTriggeredOnInput: userTriggeredOnInput,
20225 collectFonts: collectFonts,
20226 doc: doc,
20227 maskInputFn: maskInputFn,
20228 maskTextFn: maskTextFn,
20229 keepIframeSrcFn: keepIframeSrcFn,
20230 blockSelector: blockSelector,
20231 slimDOMOptions: slimDOMOptions,
20232 dataURLOptions: dataURLOptions,
20233 mirror: mirror,
20234 iframeManager: iframeManager,
20235 stylesheetManager: stylesheetManager,
20236 shadowDomManager: shadowDomManager,
20237 processedNodeManager: processedNodeManager,
20238 canvasManager: canvasManager,
20239 ignoreCSSAttributes: ignoreCSSAttributes,
20240 plugins: ((_a2 = plugins == null ? void 0 : plugins.filter(function(p) {
20241 return p.observer;
20242 })) == null ? void 0 : _a2.map(function(p) {
20243 return {
20244 observer: p.observer,
20245 options: p.options,
20246 callback: function(payload) {
20247 return wrappedEmit({
20248 type: EventType.Plugin,
20249 data: {
20250 plugin: p.name,
20251 payload: payload
20252 }
20253 });
20254 }
20255 };
20256 })) || []
20257 }, hooks);
20258 };
20259 iframeManager.addLoadListener(function(iframeEl) {
20260 try {
20261 handlers.push(observe(iframeEl.contentDocument));
20262 } catch (error) {
20263 console.warn(error);
20264 }
20265 });
20266 var init = function() {
20267 takeFullSnapshot$1();
20268 handlers.push(observe(document));
20269 recording = true;
20270 };
20271 if (document.readyState === "interactive" || document.readyState === "complete") {
20272 init();
20273 } else {
20274 handlers.push(on("DOMContentLoaded", function() {
20275 wrappedEmit({
20276 type: EventType.DomContentLoaded,
20277 data: {}
20278 });
20279 if (recordAfter === "DOMContentLoaded") init();
20280 }));
20281 handlers.push(on("load", function() {
20282 wrappedEmit({
20283 type: EventType.Load,
20284 data: {}
20285 });
20286 if (recordAfter === "load") init();
20287 }, window));
20288 }
20289 return function() {
20290 handlers.forEach(function(handler) {
20291 try {
20292 handler();
20293 } catch (error) {
20294 var msg = String(error).toLowerCase();
20295 if (!msg.includes("cross-origin")) {
20296 console.warn(error);
20297 }
20298 }
20299 });
20300 processedNodeManager.destroy();
20301 recording = false;
20302 unregisterErrorHandler();
20303 };
20304 } catch (error) {
20305 console.warn(error);
20306 }
20307 }
20308 record.addCustomEvent = function(tag, payload) {
20309 if (!recording) {
20310 throw new Error("please add custom event after start recording");
20311 }
20312 wrappedEmit({
20313 type: EventType.Custom,
20314 data: {
20315 tag: tag,
20316 payload: payload
20317 }
20318 });
20319 };
20320 record.freezePage = function() {
20321 mutationBuffers.forEach(function(buf) {
20322 return buf.freeze();
20323 });
20324 };
20325 record.takeFullSnapshot = function(isCheckout) {
20326 if (!recording) {
20327 throw new Error("please take full snapshot after start recording");
20328 }
20329 takeFullSnapshot$1(isCheckout);
20330 };
20331 record.mirror = mirror;
20332 var n;
20333 !function(t2) {
20334 t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped";
20335 }(n || (n = {}));
20336 record.addCustomEvent;
20337 record.freezePage;
20338 record.takeFullSnapshot;
20339
20340 var setImmediate = win['setImmediate'];
20341 var builtInProp, cycle, schedulingQueue,
20342 ToString = Object.prototype.toString,
20343 timer = (typeof setImmediate !== 'undefined') ?
20344 function timer(fn) { return setImmediate(fn); } :
20345 setTimeout;
20346
20347 // dammit, IE8.
20348 try {
20349 Object.defineProperty({},'x',{});
20350 builtInProp = function builtInProp(obj,name,val,config) {
20351 return Object.defineProperty(obj,name,{
20352 value: val,
20353 writable: true,
20354 configurable: config !== false
20355 });
20356 };
20357 }
20358 catch (err) {
20359 builtInProp = function builtInProp(obj,name,val) {
20360 obj[name] = val;
20361 return obj;
20362 };
20363 }
20364
20365 // Note: using a queue instead of array for efficiency
20366 schedulingQueue = (function Queue() {
20367 var first, last, item;
20368
20369 function Item(fn,self) {
20370 this.fn = fn;
20371 this.self = self;
20372 this.next = void 0;
20373 }
20374
20375 return {
20376 add: function add(fn,self) {
20377 item = new Item(fn,self);
20378 if (last) {
20379 last.next = item;
20380 }
20381 else {
20382 first = item;
20383 }
20384 last = item;
20385 item = void 0;
20386 },
20387 drain: function drain() {
20388 var f = first;
20389 first = last = cycle = void 0;
20390
20391 while (f) {
20392 f.fn.call(f.self);
20393 f = f.next;
20394 }
20395 }
20396 };
20397 })();
20398
20399 function schedule(fn,self) {
20400 schedulingQueue.add(fn,self);
20401 if (!cycle) {
20402 cycle = timer(schedulingQueue.drain);
20403 }
20404 }
20405
20406 // promise duck typing
20407 function isThenable(o) {
20408 var _then, oType = typeof o;
20409
20410 if (o !== null && (oType === 'object' || oType === 'function')) {
20411 _then = o.then;
20412 }
20413 return typeof _then === 'function' ? _then : false;
20414 }
20415
20416 function notify() {
20417 for (var i=0; i<this.chain.length; i++) {
20418 notifyIsolated(
20419 this,
20420 (this.state === 1) ? this.chain[i].success : this.chain[i].failure,
20421 this.chain[i]
20422 );
20423 }
20424 this.chain.length = 0;
20425 }
20426
20427 // NOTE: This is a separate function to isolate
20428 // the `try..catch` so that other code can be
20429 // optimized better
20430 function notifyIsolated(self,cb,chain) {
20431 var ret, _then;
20432 try {
20433 if (cb === false) {
20434 chain.reject(self.msg);
20435 }
20436 else {
20437 if (cb === true) {
20438 ret = self.msg;
20439 }
20440 else {
20441 ret = cb.call(void 0,self.msg);
20442 }
20443
20444 if (ret === chain.promise) {
20445 chain.reject(TypeError('Promise-chain cycle'));
20446 }
20447 // eslint-disable-next-line no-cond-assign
20448 else if (_then = isThenable(ret)) {
20449 _then.call(ret,chain.resolve,chain.reject);
20450 }
20451 else {
20452 chain.resolve(ret);
20453 }
20454 }
20455 }
20456 catch (err) {
20457 chain.reject(err);
20458 }
20459 }
20460
20461 function resolve(msg) {
20462 var _then, self = this;
20463
20464 // already triggered?
20465 if (self.triggered) { return; }
20466
20467 self.triggered = true;
20468
20469 // unwrap
20470 if (self.def) {
20471 self = self.def;
20472 }
20473
20474 try {
20475 // eslint-disable-next-line no-cond-assign
20476 if (_then = isThenable(msg)) {
20477 schedule(function(){
20478 var defWrapper = new MakeDefWrapper(self);
20479 try {
20480 _then.call(msg,
20481 function $resolve$(){ resolve.apply(defWrapper,arguments); },
20482 function $reject$(){ reject.apply(defWrapper,arguments); }
20483 );
20484 }
20485 catch (err) {
20486 reject.call(defWrapper,err);
20487 }
20488 });
20489 }
20490 else {
20491 self.msg = msg;
20492 self.state = 1;
20493 if (self.chain.length > 0) {
20494 schedule(notify,self);
20495 }
20496 }
20497 }
20498 catch (err) {
20499 reject.call(new MakeDefWrapper(self),err);
20500 }
20501 }
20502
20503 function reject(msg) {
20504 var self = this;
20505
20506 // already triggered?
20507 if (self.triggered) { return; }
20508
20509 self.triggered = true;
20510
20511 // unwrap
20512 if (self.def) {
20513 self = self.def;
20514 }
20515
20516 self.msg = msg;
20517 self.state = 2;
20518 if (self.chain.length > 0) {
20519 schedule(notify,self);
20520 }
20521 }
20522
20523 function iteratePromises(Constructor,arr,resolver,rejecter) {
20524 for (var idx=0; idx<arr.length; idx++) {
20525 (function IIFE(idx){
20526 Constructor.resolve(arr[idx])
20527 .then(
20528 function $resolver$(msg){
20529 resolver(idx,msg);
20530 },
20531 rejecter
20532 );
20533 })(idx);
20534 }
20535 }
20536
20537 function MakeDefWrapper(self) {
20538 this.def = self;
20539 this.triggered = false;
20540 }
20541
20542 function MakeDef(self) {
20543 this.promise = self;
20544 this.state = 0;
20545 this.triggered = false;
20546 this.chain = [];
20547 this.msg = void 0;
20548 }
20549
20550 function NpoPromise(executor) {
20551 if (typeof executor !== 'function') {
20552 throw TypeError('Not a function');
20553 }
20554
20555 if (this['__NPO__'] !== 0) {
20556 throw TypeError('Not a promise');
20557 }
20558
20559 // instance shadowing the inherited "brand"
20560 // to signal an already "initialized" promise
20561 this['__NPO__'] = 1;
20562
20563 var def = new MakeDef(this);
20564
20565 this['then'] = function then(success,failure) {
20566 var o = {
20567 success: typeof success === 'function' ? success : true,
20568 failure: typeof failure === 'function' ? failure : false
20569 };
20570 // Note: `then(..)` itself can be borrowed to be used against
20571 // a different promise constructor for making the chained promise,
20572 // by substituting a different `this` binding.
20573 o.promise = new this.constructor(function extractChain(resolve,reject) {
20574 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20575 throw TypeError('Not a function');
20576 }
20577
20578 o.resolve = resolve;
20579 o.reject = reject;
20580 });
20581 def.chain.push(o);
20582
20583 if (def.state !== 0) {
20584 schedule(notify,def);
20585 }
20586
20587 return o.promise;
20588 };
20589 this['catch'] = function $catch$(failure) {
20590 return this.then(void 0,failure);
20591 };
20592
20593 try {
20594 executor.call(
20595 void 0,
20596 function publicResolve(msg){
20597 resolve.call(def,msg);
20598 },
20599 function publicReject(msg) {
20600 reject.call(def,msg);
20601 }
20602 );
20603 }
20604 catch (err) {
20605 reject.call(def,err);
20606 }
20607 }
20608
20609 var PromisePrototype = builtInProp({},'constructor',NpoPromise,
20610 /*configurable=*/false
20611 );
20612
20613 // Note: Android 4 cannot use `Object.defineProperty(..)` here
20614 NpoPromise.prototype = PromisePrototype;
20615
20616 // built-in "brand" to signal an "uninitialized" promise
20617 builtInProp(PromisePrototype,'__NPO__',0,
20618 /*configurable=*/false
20619 );
20620
20621 builtInProp(NpoPromise,'resolve',function Promise$resolve(msg) {
20622 var Constructor = this;
20623
20624 // spec mandated checks
20625 // note: best "isPromise" check that's practical for now
20626 if (msg && typeof msg === 'object' && msg['__NPO__'] === 1) {
20627 return msg;
20628 }
20629
20630 return new Constructor(function executor(resolve,reject){
20631 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20632 throw TypeError('Not a function');
20633 }
20634
20635 resolve(msg);
20636 });
20637 });
20638
20639 builtInProp(NpoPromise,'reject',function Promise$reject(msg) {
20640 return new this(function executor(resolve,reject){
20641 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20642 throw TypeError('Not a function');
20643 }
20644
20645 reject(msg);
20646 });
20647 });
20648
20649 builtInProp(NpoPromise,'all',function Promise$all(arr) {
20650 var Constructor = this;
20651
20652 // spec mandated checks
20653 if (ToString.call(arr) !== '[object Array]') {
20654 return Constructor.reject(TypeError('Not an array'));
20655 }
20656 if (arr.length === 0) {
20657 return Constructor.resolve([]);
20658 }
20659
20660 return new Constructor(function executor(resolve,reject){
20661 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20662 throw TypeError('Not a function');
20663 }
20664
20665 var len = arr.length, msgs = Array(len), count = 0;
20666
20667 iteratePromises(Constructor,arr,function resolver(idx,msg) {
20668 msgs[idx] = msg;
20669 if (++count === len) {
20670 resolve(msgs);
20671 }
20672 },reject);
20673 });
20674 });
20675
20676 builtInProp(NpoPromise,'race',function Promise$race(arr) {
20677 var Constructor = this;
20678
20679 // spec mandated checks
20680 if (ToString.call(arr) !== '[object Array]') {
20681 return Constructor.reject(TypeError('Not an array'));
20682 }
20683
20684 return new Constructor(function executor(resolve,reject){
20685 if (typeof resolve !== 'function' || typeof reject !== 'function') {
20686 throw TypeError('Not a function');
20687 }
20688
20689 iteratePromises(Constructor,arr,function resolver(idx,msg){
20690 resolve(msg);
20691 },reject);
20692 });
20693 });
20694
20695 var PromisePolyfill;
20696 if (typeof Promise !== 'undefined' && Promise.toString().indexOf('[native code]') !== -1) {
20697 PromisePolyfill = Promise;
20698 } else {
20699 PromisePolyfill = NpoPromise;
20700 }
20701
20702 var Config = {
20703 DEBUG: false,
20704 LIB_VERSION: '2.71.1'
20705 };
20706
20707 /* eslint camelcase: "off", eqeqeq: "off" */
20708
20709 // Maximum allowed session recording length
20710 var MAX_RECORDING_MS = 24 * 60 * 60 * 1000; // 24 hours
20711 // Maximum allowed value for minimum session recording length
20712 var MAX_VALUE_FOR_MIN_RECORDING_MS = 8 * 1000; // 8 seconds
20713
20714 /*
20715 * Saved references to long variable names, so that closure compiler can
20716 * minimize file size.
20717 */
20718
20719 var ArrayProto = Array.prototype,
20720 FuncProto = Function.prototype,
20721 ObjProto = Object.prototype,
20722 slice = ArrayProto.slice,
20723 toString = ObjProto.toString,
20724 hasOwnProperty = ObjProto.hasOwnProperty,
20725 windowConsole = win.console,
20726 navigator = win.navigator,
20727 document$1 = win.document,
20728 windowOpera = win.opera,
20729 screen = win.screen,
20730 userAgent = navigator.userAgent;
20731
20732 var nativeBind = FuncProto.bind,
20733 nativeForEach = ArrayProto.forEach,
20734 nativeIndexOf = ArrayProto.indexOf,
20735 nativeMap = ArrayProto.map,
20736 nativeIsArray = Array.isArray,
20737 breaker = {};
20738
20739 var _ = {
20740 trim: function(str) {
20741 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
20742 return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
20743 }
20744 };
20745
20746 // Console override
20747 var console$1 = {
20748 /** @type {function(...*)} */
20749 log: function() {
20750 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
20751 try {
20752 windowConsole.log.apply(windowConsole, arguments);
20753 } catch (err) {
20754 _.each(arguments, function(arg) {
20755 windowConsole.log(arg);
20756 });
20757 }
20758 }
20759 },
20760 /** @type {function(...*)} */
20761 warn: function() {
20762 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
20763 var args = ['Mixpanel warning:'].concat(_.toArray(arguments));
20764 try {
20765 windowConsole.warn.apply(windowConsole, args);
20766 } catch (err) {
20767 _.each(args, function(arg) {
20768 windowConsole.warn(arg);
20769 });
20770 }
20771 }
20772 },
20773 /** @type {function(...*)} */
20774 error: function() {
20775 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
20776 var args = ['Mixpanel error:'].concat(_.toArray(arguments));
20777 try {
20778 windowConsole.error.apply(windowConsole, args);
20779 } catch (err) {
20780 _.each(args, function(arg) {
20781 windowConsole.error(arg);
20782 });
20783 }
20784 }
20785 },
20786 /** @type {function(...*)} */
20787 critical: function() {
20788 if (!_.isUndefined(windowConsole) && windowConsole) {
20789 var args = ['Mixpanel error:'].concat(_.toArray(arguments));
20790 try {
20791 windowConsole.error.apply(windowConsole, args);
20792 } catch (err) {
20793 _.each(args, function(arg) {
20794 windowConsole.error(arg);
20795 });
20796 }
20797 }
20798 }
20799 };
20800
20801 var log_func_with_prefix = function(func, prefix) {
20802 return function() {
20803 arguments[0] = '[' + prefix + '] ' + arguments[0];
20804 return func.apply(console$1, arguments);
20805 };
20806 };
20807 var console_with_prefix = function(prefix) {
20808 return {
20809 log: log_func_with_prefix(console$1.log, prefix),
20810 error: log_func_with_prefix(console$1.error, prefix),
20811 critical: log_func_with_prefix(console$1.critical, prefix)
20812 };
20813 };
20814
20815
20816 var safewrap = function(f) {
20817 return function() {
20818 try {
20819 return f.apply(this, arguments);
20820 } catch (e) {
20821 console$1.critical('Implementation error. Please turn on debug and contact support@mixpanel.com.');
20822 if (Config.DEBUG){
20823 console$1.critical(e);
20824 }
20825 }
20826 };
20827 };
20828
20829 var safewrapClass = function(klass) {
20830 var proto = klass.prototype;
20831 for (var func in proto) {
20832 if (typeof(proto[func]) === 'function') {
20833 proto[func] = safewrap(proto[func]);
20834 }
20835 }
20836 };
20837
20838
20839 // UNDERSCORE
20840 // Embed part of the Underscore Library
20841 _.bind = function(func, context) {
20842 var args, bound;
20843 if (nativeBind && func.bind === nativeBind) {
20844 return nativeBind.apply(func, slice.call(arguments, 1));
20845 }
20846 if (!_.isFunction(func)) {
20847 throw new TypeError();
20848 }
20849 args = slice.call(arguments, 2);
20850 bound = function() {
20851 if (!(this instanceof bound)) {
20852 return func.apply(context, args.concat(slice.call(arguments)));
20853 }
20854 var ctor = {};
20855 ctor.prototype = func.prototype;
20856 var self = new ctor();
20857 ctor.prototype = null;
20858 var result = func.apply(self, args.concat(slice.call(arguments)));
20859 if (Object(result) === result) {
20860 return result;
20861 }
20862 return self;
20863 };
20864 return bound;
20865 };
20866
20867 /**
20868 * @param {*=} obj
20869 * @param {function(...*)=} iterator
20870 * @param {Object=} context
20871 */
20872 _.each = function(obj, iterator, context) {
20873 if (obj === null || obj === undefined) {
20874 return;
20875 }
20876 if (nativeForEach && obj.forEach === nativeForEach) {
20877 obj.forEach(iterator, context);
20878 } else if (obj.length === +obj.length) {
20879 for (var i = 0, l = obj.length; i < l; i++) {
20880 if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {
20881 return;
20882 }
20883 }
20884 } else {
20885 for (var key in obj) {
20886 if (hasOwnProperty.call(obj, key)) {
20887 if (iterator.call(context, obj[key], key, obj) === breaker) {
20888 return;
20889 }
20890 }
20891 }
20892 }
20893 };
20894
20895 _.extend = function(obj) {
20896 _.each(slice.call(arguments, 1), function(source) {
20897 for (var prop in source) {
20898 if (source[prop] !== void 0) {
20899 obj[prop] = source[prop];
20900 }
20901 }
20902 });
20903 return obj;
20904 };
20905
20906 _.isArray = nativeIsArray || function(obj) {
20907 return toString.call(obj) === '[object Array]';
20908 };
20909
20910 // from a comment on http://dbj.org/dbj/?p=286
20911 // fails on only one very rare and deliberate custom object:
20912 // var bomb = { toString : undefined, valueOf: function(o) { return "function BOMBA!"; }};
20913 _.isFunction = function(f) {
20914 try {
20915 return /^\s*\bfunction\b/.test(f);
20916 } catch (x) {
20917 return false;
20918 }
20919 };
20920
20921 _.isArguments = function(obj) {
20922 return !!(obj && hasOwnProperty.call(obj, 'callee'));
20923 };
20924
20925 _.toArray = function(iterable) {
20926 if (!iterable) {
20927 return [];
20928 }
20929 if (iterable.toArray) {
20930 return iterable.toArray();
20931 }
20932 if (_.isArray(iterable)) {
20933 return slice.call(iterable);
20934 }
20935 if (_.isArguments(iterable)) {
20936 return slice.call(iterable);
20937 }
20938 return _.values(iterable);
20939 };
20940
20941 _.map = function(arr, callback, context) {
20942 if (nativeMap && arr.map === nativeMap) {
20943 return arr.map(callback, context);
20944 } else {
20945 var results = [];
20946 _.each(arr, function(item) {
20947 results.push(callback.call(context, item));
20948 });
20949 return results;
20950 }
20951 };
20952
20953 _.keys = function(obj) {
20954 var results = [];
20955 if (obj === null) {
20956 return results;
20957 }
20958 _.each(obj, function(value, key) {
20959 results[results.length] = key;
20960 });
20961 return results;
20962 };
20963
20964 _.values = function(obj) {
20965 var results = [];
20966 if (obj === null) {
20967 return results;
20968 }
20969 _.each(obj, function(value) {
20970 results[results.length] = value;
20971 });
20972 return results;
20973 };
20974
20975 _.include = function(obj, target) {
20976 var found = false;
20977 if (obj === null) {
20978 return found;
20979 }
20980 if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
20981 return obj.indexOf(target) != -1;
20982 }
20983 _.each(obj, function(value) {
20984 if (found || (found = (value === target))) {
20985 return breaker;
20986 }
20987 });
20988 return found;
20989 };
20990
20991 _.includes = function(str, needle) {
20992 return str.indexOf(needle) !== -1;
20993 };
20994
20995 // Underscore Addons
20996 _.inherit = function(subclass, superclass) {
20997 subclass.prototype = new superclass();
20998 subclass.prototype.constructor = subclass;
20999 subclass.superclass = superclass.prototype;
21000 return subclass;
21001 };
21002
21003 _.isObject = function(obj) {
21004 return (obj === Object(obj) && !_.isArray(obj));
21005 };
21006
21007 _.isEmptyObject = function(obj) {
21008 if (_.isObject(obj)) {
21009 for (var key in obj) {
21010 if (hasOwnProperty.call(obj, key)) {
21011 return false;
21012 }
21013 }
21014 return true;
21015 }
21016 return false;
21017 };
21018
21019 _.isUndefined = function(obj) {
21020 return obj === void 0;
21021 };
21022
21023 _.isString = function(obj) {
21024 return toString.call(obj) == '[object String]';
21025 };
21026
21027 _.isDate = function(obj) {
21028 return toString.call(obj) == '[object Date]';
21029 };
21030
21031 _.isNumber = function(obj) {
21032 return toString.call(obj) == '[object Number]';
21033 };
21034
21035 _.isElement = function(obj) {
21036 return !!(obj && obj.nodeType === 1);
21037 };
21038
21039 _.encodeDates = function(obj) {
21040 _.each(obj, function(v, k) {
21041 if (_.isDate(v)) {
21042 obj[k] = _.formatDate(v);
21043 } else if (_.isObject(v)) {
21044 obj[k] = _.encodeDates(v); // recurse
21045 }
21046 });
21047 return obj;
21048 };
21049
21050 _.timestamp = function() {
21051 Date.now = Date.now || function() {
21052 return +new Date;
21053 };
21054 return Date.now();
21055 };
21056
21057 _.formatDate = function(d) {
21058 // YYYY-MM-DDTHH:MM:SS in UTC
21059 function pad(n) {
21060 return n < 10 ? '0' + n : n;
21061 }
21062 return d.getUTCFullYear() + '-' +
21063 pad(d.getUTCMonth() + 1) + '-' +
21064 pad(d.getUTCDate()) + 'T' +
21065 pad(d.getUTCHours()) + ':' +
21066 pad(d.getUTCMinutes()) + ':' +
21067 pad(d.getUTCSeconds());
21068 };
21069
21070 _.strip_empty_properties = function(p) {
21071 var ret = {};
21072 _.each(p, function(v, k) {
21073 if (_.isString(v) && v.length > 0) {
21074 ret[k] = v;
21075 }
21076 });
21077 return ret;
21078 };
21079
21080 /*
21081 * this function returns a copy of object after truncating it. If
21082 * passed an Array or Object it will iterate through obj and
21083 * truncate all the values recursively.
21084 */
21085 _.truncate = function(obj, length) {
21086 var ret;
21087
21088 if (typeof(obj) === 'string') {
21089 ret = obj.slice(0, length);
21090 } else if (_.isArray(obj)) {
21091 ret = [];
21092 _.each(obj, function(val) {
21093 ret.push(_.truncate(val, length));
21094 });
21095 } else if (_.isObject(obj)) {
21096 ret = {};
21097 _.each(obj, function(val, key) {
21098 ret[key] = _.truncate(val, length);
21099 });
21100 } else {
21101 ret = obj;
21102 }
21103
21104 return ret;
21105 };
21106
21107 _.JSONEncode = (function() {
21108 return function(mixed_val) {
21109 var value = mixed_val;
21110 var quote = function(string) {
21111 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
21112 var meta = { // table of character substitutions
21113 '\b': '\\b',
21114 '\t': '\\t',
21115 '\n': '\\n',
21116 '\f': '\\f',
21117 '\r': '\\r',
21118 '"': '\\"',
21119 '\\': '\\\\'
21120 };
21121
21122 escapable.lastIndex = 0;
21123 return escapable.test(string) ?
21124 '"' + string.replace(escapable, function(a) {
21125 var c = meta[a];
21126 return typeof c === 'string' ? c :
21127 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
21128 }) + '"' :
21129 '"' + string + '"';
21130 };
21131
21132 var str = function(key, holder) {
21133 var gap = '';
21134 var indent = ' ';
21135 var i = 0; // The loop counter.
21136 var k = ''; // The member key.
21137 var v = ''; // The member value.
21138 var length = 0;
21139 var mind = gap;
21140 var partial = [];
21141 var value = holder[key];
21142
21143 // If the value has a toJSON method, call it to obtain a replacement value.
21144 if (value && typeof value === 'object' &&
21145 typeof value.toJSON === 'function') {
21146 value = value.toJSON(key);
21147 }
21148
21149 // What happens next depends on the value's type.
21150 switch (typeof value) {
21151 case 'string':
21152 return quote(value);
21153
21154 case 'number':
21155 // JSON numbers must be finite. Encode non-finite numbers as null.
21156 return isFinite(value) ? String(value) : 'null';
21157
21158 case 'boolean':
21159 case 'null':
21160 // If the value is a boolean or null, convert it to a string. Note:
21161 // typeof null does not produce 'null'. The case is included here in
21162 // the remote chance that this gets fixed someday.
21163
21164 return String(value);
21165
21166 case 'object':
21167 // If the type is 'object', we might be dealing with an object or an array or
21168 // null.
21169 // Due to a specification blunder in ECMAScript, typeof null is 'object',
21170 // so watch out for that case.
21171 if (!value) {
21172 return 'null';
21173 }
21174
21175 // Make an array to hold the partial results of stringifying this object value.
21176 gap += indent;
21177 partial = [];
21178
21179 // Is the value an array?
21180 if (toString.apply(value) === '[object Array]') {
21181 // The value is an array. Stringify every element. Use null as a placeholder
21182 // for non-JSON values.
21183
21184 length = value.length;
21185 for (i = 0; i < length; i += 1) {
21186 partial[i] = str(i, value) || 'null';
21187 }
21188
21189 // Join all of the elements together, separated with commas, and wrap them in
21190 // brackets.
21191 v = partial.length === 0 ? '[]' :
21192 gap ? '[\n' + gap +
21193 partial.join(',\n' + gap) + '\n' +
21194 mind + ']' :
21195 '[' + partial.join(',') + ']';
21196 gap = mind;
21197 return v;
21198 }
21199
21200 // Iterate through all of the keys in the object.
21201 for (k in value) {
21202 if (hasOwnProperty.call(value, k)) {
21203 v = str(k, value);
21204 if (v) {
21205 partial.push(quote(k) + (gap ? ': ' : ':') + v);
21206 }
21207 }
21208 }
21209
21210 // Join all of the member texts together, separated with commas,
21211 // and wrap them in braces.
21212 v = partial.length === 0 ? '{}' :
21213 gap ? '{' + partial.join(',') + '' +
21214 mind + '}' : '{' + partial.join(',') + '}';
21215 gap = mind;
21216 return v;
21217 }
21218 };
21219
21220 // Make a fake root object containing our value under the key of ''.
21221 // Return the result of stringifying the value.
21222 return str('', {
21223 '': value
21224 });
21225 };
21226 })();
21227
21228 /**
21229 * From https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
21230 * Slightly modified to throw a real Error rather than a POJO
21231 */
21232 _.JSONDecode = (function() {
21233 var at, // The index of the current character
21234 ch, // The current character
21235 escapee = {
21236 '"': '"',
21237 '\\': '\\',
21238 '/': '/',
21239 'b': '\b',
21240 'f': '\f',
21241 'n': '\n',
21242 'r': '\r',
21243 't': '\t'
21244 },
21245 text,
21246 error = function(m) {
21247 var e = new SyntaxError(m);
21248 e.at = at;
21249 e.text = text;
21250 throw e;
21251 },
21252 next = function(c) {
21253 // If a c parameter is provided, verify that it matches the current character.
21254 if (c && c !== ch) {
21255 error('Expected \'' + c + '\' instead of \'' + ch + '\'');
21256 }
21257 // Get the next character. When there are no more characters,
21258 // return the empty string.
21259 ch = text.charAt(at);
21260 at += 1;
21261 return ch;
21262 },
21263 number = function() {
21264 // Parse a number value.
21265 var number,
21266 string = '';
21267
21268 if (ch === '-') {
21269 string = '-';
21270 next('-');
21271 }
21272 while (ch >= '0' && ch <= '9') {
21273 string += ch;
21274 next();
21275 }
21276 if (ch === '.') {
21277 string += '.';
21278 while (next() && ch >= '0' && ch <= '9') {
21279 string += ch;
21280 }
21281 }
21282 if (ch === 'e' || ch === 'E') {
21283 string += ch;
21284 next();
21285 if (ch === '-' || ch === '+') {
21286 string += ch;
21287 next();
21288 }
21289 while (ch >= '0' && ch <= '9') {
21290 string += ch;
21291 next();
21292 }
21293 }
21294 number = +string;
21295 if (!isFinite(number)) {
21296 error('Bad number');
21297 } else {
21298 return number;
21299 }
21300 },
21301
21302 string = function() {
21303 // Parse a string value.
21304 var hex,
21305 i,
21306 string = '',
21307 uffff;
21308 // When parsing for string values, we must look for " and \ characters.
21309 if (ch === '"') {
21310 while (next()) {
21311 if (ch === '"') {
21312 next();
21313 return string;
21314 }
21315 if (ch === '\\') {
21316 next();
21317 if (ch === 'u') {
21318 uffff = 0;
21319 for (i = 0; i < 4; i += 1) {
21320 hex = parseInt(next(), 16);
21321 if (!isFinite(hex)) {
21322 break;
21323 }
21324 uffff = uffff * 16 + hex;
21325 }
21326 string += String.fromCharCode(uffff);
21327 } else if (typeof escapee[ch] === 'string') {
21328 string += escapee[ch];
21329 } else {
21330 break;
21331 }
21332 } else {
21333 string += ch;
21334 }
21335 }
21336 }
21337 error('Bad string');
21338 },
21339 white = function() {
21340 // Skip whitespace.
21341 while (ch && ch <= ' ') {
21342 next();
21343 }
21344 },
21345 word = function() {
21346 // true, false, or null.
21347 switch (ch) {
21348 case 't':
21349 next('t');
21350 next('r');
21351 next('u');
21352 next('e');
21353 return true;
21354 case 'f':
21355 next('f');
21356 next('a');
21357 next('l');
21358 next('s');
21359 next('e');
21360 return false;
21361 case 'n':
21362 next('n');
21363 next('u');
21364 next('l');
21365 next('l');
21366 return null;
21367 }
21368 error('Unexpected "' + ch + '"');
21369 },
21370 value, // Placeholder for the value function.
21371 array = function() {
21372 // Parse an array value.
21373 var array = [];
21374
21375 if (ch === '[') {
21376 next('[');
21377 white();
21378 if (ch === ']') {
21379 next(']');
21380 return array; // empty array
21381 }
21382 while (ch) {
21383 array.push(value());
21384 white();
21385 if (ch === ']') {
21386 next(']');
21387 return array;
21388 }
21389 next(',');
21390 white();
21391 }
21392 }
21393 error('Bad array');
21394 },
21395 object = function() {
21396 // Parse an object value.
21397 var key,
21398 object = {};
21399
21400 if (ch === '{') {
21401 next('{');
21402 white();
21403 if (ch === '}') {
21404 next('}');
21405 return object; // empty object
21406 }
21407 while (ch) {
21408 key = string();
21409 white();
21410 next(':');
21411 if (Object.hasOwnProperty.call(object, key)) {
21412 error('Duplicate key "' + key + '"');
21413 }
21414 object[key] = value();
21415 white();
21416 if (ch === '}') {
21417 next('}');
21418 return object;
21419 }
21420 next(',');
21421 white();
21422 }
21423 }
21424 error('Bad object');
21425 };
21426
21427 value = function() {
21428 // Parse a JSON value. It could be an object, an array, a string,
21429 // a number, or a word.
21430 white();
21431 switch (ch) {
21432 case '{':
21433 return object();
21434 case '[':
21435 return array();
21436 case '"':
21437 return string();
21438 case '-':
21439 return number();
21440 default:
21441 return ch >= '0' && ch <= '9' ? number() : word();
21442 }
21443 };
21444
21445 // Return the json_parse function. It will have access to all of the
21446 // above functions and variables.
21447 return function(source) {
21448 var result;
21449
21450 text = source;
21451 at = 0;
21452 ch = ' ';
21453 result = value();
21454 white();
21455 if (ch) {
21456 error('Syntax error');
21457 }
21458
21459 return result;
21460 };
21461 })();
21462
21463 _.base64Encode = function(data) {
21464 var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
21465 var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
21466 ac = 0,
21467 enc = '',
21468 tmp_arr = [];
21469
21470 if (!data) {
21471 return data;
21472 }
21473
21474 data = _.utf8Encode(data);
21475
21476 do { // pack three octets into four hexets
21477 o1 = data.charCodeAt(i++);
21478 o2 = data.charCodeAt(i++);
21479 o3 = data.charCodeAt(i++);
21480
21481 bits = o1 << 16 | o2 << 8 | o3;
21482
21483 h1 = bits >> 18 & 0x3f;
21484 h2 = bits >> 12 & 0x3f;
21485 h3 = bits >> 6 & 0x3f;
21486 h4 = bits & 0x3f;
21487
21488 // use hexets to index into b64, and append result to encoded string
21489 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
21490 } while (i < data.length);
21491
21492 enc = tmp_arr.join('');
21493
21494 switch (data.length % 3) {
21495 case 1:
21496 enc = enc.slice(0, -2) + '==';
21497 break;
21498 case 2:
21499 enc = enc.slice(0, -1) + '=';
21500 break;
21501 }
21502
21503 return enc;
21504 };
21505
21506 _.utf8Encode = function(string) {
21507 string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
21508
21509 var utftext = '',
21510 start,
21511 end;
21512 var stringl = 0,
21513 n;
21514
21515 start = end = 0;
21516 stringl = string.length;
21517
21518 for (n = 0; n < stringl; n++) {
21519 var c1 = string.charCodeAt(n);
21520 var enc = null;
21521
21522 if (c1 < 128) {
21523 end++;
21524 } else if ((c1 > 127) && (c1 < 2048)) {
21525 enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
21526 } else {
21527 enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
21528 }
21529 if (enc !== null) {
21530 if (end > start) {
21531 utftext += string.substring(start, end);
21532 }
21533 utftext += enc;
21534 start = end = n + 1;
21535 }
21536 }
21537
21538 if (end > start) {
21539 utftext += string.substring(start, string.length);
21540 }
21541
21542 return utftext;
21543 };
21544
21545 _.UUID = function() {
21546 try {
21547 // use native Crypto API when available
21548 return win['crypto']['randomUUID']();
21549 } catch (err) {
21550 // fall back to generating our own UUID
21551 // based on https://gist.github.com/scwood/3bff42cc005cc20ab7ec98f0d8e1d59d
21552 var uuid = new Array(36);
21553 for (var i = 0; i < 36; i++) {
21554 uuid[i] = Math.floor(Math.random() * 16);
21555 }
21556 uuid[14] = 4; // set bits 12-15 of time-high-and-version to 0100
21557 uuid[19] = uuid[19] &= -5; // set bit 6 of clock-seq-and-reserved to zero
21558 uuid[19] = uuid[19] |= (1 << 3); // set bit 7 of clock-seq-and-reserved to one
21559 uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
21560
21561 return _.map(uuid, function(x) {
21562 return x.toString(16);
21563 }).join('');
21564 }
21565 };
21566
21567 // _.isBlockedUA()
21568 // This is to block various web spiders from executing our JS and
21569 // sending false tracking data
21570 var BLOCKED_UA_STRS = [
21571 'ahrefsbot',
21572 'ahrefssiteaudit',
21573 'amazonbot',
21574 'baiduspider',
21575 'bingbot',
21576 'bingpreview',
21577 'chrome-lighthouse',
21578 'facebookexternal',
21579 'petalbot',
21580 'pinterest',
21581 'screaming frog',
21582 'yahoo! slurp',
21583 'yandex',
21584
21585 // a whole bunch of goog-specific crawlers
21586 // https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
21587 'adsbot-google',
21588 'apis-google',
21589 'duplexweb-google',
21590 'feedfetcher-google',
21591 'google favicon',
21592 'google web preview',
21593 'google-read-aloud',
21594 'googlebot',
21595 'googleweblight',
21596 'mediapartners-google',
21597 'storebot-google'
21598 ];
21599 _.isBlockedUA = function(ua) {
21600 var i;
21601 ua = ua.toLowerCase();
21602 for (i = 0; i < BLOCKED_UA_STRS.length; i++) {
21603 if (ua.indexOf(BLOCKED_UA_STRS[i]) !== -1) {
21604 return true;
21605 }
21606 }
21607 return false;
21608 };
21609
21610 /**
21611 * @param {Object=} formdata
21612 * @param {string=} arg_separator
21613 */
21614 _.HTTPBuildQuery = function(formdata, arg_separator) {
21615 var use_val, use_key, tmp_arr = [];
21616
21617 if (_.isUndefined(arg_separator)) {
21618 arg_separator = '&';
21619 }
21620
21621 _.each(formdata, function(val, key) {
21622 use_val = encodeURIComponent(val.toString());
21623 use_key = encodeURIComponent(key);
21624 tmp_arr[tmp_arr.length] = use_key + '=' + use_val;
21625 });
21626
21627 return tmp_arr.join(arg_separator);
21628 };
21629
21630 _.getQueryParam = function(url, param) {
21631 // Expects a raw URL
21632
21633 param = param.replace(/[[]/g, '\\[').replace(/[\]]/g, '\\]');
21634 var regexS = '[\\?&]' + param + '=([^&#]*)',
21635 regex = new RegExp(regexS),
21636 results = regex.exec(url);
21637 if (results === null || (results && typeof(results[1]) !== 'string' && results[1].length)) {
21638 return '';
21639 } else {
21640 var result = results[1];
21641 try {
21642 result = decodeURIComponent(result);
21643 } catch(err) {
21644 console$1.error('Skipping decoding for malformed query param: ' + result);
21645 }
21646 return result.replace(/\+/g, ' ');
21647 }
21648 };
21649
21650
21651 // _.cookie
21652 // Methods partially borrowed from quirksmode.org/js/cookies.html
21653 _.cookie = {
21654 get: function(name) {
21655 var nameEQ = name + '=';
21656 var ca = document$1.cookie.split(';');
21657 for (var i = 0; i < ca.length; i++) {
21658 var c = ca[i];
21659 while (c.charAt(0) == ' ') {
21660 c = c.substring(1, c.length);
21661 }
21662 if (c.indexOf(nameEQ) === 0) {
21663 return decodeURIComponent(c.substring(nameEQ.length, c.length));
21664 }
21665 }
21666 return null;
21667 },
21668
21669 parse: function(name) {
21670 var cookie;
21671 try {
21672 cookie = _.JSONDecode(_.cookie.get(name)) || {};
21673 } catch (err) {
21674 // noop
21675 }
21676 return cookie;
21677 },
21678
21679 set_seconds: function(name, value, seconds, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
21680 var cdomain = '',
21681 expires = '',
21682 secure = '';
21683
21684 if (domain_override) {
21685 cdomain = '; domain=' + domain_override;
21686 } else if (is_cross_subdomain) {
21687 var domain = extract_domain(document$1.location.hostname);
21688 cdomain = domain ? '; domain=.' + domain : '';
21689 }
21690
21691 if (seconds) {
21692 var date = new Date();
21693 date.setTime(date.getTime() + (seconds * 1000));
21694 expires = '; expires=' + date.toGMTString();
21695 }
21696
21697 if (is_cross_site) {
21698 is_secure = true;
21699 secure = '; SameSite=None';
21700 }
21701 if (is_secure) {
21702 secure += '; secure';
21703 }
21704
21705 document$1.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
21706 },
21707
21708 set: function(name, value, days, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
21709 var cdomain = '', expires = '', secure = '';
21710
21711 if (domain_override) {
21712 cdomain = '; domain=' + domain_override;
21713 } else if (is_cross_subdomain) {
21714 var domain = extract_domain(document$1.location.hostname);
21715 cdomain = domain ? '; domain=.' + domain : '';
21716 }
21717
21718 if (days) {
21719 var date = new Date();
21720 date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
21721 expires = '; expires=' + date.toGMTString();
21722 }
21723
21724 if (is_cross_site) {
21725 is_secure = true;
21726 secure = '; SameSite=None';
21727 }
21728 if (is_secure) {
21729 secure += '; secure';
21730 }
21731
21732 var new_cookie_val = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
21733 document$1.cookie = new_cookie_val;
21734 return new_cookie_val;
21735 },
21736
21737 remove: function(name, is_cross_subdomain, domain_override) {
21738 _.cookie.set(name, '', -1, is_cross_subdomain, false, false, domain_override);
21739 }
21740 };
21741
21742 var _testStorageSupported = function (storage) {
21743 var supported = true;
21744 try {
21745 var key = '__mplss_' + cheap_guid(8),
21746 val = 'xyz';
21747 storage.setItem(key, val);
21748 if (storage.getItem(key) !== val) {
21749 supported = false;
21750 }
21751 storage.removeItem(key);
21752 } catch (err) {
21753 supported = false;
21754 }
21755 return supported;
21756 };
21757
21758 var _localStorageSupported = null;
21759 var localStorageSupported = function(storage, forceCheck) {
21760 if (_localStorageSupported !== null && !forceCheck) {
21761 return _localStorageSupported;
21762 }
21763 return _localStorageSupported = _testStorageSupported(storage || win.localStorage);
21764 };
21765
21766 var _sessionStorageSupported = null;
21767 var sessionStorageSupported = function(storage, forceCheck) {
21768 if (_sessionStorageSupported !== null && !forceCheck) {
21769 return _sessionStorageSupported;
21770 }
21771 return _sessionStorageSupported = _testStorageSupported(storage || win.sessionStorage);
21772 };
21773
21774 function _storageWrapper(storage, name, is_supported_fn) {
21775 var log_error = function(msg) {
21776 console$1.error(name + ' error: ' + msg);
21777 };
21778
21779 return {
21780 is_supported: function(forceCheck) {
21781 var supported = is_supported_fn(storage, forceCheck);
21782 if (!supported) {
21783 console$1.error(name + ' unsupported');
21784 }
21785 return supported;
21786 },
21787 error: log_error,
21788 get: function(key) {
21789 try {
21790 return storage.getItem(key);
21791 } catch (err) {
21792 log_error(err);
21793 }
21794 return null;
21795 },
21796 parse: function(key) {
21797 try {
21798 return _.JSONDecode(storage.getItem(key)) || {};
21799 } catch (err) {
21800 // noop
21801 }
21802 return null;
21803 },
21804 set: function(key, value) {
21805 try {
21806 storage.setItem(key, value);
21807 } catch (err) {
21808 log_error(err);
21809 }
21810 },
21811 remove: function(key) {
21812 try {
21813 storage.removeItem(key);
21814 } catch (err) {
21815 log_error(err);
21816 }
21817 }
21818 };
21819 }
21820
21821 _.localStorage = _storageWrapper(win.localStorage, 'localStorage', localStorageSupported);
21822 _.sessionStorage = _storageWrapper(win.sessionStorage, 'sessionStorage', sessionStorageSupported);
21823
21824 _.register_event = (function() {
21825 // written by Dean Edwards, 2005
21826 // with input from Tino Zijdel - crisp@xs4all.nl
21827 // with input from Carl Sverre - mail@carlsverre.com
21828 // with input from Mixpanel
21829 // http://dean.edwards.name/weblog/2005/10/add-event/
21830 // https://gist.github.com/1930440
21831
21832 /**
21833 * @param {Object} element
21834 * @param {string} type
21835 * @param {function(...*)} handler
21836 * @param {boolean=} oldSchool
21837 * @param {boolean=} useCapture
21838 */
21839 var register_event = function(element, type, handler, oldSchool, useCapture) {
21840 if (!element) {
21841 console$1.error('No valid element provided to register_event');
21842 return;
21843 }
21844
21845 if (element.addEventListener && !oldSchool) {
21846 element.addEventListener(type, handler, !!useCapture);
21847 } else {
21848 var ontype = 'on' + type;
21849 var old_handler = element[ontype]; // can be undefined
21850 element[ontype] = makeHandler(element, handler, old_handler);
21851 }
21852 };
21853
21854 function makeHandler(element, new_handler, old_handlers) {
21855 var handler = function(event) {
21856 event = event || fixEvent(win.event);
21857
21858 // this basically happens in firefox whenever another script
21859 // overwrites the onload callback and doesn't pass the event
21860 // object to previously defined callbacks. All the browsers
21861 // that don't define window.event implement addEventListener
21862 // so the dom_loaded handler will still be fired as usual.
21863 if (!event) {
21864 return undefined;
21865 }
21866
21867 var ret = true;
21868 var old_result, new_result;
21869
21870 if (_.isFunction(old_handlers)) {
21871 old_result = old_handlers(event);
21872 }
21873 new_result = new_handler.call(element, event);
21874
21875 if ((false === old_result) || (false === new_result)) {
21876 ret = false;
21877 }
21878
21879 return ret;
21880 };
21881
21882 return handler;
21883 }
21884
21885 function fixEvent(event) {
21886 if (event) {
21887 event.preventDefault = fixEvent.preventDefault;
21888 event.stopPropagation = fixEvent.stopPropagation;
21889 }
21890 return event;
21891 }
21892 fixEvent.preventDefault = function() {
21893 this.returnValue = false;
21894 };
21895 fixEvent.stopPropagation = function() {
21896 this.cancelBubble = true;
21897 };
21898
21899 return register_event;
21900 })();
21901
21902
21903 var TOKEN_MATCH_REGEX = new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$');
21904
21905 _.dom_query = (function() {
21906 /* document.getElementsBySelector(selector)
21907 - returns an array of element objects from the current document
21908 matching the CSS selector. Selectors can contain element names,
21909 class names and ids and can be nested. For example:
21910
21911 elements = document.getElementsBySelector('div#main p a.external')
21912
21913 Will return an array of all 'a' elements with 'external' in their
21914 class attribute that are contained inside 'p' elements that are
21915 contained inside the 'div' element which has id="main"
21916
21917 New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
21918 See http://www.w3.org/TR/css3-selectors/#attribute-selectors
21919
21920 Version 0.4 - Simon Willison, March 25th 2003
21921 -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
21922 -- Opera 7 fails
21923
21924 Version 0.5 - Carl Sverre, Jan 7th 2013
21925 -- Now uses jQuery-esque `hasClass` for testing class name
21926 equality. This fixes a bug related to '-' characters being
21927 considered not part of a 'word' in regex.
21928 */
21929
21930 function getAllChildren(e) {
21931 // Returns all children of element. Workaround required for IE5/Windows. Ugh.
21932 return e.all ? e.all : e.getElementsByTagName('*');
21933 }
21934
21935 var bad_whitespace = /[\t\r\n]/g;
21936
21937 function hasClass(elem, selector) {
21938 var className = ' ' + selector + ' ';
21939 return ((' ' + elem.className + ' ').replace(bad_whitespace, ' ').indexOf(className) >= 0);
21940 }
21941
21942 function getElementsBySelector(selector) {
21943 // Attempt to fail gracefully in lesser browsers
21944 if (!document$1.getElementsByTagName) {
21945 return [];
21946 }
21947 // Split selector in to tokens
21948 var tokens = selector.split(' ');
21949 var token, bits, tagName, found, foundCount, i, j, k, elements, currentContextIndex;
21950 var currentContext = [document$1];
21951 for (i = 0; i < tokens.length; i++) {
21952 token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, '');
21953 if (token.indexOf('#') > -1) {
21954 // Token is an ID selector
21955 bits = token.split('#');
21956 tagName = bits[0];
21957 var id = bits[1];
21958 var element = document$1.getElementById(id);
21959 if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) {
21960 // element not found or tag with that ID not found, return false
21961 return [];
21962 }
21963 // Set currentContext to contain just this element
21964 currentContext = [element];
21965 continue; // Skip to next token
21966 }
21967 if (token.indexOf('.') > -1) {
21968 // Token contains a class selector
21969 bits = token.split('.');
21970 tagName = bits[0];
21971 var className = bits[1];
21972 if (!tagName) {
21973 tagName = '*';
21974 }
21975 // Get elements matching tag, filter them for class selector
21976 found = [];
21977 foundCount = 0;
21978 for (j = 0; j < currentContext.length; j++) {
21979 if (tagName == '*') {
21980 elements = getAllChildren(currentContext[j]);
21981 } else {
21982 elements = currentContext[j].getElementsByTagName(tagName);
21983 }
21984 for (k = 0; k < elements.length; k++) {
21985 found[foundCount++] = elements[k];
21986 }
21987 }
21988 currentContext = [];
21989 currentContextIndex = 0;
21990 for (j = 0; j < found.length; j++) {
21991 if (found[j].className &&
21992 _.isString(found[j].className) && // some SVG elements have classNames which are not strings
21993 hasClass(found[j], className)
21994 ) {
21995 currentContext[currentContextIndex++] = found[j];
21996 }
21997 }
21998 continue; // Skip to next token
21999 }
22000 // Code to deal with attribute selectors
22001 var token_match = token.match(TOKEN_MATCH_REGEX);
22002 if (token_match) {
22003 tagName = token_match[1];
22004 var attrName = token_match[2];
22005 var attrOperator = token_match[3];
22006 var attrValue = token_match[4];
22007 if (!tagName) {
22008 tagName = '*';
22009 }
22010 // Grab all of the tagName elements within current context
22011 found = [];
22012 foundCount = 0;
22013 for (j = 0; j < currentContext.length; j++) {
22014 if (tagName == '*') {
22015 elements = getAllChildren(currentContext[j]);
22016 } else {
22017 elements = currentContext[j].getElementsByTagName(tagName);
22018 }
22019 for (k = 0; k < elements.length; k++) {
22020 found[foundCount++] = elements[k];
22021 }
22022 }
22023 currentContext = [];
22024 currentContextIndex = 0;
22025 var checkFunction; // This function will be used to filter the elements
22026 switch (attrOperator) {
22027 case '=': // Equality
22028 checkFunction = function(e) {
22029 return (e.getAttribute(attrName) == attrValue);
22030 };
22031 break;
22032 case '~': // Match one of space seperated words
22033 checkFunction = function(e) {
22034 return (e.getAttribute(attrName).match(new RegExp('\\b' + attrValue + '\\b')));
22035 };
22036 break;
22037 case '|': // Match start with value followed by optional hyphen
22038 checkFunction = function(e) {
22039 return (e.getAttribute(attrName).match(new RegExp('^' + attrValue + '-?')));
22040 };
22041 break;
22042 case '^': // Match starts with value
22043 checkFunction = function(e) {
22044 return (e.getAttribute(attrName).indexOf(attrValue) === 0);
22045 };
22046 break;
22047 case '$': // Match ends with value - fails with "Warning" in Opera 7
22048 checkFunction = function(e) {
22049 return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length);
22050 };
22051 break;
22052 case '*': // Match ends with value
22053 checkFunction = function(e) {
22054 return (e.getAttribute(attrName).indexOf(attrValue) > -1);
22055 };
22056 break;
22057 default:
22058 // Just test for existence of attribute
22059 checkFunction = function(e) {
22060 return e.getAttribute(attrName);
22061 };
22062 }
22063 currentContext = [];
22064 currentContextIndex = 0;
22065 for (j = 0; j < found.length; j++) {
22066 if (checkFunction(found[j])) {
22067 currentContext[currentContextIndex++] = found[j];
22068 }
22069 }
22070 // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
22071 continue; // Skip to next token
22072 }
22073 // If we get here, token is JUST an element (not a class or ID selector)
22074 tagName = token;
22075 found = [];
22076 foundCount = 0;
22077 for (j = 0; j < currentContext.length; j++) {
22078 elements = currentContext[j].getElementsByTagName(tagName);
22079 for (k = 0; k < elements.length; k++) {
22080 found[foundCount++] = elements[k];
22081 }
22082 }
22083 currentContext = found;
22084 }
22085 return currentContext;
22086 }
22087
22088 return function(query) {
22089 if (_.isElement(query)) {
22090 return [query];
22091 } else if (_.isObject(query) && !_.isUndefined(query.length)) {
22092 return query;
22093 } else {
22094 return getElementsBySelector.call(this, query);
22095 }
22096 };
22097 })();
22098
22099 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'];
22100 var CLICK_IDS = ['dclid', 'fbclid', 'gclid', 'ko_click_id', 'li_fat_id', 'msclkid', 'sccid', 'ttclid', 'twclid', 'wbraid'];
22101
22102 _.info = {
22103 campaignParams: function(default_value) {
22104 var kw = '',
22105 params = {};
22106 _.each(CAMPAIGN_KEYWORDS, function(kwkey) {
22107 kw = _.getQueryParam(document$1.URL, kwkey);
22108 if (kw.length) {
22109 params[kwkey] = kw;
22110 } else if (default_value !== undefined) {
22111 params[kwkey] = default_value;
22112 }
22113 });
22114
22115 return params;
22116 },
22117
22118 clickParams: function() {
22119 var id = '',
22120 params = {};
22121 _.each(CLICK_IDS, function(idkey) {
22122 id = _.getQueryParam(document$1.URL, idkey);
22123 if (id.length) {
22124 params[idkey] = id;
22125 }
22126 });
22127
22128 return params;
22129 },
22130
22131 marketingParams: function() {
22132 return _.extend(_.info.campaignParams(), _.info.clickParams());
22133 },
22134
22135 searchEngine: function(referrer) {
22136 if (referrer.search('https?://(.*)google.([^/?]*)') === 0) {
22137 return 'google';
22138 } else if (referrer.search('https?://(.*)bing.com') === 0) {
22139 return 'bing';
22140 } else if (referrer.search('https?://(.*)yahoo.com') === 0) {
22141 return 'yahoo';
22142 } else if (referrer.search('https?://(.*)duckduckgo.com') === 0) {
22143 return 'duckduckgo';
22144 } else {
22145 return null;
22146 }
22147 },
22148
22149 searchInfo: function(referrer) {
22150 var search = _.info.searchEngine(referrer),
22151 param = (search != 'yahoo') ? 'q' : 'p',
22152 ret = {};
22153
22154 if (search !== null) {
22155 ret['$search_engine'] = search;
22156
22157 var keyword = _.getQueryParam(referrer, param);
22158 if (keyword.length) {
22159 ret['mp_keyword'] = keyword;
22160 }
22161 }
22162
22163 return ret;
22164 },
22165
22166 /**
22167 * This function detects which browser is running this script.
22168 * The order of the checks are important since many user agents
22169 * include key words used in later checks.
22170 */
22171 browser: function(user_agent, vendor, opera) {
22172 vendor = vendor || ''; // vendor is undefined for at least IE9
22173 if (opera || _.includes(user_agent, ' OPR/')) {
22174 if (_.includes(user_agent, 'Mini')) {
22175 return 'Opera Mini';
22176 }
22177 return 'Opera';
22178 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
22179 return 'BlackBerry';
22180 } else if (_.includes(user_agent, 'IEMobile') || _.includes(user_agent, 'WPDesktop')) {
22181 return 'Internet Explorer Mobile';
22182 } else if (_.includes(user_agent, 'SamsungBrowser/')) {
22183 // https://developer.samsung.com/internet/user-agent-string-format
22184 return 'Samsung Internet';
22185 } else if (_.includes(user_agent, 'Edge') || _.includes(user_agent, 'Edg/')) {
22186 return 'Microsoft Edge';
22187 } else if (_.includes(user_agent, 'FBIOS')) {
22188 return 'Facebook Mobile';
22189 } else if (_.includes(user_agent, 'Whale/')) {
22190 // https://user-agents.net/browsers/whale-browser
22191 return 'Whale Browser';
22192 } else if (_.includes(user_agent, 'Chrome')) {
22193 return 'Chrome';
22194 } else if (_.includes(user_agent, 'CriOS')) {
22195 return 'Chrome iOS';
22196 } else if (_.includes(user_agent, 'UCWEB') || _.includes(user_agent, 'UCBrowser')) {
22197 return 'UC Browser';
22198 } else if (_.includes(user_agent, 'FxiOS')) {
22199 return 'Firefox iOS';
22200 } else if (_.includes(vendor, 'Apple')) {
22201 if (_.includes(user_agent, 'Mobile')) {
22202 return 'Mobile Safari';
22203 }
22204 return 'Safari';
22205 } else if (_.includes(user_agent, 'Android')) {
22206 return 'Android Mobile';
22207 } else if (_.includes(user_agent, 'Konqueror')) {
22208 return 'Konqueror';
22209 } else if (_.includes(user_agent, 'Firefox')) {
22210 return 'Firefox';
22211 } else if (_.includes(user_agent, 'MSIE') || _.includes(user_agent, 'Trident/')) {
22212 return 'Internet Explorer';
22213 } else if (_.includes(user_agent, 'Gecko')) {
22214 return 'Mozilla';
22215 } else {
22216 return '';
22217 }
22218 },
22219
22220 /**
22221 * This function detects which browser version is running this script,
22222 * parsing major and minor version (e.g., 42.1). User agent strings from:
22223 * http://www.useragentstring.com/pages/useragentstring.php
22224 */
22225 browserVersion: function(userAgent, vendor, opera) {
22226 var browser = _.info.browser(userAgent, vendor, opera);
22227 var versionRegexs = {
22228 'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
22229 'Microsoft Edge': /Edge?\/(\d+(\.\d+)?)/,
22230 'Chrome': /Chrome\/(\d+(\.\d+)?)/,
22231 'Chrome iOS': /CriOS\/(\d+(\.\d+)?)/,
22232 'UC Browser' : /(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,
22233 'Safari': /Version\/(\d+(\.\d+)?)/,
22234 'Mobile Safari': /Version\/(\d+(\.\d+)?)/,
22235 'Opera': /(Opera|OPR)\/(\d+(\.\d+)?)/,
22236 'Firefox': /Firefox\/(\d+(\.\d+)?)/,
22237 'Firefox iOS': /FxiOS\/(\d+(\.\d+)?)/,
22238 'Konqueror': /Konqueror:(\d+(\.\d+)?)/,
22239 'BlackBerry': /BlackBerry (\d+(\.\d+)?)/,
22240 'Android Mobile': /android\s(\d+(\.\d+)?)/,
22241 'Samsung Internet': /SamsungBrowser\/(\d+(\.\d+)?)/,
22242 'Internet Explorer': /(rv:|MSIE )(\d+(\.\d+)?)/,
22243 'Mozilla': /rv:(\d+(\.\d+)?)/,
22244 'Whale Browser': /Whale\/(\d+(\.\d+)?)/
22245 };
22246 var regex = versionRegexs[browser];
22247 if (regex === undefined) {
22248 return null;
22249 }
22250 var matches = userAgent.match(regex);
22251 if (!matches) {
22252 return null;
22253 }
22254 return parseFloat(matches[matches.length - 2]);
22255 },
22256
22257 os: function() {
22258 var a = userAgent;
22259 if (/Windows/i.test(a)) {
22260 if (/Phone/.test(a) || /WPDesktop/.test(a)) {
22261 return 'Windows Phone';
22262 }
22263 return 'Windows';
22264 } else if (/(iPhone|iPad|iPod)/.test(a)) {
22265 return 'iOS';
22266 } else if (/Android/.test(a)) {
22267 return 'Android';
22268 } else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) {
22269 return 'BlackBerry';
22270 } else if (/Mac/i.test(a)) {
22271 return 'Mac OS X';
22272 } else if (/Linux/.test(a)) {
22273 return 'Linux';
22274 } else if (/CrOS/.test(a)) {
22275 return 'Chrome OS';
22276 } else {
22277 return '';
22278 }
22279 },
22280
22281 device: function(user_agent) {
22282 if (/Windows Phone/i.test(user_agent) || /WPDesktop/.test(user_agent)) {
22283 return 'Windows Phone';
22284 } else if (/iPad/.test(user_agent)) {
22285 return 'iPad';
22286 } else if (/iPod/.test(user_agent)) {
22287 return 'iPod Touch';
22288 } else if (/iPhone/.test(user_agent)) {
22289 return 'iPhone';
22290 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
22291 return 'BlackBerry';
22292 } else if (/Android/.test(user_agent)) {
22293 return 'Android';
22294 } else {
22295 return '';
22296 }
22297 },
22298
22299 referringDomain: function(referrer) {
22300 var split = referrer.split('/');
22301 if (split.length >= 3) {
22302 return split[2];
22303 }
22304 return '';
22305 },
22306
22307 currentUrl: function() {
22308 return win.location.href;
22309 },
22310
22311 properties: function(extra_props) {
22312 if (typeof extra_props !== 'object') {
22313 extra_props = {};
22314 }
22315 return _.extend(_.strip_empty_properties({
22316 '$os': _.info.os(),
22317 '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera),
22318 '$referrer': document$1.referrer,
22319 '$referring_domain': _.info.referringDomain(document$1.referrer),
22320 '$device': _.info.device(userAgent)
22321 }), {
22322 '$current_url': _.info.currentUrl(),
22323 '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera),
22324 '$screen_height': screen.height,
22325 '$screen_width': screen.width,
22326 'mp_lib': 'web',
22327 '$lib_version': Config.LIB_VERSION,
22328 '$insert_id': cheap_guid(),
22329 'time': _.timestamp() / 1000 // epoch time in seconds
22330 }, _.strip_empty_properties(extra_props));
22331 },
22332
22333 people_properties: function() {
22334 return _.extend(_.strip_empty_properties({
22335 '$os': _.info.os(),
22336 '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera)
22337 }), {
22338 '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera)
22339 });
22340 },
22341
22342 mpPageViewProperties: function() {
22343 return _.strip_empty_properties({
22344 'current_page_title': document$1.title,
22345 'current_domain': win.location.hostname,
22346 'current_url_path': win.location.pathname,
22347 'current_url_protocol': win.location.protocol,
22348 'current_url_search': win.location.search
22349 });
22350 }
22351 };
22352
22353 /**
22354 * Returns a throttled function that will only run at most every `waitMs` and returns a promise that resolves with the next invocation.
22355 * Throttled calls will build up a batch of args and invoke the callback with all args since the last invocation.
22356 */
22357 var batchedThrottle = function (fn, waitMs) {
22358 var timeoutPromise = null;
22359 var throttledItems = [];
22360 return function (item) {
22361 var self = this;
22362 throttledItems.push(item);
22363
22364 if (!timeoutPromise) {
22365 timeoutPromise = new PromisePolyfill(function (resolve) {
22366 setTimeout(function () {
22367 var returnValue = fn.apply(self, [throttledItems]);
22368 timeoutPromise = null;
22369 throttledItems = [];
22370 resolve(returnValue);
22371 }, waitMs);
22372 });
22373 }
22374 return timeoutPromise;
22375 };
22376 };
22377
22378 var cheap_guid = function(maxlen) {
22379 var guid = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
22380 return maxlen ? guid.substring(0, maxlen) : guid;
22381 };
22382
22383 /**
22384 * Generates a W3C traceparent header for easy interop with distributed tracing systems i.e Open Telemetry
22385 * https://www.w3.org/TR/trace-context/#traceparent-header
22386 */
22387 var generateTraceparent = function() {
22388 var traceID = _.UUID().replace(/-/g, '');
22389 var parentID = _.UUID().replace(/-/g, '').substring(0, 16);
22390
22391 // Sampled trace
22392 var traceFlags = '01';
22393
22394 return '00-' + traceID + '-' + parentID + '-' + traceFlags;
22395 };
22396
22397 // naive way to extract domain name (example.com) from full hostname (my.sub.example.com)
22398 var SIMPLE_DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]*\.[a-z]+$/i;
22399 // this next one attempts to account for some ccSLDs, e.g. extracting oxford.ac.uk from www.oxford.ac.uk
22400 var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
22401 /**
22402 * Attempts to extract main domain name from full hostname, using a few blunt heuristics. For
22403 * common TLDs like .com/.org that always have a simple SLD.TLD structure (example.com), we
22404 * simply extract the last two .-separated parts of the hostname (SIMPLE_DOMAIN_MATCH_REGEX).
22405 * For others, we attempt to account for short ccSLD+TLD combos (.ac.uk) with the legacy
22406 * DOMAIN_MATCH_REGEX (kept to maintain backwards compatibility with existing Mixpanel
22407 * integrations). The only _reliable_ way to extract domain from hostname is with an up-to-date
22408 * list like at https://publicsuffix.org/ so for cases that this helper fails at, the SDK
22409 * offers the 'cookie_domain' config option to set it explicitly.
22410 * @example
22411 * extract_domain('my.sub.example.com')
22412 * // 'example.com'
22413 */
22414 var extract_domain = function(hostname) {
22415 var domain_regex = DOMAIN_MATCH_REGEX;
22416 var parts = hostname.split('.');
22417 var tld = parts[parts.length - 1];
22418 if (tld.length > 4 || tld === 'com' || tld === 'org') {
22419 domain_regex = SIMPLE_DOMAIN_MATCH_REGEX;
22420 }
22421 var matches = hostname.match(domain_regex);
22422 return matches ? matches[0] : '';
22423 };
22424
22425 /**
22426 * Check whether we have network connection. default to true for browsers that don't support navigator.onLine (IE)
22427 * @returns {boolean}
22428 */
22429 var isOnline = function() {
22430 var onLine = win.navigator['onLine'];
22431 return _.isUndefined(onLine) || onLine;
22432 };
22433
22434 var NOOP_FUNC = function () {};
22435
22436 var JSONStringify = null, JSONParse = null;
22437 if (typeof JSON !== 'undefined') {
22438 JSONStringify = JSON.stringify;
22439 JSONParse = JSON.parse;
22440 }
22441 JSONStringify = JSONStringify || _.JSONEncode;
22442 JSONParse = JSONParse || _.JSONDecode;
22443
22444 // UNMINIFIED EXPORTS (for closure compiler)
22445 _['info'] = _.info;
22446 _['info']['browser'] = _.info.browser;
22447 _['info']['browserVersion'] = _.info.browserVersion;
22448 _['info']['device'] = _.info.device;
22449 _['info']['properties'] = _.info.properties;
22450 _['isBlockedUA'] = _.isBlockedUA;
22451 _['isEmptyObject'] = _.isEmptyObject;
22452 _['isObject'] = _.isObject;
22453 _['JSONDecode'] = _.JSONDecode;
22454 _['JSONEncode'] = _.JSONEncode;
22455 _['toArray'] = _.toArray;
22456 _['NPO'] = NpoPromise;
22457
22458 var MIXPANEL_DB_NAME = 'mixpanelBrowserDb';
22459
22460 var RECORDING_EVENTS_STORE_NAME = 'mixpanelRecordingEvents';
22461 var RECORDING_REGISTRY_STORE_NAME = 'mixpanelRecordingRegistry';
22462
22463 // note: increment the version number when adding new object stores
22464 var DB_VERSION = 1;
22465 var OBJECT_STORES = [RECORDING_EVENTS_STORE_NAME, RECORDING_REGISTRY_STORE_NAME];
22466
22467 /**
22468 * @type {import('./wrapper').StorageWrapper}
22469 */
22470 var IDBStorageWrapper = function (storeName) {
22471 /**
22472 * @type {Promise<IDBDatabase>|null}
22473 */
22474 this.dbPromise = null;
22475 this.storeName = storeName;
22476 };
22477
22478 IDBStorageWrapper.prototype._openDb = function () {
22479 return new PromisePolyfill(function (resolve, reject) {
22480 var openRequest = win.indexedDB.open(MIXPANEL_DB_NAME, DB_VERSION);
22481 openRequest['onerror'] = function () {
22482 reject(openRequest.error);
22483 };
22484
22485 openRequest['onsuccess'] = function () {
22486 resolve(openRequest.result);
22487 };
22488
22489 openRequest['onupgradeneeded'] = function (ev) {
22490 var db = ev.target.result;
22491
22492 OBJECT_STORES.forEach(function (storeName) {
22493 db.createObjectStore(storeName);
22494 });
22495 };
22496 });
22497 };
22498
22499 IDBStorageWrapper.prototype.init = function () {
22500 if (!win.indexedDB) {
22501 return PromisePolyfill.reject('indexedDB is not supported in this browser');
22502 }
22503
22504 if (!this.dbPromise) {
22505 this.dbPromise = this._openDb();
22506 }
22507
22508 return this.dbPromise
22509 .then(function (dbOrError) {
22510 if (dbOrError instanceof win['IDBDatabase']) {
22511 return PromisePolyfill.resolve();
22512 } else {
22513 return PromisePolyfill.reject(dbOrError);
22514 }
22515 });
22516 };
22517
22518 IDBStorageWrapper.prototype.isInitialized = function () {
22519 return !!this.dbPromise;
22520 };
22521
22522 /**
22523 * @param {IDBTransactionMode} mode
22524 * @param {function(IDBObjectStore): void} storeCb
22525 */
22526 IDBStorageWrapper.prototype.makeTransaction = function (mode, storeCb) {
22527 var storeName = this.storeName;
22528 var doTransaction = function (db) {
22529 return new PromisePolyfill(function (resolve, reject) {
22530 var transaction = db.transaction(storeName, mode);
22531 transaction.oncomplete = function () {
22532 resolve(transaction);
22533 };
22534 transaction.onabort = transaction.onerror = function () {
22535 reject(transaction.error);
22536 };
22537
22538 storeCb(transaction.objectStore(storeName));
22539 });
22540 };
22541
22542 return this.dbPromise
22543 .then(doTransaction)
22544 .catch(function (err) {
22545 if (err && err['name'] === 'InvalidStateError') {
22546 // try reopening the DB if the connection is closed
22547 this.dbPromise = this._openDb();
22548 return this.dbPromise.then(doTransaction);
22549 } else {
22550 return PromisePolyfill.reject(err);
22551 }
22552 }.bind(this));
22553 };
22554
22555 IDBStorageWrapper.prototype.setItem = function (key, value) {
22556 return this.makeTransaction('readwrite', function (objectStore) {
22557 objectStore.put(value, key);
22558 });
22559 };
22560
22561 IDBStorageWrapper.prototype.getItem = function (key) {
22562 var req;
22563 return this.makeTransaction('readonly', function (objectStore) {
22564 req = objectStore.get(key);
22565 }).then(function () {
22566 return req.result;
22567 });
22568 };
22569
22570 IDBStorageWrapper.prototype.removeItem = function (key) {
22571 return this.makeTransaction('readwrite', function (objectStore) {
22572 objectStore.delete(key);
22573 });
22574 };
22575
22576 IDBStorageWrapper.prototype.getAll = function () {
22577 var req;
22578 return this.makeTransaction('readonly', function (objectStore) {
22579 req = objectStore.getAll();
22580 }).then(function () {
22581 return req.result;
22582 });
22583 };
22584
22585 /**
22586 * GDPR utils
22587 *
22588 * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection
22589 * and privacy for all individuals within the European Union. It addresses the export of personal
22590 * data outside the EU. The GDPR aims primarily to give control back to citizens and residents
22591 * over their personal data and to simplify the regulatory environment for international business
22592 * by unifying the regulation within the EU.
22593 *
22594 * This set of utilities is intended to enable opt in/out functionality in the Mixpanel JS SDK.
22595 * These functions are used internally by the SDK and are not intended to be publicly exposed.
22596 */
22597
22598
22599 /**
22600 * A function used to track a Mixpanel event (e.g. MixpanelLib.track)
22601 * @callback trackFunction
22602 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
22603 * @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.
22604 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
22605 */
22606
22607 /** Public **/
22608
22609 var GDPR_DEFAULT_PERSISTENCE_PREFIX = '__mp_opt_in_out_';
22610
22611 /**
22612 * Opt the user in to data tracking and cookies/localstorage for the given token
22613 * @param {string} token - Mixpanel project tracking token
22614 * @param {Object} [options]
22615 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
22616 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
22617 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
22618 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22619 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22620 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
22621 * @param {string} [options.cookieDomain] - custom cookie domain
22622 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
22623 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
22624 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
22625 */
22626 function optIn(token, options) {
22627 _optInOut(true, token, options);
22628 }
22629
22630 /**
22631 * Opt the user out of data tracking and cookies/localstorage for the given token
22632 * @param {string} token - Mixpanel project tracking token
22633 * @param {Object} [options]
22634 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22635 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22636 * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires
22637 * @param {string} [options.cookieDomain] - custom cookie domain
22638 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
22639 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not
22640 * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not
22641 */
22642 function optOut(token, options) {
22643 _optInOut(false, token, options);
22644 }
22645
22646 /**
22647 * Check whether the user has opted in to data tracking and cookies/localstorage for the given token
22648 * @param {string} token - Mixpanel project tracking token
22649 * @param {Object} [options]
22650 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22651 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22652 * @returns {boolean} whether the user has opted in to the given opt type
22653 */
22654 function hasOptedIn(token, options) {
22655 return _getStorageValue(token, options) === '1';
22656 }
22657
22658 /**
22659 * Check whether the user has opted out of data tracking and cookies/localstorage for the given token
22660 * @param {string} token - Mixpanel project tracking token
22661 * @param {Object} [options]
22662 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22663 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22664 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
22665 * @returns {boolean} whether the user has opted out of the given opt type
22666 */
22667 function hasOptedOut(token, options) {
22668 if (_hasDoNotTrackFlagOn(options)) {
22669 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"');
22670 return true;
22671 }
22672 var optedOut = _getStorageValue(token, options) === '0';
22673 if (optedOut) {
22674 console$1.warn('You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data.');
22675 }
22676 return optedOut;
22677 }
22678
22679 /**
22680 * Wrap a MixpanelLib method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
22681 * If the user has opted out, return early instead of executing the method.
22682 * If a callback argument was provided, execute it passing the 0 error code.
22683 * @param {function} method - wrapped method to be executed if the user has not opted out
22684 * @returns {*} the result of executing method OR undefined if the user has opted out
22685 */
22686 function addOptOutCheckMixpanelLib(method) {
22687 return _addOptOutCheck(method, function(name) {
22688 return this.get_config(name);
22689 });
22690 }
22691
22692 /**
22693 * Wrap a MixpanelPeople method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
22694 * If the user has opted out, return early instead of executing the method.
22695 * If a callback argument was provided, execute it passing the 0 error code.
22696 * @param {function} method - wrapped method to be executed if the user has not opted out
22697 * @returns {*} the result of executing method OR undefined if the user has opted out
22698 */
22699 function addOptOutCheckMixpanelPeople(method) {
22700 return _addOptOutCheck(method, function(name) {
22701 return this._get_config(name);
22702 });
22703 }
22704
22705 /**
22706 * Wrap a MixpanelGroup method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
22707 * If the user has opted out, return early instead of executing the method.
22708 * If a callback argument was provided, execute it passing the 0 error code.
22709 * @param {function} method - wrapped method to be executed if the user has not opted out
22710 * @returns {*} the result of executing method OR undefined if the user has opted out
22711 */
22712 function addOptOutCheckMixpanelGroup(method) {
22713 return _addOptOutCheck(method, function(name) {
22714 return this._get_config(name);
22715 });
22716 }
22717
22718 /**
22719 * Clear the user's opt in/out status of data tracking and cookies/localstorage for the given token
22720 * @param {string} token - Mixpanel project tracking token
22721 * @param {Object} [options]
22722 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
22723 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22724 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
22725 * @param {string} [options.cookieDomain] - custom cookie domain
22726 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
22727 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
22728 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
22729 */
22730 function clearOptInOut(token, options) {
22731 options = options || {};
22732 _getStorage(options).remove(
22733 _getStorageKey(token, options), !!options.crossSubdomainCookie, options.cookieDomain
22734 );
22735 }
22736
22737 /** Private **/
22738
22739 /**
22740 * Get storage util
22741 * @param {Object} [options]
22742 * @param {string} [options.persistenceType]
22743 * @returns {object} either _.cookie or _.localstorage
22744 */
22745 function _getStorage(options) {
22746 options = options || {};
22747 return options.persistenceType === 'localStorage' ? _.localStorage : _.cookie;
22748 }
22749
22750 /**
22751 * Get the name of the cookie that is used for the given opt type (tracking, cookie, etc.)
22752 * @param {string} token - Mixpanel project tracking token
22753 * @param {Object} [options]
22754 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22755 * @returns {string} the name of the cookie for the given opt type
22756 */
22757 function _getStorageKey(token, options) {
22758 options = options || {};
22759 return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token;
22760 }
22761
22762 /**
22763 * Get the value of the cookie that is used for the given opt type (tracking, cookie, etc.)
22764 * @param {string} token - Mixpanel project tracking token
22765 * @param {Object} [options]
22766 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22767 * @returns {string} the value of the cookie for the given opt type
22768 */
22769 function _getStorageValue(token, options) {
22770 return _getStorage(options).get(_getStorageKey(token, options));
22771 }
22772
22773 /**
22774 * Check whether the user has set the DNT/doNotTrack setting to true in their browser
22775 * @param {Object} [options]
22776 * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests
22777 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
22778 * @returns {boolean} whether the DNT setting is true
22779 */
22780 function _hasDoNotTrackFlagOn(options) {
22781 if (options && options.ignoreDnt) {
22782 return false;
22783 }
22784 var win$1 = (options && options.window) || win;
22785 var nav = win$1['navigator'] || {};
22786 var hasDntOn = false;
22787
22788 _.each([
22789 nav['doNotTrack'], // standard
22790 nav['msDoNotTrack'],
22791 win$1['doNotTrack']
22792 ], function(dntValue) {
22793 if (_.includes([true, 1, '1', 'yes'], dntValue)) {
22794 hasDntOn = true;
22795 }
22796 });
22797
22798 return hasDntOn;
22799 }
22800
22801 /**
22802 * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type
22803 * @param {boolean} optValue - whether to opt the user in or out for the given opt type
22804 * @param {string} token - Mixpanel project tracking token
22805 * @param {Object} [options]
22806 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
22807 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
22808 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
22809 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
22810 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
22811 * @param {string} [options.cookieDomain] - custom cookie domain
22812 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
22813 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
22814 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
22815 */
22816 function _optInOut(optValue, token, options) {
22817 if (!_.isString(token) || !token.length) {
22818 console$1.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token');
22819 return;
22820 }
22821
22822 options = options || {};
22823
22824 _getStorage(options).set(
22825 _getStorageKey(token, options),
22826 optValue ? 1 : 0,
22827 _.isNumber(options.cookieExpiration) ? options.cookieExpiration : null,
22828 !!options.crossSubdomainCookie,
22829 !!options.secureCookie,
22830 !!options.crossSiteCookie,
22831 options.cookieDomain
22832 );
22833
22834 if (options.track && optValue) { // only track event if opting in (optValue=true)
22835 options.track(options.trackEventName || '$opt_in', options.trackProperties, {
22836 'send_immediately': true
22837 });
22838 }
22839 }
22840
22841 /**
22842 * Wrap a method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
22843 * If the user has opted out, return early instead of executing the method.
22844 * If a callback argument was provided, execute it passing the 0 error code.
22845 * @param {function} method - wrapped method to be executed if the user has not opted out
22846 * @param {function} getConfigValue - getter function for the Mixpanel API token and other options to be used with opt-out check
22847 * @returns {*} the result of executing method OR undefined if the user has opted out
22848 */
22849 function _addOptOutCheck(method, getConfigValue) {
22850 return function() {
22851 var optedOut = false;
22852
22853 try {
22854 var token = getConfigValue.call(this, 'token');
22855 var ignoreDnt = getConfigValue.call(this, 'ignore_dnt');
22856 var persistenceType = getConfigValue.call(this, 'opt_out_tracking_persistence_type');
22857 var persistencePrefix = getConfigValue.call(this, 'opt_out_tracking_cookie_prefix');
22858 var win = getConfigValue.call(this, 'window'); // used to override window during browser tests
22859
22860 if (token) { // if there was an issue getting the token, continue method execution as normal
22861 optedOut = hasOptedOut(token, {
22862 ignoreDnt: ignoreDnt,
22863 persistenceType: persistenceType,
22864 persistencePrefix: persistencePrefix,
22865 window: win
22866 });
22867 }
22868 } catch(err) {
22869 console$1.error('Unexpected error when checking tracking opt-out status: ' + err);
22870 }
22871
22872 if (!optedOut) {
22873 return method.apply(this, arguments);
22874 }
22875
22876 var callback = arguments[arguments.length - 1];
22877 if (typeof(callback) === 'function') {
22878 callback(0);
22879 }
22880
22881 return;
22882 };
22883 }
22884
22885 var logger$6 = console_with_prefix('lock');
22886
22887 /**
22888 * SharedLock: a mutex built on HTML5 localStorage, to ensure that only one browser
22889 * window/tab at a time will be able to access shared resources.
22890 *
22891 * Based on the Alur and Taubenfeld fast lock
22892 * (http://www.cs.rochester.edu/research/synchronization/pseudocode/fastlock.html)
22893 * with an added timeout to ensure there will be eventual progress in the event
22894 * that a window is closed in the middle of the callback.
22895 *
22896 * Implementation based on the original version by David Wolever (https://github.com/wolever)
22897 * at https://gist.github.com/wolever/5fd7573d1ef6166e8f8c4af286a69432.
22898 *
22899 * @example
22900 * const myLock = new SharedLock('some-key');
22901 * myLock.withLock(function() {
22902 * console.log('I hold the mutex!');
22903 * });
22904 *
22905 * @constructor
22906 */
22907 var SharedLock = function(key, options) {
22908 options = options || {};
22909
22910 this.storageKey = key;
22911 this.storage = options.storage || win.localStorage;
22912 this.pollIntervalMS = options.pollIntervalMS || 100;
22913 this.timeoutMS = options.timeoutMS || 2000;
22914
22915 // dependency-inject promise implementation for testing purposes
22916 this.promiseImpl = options.promiseImpl || PromisePolyfill;
22917 };
22918
22919 // pass in a specific pid to test contention scenarios; otherwise
22920 // it is chosen randomly for each acquisition attempt
22921 SharedLock.prototype.withLock = function(lockedCB, pid) {
22922 var Promise = this.promiseImpl;
22923 return new Promise(_.bind(function (resolve, reject) {
22924 var i = pid || (new Date().getTime() + '|' + Math.random());
22925 var startTime = new Date().getTime();
22926 var key = this.storageKey;
22927 var pollIntervalMS = this.pollIntervalMS;
22928 var timeoutMS = this.timeoutMS;
22929 var storage = this.storage;
22930
22931 var keyX = key + ':X';
22932 var keyY = key + ':Y';
22933 var keyZ = key + ':Z';
22934
22935 var delay = function(cb) {
22936 if (new Date().getTime() - startTime > timeoutMS) {
22937 logger$6.error('Timeout waiting for mutex on ' + key + '; clearing lock. [' + i + ']');
22938 storage.removeItem(keyZ);
22939 storage.removeItem(keyY);
22940 loop();
22941 return;
22942 }
22943 setTimeout(function() {
22944 try {
22945 cb();
22946 } catch(err) {
22947 reject(err);
22948 }
22949 }, pollIntervalMS * (Math.random() + 0.1));
22950 };
22951
22952 var waitFor = function(predicate, cb) {
22953 if (predicate()) {
22954 cb();
22955 } else {
22956 delay(function() {
22957 waitFor(predicate, cb);
22958 });
22959 }
22960 };
22961
22962 var getSetY = function() {
22963 var valY = storage.getItem(keyY);
22964 if (valY && valY !== i) { // if Y == i then this process already has the lock (useful for test cases)
22965 return false;
22966 } else {
22967 storage.setItem(keyY, i);
22968 if (storage.getItem(keyY) === i) {
22969 return true;
22970 } else {
22971 if (!localStorageSupported(storage, true)) {
22972 reject(new Error('localStorage support dropped while acquiring lock'));
22973 }
22974 return false;
22975 }
22976 }
22977 };
22978
22979 var loop = function() {
22980 storage.setItem(keyX, i);
22981
22982 waitFor(getSetY, function() {
22983 if (storage.getItem(keyX) === i) {
22984 criticalSection();
22985 return;
22986 }
22987
22988 delay(function() {
22989 if (storage.getItem(keyY) !== i) {
22990 loop();
22991 return;
22992 }
22993 waitFor(function() {
22994 return !storage.getItem(keyZ);
22995 }, criticalSection);
22996 });
22997 });
22998 };
22999
23000 var criticalSection = function() {
23001 storage.setItem(keyZ, '1');
23002 var removeLock = function () {
23003 storage.removeItem(keyZ);
23004 if (storage.getItem(keyY) === i) {
23005 storage.removeItem(keyY);
23006 }
23007 if (storage.getItem(keyX) === i) {
23008 storage.removeItem(keyX);
23009 }
23010 };
23011
23012 lockedCB()
23013 .then(function (ret) {
23014 removeLock();
23015 resolve(ret);
23016 })
23017 .catch(function (err) {
23018 removeLock();
23019 reject(err);
23020 });
23021 };
23022
23023 try {
23024 if (localStorageSupported(storage, true)) {
23025 loop();
23026 } else {
23027 throw new Error('localStorage support check failed');
23028 }
23029 } catch(err) {
23030 reject(err);
23031 }
23032 }, this));
23033 };
23034
23035 /**
23036 * @type {import('./wrapper').StorageWrapper}
23037 */
23038 var LocalStorageWrapper = function (storageOverride) {
23039 this.storage = storageOverride || win.localStorage;
23040 };
23041
23042 LocalStorageWrapper.prototype.init = function () {
23043 return PromisePolyfill.resolve();
23044 };
23045
23046 LocalStorageWrapper.prototype.isInitialized = function () {
23047 return true;
23048 };
23049
23050 LocalStorageWrapper.prototype.setItem = function (key, value) {
23051 return new PromisePolyfill(_.bind(function (resolve, reject) {
23052 try {
23053 this.storage.setItem(key, JSONStringify(value));
23054 } catch (e) {
23055 reject(e);
23056 }
23057 resolve();
23058 }, this));
23059 };
23060
23061 LocalStorageWrapper.prototype.getItem = function (key) {
23062 return new PromisePolyfill(_.bind(function (resolve, reject) {
23063 var item;
23064 try {
23065 item = JSONParse(this.storage.getItem(key));
23066 } catch (e) {
23067 reject(e);
23068 }
23069 resolve(item);
23070 }, this));
23071 };
23072
23073 LocalStorageWrapper.prototype.removeItem = function (key) {
23074 return new PromisePolyfill(_.bind(function (resolve, reject) {
23075 try {
23076 this.storage.removeItem(key);
23077 } catch (e) {
23078 reject(e);
23079 }
23080 resolve();
23081 }, this));
23082 };
23083
23084 var logger$5 = console_with_prefix('batch');
23085
23086 /**
23087 * RequestQueue: queue for batching API requests with localStorage backup for retries.
23088 * Maintains an in-memory queue which represents the source of truth for the current
23089 * page, but also writes all items out to a copy in the browser's localStorage, which
23090 * can be read on subsequent pageloads and retried. For batchability, all the request
23091 * items in the queue should be of the same type (events, people updates, group updates)
23092 * so they can be sent in a single request to the same API endpoint.
23093 *
23094 * LocalStorage keying and locking: In order for reloads and subsequent pageloads of
23095 * the same site to access the same persisted data, they must share the same localStorage
23096 * key (for instance based on project token and queue type). Therefore access to the
23097 * localStorage entry is guarded by an asynchronous mutex (SharedLock) to prevent
23098 * simultaneously open windows/tabs from overwriting each other's data (which would lead
23099 * to data loss in some situations).
23100 * @constructor
23101 */
23102 var RequestQueue = function (storageKey, options) {
23103 options = options || {};
23104 this.storageKey = storageKey;
23105 this.usePersistence = options.usePersistence;
23106 if (this.usePersistence) {
23107 this.queueStorage = options.queueStorage || new LocalStorageWrapper();
23108 this.lock = new SharedLock(storageKey, {
23109 storage: options.sharedLockStorage || win.localStorage,
23110 timeoutMS: options.sharedLockTimeoutMS,
23111 });
23112 }
23113 this.reportError = options.errorReporter || _.bind(logger$5.error, logger$5);
23114
23115 this.pid = options.pid || null; // pass pid to test out storage lock contention scenarios
23116
23117 this.memQueue = [];
23118 this.initialized = false;
23119
23120 if (options.enqueueThrottleMs) {
23121 this.enqueuePersisted = batchedThrottle(_.bind(this._enqueuePersisted, this), options.enqueueThrottleMs);
23122 } else {
23123 this.enqueuePersisted = _.bind(function (queueEntry) {
23124 return this._enqueuePersisted([queueEntry]);
23125 }, this);
23126 }
23127 };
23128
23129 RequestQueue.prototype.ensureInit = function () {
23130 if (this.initialized || !this.usePersistence) {
23131 return PromisePolyfill.resolve();
23132 }
23133
23134 return this.queueStorage
23135 .init()
23136 .then(_.bind(function () {
23137 this.initialized = true;
23138 }, this))
23139 .catch(_.bind(function (err) {
23140 this.reportError('Error initializing queue persistence. Disabling persistence', err);
23141 this.initialized = true;
23142 this.usePersistence = false;
23143 }, this));
23144 };
23145
23146 /**
23147 * Add one item to queues (memory and localStorage). The queued entry includes
23148 * the given item along with an auto-generated ID and a "flush-after" timestamp.
23149 * It is expected that the item will be sent over the network and dequeued
23150 * before the flush-after time; if this doesn't happen it is considered orphaned
23151 * (e.g., the original tab where it was enqueued got closed before it could be
23152 * sent) and the item can be sent by any tab that finds it in localStorage.
23153 *
23154 * The final callback param is called with a param indicating success or
23155 * failure of the enqueue operation; it is asynchronous because the localStorage
23156 * lock is asynchronous.
23157 */
23158 RequestQueue.prototype.enqueue = function (item, flushInterval) {
23159 var queueEntry = {
23160 'id': cheap_guid(),
23161 'flushAfter': new Date().getTime() + flushInterval * 2,
23162 'payload': item
23163 };
23164
23165 if (!this.usePersistence) {
23166 this.memQueue.push(queueEntry);
23167 return PromisePolyfill.resolve(true);
23168 } else {
23169 return this.enqueuePersisted(queueEntry);
23170 }
23171 };
23172
23173 RequestQueue.prototype._enqueuePersisted = function (queueEntries) {
23174 var enqueueItem = _.bind(function () {
23175 return this.ensureInit()
23176 .then(_.bind(function () {
23177 return this.readFromStorage();
23178 }, this))
23179 .then(_.bind(function (storedQueue) {
23180 return this.saveToStorage(storedQueue.concat(queueEntries));
23181 }, this))
23182 .then(_.bind(function (succeeded) {
23183 // only add to in-memory queue when storage succeeds
23184 if (succeeded) {
23185 this.memQueue = this.memQueue.concat(queueEntries);
23186 }
23187
23188 return succeeded;
23189 }, this))
23190 .catch(_.bind(function (err) {
23191 this.reportError('Error enqueueing items', err, queueEntries);
23192 return false;
23193 }, this));
23194 }, this);
23195
23196 return this.lock
23197 .withLock(enqueueItem, this.pid)
23198 .catch(_.bind(function (err) {
23199 this.reportError('Error acquiring storage lock', err);
23200 return false;
23201 }, this));
23202 };
23203
23204 /**
23205 * Read out the given number of queue entries. If this.memQueue
23206 * has fewer than batchSize items, then look for "orphaned" items
23207 * in the persisted queue (items where the 'flushAfter' time has
23208 * already passed).
23209 */
23210 RequestQueue.prototype.fillBatch = function (batchSize) {
23211 var batch = this.memQueue.slice(0, batchSize);
23212 if (this.usePersistence && batch.length < batchSize) {
23213 // don't need lock just to read events; localStorage is thread-safe
23214 // and the worst that could happen is a duplicate send of some
23215 // orphaned events, which will be deduplicated on the server side
23216 return this.ensureInit()
23217 .then(_.bind(function () {
23218 return this.readFromStorage();
23219 }, this))
23220 .then(_.bind(function (storedQueue) {
23221 if (storedQueue.length) {
23222 // item IDs already in batch; don't duplicate out of storage
23223 var idsInBatch = {}; // poor man's Set
23224 _.each(batch, function (item) {
23225 idsInBatch[item['id']] = true;
23226 });
23227
23228 for (var i = 0; i < storedQueue.length; i++) {
23229 var item = storedQueue[i];
23230 if (new Date().getTime() > item['flushAfter'] && !idsInBatch[item['id']]) {
23231 item.orphaned = true;
23232 batch.push(item);
23233 if (batch.length >= batchSize) {
23234 break;
23235 }
23236 }
23237 }
23238 }
23239
23240 return batch;
23241 }, this));
23242 } else {
23243 return PromisePolyfill.resolve(batch);
23244 }
23245 };
23246
23247 /**
23248 * Remove items with matching 'id' from array (immutably)
23249 * also remove any item without a valid id (e.g., malformed
23250 * storage entries).
23251 */
23252 var filterOutIDsAndInvalid = function (items, idSet) {
23253 var filteredItems = [];
23254 _.each(items, function (item) {
23255 if (item['id'] && !idSet[item['id']]) {
23256 filteredItems.push(item);
23257 }
23258 });
23259 return filteredItems;
23260 };
23261
23262 /**
23263 * Remove items with matching IDs from both in-memory queue
23264 * and persisted queue
23265 */
23266 RequestQueue.prototype.removeItemsByID = function (ids) {
23267 var idSet = {}; // poor man's Set
23268 _.each(ids, function (id) {
23269 idSet[id] = true;
23270 });
23271
23272 this.memQueue = filterOutIDsAndInvalid(this.memQueue, idSet);
23273 if (!this.usePersistence) {
23274 return PromisePolyfill.resolve(true);
23275 } else {
23276 var removeFromStorage = _.bind(function () {
23277 return this.ensureInit()
23278 .then(_.bind(function () {
23279 return this.readFromStorage();
23280 }, this))
23281 .then(_.bind(function (storedQueue) {
23282 storedQueue = filterOutIDsAndInvalid(storedQueue, idSet);
23283 return this.saveToStorage(storedQueue);
23284 }, this))
23285 .then(_.bind(function () {
23286 return this.readFromStorage();
23287 }, this))
23288 .then(_.bind(function (storedQueue) {
23289 // an extra check: did storage report success but somehow
23290 // the items are still there?
23291 for (var i = 0; i < storedQueue.length; i++) {
23292 var item = storedQueue[i];
23293 if (item['id'] && !!idSet[item['id']]) {
23294 throw new Error('Item not removed from storage');
23295 }
23296 }
23297 return true;
23298 }, this))
23299 .catch(_.bind(function (err) {
23300 this.reportError('Error removing items', err, ids);
23301 return false;
23302 }, this));
23303 }, this);
23304
23305 return this.lock
23306 .withLock(removeFromStorage, this.pid)
23307 .catch(_.bind(function (err) {
23308 this.reportError('Error acquiring storage lock', err);
23309 if (!localStorageSupported(this.lock.storage, true)) {
23310 // Looks like localStorage writes have stopped working sometime after
23311 // initialization (probably full), and so nobody can acquire locks
23312 // anymore. Consider it temporarily safe to remove items without the
23313 // lock, since nobody's writing successfully anyway.
23314 return removeFromStorage()
23315 .then(_.bind(function (success) {
23316 if (!success) {
23317 // OK, we couldn't even write out the smaller queue. Try clearing it
23318 // entirely.
23319 return this.queueStorage.removeItem(this.storageKey).then(function () {
23320 return success;
23321 });
23322 }
23323 return success;
23324 }, this))
23325 .catch(_.bind(function (err) {
23326 this.reportError('Error clearing queue', err);
23327 return false;
23328 }, this));
23329 } else {
23330 return false;
23331 }
23332 }, this));
23333 }
23334 };
23335
23336 // internal helper for RequestQueue.updatePayloads
23337 var updatePayloads = function (existingItems, itemsToUpdate) {
23338 var newItems = [];
23339 _.each(existingItems, function (item) {
23340 var id = item['id'];
23341 if (id in itemsToUpdate) {
23342 var newPayload = itemsToUpdate[id];
23343 if (newPayload !== null) {
23344 item['payload'] = newPayload;
23345 newItems.push(item);
23346 }
23347 } else {
23348 // no update
23349 newItems.push(item);
23350 }
23351 });
23352 return newItems;
23353 };
23354
23355 /**
23356 * Update payloads of given items in both in-memory queue and
23357 * persisted queue. Items set to null are removed from queues.
23358 */
23359 RequestQueue.prototype.updatePayloads = function (itemsToUpdate) {
23360 this.memQueue = updatePayloads(this.memQueue, itemsToUpdate);
23361 if (!this.usePersistence) {
23362 return PromisePolyfill.resolve(true);
23363 } else {
23364 return this.lock
23365 .withLock(_.bind(function lockAcquired() {
23366 return this.ensureInit()
23367 .then(_.bind(function () {
23368 return this.readFromStorage();
23369 }, this))
23370 .then(_.bind(function (storedQueue) {
23371 storedQueue = updatePayloads(storedQueue, itemsToUpdate);
23372 return this.saveToStorage(storedQueue);
23373 }, this))
23374 .catch(_.bind(function (err) {
23375 this.reportError('Error updating items', itemsToUpdate, err);
23376 return false;
23377 }, this));
23378 }, this), this.pid)
23379 .catch(_.bind(function (err) {
23380 this.reportError('Error acquiring storage lock', err);
23381 return false;
23382 }, this));
23383 }
23384 };
23385
23386 /**
23387 * Read and parse items array from localStorage entry, handling
23388 * malformed/missing data if necessary.
23389 */
23390 RequestQueue.prototype.readFromStorage = function () {
23391 return this.ensureInit()
23392 .then(_.bind(function () {
23393 return this.queueStorage.getItem(this.storageKey);
23394 }, this))
23395 .then(_.bind(function (storageEntry) {
23396 if (storageEntry) {
23397 if (!_.isArray(storageEntry)) {
23398 this.reportError('Invalid storage entry:', storageEntry);
23399 storageEntry = null;
23400 }
23401 }
23402 return storageEntry || [];
23403 }, this))
23404 .catch(_.bind(function (err) {
23405 this.reportError('Error retrieving queue', err);
23406 return [];
23407 }, this));
23408 };
23409
23410 /**
23411 * Serialize the given items array to localStorage.
23412 */
23413 RequestQueue.prototype.saveToStorage = function (queue) {
23414 return this.ensureInit()
23415 .then(_.bind(function () {
23416 return this.queueStorage.setItem(this.storageKey, queue);
23417 }, this))
23418 .then(function () {
23419 return true;
23420 })
23421 .catch(_.bind(function (err) {
23422 this.reportError('Error saving queue', err);
23423 return false;
23424 }, this));
23425 };
23426
23427 /**
23428 * Clear out queues (memory and localStorage).
23429 */
23430 RequestQueue.prototype.clear = function () {
23431 this.memQueue = [];
23432
23433 if (this.usePersistence) {
23434 return this.ensureInit()
23435 .then(_.bind(function () {
23436 return this.queueStorage.removeItem(this.storageKey);
23437 }, this));
23438 } else {
23439 return PromisePolyfill.resolve();
23440 }
23441 };
23442
23443 // maximum interval between request retries after exponential backoff
23444 var MAX_RETRY_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
23445
23446 var logger$4 = console_with_prefix('batch');
23447
23448 /**
23449 * RequestBatcher: manages the queueing, flushing, retry etc of requests of one
23450 * type (events, people, groups).
23451 * Uses RequestQueue to manage the backing store.
23452 * @constructor
23453 */
23454 var RequestBatcher = function(storageKey, options) {
23455 this.errorReporter = options.errorReporter;
23456 this.queue = new RequestQueue(storageKey, {
23457 errorReporter: _.bind(this.reportError, this),
23458 queueStorage: options.queueStorage,
23459 sharedLockStorage: options.sharedLockStorage,
23460 sharedLockTimeoutMS: options.sharedLockTimeoutMS,
23461 usePersistence: options.usePersistence,
23462 enqueueThrottleMs: options.enqueueThrottleMs
23463 });
23464
23465 this.libConfig = options.libConfig;
23466 this.sendRequest = options.sendRequestFunc;
23467 this.beforeSendHook = options.beforeSendHook;
23468 this.stopAllBatching = options.stopAllBatchingFunc;
23469
23470 // seed variable batch size + flush interval with configured values
23471 this.batchSize = this.libConfig['batch_size'];
23472 this.flushInterval = this.libConfig['batch_flush_interval_ms'];
23473
23474 this.stopped = !this.libConfig['batch_autostart'];
23475 this.consecutiveRemovalFailures = 0;
23476
23477 // extra client-side dedupe
23478 this.itemIdsSentSuccessfully = {};
23479
23480 // Make the flush occur at the interval specified by flushIntervalMs, default behavior will attempt consecutive flushes
23481 // as long as the queue is not empty. This is useful for high-frequency events like Session Replay where we might end up
23482 // in a request loop and get ratelimited by the server.
23483 this.flushOnlyOnInterval = options.flushOnlyOnInterval || false;
23484
23485 this._flushPromise = null;
23486 };
23487
23488 /**
23489 * Add one item to queue.
23490 */
23491 RequestBatcher.prototype.enqueue = function(item) {
23492 return this.queue.enqueue(item, this.flushInterval);
23493 };
23494
23495 /**
23496 * Start flushing batches at the configured time interval. Must call
23497 * this method upon SDK init in order to send anything over the network.
23498 */
23499 RequestBatcher.prototype.start = function() {
23500 this.stopped = false;
23501 this.consecutiveRemovalFailures = 0;
23502 return this.flush();
23503 };
23504
23505 /**
23506 * Stop flushing batches. Can be restarted by calling start().
23507 */
23508 RequestBatcher.prototype.stop = function() {
23509 this.stopped = true;
23510 if (this.timeoutID) {
23511 clearTimeout(this.timeoutID);
23512 this.timeoutID = null;
23513 }
23514 };
23515
23516 /**
23517 * Clear out queue.
23518 */
23519 RequestBatcher.prototype.clear = function() {
23520 return this.queue.clear();
23521 };
23522
23523 /**
23524 * Restore batch size configuration to whatever is set in the main SDK.
23525 */
23526 RequestBatcher.prototype.resetBatchSize = function() {
23527 this.batchSize = this.libConfig['batch_size'];
23528 };
23529
23530 /**
23531 * Restore flush interval time configuration to whatever is set in the main SDK.
23532 */
23533 RequestBatcher.prototype.resetFlush = function() {
23534 this.scheduleFlush(this.libConfig['batch_flush_interval_ms']);
23535 };
23536
23537 /**
23538 * Schedule the next flush in the given number of milliseconds.
23539 */
23540 RequestBatcher.prototype.scheduleFlush = function(flushMS) {
23541 this.flushInterval = flushMS;
23542 if (!this.stopped) { // don't schedule anymore if batching has been stopped
23543 this.timeoutID = setTimeout(_.bind(function() {
23544 if (!this.stopped) {
23545 this._flushPromise = this.flush();
23546 }
23547 }, this), this.flushInterval);
23548 }
23549 };
23550
23551 /**
23552 * Send a request using the sendRequest callback, but promisified.
23553 * TODO: sendRequest should be promisified in the first place.
23554 */
23555 RequestBatcher.prototype.sendRequestPromise = function(data, options) {
23556 return new PromisePolyfill(_.bind(function(resolve) {
23557 this.sendRequest(data, options, resolve);
23558 }, this));
23559 };
23560
23561
23562 /**
23563 * Flush one batch to network. Depending on success/failure modes, it will either
23564 * remove the batch from the queue or leave it in for retry, and schedule the next
23565 * flush. In cases of most network or API failures, it will back off exponentially
23566 * when retrying.
23567 * @param {Object} [options]
23568 * @param {boolean} [options.sendBeacon] - whether to send batch with
23569 * navigator.sendBeacon (only useful for sending batches before page unloads, as
23570 * sendBeacon offers no callbacks or status indications)
23571 */
23572 RequestBatcher.prototype.flush = function(options) {
23573 if (this.requestInProgress) {
23574 logger$4.log('Flush: Request already in progress');
23575 return PromisePolyfill.resolve();
23576 }
23577
23578 this.requestInProgress = true;
23579
23580 options = options || {};
23581 var timeoutMS = this.libConfig['batch_request_timeout_ms'];
23582 var startTime = new Date().getTime();
23583 var currentBatchSize = this.batchSize;
23584
23585 return this.queue.fillBatch(currentBatchSize)
23586 .then(_.bind(function(batch) {
23587
23588 // if there's more items in the queue than the batch size, attempt
23589 // to flush again after the current batch is done.
23590 var attemptSecondaryFlush = batch.length === currentBatchSize;
23591 var dataForRequest = [];
23592 var transformedItems = {};
23593 _.each(batch, function(item) {
23594 var payload = item['payload'];
23595 if (this.beforeSendHook && !item.orphaned) {
23596 payload = this.beforeSendHook(payload);
23597 }
23598 if (payload) {
23599 // mp_sent_by_lib_version prop captures which lib version actually
23600 // sends each event (regardless of which version originally queued
23601 // it for sending)
23602 if (payload['event'] && payload['properties']) {
23603 payload['properties'] = _.extend(
23604 {},
23605 payload['properties'],
23606 {'mp_sent_by_lib_version': Config.LIB_VERSION}
23607 );
23608 }
23609 var addPayload = true;
23610 var itemId = item['id'];
23611 if (itemId) {
23612 if ((this.itemIdsSentSuccessfully[itemId] || 0) > 5) {
23613 this.reportError('[dupe] item ID sent too many times, not sending', {
23614 item: item,
23615 batchSize: batch.length,
23616 timesSent: this.itemIdsSentSuccessfully[itemId]
23617 });
23618 addPayload = false;
23619 }
23620 } else {
23621 this.reportError('[dupe] found item with no ID', {item: item});
23622 }
23623
23624 if (addPayload) {
23625 dataForRequest.push(payload);
23626 }
23627 }
23628 transformedItems[item['id']] = payload;
23629 }, this);
23630
23631 if (dataForRequest.length < 1) {
23632 this.requestInProgress = false;
23633 this.resetFlush();
23634 return PromisePolyfill.resolve(); // nothing to do
23635 }
23636
23637 var removeItemsFromQueue = _.bind(function () {
23638 return this.queue
23639 .removeItemsByID(
23640 _.map(batch, function (item) {
23641 return item['id'];
23642 })
23643 )
23644 .then(_.bind(function (succeeded) {
23645 // client-side dedupe
23646 _.each(batch, _.bind(function(item) {
23647 var itemId = item['id'];
23648 if (itemId) {
23649 this.itemIdsSentSuccessfully[itemId] = this.itemIdsSentSuccessfully[itemId] || 0;
23650 this.itemIdsSentSuccessfully[itemId]++;
23651 if (this.itemIdsSentSuccessfully[itemId] > 5) {
23652 this.reportError('[dupe] item ID sent too many times', {
23653 item: item,
23654 batchSize: batch.length,
23655 timesSent: this.itemIdsSentSuccessfully[itemId]
23656 });
23657 }
23658 } else {
23659 this.reportError('[dupe] found item with no ID while removing', {item: item});
23660 }
23661 }, this));
23662
23663 if (succeeded) {
23664 this.consecutiveRemovalFailures = 0;
23665 if (this.flushOnlyOnInterval && !attemptSecondaryFlush) {
23666 this.resetFlush(); // schedule next batch with a delay
23667 return PromisePolyfill.resolve();
23668 } else {
23669 return this.flush(); // handle next batch if the queue isn't empty
23670 }
23671 } else {
23672 if (++this.consecutiveRemovalFailures > 5) {
23673 this.reportError('Too many queue failures; disabling batching system.');
23674 this.stopAllBatching();
23675 } else {
23676 this.resetFlush();
23677 }
23678 return PromisePolyfill.resolve();
23679 }
23680 }, this));
23681 }, this);
23682
23683 var batchSendCallback = _.bind(function(res) {
23684 this.requestInProgress = false;
23685
23686 try {
23687
23688 // handle API response in a try-catch to make sure we can reset the
23689 // flush operation if something goes wrong
23690
23691 if (options.unloading) {
23692 // update persisted data to include hook transformations
23693 return this.queue.updatePayloads(transformedItems);
23694 } else if (
23695 _.isObject(res) &&
23696 res.error === 'timeout' &&
23697 new Date().getTime() - startTime >= timeoutMS
23698 ) {
23699 this.reportError('Network timeout; retrying');
23700 return this.flush();
23701 } else if (
23702 _.isObject(res) &&
23703 (
23704 res.httpStatusCode >= 500
23705 || res.httpStatusCode === 429
23706 || (res.httpStatusCode <= 0 && !isOnline())
23707 || res.error === 'timeout'
23708 )
23709 ) {
23710 // network or API error, or 429 Too Many Requests, retry
23711 var retryMS = this.flushInterval * 2;
23712 if (res.retryAfter) {
23713 retryMS = (parseInt(res.retryAfter, 10) * 1000) || retryMS;
23714 }
23715 retryMS = Math.min(MAX_RETRY_INTERVAL_MS, retryMS);
23716 this.reportError('Error; retry in ' + retryMS + ' ms');
23717 this.scheduleFlush(retryMS);
23718 return PromisePolyfill.resolve();
23719 } else if (_.isObject(res) && res.httpStatusCode === 413) {
23720 // 413 Payload Too Large
23721 if (batch.length > 1) {
23722 var halvedBatchSize = Math.max(1, Math.floor(currentBatchSize / 2));
23723 this.batchSize = Math.min(this.batchSize, halvedBatchSize, batch.length - 1);
23724 this.reportError('413 response; reducing batch size to ' + this.batchSize);
23725 this.resetFlush();
23726 return PromisePolyfill.resolve();
23727 } else {
23728 this.reportError('Single-event request too large; dropping', batch);
23729 this.resetBatchSize();
23730 return removeItemsFromQueue();
23731 }
23732 } else {
23733 // successful network request+response; remove each item in batch from queue
23734 // (even if it was e.g. a 400, in which case retrying won't help)
23735 return removeItemsFromQueue();
23736 }
23737 } catch(err) {
23738 this.reportError('Error handling API response', err);
23739 this.resetFlush();
23740 }
23741 }, this);
23742 var requestOptions = {
23743 method: 'POST',
23744 verbose: true,
23745 ignore_json_errors: true, // eslint-disable-line camelcase
23746 timeout_ms: timeoutMS // eslint-disable-line camelcase
23747 };
23748 if (options.unloading) {
23749 requestOptions.transport = 'sendBeacon';
23750 }
23751 logger$4.log('MIXPANEL REQUEST:', dataForRequest);
23752 return this.sendRequestPromise(dataForRequest, requestOptions).then(batchSendCallback);
23753 }, this))
23754 .catch(_.bind(function(err) {
23755 this.reportError('Error flushing request queue', err);
23756 this.resetFlush();
23757 }, this));
23758 };
23759
23760 /**
23761 * Log error to global logger and optional user-defined logger.
23762 */
23763 RequestBatcher.prototype.reportError = function(msg, err) {
23764 logger$4.error.apply(logger$4.error, arguments);
23765 if (this.errorReporter) {
23766 try {
23767 if (!(err instanceof Error)) {
23768 err = new Error(msg);
23769 }
23770 this.errorReporter(msg, err);
23771 } catch(err) {
23772 logger$4.error(err);
23773 }
23774 }
23775 };
23776
23777 /**
23778 * @param {import('./session-recording').SerializedRecording} serializedRecording
23779 * @returns {boolean}
23780 */
23781 var isRecordingExpired = function(serializedRecording) {
23782 var now = Date.now();
23783 return !serializedRecording || now > serializedRecording['maxExpires'] || now > serializedRecording['idleExpires'];
23784 };
23785
23786 var RECORD_ENQUEUE_THROTTLE_MS = 250;
23787
23788 var logger$3 = console_with_prefix('recorder');
23789 var CompressionStream = win['CompressionStream'];
23790
23791 var RECORDER_BATCHER_LIB_CONFIG = {
23792 'batch_size': 1000,
23793 'batch_flush_interval_ms': 10 * 1000,
23794 'batch_request_timeout_ms': 90 * 1000,
23795 'batch_autostart': true
23796 };
23797
23798 var ACTIVE_SOURCES = new Set([
23799 IncrementalSource.MouseMove,
23800 IncrementalSource.MouseInteraction,
23801 IncrementalSource.Scroll,
23802 IncrementalSource.ViewportResize,
23803 IncrementalSource.Input,
23804 IncrementalSource.TouchMove,
23805 IncrementalSource.MediaInteraction,
23806 IncrementalSource.Drag,
23807 IncrementalSource.Selection,
23808 ]);
23809
23810 function isUserEvent(ev) {
23811 return ev.type === EventType.IncrementalSnapshot && ACTIVE_SOURCES.has(ev.data.source);
23812 }
23813
23814 /**
23815 * @typedef {Object} SerializedRecording
23816 * @property {number} idleExpires
23817 * @property {number} maxExpires
23818 * @property {number} replayStartTime
23819 * @property {number} seqNo
23820 * @property {string} batchStartUrl
23821 * @property {string} replayId
23822 * @property {string} tabId
23823 * @property {string} replayStartUrl
23824 */
23825
23826 /**
23827 * @typedef {Object} SessionRecordingOptions
23828 * @property {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
23829 * @property {String} [options.replayId] - unique uuid for a single replay
23830 * @property {Function} [options.onIdleTimeout] - callback when a recording reaches idle timeout
23831 * @property {Function} [options.onMaxLengthReached] - callback when a recording reaches its maximum length
23832 * @property {Function} [options.rrwebRecord] - rrweb's `record` function
23833 * @property {Function} [options.onBatchSent] - callback when a batch of events is sent to the server
23834 * @property {Storage} [options.sharedLockStorage] - optional storage for shared lock, used for test dependency injection
23835 * optional properties for deserialization:
23836 * @property {number} idleExpires
23837 * @property {number} maxExpires
23838 * @property {number} replayStartTime
23839 * @property {number} seqNo
23840 * @property {string} batchStartUrl
23841 * @property {string} replayStartUrl
23842 */
23843
23844 /**
23845 * @typedef {Object} UserIdInfo
23846 * @property {string} distinct_id
23847 * @property {string} user_id
23848 * @property {string} device_id
23849 */
23850
23851
23852 /**
23853 * This class encapsulates a single session recording and its lifecycle.
23854 * @param {SessionRecordingOptions} options
23855 */
23856 var SessionRecording = function(options) {
23857 this._mixpanel = options.mixpanelInstance;
23858 this._onIdleTimeout = options.onIdleTimeout || NOOP_FUNC;
23859 this._onMaxLengthReached = options.onMaxLengthReached || NOOP_FUNC;
23860 this._onBatchSent = options.onBatchSent || NOOP_FUNC;
23861 this._rrwebRecord = options.rrwebRecord || null;
23862
23863 // internal rrweb stopRecording function
23864 this._stopRecording = null;
23865 this.replayId = options.replayId;
23866
23867 this.batchStartUrl = options.batchStartUrl || null;
23868 this.replayStartUrl = options.replayStartUrl || null;
23869 this.idleExpires = options.idleExpires || null;
23870 this.maxExpires = options.maxExpires || null;
23871 this.replayStartTime = options.replayStartTime || null;
23872 this.seqNo = options.seqNo || 0;
23873
23874 this.idleTimeoutId = null;
23875 this.maxTimeoutId = null;
23876
23877 this.recordMaxMs = MAX_RECORDING_MS;
23878 this.recordMinMs = 0;
23879
23880 // disable persistence if localStorage is not supported
23881 // request-queue will automatically disable persistence if indexedDB fails to initialize
23882 var usePersistence = localStorageSupported(options.sharedLockStorage, true) && !this.getConfig('disable_persistence');
23883
23884 // each replay has its own batcher key to avoid conflicts between rrweb events of different recordings
23885 this.batcherKey = '__mprec_' + this.getConfig('name') + '_' + this.getConfig('token') + '_' + this.replayId;
23886 this.queueStorage = new IDBStorageWrapper(RECORDING_EVENTS_STORE_NAME);
23887 this.batcher = new RequestBatcher(this.batcherKey, {
23888 errorReporter: this.reportError.bind(this),
23889 flushOnlyOnInterval: true,
23890 libConfig: RECORDER_BATCHER_LIB_CONFIG,
23891 sendRequestFunc: this.flushEventsWithOptOut.bind(this),
23892 queueStorage: this.queueStorage,
23893 sharedLockStorage: options.sharedLockStorage,
23894 usePersistence: usePersistence,
23895 stopAllBatchingFunc: this.stopRecording.bind(this),
23896
23897 // increased throttle and shared lock timeout because recording events are very high frequency.
23898 // this will minimize the amount of lock contention between enqueued events.
23899 // for session recordings there is a lock for each tab anyway, so there's no risk of deadlock between tabs.
23900 enqueueThrottleMs: RECORD_ENQUEUE_THROTTLE_MS,
23901 sharedLockTimeoutMS: 10 * 1000,
23902 });
23903 };
23904
23905 /**
23906 * @returns {UserIdInfo}
23907 */
23908 SessionRecording.prototype.getUserIdInfo = function () {
23909 if (this.finalFlushUserIdInfo) {
23910 return this.finalFlushUserIdInfo;
23911 }
23912
23913 var userIdInfo = {
23914 'distinct_id': String(this._mixpanel.get_distinct_id()),
23915 };
23916
23917 // send ID management props if they exist
23918 var deviceId = this._mixpanel.get_property('$device_id');
23919 if (deviceId) {
23920 userIdInfo['$device_id'] = deviceId;
23921 }
23922 var userId = this._mixpanel.get_property('$user_id');
23923 if (userId) {
23924 userIdInfo['$user_id'] = userId;
23925 }
23926 return userIdInfo;
23927 };
23928
23929 SessionRecording.prototype.unloadPersistedData = function () {
23930 this.batcher.stop();
23931 return this.batcher.flush()
23932 .then(function () {
23933 return this.queueStorage.removeItem(this.batcherKey);
23934 }.bind(this));
23935 };
23936
23937 SessionRecording.prototype.getConfig = function(configVar) {
23938 return this._mixpanel.get_config(configVar);
23939 };
23940
23941 // Alias for getConfig, used by the common addOptOutCheckMixpanelLib function which
23942 // reaches into this class instance and expects the snake case version of the function.
23943 // eslint-disable-next-line camelcase
23944 SessionRecording.prototype.get_config = function(configVar) {
23945 return this.getConfig(configVar);
23946 };
23947
23948 SessionRecording.prototype.startRecording = function (shouldStopBatcher) {
23949 if (this._rrwebRecord === null) {
23950 this.reportError('rrweb record function not provided. ');
23951 return;
23952 }
23953
23954 if (this._stopRecording !== null) {
23955 logger$3.log('Recording already in progress, skipping startRecording.');
23956 return;
23957 }
23958
23959 this.recordMaxMs = this.getConfig('record_max_ms');
23960 if (this.recordMaxMs > MAX_RECORDING_MS) {
23961 this.recordMaxMs = MAX_RECORDING_MS;
23962 logger$3.critical('record_max_ms cannot be greater than ' + MAX_RECORDING_MS + 'ms. Capping value.');
23963 }
23964
23965 if (!this.maxExpires) {
23966 this.maxExpires = new Date().getTime() + this.recordMaxMs;
23967 }
23968
23969 this.recordMinMs = this.getConfig('record_min_ms');
23970 if (this.recordMinMs > MAX_VALUE_FOR_MIN_RECORDING_MS) {
23971 this.recordMinMs = MAX_VALUE_FOR_MIN_RECORDING_MS;
23972 logger$3.critical('record_min_ms cannot be greater than ' + MAX_VALUE_FOR_MIN_RECORDING_MS + 'ms. Capping value.');
23973 }
23974
23975 if (!this.replayStartTime) {
23976 this.replayStartTime = new Date().getTime();
23977 this.batchStartUrl = _.info.currentUrl();
23978 this.replayStartUrl = _.info.currentUrl();
23979 }
23980
23981 if (shouldStopBatcher || this.recordMinMs > 0) {
23982 // the primary case for shouldStopBatcher is when we're starting recording after a reset
23983 // and don't want to send anything over the network until there's
23984 // actual user activity
23985 // this also applies if the minimum recording length has not been hit yet
23986 // so that we don't send data until we know the recording will be long enough
23987 this.batcher.stop();
23988 } else {
23989 this.batcher.start();
23990 }
23991
23992 var resetIdleTimeout = function () {
23993 clearTimeout(this.idleTimeoutId);
23994 var idleTimeoutMs = this.getConfig('record_idle_timeout_ms');
23995 this.idleTimeoutId = setTimeout(this._onIdleTimeout, idleTimeoutMs);
23996 this.idleExpires = new Date().getTime() + idleTimeoutMs;
23997 }.bind(this);
23998 resetIdleTimeout();
23999
24000 var blockSelector = this.getConfig('record_block_selector');
24001 if (blockSelector === '' || blockSelector === null) {
24002 blockSelector = undefined;
24003 }
24004
24005 try {
24006 this._stopRecording = this._rrwebRecord({
24007 'emit': function (ev) {
24008 if (this.idleExpires && this.idleExpires < ev.timestamp) {
24009 this._onIdleTimeout();
24010 return;
24011 }
24012 if (isUserEvent(ev)) {
24013 if (this.batcher.stopped && new Date().getTime() - this.replayStartTime >= this.recordMinMs) {
24014 // start flushing again after user activity
24015 this.batcher.start();
24016 }
24017 resetIdleTimeout();
24018 }
24019 // promise only used to await during tests
24020 this.__enqueuePromise = this.batcher.enqueue(ev);
24021 }.bind(this),
24022 'blockClass': this.getConfig('record_block_class'),
24023 'blockSelector': blockSelector,
24024 'collectFonts': this.getConfig('record_collect_fonts'),
24025 'dataURLOptions': { // canvas image options (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL)
24026 'type': 'image/webp',
24027 'quality': 0.6
24028 },
24029 'maskAllInputs': true,
24030 'maskTextClass': this.getConfig('record_mask_text_class'),
24031 'maskTextSelector': this.getConfig('record_mask_text_selector'),
24032 'recordCanvas': this.getConfig('record_canvas'),
24033 'sampling': {
24034 'canvas': 15
24035 }
24036 });
24037 } catch (err) {
24038 this.reportError('Unexpected error when starting rrweb recording.', err);
24039 }
24040
24041 if (typeof this._stopRecording !== 'function') {
24042 this.reportError('rrweb failed to start, skipping this recording.');
24043 this._stopRecording = null;
24044 this.stopRecording(); // stop batcher looping and any timeouts
24045 return;
24046 }
24047
24048 var maxTimeoutMs = this.maxExpires - new Date().getTime();
24049 this.maxTimeoutId = setTimeout(this._onMaxLengthReached.bind(this), maxTimeoutMs);
24050 };
24051
24052 SessionRecording.prototype.stopRecording = function (skipFlush) {
24053 // store the user ID info in case this is getting called in mixpanel.reset()
24054 this.finalFlushUserIdInfo = this.getUserIdInfo();
24055
24056 if (!this.isRrwebStopped()) {
24057 try {
24058 this._stopRecording();
24059 } catch (err) {
24060 this.reportError('Error with rrweb stopRecording', err);
24061 }
24062 this._stopRecording = null;
24063 }
24064
24065 var flushPromise;
24066 if (this.batcher.stopped) {
24067 // never got user activity to flush after reset, so just clear the batcher
24068 flushPromise = this.batcher.clear();
24069 } else if (!skipFlush) {
24070 // flush any remaining events from running batcher
24071 flushPromise = this.batcher.flush();
24072 }
24073 this.batcher.stop();
24074
24075 clearTimeout(this.idleTimeoutId);
24076 clearTimeout(this.maxTimeoutId);
24077 return flushPromise;
24078 };
24079
24080 SessionRecording.prototype.isRrwebStopped = function () {
24081 return this._stopRecording === null;
24082 };
24083
24084
24085 /**
24086 * Flushes the current batch of events to the server, but passes an opt-out callback to make sure
24087 * we stop recording and dump any queued events if the user has opted out.
24088 */
24089 SessionRecording.prototype.flushEventsWithOptOut = function (data, options, cb) {
24090 var onOptOut = function (code) {
24091 // addOptOutCheckMixpanelLib invokes this function with code=0 when the user has opted out
24092 if (code === 0) {
24093 this.stopRecording();
24094 cb({error: 'Tracking has been opted out, stopping recording.'});
24095 }
24096 }.bind(this);
24097
24098 this._flushEvents(data, options, cb, onOptOut);
24099 };
24100
24101 /**
24102 * @returns {SerializedRecording}
24103 */
24104 SessionRecording.prototype.serialize = function () {
24105 // don't break if mixpanel instance was destroyed at some point
24106 var tabId;
24107 try {
24108 tabId = this._mixpanel.get_tab_id();
24109 } catch (e) {
24110 this.reportError('Error getting tab ID for serialization ', e);
24111 tabId = null;
24112 }
24113
24114 return {
24115 'replayId': this.replayId,
24116 'seqNo': this.seqNo,
24117 'replayStartTime': this.replayStartTime,
24118 'batchStartUrl': this.batchStartUrl,
24119 'replayStartUrl': this.replayStartUrl,
24120 'idleExpires': this.idleExpires,
24121 'maxExpires': this.maxExpires,
24122 'tabId': tabId,
24123 };
24124 };
24125
24126
24127 /**
24128 * @static
24129 * @param {SerializedRecording} serializedRecording
24130 * @param {SessionRecordingOptions} options
24131 * @returns {SessionRecording}
24132 */
24133 SessionRecording.deserialize = function (serializedRecording, options) {
24134 var recording = new SessionRecording(_.extend({}, options, {
24135 replayId: serializedRecording['replayId'],
24136 batchStartUrl: serializedRecording['batchStartUrl'],
24137 replayStartUrl: serializedRecording['replayStartUrl'],
24138 idleExpires: serializedRecording['idleExpires'],
24139 maxExpires: serializedRecording['maxExpires'],
24140 replayStartTime: serializedRecording['replayStartTime'],
24141 seqNo: serializedRecording['seqNo'],
24142 sharedLockStorage: options.sharedLockStorage,
24143 }));
24144
24145 return recording;
24146 };
24147
24148 SessionRecording.prototype._sendRequest = function(currentReplayId, reqParams, reqBody, callback) {
24149 var onSuccess = function (response, responseBody) {
24150 // Update batch specific props only if the request was successful to guarantee ordering.
24151 // RequestBatcher will always flush the next batch after the previous one succeeds.
24152 // extra check to see if the replay ID has changed so that we don't increment the seqNo on the wrong replay
24153 if (response.status === 200 && this.replayId === currentReplayId) {
24154 this.seqNo++;
24155 this.batchStartUrl = _.info.currentUrl();
24156 }
24157
24158 this._onBatchSent();
24159 callback({
24160 status: 0,
24161 httpStatusCode: response.status,
24162 responseBody: responseBody,
24163 retryAfter: response.headers.get('Retry-After')
24164 });
24165 }.bind(this);
24166 var apiHost = (this._mixpanel.get_api_host && this._mixpanel.get_api_host('record')) || this.getConfig('api_host');
24167 win['fetch'](apiHost + '/' + this.getConfig('api_routes')['record'] + '?' + new URLSearchParams(reqParams), {
24168 'method': 'POST',
24169 'headers': {
24170 'Authorization': 'Basic ' + btoa(this.getConfig('token') + ':'),
24171 'Content-Type': 'application/octet-stream'
24172 },
24173 'body': reqBody,
24174 }).then(function (response) {
24175 response.json().then(function (responseBody) {
24176 onSuccess(response, responseBody);
24177 }).catch(function (error) {
24178 callback({error: error});
24179 });
24180 }).catch(function (error) {
24181 callback({error: error, httpStatusCode: 0});
24182 });
24183 };
24184
24185 SessionRecording.prototype._flushEvents = addOptOutCheckMixpanelLib(function (data, options, callback) {
24186 var numEvents = data.length;
24187
24188 if (numEvents > 0) {
24189 var replayId = this.replayId;
24190
24191 // each rrweb event has a timestamp - leverage those to get time properties
24192 var batchStartTime = Infinity;
24193 var batchEndTime = -Infinity;
24194 var hasFullSnapshot = false;
24195 for (var i = 0; i < numEvents; i++) {
24196 batchStartTime = Math.min(batchStartTime, data[i].timestamp);
24197 batchEndTime = Math.max(batchEndTime, data[i].timestamp);
24198 if (data[i].type === EventType.FullSnapshot) {
24199 hasFullSnapshot = true;
24200 }
24201 }
24202
24203 if (this.seqNo === 0) {
24204 if (!hasFullSnapshot) {
24205 callback({error: 'First batch does not contain a full snapshot. Aborting recording.'});
24206 this.stopRecording(true);
24207 return;
24208 }
24209 this.replayStartTime = batchStartTime;
24210 } else if (!this.replayStartTime) {
24211 this.reportError('Replay start time not set but seqNo is not 0. Using current batch start time as a fallback.');
24212 this.replayStartTime = batchStartTime;
24213 }
24214
24215 var replayLengthMs = batchEndTime - this.replayStartTime;
24216
24217 var reqParams = {
24218 '$current_url': this.batchStartUrl,
24219 '$lib_version': Config.LIB_VERSION,
24220 'batch_start_time': batchStartTime / 1000,
24221 'mp_lib': 'web',
24222 'replay_id': replayId,
24223 'replay_length_ms': replayLengthMs,
24224 'replay_start_time': this.replayStartTime / 1000,
24225 'replay_start_url': this.replayStartUrl,
24226 'seq': this.seqNo
24227 };
24228 var eventsJson = JSON.stringify(data);
24229 Object.assign(reqParams, this.getUserIdInfo());
24230
24231 if (CompressionStream) {
24232 var jsonStream = new Blob([eventsJson], {type: 'application/json'}).stream();
24233 var gzipStream = jsonStream.pipeThrough(new CompressionStream('gzip'));
24234 new Response(gzipStream)
24235 .blob()
24236 .then(function(compressedBlob) {
24237 reqParams['format'] = 'gzip';
24238 this._sendRequest(replayId, reqParams, compressedBlob, callback);
24239 }.bind(this));
24240 } else {
24241 reqParams['format'] = 'body';
24242 this._sendRequest(replayId, reqParams, eventsJson, callback);
24243 }
24244 }
24245 });
24246
24247
24248 SessionRecording.prototype.reportError = function(msg, err) {
24249 logger$3.error.apply(logger$3.error, arguments);
24250 try {
24251 if (!err && !(msg instanceof Error)) {
24252 msg = new Error(msg);
24253 }
24254 this.getConfig('error_reporter')(msg, err);
24255 } catch(err) {
24256 logger$3.error(err);
24257 }
24258 };
24259
24260 /**
24261 * Module for handling the storage and retrieval of recording metadata as well as any active recordings.
24262 * Makes sure that only one tab can be recording at a time.
24263 */
24264 var RecordingRegistry = function (options) {
24265 /** @type {IDBStorageWrapper} */
24266 this.idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
24267 this.errorReporter = options.errorReporter;
24268 this.mixpanelInstance = options.mixpanelInstance;
24269 this.sharedLockStorage = options.sharedLockStorage;
24270 };
24271
24272 RecordingRegistry.prototype.isPersistenceEnabled = function() {
24273 return !this.mixpanelInstance.get_config('disable_persistence');
24274 };
24275
24276 RecordingRegistry.prototype.handleError = function (err) {
24277 this.errorReporter('IndexedDB error: ', err);
24278 };
24279
24280 /**
24281 * @param {import('./session-recording').SerializedRecording} serializedRecording
24282 */
24283 RecordingRegistry.prototype.setActiveRecording = function (serializedRecording) {
24284 if (!this.isPersistenceEnabled()) {
24285 return PromisePolyfill.resolve();
24286 }
24287
24288 var tabId = serializedRecording['tabId'];
24289 if (!tabId) {
24290 console.warn('No tab ID is set, cannot persist recording metadata.');
24291 return PromisePolyfill.resolve();
24292 }
24293
24294 return this.idb.init()
24295 .then(function () {
24296 return this.idb.setItem(tabId, serializedRecording);
24297 }.bind(this))
24298 .catch(this.handleError.bind(this));
24299 };
24300
24301 /**
24302 * @returns {Promise<import('./session-recording').SerializedRecording>}
24303 */
24304 RecordingRegistry.prototype.getActiveRecording = function () {
24305 if (!this.isPersistenceEnabled()) {
24306 return PromisePolyfill.resolve(null);
24307 }
24308
24309 return this.idb.init()
24310 .then(function () {
24311 return this.idb.getItem(this.mixpanelInstance.get_tab_id());
24312 }.bind(this))
24313 .then(function (serializedRecording) {
24314 return isRecordingExpired(serializedRecording) ? null : serializedRecording;
24315 }.bind(this))
24316 .catch(this.handleError.bind(this));
24317 };
24318
24319 RecordingRegistry.prototype.clearActiveRecording = function () {
24320 if (this.isPersistenceEnabled()) {
24321 // mark recording as expired instead of deleting it in case the page unloads mid-flush and doesn't make it to ingestion.
24322 // this will ensure the next pageload will flush the remaining events, but not try to continue the recording.
24323 return this.markActiveRecordingExpired();
24324 } else {
24325 return this.deleteActiveRecording();
24326 }
24327 };
24328
24329 RecordingRegistry.prototype.markActiveRecordingExpired = function () {
24330 return this.getActiveRecording()
24331 .then(function (serializedRecording) {
24332 if (serializedRecording) {
24333 serializedRecording['maxExpires'] = 0;
24334 return this.setActiveRecording(serializedRecording);
24335 }
24336 }.bind(this))
24337 .catch(this.handleError.bind(this));
24338 };
24339
24340 RecordingRegistry.prototype.deleteActiveRecording = function () {
24341 // avoid initializing IDB if this registry instance hasn't already written a recording
24342 if (this.idb.isInitialized()) {
24343 return this.idb.removeItem(this.mixpanelInstance.get_tab_id())
24344 .catch(this.handleError.bind(this));
24345 } else {
24346 return PromisePolyfill.resolve();
24347 }
24348 };
24349
24350 /**
24351 * Flush any inactive recordings from the registry to minimize data loss.
24352 * The main idea here is that we can flush remaining rrweb events on the next page load if a tab is closed mid-batch.
24353 */
24354 RecordingRegistry.prototype.flushInactiveRecordings = function () {
24355 if (!this.isPersistenceEnabled()) {
24356 return PromisePolyfill.resolve([]);
24357 }
24358
24359 return this.idb.init()
24360 .then(function() {
24361 return this.idb.getAll();
24362 }.bind(this))
24363 .then(function (serializedRecordings) {
24364 // clean up any expired recordings from the registry, non-expired ones may be active in other tabs
24365 var unloadPromises = serializedRecordings
24366 .filter(function (serializedRecording) {
24367 return isRecordingExpired(serializedRecording);
24368 })
24369 .map(function (serializedRecording) {
24370 var sessionRecording = SessionRecording.deserialize(serializedRecording, {
24371 mixpanelInstance: this.mixpanelInstance,
24372 sharedLockStorage: this.sharedLockStorage
24373 });
24374 return sessionRecording.unloadPersistedData()
24375 .then(function () {
24376 // expired recording was successfully flushed, we can clean it up from the registry
24377 return this.idb.removeItem(serializedRecording['tabId']);
24378 }.bind(this))
24379 .catch(this.handleError.bind(this));
24380 }.bind(this));
24381
24382 return PromisePolyfill.all(unloadPromises);
24383 }.bind(this))
24384 .catch(this.handleError.bind(this));
24385 };
24386
24387 var logger$2 = console_with_prefix('recorder');
24388
24389 /**
24390 * Recorder API: bundles rrweb and and exposes methods to start and stop recordings.
24391 * @param {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
24392 */
24393 var MixpanelRecorder = function(mixpanelInstance, rrwebRecord, sharedLockStorage) {
24394 this.mixpanelInstance = mixpanelInstance;
24395 this.rrwebRecord = rrwebRecord || record;
24396 this.sharedLockStorage = sharedLockStorage;
24397
24398 /**
24399 * @member {import('./registry').RecordingRegistry}
24400 */
24401 this.recordingRegistry = new RecordingRegistry({
24402 mixpanelInstance: this.mixpanelInstance,
24403 errorReporter: logger$2.error,
24404 sharedLockStorage: sharedLockStorage
24405 });
24406 this._flushInactivePromise = this.recordingRegistry.flushInactiveRecordings();
24407
24408 this.activeRecording = null;
24409 this.stopRecordingInProgress = false;
24410 };
24411
24412 MixpanelRecorder.prototype.startRecording = function(options) {
24413 options = options || {};
24414 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
24415 logger$2.log('Recording already in progress, skipping startRecording.');
24416 return;
24417 }
24418
24419 var onIdleTimeout = function () {
24420 logger$2.log('Idle timeout reached, restarting recording.');
24421 this.resetRecording();
24422 }.bind(this);
24423
24424 var onMaxLengthReached = function () {
24425 logger$2.log('Max recording length reached, stopping recording.');
24426 this.resetRecording();
24427 }.bind(this);
24428
24429 var onBatchSent = function () {
24430 this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
24431 this['__flushPromise'] = this.activeRecording.batcher._flushPromise;
24432 }.bind(this);
24433
24434 /**
24435 * @type {import('./session-recording').SessionRecordingOptions}
24436 */
24437 var sessionRecordingOptions = {
24438 mixpanelInstance: this.mixpanelInstance,
24439 onBatchSent: onBatchSent,
24440 onIdleTimeout: onIdleTimeout,
24441 onMaxLengthReached: onMaxLengthReached,
24442 replayId: _.UUID(),
24443 rrwebRecord: this.rrwebRecord,
24444 sharedLockStorage: this.sharedLockStorage
24445 };
24446
24447 if (options.activeSerializedRecording) {
24448 this.activeRecording = SessionRecording.deserialize(options.activeSerializedRecording, sessionRecordingOptions);
24449 } else {
24450 this.activeRecording = new SessionRecording(sessionRecordingOptions);
24451 }
24452
24453 this.activeRecording.startRecording(options.shouldStopBatcher);
24454 return this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
24455 };
24456
24457 MixpanelRecorder.prototype.stopRecording = function() {
24458 // Prevents activeSerializedRecording from being reused when stopping the recording.
24459 this.stopRecordingInProgress = true;
24460 return this._stopCurrentRecording(false, true).then(function() {
24461 return this.recordingRegistry.clearActiveRecording();
24462 }.bind(this)).then(function() {
24463 this.stopRecordingInProgress = false;
24464 }.bind(this));
24465 };
24466
24467 MixpanelRecorder.prototype.pauseRecording = function() {
24468 return this._stopCurrentRecording(false);
24469 };
24470
24471 MixpanelRecorder.prototype._stopCurrentRecording = function(skipFlush, disableActiveRecording) {
24472 if (this.activeRecording) {
24473 var stopRecordingPromise = this.activeRecording.stopRecording(skipFlush);
24474 if (disableActiveRecording) {
24475 this.activeRecording = null;
24476 }
24477 return stopRecordingPromise;
24478 }
24479 return PromisePolyfill.resolve();
24480 };
24481
24482 MixpanelRecorder.prototype.resumeRecording = function (startNewIfInactive) {
24483 if (this.activeRecording && this.activeRecording.isRrwebStopped()) {
24484 this.activeRecording.startRecording(false);
24485 return PromisePolyfill.resolve(null);
24486 }
24487
24488 return this.recordingRegistry.getActiveRecording()
24489 .then(function (activeSerializedRecording) {
24490 if (activeSerializedRecording && !this.stopRecordingInProgress) {
24491 return this.startRecording({activeSerializedRecording: activeSerializedRecording});
24492 } else if (startNewIfInactive) {
24493 return this.startRecording({shouldStopBatcher: false});
24494 } else {
24495 logger$2.log('No resumable recording found.');
24496 return null;
24497 }
24498 }.bind(this));
24499 };
24500
24501
24502 MixpanelRecorder.prototype.resetRecording = function () {
24503 this.stopRecording();
24504 this.startRecording({shouldStopBatcher: true});
24505 };
24506
24507 MixpanelRecorder.prototype.getActiveReplayId = function () {
24508 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
24509 return this.activeRecording.replayId;
24510 } else {
24511 return null;
24512 }
24513 };
24514
24515 // getter so that older mixpanel-core versions can still retrieve the replay ID
24516 // when pulling the latest recorder bundle from the CDN
24517 Object.defineProperty(MixpanelRecorder.prototype, 'replayId', {
24518 get: function () {
24519 return this.getActiveReplayId();
24520 }
24521 });
24522
24523 win['__mp_recorder'] = MixpanelRecorder;
24524
24525 // stateless utils
24526 // mostly from https://github.com/mixpanel/mixpanel-js/blob/989ada50f518edab47b9c4fd9535f9fbd5ec5fc0/src/autotrack-utils.js
24527
24528
24529 var EV_CHANGE = 'change';
24530 var EV_CLICK = 'click';
24531 var EV_HASHCHANGE = 'hashchange';
24532 var EV_INPUT = 'input';
24533 var EV_LOAD = 'load';
24534 var EV_MP_LOCATION_CHANGE = 'mp_locationchange';
24535 var EV_POPSTATE = 'popstate';
24536 // TODO scrollend isn't available in Safari: document or polyfill?
24537 var EV_SCROLLEND = 'scrollend';
24538 var EV_SCROLL = 'scroll';
24539 var EV_SELECT = 'select';
24540 var EV_SUBMIT = 'submit';
24541 var EV_TOGGLE = 'toggle';
24542 var EV_VISIBILITYCHANGE = 'visibilitychange';
24543
24544 var CLICK_EVENT_PROPS = [
24545 'clientX', 'clientY',
24546 'offsetX', 'offsetY',
24547 'pageX', 'pageY',
24548 'screenX', 'screenY',
24549 'x', 'y'
24550 ];
24551 var OPT_IN_CLASSES = ['mp-include'];
24552 var OPT_OUT_CLASSES = ['mp-no-track'];
24553 var SENSITIVE_DATA_CLASSES = OPT_OUT_CLASSES.concat(['mp-sensitive']);
24554 var TRACKED_ATTRS = [
24555 'aria-label', 'aria-labelledby', 'aria-describedby',
24556 'href', 'name', 'role', 'title', 'type'
24557 ];
24558
24559 var INTERACTIVE_ARIA_ROLES = {
24560 'button': true,
24561 'checkbox': true,
24562 'combobox': true,
24563 'grid': true,
24564 'link': true,
24565 'listbox': true,
24566 'menu': true,
24567 'menubar': true,
24568 'menuitem': true,
24569 'menuitemcheckbox': true,
24570 'menuitemradio': true,
24571 'navigation': true,
24572 'option': true,
24573 'radio': true,
24574 'radiogroup': true,
24575 'searchbox': true,
24576 'slider': true,
24577 'spinbutton': true,
24578 'switch': true,
24579 'tab': true,
24580 'tablist': true,
24581 'textbox': true,
24582 'tree': true,
24583 'treegrid': true,
24584 'treeitem': true
24585 };
24586
24587 var ALWAYS_NON_INTERACTIVE_TAGS = {
24588 // Document metadata
24589 'base': true,
24590 'head': true,
24591 'html': true,
24592 'link': true,
24593 'meta': true,
24594 'script': true,
24595 'style': true,
24596 'title': true,
24597 // Text formatting
24598 'br': true,
24599 'hr': true,
24600 'wbr': true,
24601 // Other
24602 'noscript': true,
24603 'picture': true,
24604 'source': true,
24605 'template': true,
24606 'track': true
24607 };
24608
24609 // Common container tags that need additional checks
24610 var TEXT_CONTAINER_TAGS = {
24611 'article': true,
24612 'div': true,
24613 'h1': true,
24614 'h2': true,
24615 'h3': true,
24616 'h4': true,
24617 'h5': true,
24618 'h6': true,
24619 'p': true,
24620 'section': true,
24621 'span': true
24622 };
24623
24624 var EVENT_HANDLER_ATTRIBUTES = [
24625 'onclick', 'onmousedown', 'onmouseup', 'onpointerdown', 'onpointerup', 'ontouchend', 'ontouchstart'
24626 ];
24627
24628 var MAX_DEPTH = 5;
24629
24630 var logger$1 = console_with_prefix('autocapture');
24631
24632
24633 function getClasses(el) {
24634 var classes = {};
24635 var classList = getClassName(el).split(' ');
24636 for (var i = 0; i < classList.length; i++) {
24637 var cls = classList[i];
24638 if (cls) {
24639 classes[cls] = true;
24640 }
24641 }
24642 return classes;
24643 }
24644
24645 /*
24646 * Get the className of an element, accounting for edge cases where element.className is an object
24647 * @param {Element} el - element to get the className of
24648 * @returns {string} the element's class
24649 */
24650 function getClassName(el) {
24651 switch(typeof el.className) {
24652 case 'string':
24653 return el.className;
24654 case 'object': // handle cases where className might be SVGAnimatedString or some other type
24655 return el.className.baseVal || el.getAttribute('class') || '';
24656 default: // future proof
24657 return '';
24658 }
24659 }
24660
24661 function getPreviousElementSibling(el) {
24662 if (el.previousElementSibling) {
24663 return el.previousElementSibling;
24664 } else {
24665 do {
24666 el = el.previousSibling;
24667 } while (el && !isElementNode(el));
24668 return el;
24669 }
24670 }
24671
24672 function getPropertiesFromElement(el, ev, blockAttrsSet, extraAttrs, allowElementCallback, allowSelectors) {
24673 var props = {
24674 '$classes': getClassName(el).split(' '),
24675 '$tag_name': el.tagName.toLowerCase()
24676 };
24677 var elId = el.id;
24678 if (elId) {
24679 props['$id'] = elId;
24680 }
24681
24682 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors)) {
24683 _.each(TRACKED_ATTRS.concat(extraAttrs), function(attr) {
24684 if (el.hasAttribute(attr) && !blockAttrsSet[attr]) {
24685 var attrVal = el.getAttribute(attr);
24686 if (shouldTrackValue(attrVal)) {
24687 props['$attr-' + attr] = attrVal;
24688 }
24689 }
24690 });
24691 }
24692
24693 var nthChild = 1;
24694 var nthOfType = 1;
24695 var currentElem = el;
24696 while (currentElem = getPreviousElementSibling(currentElem)) { // eslint-disable-line no-cond-assign
24697 nthChild++;
24698 if (currentElem.tagName === el.tagName) {
24699 nthOfType++;
24700 }
24701 }
24702 props['$nth_child'] = nthChild;
24703 props['$nth_of_type'] = nthOfType;
24704
24705 return props;
24706 }
24707
24708 function getPropsForDOMEvent(ev, config) {
24709 var allowElementCallback = config.allowElementCallback;
24710 var allowSelectors = config.allowSelectors || [];
24711 var blockAttrs = config.blockAttrs || [];
24712 var blockElementCallback = config.blockElementCallback;
24713 var blockSelectors = config.blockSelectors || [];
24714 var captureTextContent = config.captureTextContent || false;
24715 var captureExtraAttrs = config.captureExtraAttrs || [];
24716 var capturedForHeatMap = config.capturedForHeatMap || false;
24717
24718 // convert array to set every time, as the config may have changed
24719 var blockAttrsSet = {};
24720 _.each(blockAttrs, function(attr) {
24721 blockAttrsSet[attr] = true;
24722 });
24723
24724 var props = null;
24725
24726 var target = typeof ev.target === 'undefined' ? ev.srcElement : ev.target;
24727 if (isTextNode(target)) { // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
24728 target = target.parentNode;
24729 }
24730
24731 if (
24732 shouldTrackDomEvent(target, ev) &&
24733 isElementAllowed(target, ev, allowElementCallback, allowSelectors) &&
24734 !isElementBlocked(target, ev, blockElementCallback, blockSelectors)
24735 ) {
24736 var targetElementList = [target];
24737 var curEl = target;
24738 while (curEl.parentNode && !isTag(curEl, 'body')) {
24739 targetElementList.push(curEl.parentNode);
24740 curEl = curEl.parentNode;
24741 }
24742
24743 var elementsJson = [];
24744 var href, explicitNoTrack = false;
24745 _.each(targetElementList, function(el) {
24746 var shouldTrackDetails = shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors);
24747
24748 // if the element or a parent element is an anchor tag
24749 // include the href as a property
24750 if (!blockAttrsSet['href'] && el.tagName.toLowerCase() === 'a') {
24751 href = el.getAttribute('href');
24752 href = shouldTrackDetails && shouldTrackValue(href) && href;
24753 }
24754
24755 if (isElementBlocked(el, ev, blockElementCallback, blockSelectors)) {
24756 explicitNoTrack = true;
24757 }
24758
24759 elementsJson.push(getPropertiesFromElement(el, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors));
24760 }, this);
24761
24762 if (!explicitNoTrack) {
24763 var docElement = document$1['documentElement'];
24764 props = {
24765 '$event_type': ev.type,
24766 '$host': win.location.host,
24767 '$pathname': win.location.pathname,
24768 '$elements': elementsJson,
24769 '$el_attr__href': href,
24770 '$viewportHeight': Math.max(docElement['clientHeight'], win['innerHeight'] || 0),
24771 '$viewportWidth': Math.max(docElement['clientWidth'], win['innerWidth'] || 0),
24772 '$pageHeight': document$1['body']['offsetHeight'] || 0,
24773 '$pageWidth': document$1['body']['offsetWidth'] || 0,
24774 };
24775 _.each(captureExtraAttrs, function(attr) {
24776 if (!blockAttrsSet[attr] && target.hasAttribute(attr)) {
24777 var attrVal = target.getAttribute(attr);
24778 if (shouldTrackValue(attrVal)) {
24779 props['$el_attr__' + attr] = attrVal;
24780 }
24781 }
24782 });
24783
24784 if (captureTextContent) {
24785 elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
24786 if (elementText && elementText.length) {
24787 props['$el_text'] = elementText;
24788 }
24789 }
24790
24791 if (ev.type === EV_CLICK) {
24792 _.each(CLICK_EVENT_PROPS, function(prop) {
24793 if (prop in ev) {
24794 props['$' + prop] = ev[prop];
24795 }
24796 });
24797 if (capturedForHeatMap) {
24798 props['$captured_for_heatmap'] = true;
24799 }
24800 target = guessRealClickTarget(ev);
24801 }
24802 // prioritize text content from "real" click target if different from original target
24803 if (captureTextContent) {
24804 var elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
24805 if (elementText && elementText.length) {
24806 props['$el_text'] = elementText;
24807 }
24808 }
24809
24810 if (target) {
24811 // target may have been recalculated; check allowlists and blocklists again
24812 if (
24813 !isElementAllowed(target, ev, allowElementCallback, allowSelectors) ||
24814 isElementBlocked(target, ev, blockElementCallback, blockSelectors)
24815 ) {
24816 return null;
24817 }
24818
24819 var targetProps = getPropertiesFromElement(target, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors);
24820 props['$target'] = targetProps;
24821 // pull up more props onto main event props
24822 props['$el_classes'] = targetProps['$classes'];
24823 _.extend(props, _.strip_empty_properties({
24824 '$el_id': targetProps['$id'],
24825 '$el_tag_name': targetProps['$tag_name']
24826 }));
24827 }
24828 }
24829 }
24830
24831 return props;
24832 }
24833
24834
24835 /**
24836 * Get the direct text content of an element, protecting against sensitive data collection.
24837 * Concats textContent of each of the element's text node children; this avoids potential
24838 * collection of sensitive data that could happen if we used element.textContent and the
24839 * element had sensitive child elements, since element.textContent includes child content.
24840 * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
24841 * @param {Element} el - element to get the text of
24842 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
24843 * @returns {string} the element's direct text content
24844 */
24845 function getSafeText(el, ev, allowElementCallback, allowSelectors) {
24846 var elText = '';
24847
24848 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) && el.childNodes && el.childNodes.length) {
24849 _.each(el.childNodes, function(child) {
24850 if (isTextNode(child) && child.textContent) {
24851 elText += _.trim(child.textContent)
24852 // scrub potentially sensitive values
24853 .split(/(\s+)/).filter(shouldTrackValue).join('')
24854 // normalize whitespace
24855 .replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ')
24856 // truncate
24857 .substring(0, 255);
24858 }
24859 });
24860 }
24861
24862 return _.trim(elText);
24863 }
24864
24865 function guessRealClickTarget(ev) {
24866 var target = ev.target;
24867 var composedPath = ev['composedPath']();
24868 for (var i = 0; i < composedPath.length; i++) {
24869 var node = composedPath[i];
24870 if (
24871 isTag(node, 'a') ||
24872 isTag(node, 'button') ||
24873 isTag(node, 'input') ||
24874 isTag(node, 'select') ||
24875 (node.getAttribute && node.getAttribute('role') === 'button')
24876 ) {
24877 target = node;
24878 break;
24879 }
24880 if (node === target) {
24881 break;
24882 }
24883 }
24884 return target;
24885 }
24886
24887 function isElementAllowed(el, ev, allowElementCallback, allowSelectors) {
24888 if (allowElementCallback) {
24889 try {
24890 if (!allowElementCallback(el, ev)) {
24891 return false;
24892 }
24893 } catch (err) {
24894 logger$1.critical('Error while checking element in allowElementCallback', err);
24895 return false;
24896 }
24897 }
24898
24899 if (!allowSelectors.length) {
24900 // no allowlist; all elements are fair game
24901 return true;
24902 }
24903
24904 for (var i = 0; i < allowSelectors.length; i++) {
24905 var sel = allowSelectors[i];
24906 try {
24907 if (el['matches'](sel)) {
24908 return true;
24909 }
24910 } catch (err) {
24911 logger$1.critical('Error while checking selector: ' + sel, err);
24912 }
24913 }
24914 return false;
24915 }
24916
24917 function isElementBlocked(el, ev, blockElementCallback, blockSelectors) {
24918 var i;
24919
24920 if (blockElementCallback) {
24921 try {
24922 if (blockElementCallback(el, ev)) {
24923 return true;
24924 }
24925 } catch (err) {
24926 logger$1.critical('Error while checking element in blockElementCallback', err);
24927 return true;
24928 }
24929 }
24930
24931 if (blockSelectors && blockSelectors.length) {
24932 // programmatically prevent tracking of elements that match CSS selectors
24933 for (i = 0; i < blockSelectors.length; i++) {
24934 var sel = blockSelectors[i];
24935 try {
24936 if (el['matches'](sel)) {
24937 return true;
24938 }
24939 } catch (err) {
24940 logger$1.critical('Error while checking selector: ' + sel, err);
24941 }
24942 }
24943 }
24944
24945 // allow users to programmatically prevent tracking of elements by adding default classes such as 'mp-no-track'
24946 var classes = getClasses(el);
24947 for (i = 0; i < OPT_OUT_CLASSES.length; i++) {
24948 if (classes[OPT_OUT_CLASSES[i]]) {
24949 return true;
24950 }
24951 }
24952
24953 return false;
24954 }
24955
24956 /*
24957 * Check whether a DOM node has nodeType Node.ELEMENT_NODE
24958 * @param {Node} node - node to check
24959 * @returns {boolean} whether node is of the correct nodeType
24960 */
24961 function isElementNode(node) {
24962 return node && node.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
24963 }
24964
24965 /*
24966 * Check whether an element is of a given tag type.
24967 * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
24968 * we want to match tagNames instead of specific references because something like
24969 * element === document.body won't always work because element might not be a native
24970 * element.
24971 * @param {Element} el - element to check
24972 * @param {string} tag - tag name (e.g., "div")
24973 * @returns {boolean} whether el is of the given tag type
24974 */
24975 function isTag(el, tag) {
24976 return el && el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
24977 }
24978
24979 /*
24980 * Check whether a DOM node is a TEXT_NODE
24981 * @param {Node} node - node to check
24982 * @returns {boolean} whether node is of type Node.TEXT_NODE
24983 */
24984 function isTextNode(node) {
24985 return node && node.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
24986 }
24987
24988 function minDOMApisSupported() {
24989 try {
24990 var testEl = document$1.createElement('div');
24991 return !!testEl['matches'];
24992 } catch (err) {
24993 return false;
24994 }
24995 }
24996
24997 function weakSetSupported() {
24998 return typeof WeakSet !== 'undefined';
24999 }
25000
25001 /*
25002 * Check whether a DOM event should be "tracked" or if it may contain sensitive data
25003 * using a variety of heuristics.
25004 * @param {Element} el - element to check
25005 * @param {Event} ev - event to check
25006 * @returns {boolean} whether the event should be tracked
25007 */
25008 function shouldTrackDomEvent(el, ev) {
25009 if (!el || isTag(el, 'html') || !isElementNode(el)) {
25010 return false;
25011 }
25012 var tag = el.tagName.toLowerCase();
25013 switch (tag) {
25014 case 'form':
25015 return ev.type === EV_SUBMIT;
25016 case 'input':
25017 if (['button', 'submit'].indexOf(el.getAttribute('type')) === -1) {
25018 return ev.type === EV_CHANGE;
25019 } else {
25020 return ev.type === EV_CLICK;
25021 }
25022 case 'select':
25023 case 'textarea':
25024 return ev.type === EV_CHANGE;
25025 default:
25026 return ev.type === EV_CLICK;
25027 }
25028 }
25029
25030 /*
25031 * Check whether a DOM element should be "tracked" or if it may contain sensitive data
25032 * using a variety of heuristics.
25033 * @param {Element} el - element to check
25034 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
25035 * @returns {boolean} whether the element should be tracked
25036 */
25037 function shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) {
25038 var i;
25039
25040 if (!isElementAllowed(el, ev, allowElementCallback, allowSelectors)) {
25041 return false;
25042 }
25043
25044 for (var curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
25045 var classes = getClasses(curEl);
25046 for (i = 0; i < SENSITIVE_DATA_CLASSES.length; i++) {
25047 if (classes[SENSITIVE_DATA_CLASSES[i]]) {
25048 return false;
25049 }
25050 }
25051 }
25052
25053 var elClasses = getClasses(el);
25054 for (i = 0; i < OPT_IN_CLASSES.length; i++) {
25055 if (elClasses[OPT_IN_CLASSES[i]]) {
25056 return true;
25057 }
25058 }
25059
25060 // don't send data from inputs or similar elements since there will always be
25061 // a risk of clientside javascript placing sensitive data in attributes
25062 if (
25063 isTag(el, 'input') ||
25064 isTag(el, 'select') ||
25065 isTag(el, 'textarea') ||
25066 el.getAttribute('contenteditable') === 'true'
25067 ) {
25068 return false;
25069 }
25070
25071 // don't include hidden or password fields
25072 var type = el.type || '';
25073 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"]
25074 switch(type.toLowerCase()) {
25075 case 'hidden':
25076 return false;
25077 case 'password':
25078 return false;
25079 }
25080 }
25081
25082 // filter out data from fields that look like sensitive fields
25083 var name = el.name || el.id || '';
25084 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"]
25085 var sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
25086 if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
25087 return false;
25088 }
25089 }
25090
25091 return true;
25092 }
25093
25094
25095 /*
25096 * Check whether a string value should be "tracked" or if it may contain sensitive data
25097 * using a variety of heuristics.
25098 * @param {string} value - string value to check
25099 * @returns {boolean} whether the element should be tracked
25100 */
25101 function shouldTrackValue(value) {
25102 if (value === null || _.isUndefined(value)) {
25103 return false;
25104 }
25105
25106 if (typeof value === 'string') {
25107 value = _.trim(value);
25108
25109 // check to see if input value looks like a credit card number
25110 // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
25111 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}))$/;
25112 if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
25113 return false;
25114 }
25115
25116 // check to see if input value looks like a social security number
25117 var ssnRegex = /(^\d{3}-?\d{2}-?\d{4}$)/;
25118 if (ssnRegex.test(value)) {
25119 return false;
25120 }
25121 }
25122
25123 return true;
25124 }
25125
25126 /**
25127 * Creates a cross-browser compatible scroll end function with appropriate event listener.
25128 * For browsers that support scrollend, returns the original function with scrollend event.
25129 * For browsers without scrollend support, returns a debounced function that triggers
25130 * 100ms after the last scroll event to simulate scrollend behavior.
25131 * @param {Function} originalFunction - The function to call when scrolling ends
25132 * @returns {Object} Object containing listener function and eventType string
25133 * @returns {Function} returns.listener - The wrapped function to use as event listener
25134 * @returns {string} returns.eventType - The event type to listen for ('scrollend' or 'scroll')
25135 */
25136 function getPolyfillScrollEndFunction(originalFunction) {
25137 var supportsScrollEnd = 'onscrollend' in win;
25138 var polyfillFunction = safewrap(originalFunction);
25139 var polyfillEvent = EV_SCROLLEND;
25140 if (!supportsScrollEnd) {
25141 // Polyfill for browsers without scrollend support: wait 100ms after the last scroll event
25142 // https://developer.chrome.com/blog/scrollend-a-new-javascript-event
25143 var scrollTimer = null;
25144 var scrollDelayMs = 100;
25145
25146 polyfillFunction = safewrap(function() {
25147 clearTimeout(scrollTimer);
25148 scrollTimer = setTimeout(originalFunction, scrollDelayMs);
25149 });
25150
25151 polyfillEvent = EV_SCROLL;
25152 }
25153
25154 return {
25155 listener: polyfillFunction,
25156 eventType: polyfillEvent
25157 };
25158 }
25159
25160 function hasInlineEventHandlers(element) {
25161 for (var i = 0; i < EVENT_HANDLER_ATTRIBUTES.length; i++) {
25162 if (element.hasAttribute(EVENT_HANDLER_ATTRIBUTES[i])) {
25163 return true;
25164 }
25165 }
25166 return false;
25167 }
25168
25169 function hasInteractiveAriaRole(element) {
25170 var role = element.getAttribute('role');
25171 if (!role) return false;
25172
25173 // Handle invalid markup where multiple roles might be specified
25174 // Only the first token is recognized per ARIA spec
25175 var primaryRole = role.trim().split(/\s+/)[0].toLowerCase();
25176
25177 return INTERACTIVE_ARIA_ROLES[primaryRole];
25178 }
25179
25180 function hasAnyInteractivityIndicators(element) {
25181 var tagName = element.tagName.toLowerCase();
25182
25183 // Check for interactive HTML elements
25184 if (tagName === 'button' ||
25185 tagName === 'input' ||
25186 tagName === 'select' ||
25187 tagName === 'textarea' ||
25188 tagName === 'details' ||
25189 tagName === 'dialog') {
25190 return true;
25191 }
25192
25193 if (element.isContentEditable) {
25194 return true;
25195 }
25196
25197 if (element.onclick || element.onmousedown || element.onmouseup || element.ontouchstart || element.ontouchend) {
25198 return true;
25199 }
25200
25201 if (hasInlineEventHandlers(element)) {
25202 return true;
25203 }
25204
25205 if (hasInteractiveAriaRole(element)) {
25206 return true;
25207 }
25208
25209 if (tagName === 'a' && element.hasAttribute('href')) {
25210 return true;
25211 }
25212
25213 if (element.hasAttribute('tabindex')) {
25214 return true;
25215 }
25216
25217 return false;
25218 }
25219
25220
25221 function isDefinitelyNonInteractive(element) {
25222 if (!element || !element.tagName) {
25223 return true;
25224 }
25225
25226 var tagName = element.tagName.toLowerCase();
25227
25228 // These tags are definitely non-interactive
25229 if (ALWAYS_NON_INTERACTIVE_TAGS[tagName]) {
25230 return true;
25231 }
25232
25233 // For all other elements, we can only be certain they're non-interactive if they lack ALL indicators of interactivity
25234 // Check for any signs of interactivity
25235 if (hasAnyInteractivityIndicators(element)) {
25236 return false;
25237 }
25238
25239 // Check parent chain for interactive context
25240 var parent = element.parentElement;
25241 var depth = 0;
25242
25243 while (parent && depth < MAX_DEPTH) {
25244 if (hasAnyInteractivityIndicators(parent)) {
25245 return false; // Element is inside an interactive parent
25246 }
25247
25248 if (parent.getRootNode && parent.getRootNode() !== document$1) {
25249 var root = parent.getRootNode();
25250 if (root.host && hasAnyInteractivityIndicators(root.host)) {
25251 return false; // Inside an interactive shadow host
25252 }
25253 }
25254
25255 parent = parent.parentElement;
25256 depth++;
25257 }
25258
25259 // Pure text containers without any interactive context
25260 if (TEXT_CONTAINER_TAGS[tagName]) {
25261 // These are non-interactive ONLY if they have no interactive indicators (already checked as part of hasAnyInteractivityIndicators)
25262 return true;
25263 }
25264
25265 // Default: we can't be certain it's non-interactive
25266 return false;
25267 }
25268
25269 /** @const */ var DEFAULT_RAGE_CLICK_THRESHOLD_PX = 30;
25270 /** @const */ var DEFAULT_RAGE_CLICK_TIMEOUT_MS = 1000;
25271 /** @const */ var DEFAULT_RAGE_CLICK_CLICK_COUNT = 4;
25272
25273 function RageClickTracker() {
25274 this.clicks = [];
25275 }
25276
25277 RageClickTracker.prototype.isRageClick = function(x, y, options) {
25278 options = options || {};
25279 var thresholdPx = options['threshold_px'] || DEFAULT_RAGE_CLICK_THRESHOLD_PX;
25280 var timeoutMs = options['timeout_ms'] || DEFAULT_RAGE_CLICK_TIMEOUT_MS;
25281 var clickCount = options['click_count'] || DEFAULT_RAGE_CLICK_CLICK_COUNT;
25282 var timestamp = Date.now();
25283
25284 var lastClick = this.clicks[this.clicks.length - 1];
25285 if (
25286 lastClick &&
25287 timestamp - lastClick.timestamp < timeoutMs &&
25288 Math.sqrt(Math.pow(x - lastClick.x, 2) + Math.pow(y - lastClick.y, 2)) < thresholdPx
25289 ) {
25290 this.clicks.push({ x: x, y: y, timestamp: timestamp });
25291 if (this.clicks.length >= clickCount) {
25292 this.clicks = [];
25293 return true;
25294 }
25295 } else {
25296 this.clicks = [{ x: x, y: y, timestamp: timestamp }];
25297 }
25298 return false;
25299 };
25300
25301 function ShadowDOMObserver(changeCallback, observerConfig) {
25302 this.changeCallback = changeCallback || function() {};
25303 this.observerConfig = observerConfig;
25304
25305 this.observedShadowRoots = null;
25306 this.shadowObservers = [];
25307 }
25308
25309 ShadowDOMObserver.prototype.getEventTarget = function(event) {
25310 if (!this.observedShadowRoots) {
25311 return;
25312 }
25313 var path = this.getComposedPath(event);
25314 if (path && path.length) {
25315 return path[0];
25316 }
25317
25318 return event['target'] || event['srcElement'];
25319 };
25320
25321
25322 ShadowDOMObserver.prototype.getComposedPath = function(event) {
25323 if ('composedPath' in event) {
25324 return event['composedPath']();
25325 }
25326
25327 return [];
25328 };
25329 ShadowDOMObserver.prototype.observeFromEvent = function(event) {
25330 if (!this.observedShadowRoots) {
25331 return;
25332 }
25333
25334 var path = this.getComposedPath(event);
25335
25336 // Check each element in path for shadow roots
25337 for (var i = 0; i < path.length; i++) {
25338 var element = path[i];
25339
25340 if (element && element.shadowRoot) {
25341 this.observeShadowRoot(element.shadowRoot);
25342 }
25343 }
25344 };
25345
25346
25347 ShadowDOMObserver.prototype.observeShadowRoot = function(shadowRoot) {
25348 if (!this.observedShadowRoots || this.observedShadowRoots.has(shadowRoot)) {
25349 return;
25350 }
25351
25352 var self = this;
25353
25354 try {
25355 this.observedShadowRoots.add(shadowRoot);
25356
25357 var observer = new window.MutationObserver(function() {
25358 self.changeCallback();
25359 });
25360
25361 observer.observe(shadowRoot, this.observerConfig);
25362 this.shadowObservers.push(observer);
25363 } catch (e) {
25364 logger$1.critical('Error while observing shadow root', e);
25365 }
25366 };
25367
25368
25369 ShadowDOMObserver.prototype.start = function() {
25370 if (this.observedShadowRoots) {
25371 return;
25372 }
25373
25374 if (!weakSetSupported()) {
25375 logger$1.critical('Shadow DOM observation unavailable: WeakSet not supported');
25376 return;
25377 }
25378
25379 this.observedShadowRoots = new WeakSet();
25380 };
25381
25382 ShadowDOMObserver.prototype.stop = function() {
25383 if (!this.observedShadowRoots) {
25384 return;
25385 }
25386
25387 for (var i = 0; i < this.shadowObservers.length; i++) {
25388 try {
25389 this.shadowObservers[i].disconnect();
25390 } catch (e) {
25391 logger$1.critical('Error while disconnecting shadow DOM observer', e);
25392 }
25393 }
25394 this.shadowObservers = [];
25395 this.observedShadowRoots = null;
25396 };
25397
25398 /** @const */ var DEFAULT_DEAD_CLICK_TIMEOUT_MS = 500;
25399 /** @const */ var INTERACTION_EVENTS = [EV_CHANGE, EV_INPUT, EV_SUBMIT, EV_SELECT, EV_TOGGLE];
25400 /** @const */ var LAYOUT_EVENTS = [EV_SCROLLEND];
25401 /** @const */ var NAVIGATION_EVENTS = [EV_HASHCHANGE];
25402 /** @const */ var MUTATION_OBSERVER_CONFIG = {
25403 characterData: true,
25404 childList: true,
25405 subtree: true,
25406 attributes: true,
25407 attributeFilter: ['style', 'class', 'hidden', 'checked', 'selected', 'value', 'display', 'visibility']
25408 };
25409
25410
25411 function DeadClickTracker(onDeadClickCallback) {
25412 this.eventListeners = [];
25413 this.mutationObserver = null;
25414 this.shadowDOMObserver = null;
25415
25416 this.isTracking = false;
25417 this.lastChangeEventTimestamp = 0;
25418 this.pendingClicks = [];
25419 this.onDeadClickCallback = onDeadClickCallback;
25420 this.processingActive = false;
25421 this.processingTimeout = null;
25422 }
25423
25424
25425 DeadClickTracker.prototype.addClick = function(event) {
25426 var element = this.shadowDOMObserver && this.shadowDOMObserver.getEventTarget(event);
25427
25428 if (!element) {
25429 element = event['target'] || event['srcElement'];
25430 }
25431
25432 if (!element || isDefinitelyNonInteractive(element)) {
25433 return false;
25434 }
25435
25436 if (this.shadowDOMObserver) {
25437 this.shadowDOMObserver.observeFromEvent(event);
25438 }
25439 this.pendingClicks.push({
25440 element: element,
25441 event: event,
25442 timestamp: Date.now()
25443 });
25444 return true;
25445 };
25446
25447 DeadClickTracker.prototype.trackClick = function(event, config) {
25448 if (!this.isTracking) {
25449 return false;
25450 }
25451
25452 var added = this.addClick(event);
25453 if (added) {
25454 this.triggerProcessing(config);
25455 }
25456 return added;
25457 };
25458
25459 DeadClickTracker.prototype.getDeadClicks = function(config) {
25460 if (this.pendingClicks.length === 0) {
25461 return [];
25462 }
25463
25464 var timeoutMs = config['timeout_ms'];
25465 var now = Date.now();
25466 var clicksToEvaluate = this.pendingClicks.slice(); // Copy array
25467 this.pendingClicks = []; // Clear original
25468
25469 var deadClicks = [];
25470
25471 for (var i = 0; i < clicksToEvaluate.length; i++) {
25472 var click = clicksToEvaluate[i];
25473
25474 if (now - click.timestamp >= timeoutMs) {
25475 // Click has exceeded timeout, check if it's dead by looking for changes after this specific click
25476 if (!this.hasChangesAfter(click.timestamp)) {
25477 deadClicks.push(click);
25478 }
25479 } else {
25480 // Still pending - add back
25481 this.pendingClicks.push(click);
25482 }
25483 }
25484
25485 return deadClicks;
25486 };
25487
25488 DeadClickTracker.prototype.hasChangesAfter = function(timestamp) {
25489 // 100ms tolerance for race condition between when we record the click and the change event
25490 return this.lastChangeEventTimestamp >= (timestamp - 100);
25491 };
25492
25493 DeadClickTracker.prototype.recordChangeEvent = function() {
25494 this.lastChangeEventTimestamp = Date.now();
25495 };
25496
25497 DeadClickTracker.prototype.triggerProcessing = function(config) {
25498 // Prevent multiple concurrent processing chains
25499 if (this.processingActive) {
25500 return;
25501 }
25502 this.processingActive = true;
25503 this.processRecursively(config);
25504 };
25505
25506 DeadClickTracker.prototype.processRecursively = function(config) {
25507 if (!this.isTracking || !this.onDeadClickCallback) {
25508 this.processingActive = false;
25509 return;
25510 }
25511
25512 var timeoutMs = config['timeout_ms'];
25513 var self = this;
25514
25515 this.processingTimeout = setTimeout(function() {
25516 if (!self.processingActive) {
25517 return;
25518 }
25519
25520 var deadClicks = self.getDeadClicks(config);
25521
25522 for (var i = 0; i < deadClicks.length; i++) {
25523 self.onDeadClickCallback(deadClicks[i].event);
25524 }
25525
25526 if (self.pendingClicks.length > 0) {
25527 self.processRecursively(config);
25528 } else {
25529 self.processingActive = false;
25530 }
25531 }, timeoutMs);
25532 };
25533
25534 DeadClickTracker.prototype.startTracking = function() {
25535 if (this.isTracking) {
25536 return;
25537 }
25538
25539 this.isTracking = true;
25540
25541 var self = this;
25542
25543 INTERACTION_EVENTS.forEach(function(event) {
25544 var handler = function() {
25545 self.recordChangeEvent();
25546 };
25547 document.addEventListener(event, handler, { capture: true, passive: true });
25548 self.eventListeners.push({ target: document, event: event, handler: handler, options: { capture: true, passive: true } });
25549 });
25550 NAVIGATION_EVENTS.forEach(function(event) {
25551 var handler = function() {
25552 self.recordChangeEvent();
25553 };
25554 window.addEventListener(event, handler);
25555 self.eventListeners.push({ target: window, event: event, handler: handler });
25556 });
25557 LAYOUT_EVENTS.forEach(function(event) {
25558 var handler = function() {
25559 self.recordChangeEvent();
25560 };
25561 window.addEventListener(event, handler, { passive: true });
25562 self.eventListeners.push({ target: window, event: event, handler: handler, options: { passive: true } });
25563 });
25564 var selectionHandler = function() {
25565 self.recordChangeEvent();
25566 };
25567 document.addEventListener('selectionchange', selectionHandler);
25568 self.eventListeners.push({ target: document, event: 'selectionchange', handler: selectionHandler });
25569
25570 // Set up MutationObserver
25571 if (window.MutationObserver) {
25572 try {
25573 this.mutationObserver = new window.MutationObserver(function() {
25574 self.recordChangeEvent();
25575 });
25576
25577 this.mutationObserver.observe(document.body || document.documentElement, MUTATION_OBSERVER_CONFIG);
25578 } catch (e) {
25579 logger$1.critical('Error while setting up mutation observer', e);
25580 }
25581 }
25582
25583 // Set up Shadow DOM observer
25584 if (window.customElements) {
25585 try {
25586 this.shadowDOMObserver = new ShadowDOMObserver(
25587 function() {
25588 self.recordChangeEvent();
25589 },
25590 MUTATION_OBSERVER_CONFIG
25591 );
25592 this.shadowDOMObserver.start();
25593 } catch (e) {
25594 logger$1.critical('Error while setting up shadow DOM observer', e);
25595 this.shadowDOMObserver = null;
25596 }
25597 }
25598 };
25599
25600 DeadClickTracker.prototype.stopTracking = function() {
25601 if (!this.isTracking) {
25602 return;
25603 }
25604
25605 this.isTracking = false;
25606 this.pendingClicks = [];
25607 this.lastChangeEventTimestamp = 0;
25608 this.processingActive = false;
25609
25610 if (this.processingTimeout) {
25611 clearTimeout(this.processingTimeout);
25612 this.processingTimeout = null;
25613 }
25614
25615 // Remove all event listeners
25616 for (var i = 0; i < this.eventListeners.length; i++) {
25617 var listener = this.eventListeners[i];
25618 try {
25619 listener.target.removeEventListener(listener.event, listener.handler, listener.options);
25620 } catch (e) {
25621 logger$1.critical('Error while removing event listener', e);
25622 }
25623 }
25624 this.eventListeners = [];
25625
25626 if (this.mutationObserver) {
25627 try {
25628 this.mutationObserver.disconnect();
25629 } catch (e) {
25630 logger$1.critical('Error while disconnecting mutation observer', e);
25631 }
25632 this.mutationObserver = null;
25633 }
25634
25635 if (this.shadowDOMObserver) {
25636 try {
25637 this.shadowDOMObserver.stop();
25638 } catch (e) {
25639 logger$1.critical('Error while stopping shadow DOM observer', e);
25640 }
25641 this.shadowDOMObserver = null;
25642 }
25643 };
25644
25645 var AUTOCAPTURE_CONFIG_KEY = 'autocapture';
25646 var LEGACY_PAGEVIEW_CONFIG_KEY = 'track_pageview';
25647
25648 var PAGEVIEW_OPTION_FULL_URL = 'full-url';
25649 var PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING = 'url-with-path-and-query-string';
25650 var PAGEVIEW_OPTION_URL_WITH_PATH = 'url-with-path';
25651
25652 var CONFIG_ALLOW_ELEMENT_CALLBACK = 'allow_element_callback';
25653 var CONFIG_ALLOW_SELECTORS = 'allow_selectors';
25654 var CONFIG_ALLOW_URL_REGEXES = 'allow_url_regexes';
25655 var CONFIG_BLOCK_ATTRS = 'block_attrs';
25656 var CONFIG_BLOCK_ELEMENT_CALLBACK = 'block_element_callback';
25657 var CONFIG_BLOCK_SELECTORS = 'block_selectors';
25658 var CONFIG_BLOCK_URL_REGEXES = 'block_url_regexes';
25659 var CONFIG_CAPTURE_EXTRA_ATTRS = 'capture_extra_attrs';
25660 var CONFIG_CAPTURE_TEXT_CONTENT = 'capture_text_content';
25661 var CONFIG_SCROLL_CAPTURE_ALL = 'scroll_capture_all';
25662 var CONFIG_SCROLL_CHECKPOINTS = 'scroll_depth_percent_checkpoints';
25663 var CONFIG_TRACK_CLICK = 'click';
25664 var CONFIG_TRACK_DEAD_CLICK = 'dead_click';
25665 var CONFIG_TRACK_INPUT = 'input';
25666 var CONFIG_TRACK_PAGEVIEW = 'pageview';
25667 var CONFIG_TRACK_RAGE_CLICK = 'rage_click';
25668 var CONFIG_TRACK_SCROLL = 'scroll';
25669 var CONFIG_TRACK_PAGE_LEAVE = 'page_leave';
25670 var CONFIG_TRACK_SUBMIT = 'submit';
25671
25672 var CONFIG_DEFAULTS$1 = {};
25673 CONFIG_DEFAULTS$1[CONFIG_ALLOW_SELECTORS] = [];
25674 CONFIG_DEFAULTS$1[CONFIG_ALLOW_URL_REGEXES] = [];
25675 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ATTRS] = [];
25676 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ELEMENT_CALLBACK] = null;
25677 CONFIG_DEFAULTS$1[CONFIG_BLOCK_SELECTORS] = [];
25678 CONFIG_DEFAULTS$1[CONFIG_BLOCK_URL_REGEXES] = [];
25679 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_EXTRA_ATTRS] = [];
25680 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_TEXT_CONTENT] = false;
25681 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CAPTURE_ALL] = false;
25682 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CHECKPOINTS] = [25, 50, 75, 100];
25683 CONFIG_DEFAULTS$1[CONFIG_TRACK_CLICK] = true;
25684 CONFIG_DEFAULTS$1[CONFIG_TRACK_DEAD_CLICK] = true;
25685 CONFIG_DEFAULTS$1[CONFIG_TRACK_INPUT] = true;
25686 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGEVIEW] = PAGEVIEW_OPTION_FULL_URL;
25687 CONFIG_DEFAULTS$1[CONFIG_TRACK_RAGE_CLICK] = true;
25688 CONFIG_DEFAULTS$1[CONFIG_TRACK_SCROLL] = true;
25689 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGE_LEAVE] = false;
25690 CONFIG_DEFAULTS$1[CONFIG_TRACK_SUBMIT] = true;
25691
25692 var DEFAULT_PROPS = {
25693 '$mp_autocapture': true
25694 };
25695
25696 var MP_EV_CLICK = '$mp_click';
25697 var MP_EV_DEAD_CLICK = '$mp_dead_click';
25698 var MP_EV_INPUT = '$mp_input_change';
25699 var MP_EV_RAGE_CLICK = '$mp_rage_click';
25700 var MP_EV_SCROLL = '$mp_scroll';
25701 var MP_EV_SUBMIT = '$mp_submit';
25702 var MP_EV_PAGE_LEAVE = '$mp_page_leave';
25703
25704 /**
25705 * Autocapture: manages automatic event tracking
25706 * @constructor
25707 */
25708 var Autocapture = function(mp) {
25709 this.mp = mp;
25710 this.maxScrollViewDepth = 0;
25711 this.hasTrackedScrollSession = false;
25712 this.previousScrollHeight = 0;
25713 };
25714
25715 Autocapture.prototype.init = function() {
25716 if (!minDOMApisSupported()) {
25717 logger$1.critical('Autocapture unavailable: missing required DOM APIs');
25718 return;
25719 }
25720 this.initPageListeners();
25721 this.initPageviewTracking();
25722 this.initClickTracking();
25723 this.initDeadClickTracking();
25724 this.initInputTracking();
25725 this.initScrollTracking();
25726 this.initSubmitTracking();
25727 this.initRageClickTracking();
25728 this.initPageLeaveTracking();
25729 };
25730
25731 Autocapture.prototype.getFullConfig = function() {
25732 var autocaptureConfig = this.mp.get_config(AUTOCAPTURE_CONFIG_KEY);
25733 if (!autocaptureConfig) {
25734 // Autocapture is completely off
25735 return {};
25736 } else if (_.isObject(autocaptureConfig)) {
25737 return _.extend({}, CONFIG_DEFAULTS$1, autocaptureConfig);
25738 } else {
25739 // Autocapture config is non-object truthy value, return default
25740 return CONFIG_DEFAULTS$1;
25741 }
25742 };
25743
25744 Autocapture.prototype.getConfig = function(key) {
25745 return this.getFullConfig()[key];
25746 };
25747
25748 Autocapture.prototype.currentUrlBlocked = function() {
25749 var i;
25750 var currentUrl = _.info.currentUrl();
25751
25752 var allowUrlRegexes = this.getConfig(CONFIG_ALLOW_URL_REGEXES) || [];
25753 if (allowUrlRegexes.length) {
25754 // we're using an allowlist, only track if current URL matches
25755 var allowed = false;
25756 for (i = 0; i < allowUrlRegexes.length; i++) {
25757 var allowRegex = allowUrlRegexes[i];
25758 try {
25759 if (currentUrl.match(allowRegex)) {
25760 allowed = true;
25761 break;
25762 }
25763 } catch (err) {
25764 logger$1.critical('Error while checking block URL regex: ' + allowRegex, err);
25765 return true;
25766 }
25767 }
25768 if (!allowed) {
25769 // wasn't allowed by any regex
25770 return true;
25771 }
25772 }
25773
25774 var blockUrlRegexes = this.getConfig(CONFIG_BLOCK_URL_REGEXES) || [];
25775 if (!blockUrlRegexes || !blockUrlRegexes.length) {
25776 return false;
25777 }
25778
25779 for (i = 0; i < blockUrlRegexes.length; i++) {
25780 try {
25781 if (currentUrl.match(blockUrlRegexes[i])) {
25782 return true;
25783 }
25784 } catch (err) {
25785 logger$1.critical('Error while checking block URL regex: ' + blockUrlRegexes[i], err);
25786 return true;
25787 }
25788 }
25789 return false;
25790 };
25791
25792 Autocapture.prototype.pageviewTrackingConfig = function() {
25793 // supports both autocapture config and old track_pageview config
25794 if (this.mp.get_config(AUTOCAPTURE_CONFIG_KEY)) {
25795 return this.getConfig(CONFIG_TRACK_PAGEVIEW);
25796 } else {
25797 return this.mp.get_config(LEGACY_PAGEVIEW_CONFIG_KEY);
25798 }
25799 };
25800
25801 // helper for event handlers
25802 Autocapture.prototype.trackDomEvent = function(ev, mpEventName) {
25803 if (this.currentUrlBlocked()) {
25804 return;
25805 }
25806
25807 var isCapturedForHeatMap = this.mp.is_recording_heatmap_data() && (
25808 (mpEventName === MP_EV_CLICK && !this.getConfig(CONFIG_TRACK_CLICK)) ||
25809 (mpEventName === MP_EV_RAGE_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK)) ||
25810 (mpEventName === MP_EV_DEAD_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK))
25811 );
25812
25813 var props = getPropsForDOMEvent(ev, {
25814 allowElementCallback: this.getConfig(CONFIG_ALLOW_ELEMENT_CALLBACK),
25815 allowSelectors: this.getConfig(CONFIG_ALLOW_SELECTORS),
25816 blockAttrs: this.getConfig(CONFIG_BLOCK_ATTRS),
25817 blockElementCallback: this.getConfig(CONFIG_BLOCK_ELEMENT_CALLBACK),
25818 blockSelectors: this.getConfig(CONFIG_BLOCK_SELECTORS),
25819 captureExtraAttrs: this.getConfig(CONFIG_CAPTURE_EXTRA_ATTRS),
25820 captureTextContent: this.getConfig(CONFIG_CAPTURE_TEXT_CONTENT),
25821 capturedForHeatMap: isCapturedForHeatMap,
25822 });
25823 if (props) {
25824 _.extend(props, DEFAULT_PROPS);
25825 this.mp.track(mpEventName, props);
25826 }
25827 };
25828
25829 Autocapture.prototype.initPageListeners = function() {
25830 win.removeEventListener(EV_POPSTATE, this.listenerPopstate);
25831 win.removeEventListener(EV_HASHCHANGE, this.listenerHashchange);
25832
25833 if (!this.pageviewTrackingConfig() && !this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config('record_heatmap_data')) {
25834 // These are all the configs that use these listeners
25835 return;
25836 }
25837
25838 this.listenerPopstate = function() {
25839 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
25840 };
25841 this.listenerHashchange = function() {
25842 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
25843 };
25844
25845 win.addEventListener(EV_POPSTATE, this.listenerPopstate);
25846 win.addEventListener(EV_HASHCHANGE, this.listenerHashchange);
25847 var nativePushState = win.history.pushState;
25848 if (typeof nativePushState === 'function') {
25849 win.history.pushState = function(state, unused, url) {
25850 nativePushState.call(win.history, state, unused, url);
25851 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
25852 };
25853 }
25854 var nativeReplaceState = win.history.replaceState;
25855 if (typeof nativeReplaceState === 'function') {
25856 win.history.replaceState = function(state, unused, url) {
25857 nativeReplaceState.call(win.history, state, unused, url);
25858 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
25859 };
25860 }
25861 };
25862
25863 Autocapture.prototype._getClickTrackingConfig = function(configKey) {
25864 var config = this.getConfig(configKey);
25865
25866 if (!config) {
25867 return null; // click tracking disabled
25868 }
25869
25870 if (config === true) {
25871 return {}; // use defaults
25872 }
25873
25874 if (typeof config === 'object') {
25875 return config; // use custom configuration
25876 }
25877
25878 return {}; // fallback to defaults for any other truthy value
25879 };
25880
25881 Autocapture.prototype._trackPageLeave = function(ev, currentUrl, currentScrollHeight) {
25882 if (this.hasTrackedScrollSession) {
25883 // User has navigated away already ending their impression.
25884 return;
25885 }
25886
25887 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.is_recording_heatmap_data()) {
25888 return;
25889 }
25890
25891 this.hasTrackedScrollSession = true;
25892 var viewportHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
25893 var scrollPercentage = Math.round(Math.max(this.maxScrollViewDepth - viewportHeight, 0) / (currentScrollHeight - viewportHeight) * 100);
25894 var foldLinePercentage = Math.round((viewportHeight / currentScrollHeight) * 100);
25895 if (currentScrollHeight <= viewportHeight) {
25896 // If the content fits within the viewport, consider it fully scrolled
25897 scrollPercentage = 100;
25898 foldLinePercentage = 100;
25899 }
25900
25901 var props = _.extend({
25902 '$max_scroll_view_depth': this.maxScrollViewDepth,
25903 '$max_scroll_percentage': scrollPercentage,
25904 '$fold_line_percentage': foldLinePercentage,
25905 '$scroll_height': currentScrollHeight,
25906 '$event_type': ev.type,
25907 '$current_url': currentUrl || _.info.currentUrl(),
25908 '$viewportHeight': viewportHeight, // This is the fold line
25909 '$viewportWidth': Math.max(document$1.documentElement.clientWidth, win.innerWidth || 0),
25910 '$captured_for_heatmap': this.mp.is_recording_heatmap_data()
25911 }, DEFAULT_PROPS);
25912
25913 // Send with beacon transport to ensure event is sent before unload
25914 this.mp.track(MP_EV_PAGE_LEAVE, props, {transport: 'sendBeacon'});
25915 };
25916
25917 Autocapture.prototype._initScrollDepthTracking = function() {
25918 win.removeEventListener(EV_SCROLL, this.listenerScrollDepth);
25919 win.removeEventListener(EV_SCROLLEND, this.listenerScrollDepth);
25920
25921 if (!this.mp.get_config('record_heatmap_data')) {
25922 return;
25923 }
25924
25925 logger$1.log('Initializing scroll depth tracking');
25926
25927 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
25928
25929 var updateScrollDepth = function() {
25930 if (this.currentUrlBlocked()) {
25931 return;
25932 }
25933 var scrollViewHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0) + win.scrollY;
25934 if (scrollViewHeight > this.maxScrollViewDepth) {
25935 this.maxScrollViewDepth = scrollViewHeight;
25936 }
25937 this.previousScrollHeight = document$1.body.scrollHeight;
25938 }.bind(this);
25939
25940 var scrollEndPolyfill = getPolyfillScrollEndFunction(updateScrollDepth);
25941 this.listenerScrollDepth = scrollEndPolyfill.listener;
25942 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScrollDepth);
25943 };
25944
25945 Autocapture.prototype.initClickTracking = function() {
25946 win.removeEventListener(EV_CLICK, this.listenerClick);
25947
25948 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.get_config('record_heatmap_data')) {
25949 return;
25950 }
25951 logger$1.log('Initializing click tracking');
25952
25953 this.listenerClick = function(ev) {
25954 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.is_recording_heatmap_data()) {
25955 return;
25956 }
25957 this.trackDomEvent(ev, MP_EV_CLICK);
25958 }.bind(this);
25959 win.addEventListener(EV_CLICK, this.listenerClick);
25960 };
25961
25962 Autocapture.prototype.initDeadClickTracking = function() {
25963 var deadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
25964
25965 if (!deadClickConfig && !this.mp.get_config('record_heatmap_data')) {
25966 this.stopDeadClickTracking();
25967 return;
25968 }
25969
25970 logger$1.log('Initializing dead click tracking');
25971 if (!this._deadClickTracker) {
25972 this._deadClickTracker = new DeadClickTracker(function(deadClickEvent) {
25973 this.trackDomEvent(deadClickEvent, MP_EV_DEAD_CLICK);
25974 }.bind(this));
25975 this._deadClickTracker.startTracking();
25976 }
25977
25978 if (!this.listenerDeadClick) {
25979 this.listenerDeadClick = function(ev) {
25980 var currentDeadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
25981 if (!currentDeadClickConfig && !this.mp.is_recording_heatmap_data()) {
25982 return;
25983 }
25984 if (this.currentUrlBlocked()) {
25985 return;
25986 }
25987 // Normalize config to ensure timeout_ms is always set
25988 var normalizedConfig = currentDeadClickConfig || {};
25989 if (!normalizedConfig['timeout_ms']) {
25990 normalizedConfig['timeout_ms'] = DEFAULT_DEAD_CLICK_TIMEOUT_MS;
25991 }
25992 this._deadClickTracker.trackClick(ev, normalizedConfig);
25993 }.bind(this);
25994 win.addEventListener(EV_CLICK, this.listenerDeadClick);
25995 }
25996 };
25997
25998 Autocapture.prototype.initInputTracking = function() {
25999 win.removeEventListener(EV_CHANGE, this.listenerChange);
26000
26001 if (!this.getConfig(CONFIG_TRACK_INPUT)) {
26002 return;
26003 }
26004 logger$1.log('Initializing input tracking');
26005
26006 this.listenerChange = function(ev) {
26007 if (!this.getConfig(CONFIG_TRACK_INPUT)) {
26008 return;
26009 }
26010 this.trackDomEvent(ev, MP_EV_INPUT);
26011 }.bind(this);
26012 win.addEventListener(EV_CHANGE, this.listenerChange);
26013 };
26014
26015 Autocapture.prototype.initPageviewTracking = function() {
26016 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
26017
26018 if (!this.pageviewTrackingConfig()) {
26019 return;
26020 }
26021 logger$1.log('Initializing pageview tracking');
26022
26023 var previousTrackedUrl = '';
26024 var tracked = false;
26025 if (!this.currentUrlBlocked()) {
26026 tracked = this.mp.track_pageview(DEFAULT_PROPS);
26027 }
26028 if (tracked) {
26029 previousTrackedUrl = _.info.currentUrl();
26030 }
26031
26032 this.listenerLocationchange = safewrap(function() {
26033 if (this.currentUrlBlocked()) {
26034 return;
26035 }
26036
26037 var currentUrl = _.info.currentUrl();
26038 var shouldTrack = false;
26039 var didPathChange = currentUrl.split('#')[0].split('?')[0] !== previousTrackedUrl.split('#')[0].split('?')[0];
26040 var trackPageviewOption = this.pageviewTrackingConfig();
26041 if (trackPageviewOption === PAGEVIEW_OPTION_FULL_URL) {
26042 shouldTrack = currentUrl !== previousTrackedUrl;
26043 } else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING) {
26044 shouldTrack = currentUrl.split('#')[0] !== previousTrackedUrl.split('#')[0];
26045 } else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH) {
26046 shouldTrack = didPathChange;
26047 }
26048
26049 if (shouldTrack) {
26050 var tracked = this.mp.track_pageview(DEFAULT_PROPS);
26051 if (tracked) {
26052 previousTrackedUrl = currentUrl;
26053 }
26054 if (didPathChange) {
26055 this.lastScrollCheckpoint = 0;
26056 logger$1.log('Path change: re-initializing scroll depth checkpoints');
26057 }
26058 }
26059 }.bind(this));
26060 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
26061 };
26062
26063 Autocapture.prototype.initRageClickTracking = function() {
26064 win.removeEventListener(EV_CLICK, this.listenerRageClick);
26065
26066 var rageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
26067 if (!rageClickConfig && !this.mp.get_config('record_heatmap_data')) {
26068 return;
26069 }
26070
26071 logger$1.log('Initializing rage click tracking');
26072 if (!this._rageClickTracker) {
26073 this._rageClickTracker = new RageClickTracker();
26074 }
26075
26076 this.listenerRageClick = function(ev) {
26077 var currentRageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
26078 if (!currentRageClickConfig && !this.mp.is_recording_heatmap_data()) {
26079 return;
26080 }
26081
26082 if (this.currentUrlBlocked()) {
26083 return;
26084 }
26085
26086 if (this._rageClickTracker.isRageClick(ev['pageX'], ev['pageY'], currentRageClickConfig)) {
26087 this.trackDomEvent(ev, MP_EV_RAGE_CLICK);
26088 }
26089 }.bind(this);
26090 win.addEventListener(EV_CLICK, this.listenerRageClick);
26091 };
26092
26093 Autocapture.prototype.initScrollTracking = function() {
26094 win.removeEventListener(EV_SCROLLEND, this.listenerScroll);
26095 win.removeEventListener(EV_SCROLL, this.listenerScroll);
26096
26097
26098 if (!this.getConfig(CONFIG_TRACK_SCROLL)) {
26099 return;
26100 }
26101 logger$1.log('Initializing scroll tracking');
26102 this.lastScrollCheckpoint = 0;
26103
26104 var scrollTrackFunction = function() {
26105 if (!this.getConfig(CONFIG_TRACK_SCROLL)) {
26106 return;
26107 }
26108 if (this.currentUrlBlocked()) {
26109 return;
26110 }
26111
26112 var shouldTrack = this.getConfig(CONFIG_SCROLL_CAPTURE_ALL);
26113 var scrollCheckpoints = (this.getConfig(CONFIG_SCROLL_CHECKPOINTS) || [])
26114 .slice()
26115 .sort(function(a, b) { return a - b; });
26116
26117 var scrollTop = win.scrollY;
26118 var props = _.extend({'$scroll_top': scrollTop}, DEFAULT_PROPS);
26119 try {
26120 var scrollHeight = document$1.body.scrollHeight;
26121 var scrollPercentage = Math.round((scrollTop / (scrollHeight - win.innerHeight)) * 100);
26122 props['$scroll_height'] = scrollHeight;
26123 props['$scroll_percentage'] = scrollPercentage;
26124 if (scrollPercentage > this.lastScrollCheckpoint) {
26125 for (var i = 0; i < scrollCheckpoints.length; i++) {
26126 var checkpoint = scrollCheckpoints[i];
26127 if (
26128 scrollPercentage >= checkpoint &&
26129 this.lastScrollCheckpoint < checkpoint
26130 ) {
26131 props['$scroll_checkpoint'] = checkpoint;
26132 this.lastScrollCheckpoint = checkpoint;
26133 shouldTrack = true;
26134 }
26135 }
26136 }
26137 } catch (err) {
26138 logger$1.critical('Error while calculating scroll percentage', err);
26139 }
26140 if (shouldTrack) {
26141 this.mp.track(MP_EV_SCROLL, props);
26142 }
26143 }.bind(this);
26144
26145 var scrollEndPolyfill = getPolyfillScrollEndFunction(scrollTrackFunction);
26146 this.listenerScroll = scrollEndPolyfill.listener;
26147 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScroll);
26148 };
26149
26150 Autocapture.prototype.initSubmitTracking = function() {
26151 win.removeEventListener(EV_SUBMIT, this.listenerSubmit);
26152
26153 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) {
26154 return;
26155 }
26156 logger$1.log('Initializing submit tracking');
26157
26158 this.listenerSubmit = function(ev) {
26159 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) {
26160 return;
26161 }
26162 this.trackDomEvent(ev, MP_EV_SUBMIT);
26163 }.bind(this);
26164 win.addEventListener(EV_SUBMIT, this.listenerSubmit);
26165 };
26166
26167 Autocapture.prototype.initPageLeaveTracking = function() {
26168 // Capture page_leave both when the user navigates away from the page (visibilitychange) as well
26169 // as when they navigate to a different page within the SPA (popstate/pushstate/hashchange).
26170 document$1.removeEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
26171 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
26172 win.removeEventListener(EV_LOAD, this.listenerPageLoad);
26173
26174 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config('record_heatmap_data')) {
26175 return;
26176 }
26177
26178 logger$1.log('Initializing page visibility tracking.');
26179 this._initScrollDepthTracking();
26180 var previousTrackedUrl = _.info.currentUrl();
26181
26182 // Initialize previousScrollHeight on `load` which handles async loading
26183 // https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
26184 this.listenerPageLoad = function() {
26185 this.previousScrollHeight = document$1.body.scrollHeight;
26186 }.bind(this);
26187 win.addEventListener(EV_LOAD, this.listenerPageLoad);
26188
26189 // Track page navigation events similar to how initPageviewTracking does it
26190 this.listenerPageLeaveLocationchange = safewrap(function(ev) {
26191 if (this.currentUrlBlocked()) {
26192 return;
26193 }
26194
26195 var currentUrl = _.info.currentUrl();
26196 // Track all URL changes including query string or fragment changes as separate scroll sessions
26197 var shouldTrack = currentUrl !== previousTrackedUrl;
26198
26199 if (shouldTrack) {
26200 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
26201 previousTrackedUrl = currentUrl;
26202 // Fragment navigation should call scroll(end) and trigger listener, don't add window.scrollY here.
26203 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
26204 this.previousScrollHeight = document$1.body.scrollHeight;
26205 this.hasTrackedScrollSession = false;
26206 }
26207 }.bind(this));
26208 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
26209
26210 this.listenerPageLeaveVisibilitychange = function(ev) {
26211 if (document$1.hidden) {
26212 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
26213 }
26214 }.bind(this);
26215 document$1.addEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
26216 };
26217
26218 Autocapture.prototype.stopDeadClickTracking = function() {
26219 if (this.listenerDeadClick) {
26220 win.removeEventListener(EV_CLICK, this.listenerDeadClick);
26221 this.listenerDeadClick = null;
26222 }
26223
26224 if (this._deadClickTracker) {
26225 this._deadClickTracker.stopTracking();
26226 this._deadClickTracker = null;
26227 }
26228 };
26229
26230 // TODO integrate error_reporter from mixpanel instance
26231 safewrapClass(Autocapture);
26232
26233 var logger = console_with_prefix('flags');
26234
26235 var FLAGS_CONFIG_KEY = 'flags';
26236
26237 var CONFIG_CONTEXT = 'context';
26238 var CONFIG_DEFAULTS = {};
26239 CONFIG_DEFAULTS[CONFIG_CONTEXT] = {};
26240
26241 /**
26242 * FeatureFlagManager: support for Mixpanel's feature flagging product
26243 * @constructor
26244 */
26245 var FeatureFlagManager = function(initOptions) {
26246 this.fetch = win['fetch'];
26247 this.getFullApiRoute = initOptions.getFullApiRoute;
26248 this.getMpConfig = initOptions.getConfigFunc;
26249 this.setMpConfig = initOptions.setConfigFunc;
26250 this.getMpProperty = initOptions.getPropertyFunc;
26251 this.track = initOptions.trackingFunc;
26252 };
26253
26254 FeatureFlagManager.prototype.init = function() {
26255 if (!this.minApisSupported()) {
26256 logger.critical('Feature Flags unavailable: missing minimum required APIs');
26257 return;
26258 }
26259
26260 this.flags = null;
26261 this.fetchFlags();
26262
26263 this.trackedFeatures = new Set();
26264 };
26265
26266 FeatureFlagManager.prototype.getFullConfig = function() {
26267 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
26268 if (!ffConfig) {
26269 // flags are completely off
26270 return {};
26271 } else if (_.isObject(ffConfig)) {
26272 return _.extend({}, CONFIG_DEFAULTS, ffConfig);
26273 } else {
26274 // config is non-object truthy value, return default
26275 return CONFIG_DEFAULTS;
26276 }
26277 };
26278
26279 FeatureFlagManager.prototype.getConfig = function(key) {
26280 return this.getFullConfig()[key];
26281 };
26282
26283 FeatureFlagManager.prototype.isSystemEnabled = function() {
26284 return !!this.getMpConfig(FLAGS_CONFIG_KEY);
26285 };
26286
26287 FeatureFlagManager.prototype.updateContext = function(newContext, options) {
26288 if (!this.isSystemEnabled()) {
26289 logger.critical('Feature Flags not enabled, cannot update context');
26290 return Promise.resolve();
26291 }
26292
26293 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
26294 if (!_.isObject(ffConfig)) {
26295 ffConfig = {};
26296 }
26297 var oldContext = (options && options['replace']) ? {} : this.getConfig(CONFIG_CONTEXT);
26298 ffConfig[CONFIG_CONTEXT] = _.extend({}, oldContext, newContext);
26299
26300 this.setMpConfig(FLAGS_CONFIG_KEY, ffConfig);
26301 return this.fetchFlags();
26302 };
26303
26304 FeatureFlagManager.prototype.areFlagsReady = function() {
26305 if (!this.isSystemEnabled()) {
26306 logger.error('Feature Flags not enabled');
26307 }
26308 return !!this.flags;
26309 };
26310
26311 FeatureFlagManager.prototype.fetchFlags = function() {
26312 if (!this.isSystemEnabled()) {
26313 return Promise.resolve();
26314 }
26315
26316 var distinctId = this.getMpProperty('distinct_id');
26317 var deviceId = this.getMpProperty('$device_id');
26318 var traceparent = generateTraceparent();
26319 logger.log('Fetching flags for distinct ID: ' + distinctId);
26320
26321 var context = _.extend({'distinct_id': distinctId, 'device_id': deviceId}, this.getConfig(CONFIG_CONTEXT));
26322 var searchParams = new URLSearchParams();
26323 searchParams.set('context', JSON.stringify(context));
26324 searchParams.set('token', this.getMpConfig('token'));
26325 searchParams.set('mp_lib', 'web');
26326 searchParams.set('$lib_version', Config.LIB_VERSION);
26327 var url = this.getFullApiRoute() + '?' + searchParams.toString();
26328
26329 this._fetchInProgressStartTime = Date.now();
26330 this.fetchPromise = this.fetch.call(win, url, {
26331 'method': 'GET',
26332 'headers': {
26333 'Authorization': 'Basic ' + btoa(this.getMpConfig('token') + ':'),
26334 'traceparent': traceparent
26335 }
26336 }).then(function(response) {
26337 this.markFetchComplete();
26338 return response.json().then(function(responseBody) {
26339 var responseFlags = responseBody['flags'];
26340 if (!responseFlags) {
26341 throw new Error('No flags in API response');
26342 }
26343 var flags = new Map();
26344 _.each(responseFlags, function(data, key) {
26345 flags.set(key, {
26346 'key': data['variant_key'],
26347 'value': data['variant_value'],
26348 'experiment_id': data['experiment_id'],
26349 'is_experiment_active': data['is_experiment_active'],
26350 'is_qa_tester': data['is_qa_tester']
26351 });
26352 });
26353 this.flags = flags;
26354 this._traceparent = traceparent;
26355 }.bind(this)).catch(function(error) {
26356 this.markFetchComplete();
26357 logger.error(error);
26358 }.bind(this));
26359 }.bind(this)).catch(function(error) {
26360 this.markFetchComplete();
26361 logger.error(error);
26362 }.bind(this));
26363
26364 return this.fetchPromise;
26365 };
26366
26367 FeatureFlagManager.prototype.markFetchComplete = function() {
26368 if (!this._fetchInProgressStartTime) {
26369 logger.error('Fetch in progress started time not set, cannot mark fetch complete');
26370 return;
26371 }
26372 this._fetchStartTime = this._fetchInProgressStartTime;
26373 this._fetchCompleteTime = Date.now();
26374 this._fetchLatency = this._fetchCompleteTime - this._fetchStartTime;
26375 this._fetchInProgressStartTime = null;
26376 };
26377
26378 FeatureFlagManager.prototype.getVariant = function(featureName, fallback) {
26379 if (!this.fetchPromise) {
26380 return new Promise(function(resolve) {
26381 logger.critical('Feature Flags not initialized');
26382 resolve(fallback);
26383 });
26384 }
26385
26386 return this.fetchPromise.then(function() {
26387 return this.getVariantSync(featureName, fallback);
26388 }.bind(this)).catch(function(error) {
26389 logger.error(error);
26390 return fallback;
26391 });
26392 };
26393
26394 FeatureFlagManager.prototype.getVariantSync = function(featureName, fallback) {
26395 if (!this.areFlagsReady()) {
26396 logger.log('Flags not loaded yet');
26397 return fallback;
26398 }
26399 var feature = this.flags.get(featureName);
26400 if (!feature) {
26401 logger.log('No flag found: "' + featureName + '"');
26402 return fallback;
26403 }
26404 this.trackFeatureCheck(featureName, feature);
26405 return feature;
26406 };
26407
26408 FeatureFlagManager.prototype.getVariantValue = function(featureName, fallbackValue) {
26409 return this.getVariant(featureName, {'value': fallbackValue}).then(function(feature) {
26410 return feature['value'];
26411 }).catch(function(error) {
26412 logger.error(error);
26413 return fallbackValue;
26414 });
26415 };
26416
26417 // TODO remove deprecated method
26418 FeatureFlagManager.prototype.getFeatureData = function(featureName, fallbackValue) {
26419 logger.critical('mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead.');
26420 return this.getVariantValue(featureName, fallbackValue);
26421 };
26422
26423 FeatureFlagManager.prototype.getVariantValueSync = function(featureName, fallbackValue) {
26424 return this.getVariantSync(featureName, {'value': fallbackValue})['value'];
26425 };
26426
26427 FeatureFlagManager.prototype.isEnabled = function(featureName, fallbackValue) {
26428 return this.getVariantValue(featureName).then(function() {
26429 return this.isEnabledSync(featureName, fallbackValue);
26430 }.bind(this)).catch(function(error) {
26431 logger.error(error);
26432 return fallbackValue;
26433 });
26434 };
26435
26436 FeatureFlagManager.prototype.isEnabledSync = function(featureName, fallbackValue) {
26437 fallbackValue = fallbackValue || false;
26438 var val = this.getVariantValueSync(featureName, fallbackValue);
26439 if (val !== true && val !== false) {
26440 logger.error('Feature flag "' + featureName + '" value: ' + val + ' is not a boolean; returning fallback value: ' + fallbackValue);
26441 val = fallbackValue;
26442 }
26443 return val;
26444 };
26445
26446 FeatureFlagManager.prototype.trackFeatureCheck = function(featureName, feature) {
26447 if (this.trackedFeatures.has(featureName)) {
26448 return;
26449 }
26450 this.trackedFeatures.add(featureName);
26451
26452 var trackingProperties = {
26453 'Experiment name': featureName,
26454 'Variant name': feature['key'],
26455 '$experiment_type': 'feature_flag',
26456 'Variant fetch start time': new Date(this._fetchStartTime).toISOString(),
26457 'Variant fetch complete time': new Date(this._fetchCompleteTime).toISOString(),
26458 'Variant fetch latency (ms)': this._fetchLatency,
26459 'Variant fetch traceparent': this._traceparent,
26460 };
26461
26462 if (feature['experiment_id'] !== 'undefined') {
26463 trackingProperties['$experiment_id'] = feature['experiment_id'];
26464 }
26465 if (feature['is_experiment_active'] !== 'undefined') {
26466 trackingProperties['$is_experiment_active'] = feature['is_experiment_active'];
26467 }
26468 if (feature['is_qa_tester'] !== 'undefined') {
26469 trackingProperties['$is_qa_tester'] = feature['is_qa_tester'];
26470 }
26471
26472 this.track('$experiment_started', trackingProperties);
26473 };
26474
26475 FeatureFlagManager.prototype.minApisSupported = function() {
26476 return !!this.fetch &&
26477 typeof Promise !== 'undefined' &&
26478 typeof Map !== 'undefined' &&
26479 typeof Set !== 'undefined';
26480 };
26481
26482 safewrapClass(FeatureFlagManager);
26483
26484 FeatureFlagManager.prototype['are_flags_ready'] = FeatureFlagManager.prototype.areFlagsReady;
26485 FeatureFlagManager.prototype['get_variant'] = FeatureFlagManager.prototype.getVariant;
26486 FeatureFlagManager.prototype['get_variant_sync'] = FeatureFlagManager.prototype.getVariantSync;
26487 FeatureFlagManager.prototype['get_variant_value'] = FeatureFlagManager.prototype.getVariantValue;
26488 FeatureFlagManager.prototype['get_variant_value_sync'] = FeatureFlagManager.prototype.getVariantValueSync;
26489 FeatureFlagManager.prototype['is_enabled'] = FeatureFlagManager.prototype.isEnabled;
26490 FeatureFlagManager.prototype['is_enabled_sync'] = FeatureFlagManager.prototype.isEnabledSync;
26491 FeatureFlagManager.prototype['update_context'] = FeatureFlagManager.prototype.updateContext;
26492
26493 // Deprecated method
26494 FeatureFlagManager.prototype['get_feature_data'] = FeatureFlagManager.prototype.getFeatureData;
26495
26496 /* eslint camelcase: "off" */
26497
26498
26499 /**
26500 * DomTracker Object
26501 * @constructor
26502 */
26503 var DomTracker = function() {};
26504
26505
26506 // interface
26507 DomTracker.prototype.create_properties = function() {};
26508 DomTracker.prototype.event_handler = function() {};
26509 DomTracker.prototype.after_track_handler = function() {};
26510
26511 DomTracker.prototype.init = function(mixpanel_instance) {
26512 this.mp = mixpanel_instance;
26513 return this;
26514 };
26515
26516 /**
26517 * @param {Object|string} query
26518 * @param {string} event_name
26519 * @param {Object=} properties
26520 * @param {function=} user_callback
26521 */
26522 DomTracker.prototype.track = function(query, event_name, properties, user_callback) {
26523 var that = this;
26524 var elements = _.dom_query(query);
26525
26526 if (elements.length === 0) {
26527 console$1.error('The DOM query (' + query + ') returned 0 elements');
26528 return;
26529 }
26530
26531 _.each(elements, function(element) {
26532 _.register_event(element, this.override_event, function(e) {
26533 var options = {};
26534 var props = that.create_properties(properties, this);
26535 var timeout = that.mp.get_config('track_links_timeout');
26536
26537 that.event_handler(e, this, options);
26538
26539 // in case the mixpanel servers don't get back to us in time
26540 window.setTimeout(that.track_callback(user_callback, props, options, true), timeout);
26541
26542 // fire the tracking event
26543 that.mp.track(event_name, props, that.track_callback(user_callback, props, options));
26544 });
26545 }, this);
26546
26547 return true;
26548 };
26549
26550 /**
26551 * @param {function} user_callback
26552 * @param {Object} props
26553 * @param {boolean=} timeout_occured
26554 */
26555 DomTracker.prototype.track_callback = function(user_callback, props, options, timeout_occured) {
26556 timeout_occured = timeout_occured || false;
26557 var that = this;
26558
26559 return function() {
26560 // options is referenced from both callbacks, so we can have
26561 // a 'lock' of sorts to ensure only one fires
26562 if (options.callback_fired) { return; }
26563 options.callback_fired = true;
26564
26565 if (user_callback && user_callback(timeout_occured, props) === false) {
26566 // user can prevent the default functionality by
26567 // returning false from their callback
26568 return;
26569 }
26570
26571 that.after_track_handler(props, options, timeout_occured);
26572 };
26573 };
26574
26575 DomTracker.prototype.create_properties = function(properties, element) {
26576 var props;
26577
26578 if (typeof(properties) === 'function') {
26579 props = properties(element);
26580 } else {
26581 props = _.extend({}, properties);
26582 }
26583
26584 return props;
26585 };
26586
26587 /**
26588 * LinkTracker Object
26589 * @constructor
26590 * @extends DomTracker
26591 */
26592 var LinkTracker = function() {
26593 this.override_event = 'click';
26594 };
26595 _.inherit(LinkTracker, DomTracker);
26596
26597 LinkTracker.prototype.create_properties = function(properties, element) {
26598 var props = LinkTracker.superclass.create_properties.apply(this, arguments);
26599
26600 if (element.href) { props['url'] = element.href; }
26601
26602 return props;
26603 };
26604
26605 LinkTracker.prototype.event_handler = function(evt, element, options) {
26606 options.new_tab = (
26607 evt.which === 2 ||
26608 evt.metaKey ||
26609 evt.ctrlKey ||
26610 element.target === '_blank'
26611 );
26612 options.href = element.href;
26613
26614 if (!options.new_tab) {
26615 evt.preventDefault();
26616 }
26617 };
26618
26619 LinkTracker.prototype.after_track_handler = function(props, options) {
26620 if (options.new_tab) { return; }
26621
26622 setTimeout(function() {
26623 window.location = options.href;
26624 }, 0);
26625 };
26626
26627 /**
26628 * FormTracker Object
26629 * @constructor
26630 * @extends DomTracker
26631 */
26632 var FormTracker = function() {
26633 this.override_event = 'submit';
26634 };
26635 _.inherit(FormTracker, DomTracker);
26636
26637 FormTracker.prototype.event_handler = function(evt, element, options) {
26638 options.element = element;
26639 evt.preventDefault();
26640 };
26641
26642 FormTracker.prototype.after_track_handler = function(props, options) {
26643 setTimeout(function() {
26644 options.element.submit();
26645 }, 0);
26646 };
26647
26648 /* eslint camelcase: "off" */
26649
26650
26651 /** @const */ var SET_ACTION = '$set';
26652 /** @const */ var SET_ONCE_ACTION = '$set_once';
26653 /** @const */ var UNSET_ACTION = '$unset';
26654 /** @const */ var ADD_ACTION = '$add';
26655 /** @const */ var APPEND_ACTION = '$append';
26656 /** @const */ var UNION_ACTION = '$union';
26657 /** @const */ var REMOVE_ACTION = '$remove';
26658 /** @const */ var DELETE_ACTION = '$delete';
26659
26660 // Common internal methods for mixpanel.people and mixpanel.group APIs.
26661 // These methods shouldn't involve network I/O.
26662 var apiActions = {
26663 set_action: function(prop, to) {
26664 var data = {};
26665 var $set = {};
26666 if (_.isObject(prop)) {
26667 _.each(prop, function(v, k) {
26668 if (!this._is_reserved_property(k)) {
26669 $set[k] = v;
26670 }
26671 }, this);
26672 } else {
26673 $set[prop] = to;
26674 }
26675
26676 data[SET_ACTION] = $set;
26677 return data;
26678 },
26679
26680 unset_action: function(prop) {
26681 var data = {};
26682 var $unset = [];
26683 if (!_.isArray(prop)) {
26684 prop = [prop];
26685 }
26686
26687 _.each(prop, function(k) {
26688 if (!this._is_reserved_property(k)) {
26689 $unset.push(k);
26690 }
26691 }, this);
26692
26693 data[UNSET_ACTION] = $unset;
26694 return data;
26695 },
26696
26697 set_once_action: function(prop, to) {
26698 var data = {};
26699 var $set_once = {};
26700 if (_.isObject(prop)) {
26701 _.each(prop, function(v, k) {
26702 if (!this._is_reserved_property(k)) {
26703 $set_once[k] = v;
26704 }
26705 }, this);
26706 } else {
26707 $set_once[prop] = to;
26708 }
26709 data[SET_ONCE_ACTION] = $set_once;
26710 return data;
26711 },
26712
26713 union_action: function(list_name, values) {
26714 var data = {};
26715 var $union = {};
26716 if (_.isObject(list_name)) {
26717 _.each(list_name, function(v, k) {
26718 if (!this._is_reserved_property(k)) {
26719 $union[k] = _.isArray(v) ? v : [v];
26720 }
26721 }, this);
26722 } else {
26723 $union[list_name] = _.isArray(values) ? values : [values];
26724 }
26725 data[UNION_ACTION] = $union;
26726 return data;
26727 },
26728
26729 append_action: function(list_name, value) {
26730 var data = {};
26731 var $append = {};
26732 if (_.isObject(list_name)) {
26733 _.each(list_name, function(v, k) {
26734 if (!this._is_reserved_property(k)) {
26735 $append[k] = v;
26736 }
26737 }, this);
26738 } else {
26739 $append[list_name] = value;
26740 }
26741 data[APPEND_ACTION] = $append;
26742 return data;
26743 },
26744
26745 remove_action: function(list_name, value) {
26746 var data = {};
26747 var $remove = {};
26748 if (_.isObject(list_name)) {
26749 _.each(list_name, function(v, k) {
26750 if (!this._is_reserved_property(k)) {
26751 $remove[k] = v;
26752 }
26753 }, this);
26754 } else {
26755 $remove[list_name] = value;
26756 }
26757 data[REMOVE_ACTION] = $remove;
26758 return data;
26759 },
26760
26761 delete_action: function() {
26762 var data = {};
26763 data[DELETE_ACTION] = '';
26764 return data;
26765 }
26766 };
26767
26768 /* eslint camelcase: "off" */
26769
26770 /**
26771 * Mixpanel Group Object
26772 * @constructor
26773 */
26774 var MixpanelGroup = function() {};
26775
26776 _.extend(MixpanelGroup.prototype, apiActions);
26777
26778 MixpanelGroup.prototype._init = function(mixpanel_instance, group_key, group_id) {
26779 this._mixpanel = mixpanel_instance;
26780 this._group_key = group_key;
26781 this._group_id = group_id;
26782 };
26783
26784 /**
26785 * Set properties on a group.
26786 *
26787 * ### Usage:
26788 *
26789 * mixpanel.get_group('company', 'mixpanel').set('Location', '405 Howard');
26790 *
26791 * // or set multiple properties at once
26792 * mixpanel.get_group('company', 'mixpanel').set({
26793 * 'Location': '405 Howard',
26794 * 'Founded' : 2009,
26795 * });
26796 * // properties can be strings, integers, dates, or lists
26797 *
26798 * @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.
26799 * @param {*} [to] A value to set on the given property name
26800 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26801 */
26802 MixpanelGroup.prototype.set = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
26803 var data = this.set_action(prop, to);
26804 if (_.isObject(prop)) {
26805 callback = to;
26806 }
26807 return this._send_request(data, callback);
26808 });
26809
26810 /**
26811 * Set properties on a group, only if they do not yet exist.
26812 * This will not overwrite previous group property values, unlike
26813 * group.set().
26814 *
26815 * ### Usage:
26816 *
26817 * mixpanel.get_group('company', 'mixpanel').set_once('Location', '405 Howard');
26818 *
26819 * // or set multiple properties at once
26820 * mixpanel.get_group('company', 'mixpanel').set_once({
26821 * 'Location': '405 Howard',
26822 * 'Founded' : 2009,
26823 * });
26824 * // properties can be strings, integers, lists or dates
26825 *
26826 * @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.
26827 * @param {*} [to] A value to set on the given property name
26828 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26829 */
26830 MixpanelGroup.prototype.set_once = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
26831 var data = this.set_once_action(prop, to);
26832 if (_.isObject(prop)) {
26833 callback = to;
26834 }
26835 return this._send_request(data, callback);
26836 });
26837
26838 /**
26839 * Unset properties on a group permanently.
26840 *
26841 * ### Usage:
26842 *
26843 * mixpanel.get_group('company', 'mixpanel').unset('Founded');
26844 *
26845 * @param {String} prop The name of the property.
26846 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26847 */
26848 MixpanelGroup.prototype.unset = addOptOutCheckMixpanelGroup(function(prop, callback) {
26849 var data = this.unset_action(prop);
26850 return this._send_request(data, callback);
26851 });
26852
26853 /**
26854 * Merge a given list with a list-valued group property, excluding duplicate values.
26855 *
26856 * ### Usage:
26857 *
26858 * // merge a value to a list, creating it if needed
26859 * mixpanel.get_group('company', 'mixpanel').union('Location', ['San Francisco', 'London']);
26860 *
26861 * @param {String} list_name Name of the property.
26862 * @param {Array} values Values to merge with the given property
26863 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26864 */
26865 MixpanelGroup.prototype.union = addOptOutCheckMixpanelGroup(function(list_name, values, callback) {
26866 if (_.isObject(list_name)) {
26867 callback = values;
26868 }
26869 var data = this.union_action(list_name, values);
26870 return this._send_request(data, callback);
26871 });
26872
26873 /**
26874 * Permanently delete a group.
26875 *
26876 * ### Usage:
26877 *
26878 * mixpanel.get_group('company', 'mixpanel').delete();
26879 *
26880 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26881 */
26882 MixpanelGroup.prototype['delete'] = addOptOutCheckMixpanelGroup(function(callback) {
26883 // bracket notation above prevents a minification error related to reserved words
26884 var data = this.delete_action();
26885 return this._send_request(data, callback);
26886 });
26887
26888 /**
26889 * Remove a property from a group. The value will be ignored if doesn't exist.
26890 *
26891 * ### Usage:
26892 *
26893 * mixpanel.get_group('company', 'mixpanel').remove('Location', 'London');
26894 *
26895 * @param {String} list_name Name of the property.
26896 * @param {Object} value Value to remove from the given group property
26897 * @param {Function} [callback] If provided, the callback will be called after the tracking event
26898 */
26899 MixpanelGroup.prototype.remove = addOptOutCheckMixpanelGroup(function(list_name, value, callback) {
26900 var data = this.remove_action(list_name, value);
26901 return this._send_request(data, callback);
26902 });
26903
26904 MixpanelGroup.prototype._send_request = function(data, callback) {
26905 data['$group_key'] = this._group_key;
26906 data['$group_id'] = this._group_id;
26907 data['$token'] = this._get_config('token');
26908
26909 var date_encoded_data = _.encodeDates(data);
26910 return this._mixpanel._track_or_batch({
26911 type: 'groups',
26912 data: date_encoded_data,
26913 endpoint: this._mixpanel.get_api_host('groups') + '/' + this._get_config('api_routes')['groups'],
26914 batcher: this._mixpanel.request_batchers.groups
26915 }, callback);
26916 };
26917
26918 MixpanelGroup.prototype._is_reserved_property = function(prop) {
26919 return prop === '$group_key' || prop === '$group_id';
26920 };
26921
26922 MixpanelGroup.prototype._get_config = function(conf) {
26923 return this._mixpanel.get_config(conf);
26924 };
26925
26926 MixpanelGroup.prototype.toString = function() {
26927 return this._mixpanel.toString() + '.group.' + this._group_key + '.' + this._group_id;
26928 };
26929
26930 // MixpanelGroup Exports
26931 MixpanelGroup.prototype['remove'] = MixpanelGroup.prototype.remove;
26932 MixpanelGroup.prototype['set'] = MixpanelGroup.prototype.set;
26933 MixpanelGroup.prototype['set_once'] = MixpanelGroup.prototype.set_once;
26934 MixpanelGroup.prototype['union'] = MixpanelGroup.prototype.union;
26935 MixpanelGroup.prototype['unset'] = MixpanelGroup.prototype.unset;
26936 MixpanelGroup.prototype['toString'] = MixpanelGroup.prototype.toString;
26937
26938 /* eslint camelcase: "off" */
26939
26940 /**
26941 * Mixpanel People Object
26942 * @constructor
26943 */
26944 var MixpanelPeople = function() {};
26945
26946 _.extend(MixpanelPeople.prototype, apiActions);
26947
26948 MixpanelPeople.prototype._init = function(mixpanel_instance) {
26949 this._mixpanel = mixpanel_instance;
26950 };
26951
26952 /*
26953 * Set properties on a user record.
26954 *
26955 * ### Usage:
26956 *
26957 * mixpanel.people.set('gender', 'm');
26958 *
26959 * // or set multiple properties at once
26960 * mixpanel.people.set({
26961 * 'Company': 'Acme',
26962 * 'Plan': 'Premium',
26963 * 'Upgrade date': new Date()
26964 * });
26965 * // properties can be strings, integers, dates, or lists
26966 *
26967 * @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.
26968 * @param {*} [to] A value to set on the given property name
26969 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
26970 */
26971 MixpanelPeople.prototype.set = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
26972 var data = this.set_action(prop, to);
26973 if (_.isObject(prop)) {
26974 callback = to;
26975 }
26976 // make sure that the referrer info has been updated and saved
26977 if (this._get_config('save_referrer')) {
26978 this._mixpanel['persistence'].update_referrer_info(document.referrer);
26979 }
26980
26981 // update $set object with default people properties
26982 data[SET_ACTION] = _.extend(
26983 {},
26984 _.info.people_properties(),
26985 data[SET_ACTION]
26986 );
26987 return this._send_request(data, callback);
26988 });
26989
26990 /*
26991 * Set properties on a user record, only if they do not yet exist.
26992 * This will not overwrite previous people property values, unlike
26993 * people.set().
26994 *
26995 * ### Usage:
26996 *
26997 * mixpanel.people.set_once('First Login Date', new Date());
26998 *
26999 * // or set multiple properties at once
27000 * mixpanel.people.set_once({
27001 * 'First Login Date': new Date(),
27002 * 'Starting Plan': 'Premium'
27003 * });
27004 *
27005 * // properties can be strings, integers or dates
27006 *
27007 * @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.
27008 * @param {*} [to] A value to set on the given property name
27009 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27010 */
27011 MixpanelPeople.prototype.set_once = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
27012 var data = this.set_once_action(prop, to);
27013 if (_.isObject(prop)) {
27014 callback = to;
27015 }
27016 return this._send_request(data, callback);
27017 });
27018
27019 /*
27020 * Unset properties on a user record (permanently removes the properties and their values from a profile).
27021 *
27022 * ### Usage:
27023 *
27024 * mixpanel.people.unset('gender');
27025 *
27026 * // or unset multiple properties at once
27027 * mixpanel.people.unset(['gender', 'Company']);
27028 *
27029 * @param {Array|String} prop If a string, this is the name of the property. If an array, this is a list of property names.
27030 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27031 */
27032 MixpanelPeople.prototype.unset = addOptOutCheckMixpanelPeople(function(prop, callback) {
27033 var data = this.unset_action(prop);
27034 return this._send_request(data, callback);
27035 });
27036
27037 /*
27038 * Increment/decrement numeric people analytics properties.
27039 *
27040 * ### Usage:
27041 *
27042 * mixpanel.people.increment('page_views', 1);
27043 *
27044 * // or, for convenience, if you're just incrementing a counter by
27045 * // 1, you can simply do
27046 * mixpanel.people.increment('page_views');
27047 *
27048 * // to decrement a counter, pass a negative number
27049 * mixpanel.people.increment('credits_left', -1);
27050 *
27051 * // like mixpanel.people.set(), you can increment multiple
27052 * // properties at once:
27053 * mixpanel.people.increment({
27054 * counter1: 1,
27055 * counter2: 6
27056 * });
27057 *
27058 * @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.
27059 * @param {Number} [by] An amount to increment the given property
27060 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27061 */
27062 MixpanelPeople.prototype.increment = addOptOutCheckMixpanelPeople(function(prop, by, callback) {
27063 var data = {};
27064 var $add = {};
27065 if (_.isObject(prop)) {
27066 _.each(prop, function(v, k) {
27067 if (!this._is_reserved_property(k)) {
27068 if (isNaN(parseFloat(v))) {
27069 console$1.error('Invalid increment value passed to mixpanel.people.increment - must be a number');
27070 return;
27071 } else {
27072 $add[k] = v;
27073 }
27074 }
27075 }, this);
27076 callback = by;
27077 } else {
27078 // convenience: mixpanel.people.increment('property'); will
27079 // increment 'property' by 1
27080 if (_.isUndefined(by)) {
27081 by = 1;
27082 }
27083 $add[prop] = by;
27084 }
27085 data[ADD_ACTION] = $add;
27086
27087 return this._send_request(data, callback);
27088 });
27089
27090 /*
27091 * Append a value to a list-valued people analytics property.
27092 *
27093 * ### Usage:
27094 *
27095 * // append a value to a list, creating it if needed
27096 * mixpanel.people.append('pages_visited', 'homepage');
27097 *
27098 * // like mixpanel.people.set(), you can append multiple
27099 * // properties at once:
27100 * mixpanel.people.append({
27101 * list1: 'bob',
27102 * list2: 123
27103 * });
27104 *
27105 * @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.
27106 * @param {*} [value] value An item to append to the list
27107 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27108 */
27109 MixpanelPeople.prototype.append = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
27110 if (_.isObject(list_name)) {
27111 callback = value;
27112 }
27113 var data = this.append_action(list_name, value);
27114 return this._send_request(data, callback);
27115 });
27116
27117 /*
27118 * Remove a value from a list-valued people analytics property.
27119 *
27120 * ### Usage:
27121 *
27122 * mixpanel.people.remove('School', 'UCB');
27123 *
27124 * @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.
27125 * @param {*} [value] value Item to remove from the list
27126 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27127 */
27128 MixpanelPeople.prototype.remove = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
27129 if (_.isObject(list_name)) {
27130 callback = value;
27131 }
27132 var data = this.remove_action(list_name, value);
27133 return this._send_request(data, callback);
27134 });
27135
27136 /*
27137 * Merge a given list with a list-valued people analytics property,
27138 * excluding duplicate values.
27139 *
27140 * ### Usage:
27141 *
27142 * // merge a value to a list, creating it if needed
27143 * mixpanel.people.union('pages_visited', 'homepage');
27144 *
27145 * // like mixpanel.people.set(), you can append multiple
27146 * // properties at once:
27147 * mixpanel.people.union({
27148 * list1: 'bob',
27149 * list2: 123
27150 * });
27151 *
27152 * // like mixpanel.people.append(), you can append multiple
27153 * // values to the same list:
27154 * mixpanel.people.union({
27155 * list1: ['bob', 'billy']
27156 * });
27157 *
27158 * @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.
27159 * @param {*} [value] Value / values to merge with the given property
27160 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27161 */
27162 MixpanelPeople.prototype.union = addOptOutCheckMixpanelPeople(function(list_name, values, callback) {
27163 if (_.isObject(list_name)) {
27164 callback = values;
27165 }
27166 var data = this.union_action(list_name, values);
27167 return this._send_request(data, callback);
27168 });
27169
27170 /*
27171 * Record that you have charged the current user a certain amount
27172 * of money. Charges recorded with track_charge() will appear in the
27173 * Mixpanel revenue report.
27174 *
27175 * ### Usage:
27176 *
27177 * // charge a user $50
27178 * mixpanel.people.track_charge(50);
27179 *
27180 * // charge a user $30.50 on the 2nd of january
27181 * mixpanel.people.track_charge(30.50, {
27182 * '$time': new Date('jan 1 2012')
27183 * });
27184 *
27185 * @param {Number} amount The amount of money charged to the current user
27186 * @param {Object} [properties] An associative array of properties associated with the charge
27187 * @param {Function} [callback] If provided, the callback will be called when the server responds
27188 * @deprecated
27189 */
27190 MixpanelPeople.prototype.track_charge = addOptOutCheckMixpanelPeople(function() {
27191 console$1.error('mixpanel.people.track_charge() is deprecated and no longer has any effect.');
27192 });
27193
27194 /*
27195 * Permanently clear all revenue report transactions from the
27196 * current user's people analytics profile.
27197 *
27198 * ### Usage:
27199 *
27200 * mixpanel.people.clear_charges();
27201 *
27202 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
27203 * @deprecated
27204 */
27205 MixpanelPeople.prototype.clear_charges = function(callback) {
27206 return this.set('$transactions', [], callback);
27207 };
27208
27209 /*
27210 * Permanently deletes the current people analytics profile from
27211 * Mixpanel (using the current distinct_id).
27212 *
27213 * ### Usage:
27214 *
27215 * // remove the all data you have stored about the current user
27216 * mixpanel.people.delete_user();
27217 *
27218 */
27219 MixpanelPeople.prototype.delete_user = function() {
27220 if (!this._identify_called()) {
27221 console$1.error('mixpanel.people.delete_user() requires you to call identify() first');
27222 return;
27223 }
27224 var data = {'$delete': this._mixpanel.get_distinct_id()};
27225 return this._send_request(data);
27226 };
27227
27228 MixpanelPeople.prototype.toString = function() {
27229 return this._mixpanel.toString() + '.people';
27230 };
27231
27232 MixpanelPeople.prototype._send_request = function(data, callback) {
27233 data['$token'] = this._get_config('token');
27234 data['$distinct_id'] = this._mixpanel.get_distinct_id();
27235 var device_id = this._mixpanel.get_property('$device_id');
27236 var user_id = this._mixpanel.get_property('$user_id');
27237 var had_persisted_distinct_id = this._mixpanel.get_property('$had_persisted_distinct_id');
27238 if (device_id) {
27239 data['$device_id'] = device_id;
27240 }
27241 if (user_id) {
27242 data['$user_id'] = user_id;
27243 }
27244 if (had_persisted_distinct_id) {
27245 data['$had_persisted_distinct_id'] = had_persisted_distinct_id;
27246 }
27247
27248 var date_encoded_data = _.encodeDates(data);
27249
27250 if (!this._identify_called()) {
27251 this._enqueue(data);
27252 if (!_.isUndefined(callback)) {
27253 if (this._get_config('verbose')) {
27254 callback({status: -1, error: null});
27255 } else {
27256 callback(-1);
27257 }
27258 }
27259 return _.truncate(date_encoded_data, 255);
27260 }
27261
27262 return this._mixpanel._track_or_batch({
27263 type: 'people',
27264 data: date_encoded_data,
27265 endpoint: this._mixpanel.get_api_host('people') + '/' + this._get_config('api_routes')['engage'],
27266 batcher: this._mixpanel.request_batchers.people
27267 }, callback);
27268 };
27269
27270 MixpanelPeople.prototype._get_config = function(conf_var) {
27271 return this._mixpanel.get_config(conf_var);
27272 };
27273
27274 MixpanelPeople.prototype._identify_called = function() {
27275 return this._mixpanel._flags.identify_called === true;
27276 };
27277
27278 // Queue up engage operations if identify hasn't been called yet.
27279 MixpanelPeople.prototype._enqueue = function(data) {
27280 if (SET_ACTION in data) {
27281 this._mixpanel['persistence']._add_to_people_queue(SET_ACTION, data);
27282 } else if (SET_ONCE_ACTION in data) {
27283 this._mixpanel['persistence']._add_to_people_queue(SET_ONCE_ACTION, data);
27284 } else if (UNSET_ACTION in data) {
27285 this._mixpanel['persistence']._add_to_people_queue(UNSET_ACTION, data);
27286 } else if (ADD_ACTION in data) {
27287 this._mixpanel['persistence']._add_to_people_queue(ADD_ACTION, data);
27288 } else if (APPEND_ACTION in data) {
27289 this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, data);
27290 } else if (REMOVE_ACTION in data) {
27291 this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, data);
27292 } else if (UNION_ACTION in data) {
27293 this._mixpanel['persistence']._add_to_people_queue(UNION_ACTION, data);
27294 } else {
27295 console$1.error('Invalid call to _enqueue():', data);
27296 }
27297 };
27298
27299 MixpanelPeople.prototype._flush_one_queue = function(action, action_method, callback, queue_to_params_fn) {
27300 var _this = this;
27301 var queued_data = _.extend({}, this._mixpanel['persistence'].load_queue(action));
27302 var action_params = queued_data;
27303
27304 if (!_.isUndefined(queued_data) && _.isObject(queued_data) && !_.isEmptyObject(queued_data)) {
27305 _this._mixpanel['persistence']._pop_from_people_queue(action, queued_data);
27306 _this._mixpanel['persistence'].save();
27307 if (queue_to_params_fn) {
27308 action_params = queue_to_params_fn(queued_data);
27309 }
27310 action_method.call(_this, action_params, function(response, data) {
27311 // on bad response, we want to add it back to the queue
27312 if (response === 0) {
27313 _this._mixpanel['persistence']._add_to_people_queue(action, queued_data);
27314 }
27315 if (!_.isUndefined(callback)) {
27316 callback(response, data);
27317 }
27318 });
27319 }
27320 };
27321
27322 // Flush queued engage operations - order does not matter,
27323 // and there are network level race conditions anyway
27324 MixpanelPeople.prototype._flush = function(
27325 _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback
27326 ) {
27327 var _this = this;
27328
27329 this._flush_one_queue(SET_ACTION, this.set, _set_callback);
27330 this._flush_one_queue(SET_ONCE_ACTION, this.set_once, _set_once_callback);
27331 this._flush_one_queue(UNSET_ACTION, this.unset, _unset_callback, function(queue) { return _.keys(queue); });
27332 this._flush_one_queue(ADD_ACTION, this.increment, _add_callback);
27333 this._flush_one_queue(UNION_ACTION, this.union, _union_callback);
27334
27335 // we have to fire off each $append individually since there is
27336 // no concat method server side
27337 var $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);
27338 if (!_.isUndefined($append_queue) && _.isArray($append_queue) && $append_queue.length) {
27339 var $append_item;
27340 var append_callback = function(response, data) {
27341 if (response === 0) {
27342 _this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, $append_item);
27343 }
27344 if (!_.isUndefined(_append_callback)) {
27345 _append_callback(response, data);
27346 }
27347 };
27348 for (var i = $append_queue.length - 1; i >= 0; i--) {
27349 $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);
27350 $append_item = $append_queue.pop();
27351 _this._mixpanel['persistence'].save();
27352 if (!_.isEmptyObject($append_item)) {
27353 _this.append($append_item, append_callback);
27354 }
27355 }
27356 }
27357
27358 // same for $remove
27359 var $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);
27360 if (!_.isUndefined($remove_queue) && _.isArray($remove_queue) && $remove_queue.length) {
27361 var $remove_item;
27362 var remove_callback = function(response, data) {
27363 if (response === 0) {
27364 _this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, $remove_item);
27365 }
27366 if (!_.isUndefined(_remove_callback)) {
27367 _remove_callback(response, data);
27368 }
27369 };
27370 for (var j = $remove_queue.length - 1; j >= 0; j--) {
27371 $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);
27372 $remove_item = $remove_queue.pop();
27373 _this._mixpanel['persistence'].save();
27374 if (!_.isEmptyObject($remove_item)) {
27375 _this.remove($remove_item, remove_callback);
27376 }
27377 }
27378 }
27379 };
27380
27381 MixpanelPeople.prototype._is_reserved_property = function(prop) {
27382 return prop === '$distinct_id' || prop === '$token' || prop === '$device_id' || prop === '$user_id' || prop === '$had_persisted_distinct_id';
27383 };
27384
27385 // MixpanelPeople Exports
27386 MixpanelPeople.prototype['set'] = MixpanelPeople.prototype.set;
27387 MixpanelPeople.prototype['set_once'] = MixpanelPeople.prototype.set_once;
27388 MixpanelPeople.prototype['unset'] = MixpanelPeople.prototype.unset;
27389 MixpanelPeople.prototype['increment'] = MixpanelPeople.prototype.increment;
27390 MixpanelPeople.prototype['append'] = MixpanelPeople.prototype.append;
27391 MixpanelPeople.prototype['remove'] = MixpanelPeople.prototype.remove;
27392 MixpanelPeople.prototype['union'] = MixpanelPeople.prototype.union;
27393 MixpanelPeople.prototype['track_charge'] = MixpanelPeople.prototype.track_charge;
27394 MixpanelPeople.prototype['clear_charges'] = MixpanelPeople.prototype.clear_charges;
27395 MixpanelPeople.prototype['delete_user'] = MixpanelPeople.prototype.delete_user;
27396 MixpanelPeople.prototype['toString'] = MixpanelPeople.prototype.toString;
27397
27398 /* eslint camelcase: "off" */
27399
27400
27401 /*
27402 * Constants
27403 */
27404 /** @const */ var SET_QUEUE_KEY = '__mps';
27405 /** @const */ var SET_ONCE_QUEUE_KEY = '__mpso';
27406 /** @const */ var UNSET_QUEUE_KEY = '__mpus';
27407 /** @const */ var ADD_QUEUE_KEY = '__mpa';
27408 /** @const */ var APPEND_QUEUE_KEY = '__mpap';
27409 /** @const */ var REMOVE_QUEUE_KEY = '__mpr';
27410 /** @const */ var UNION_QUEUE_KEY = '__mpu';
27411 // This key is deprecated, but we want to check for it to see whether aliasing is allowed.
27412 /** @const */ var PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';
27413 /** @const */ var ALIAS_ID_KEY = '__alias';
27414 /** @const */ var EVENT_TIMERS_KEY = '__timers';
27415 /** @const */ var RESERVED_PROPERTIES = [
27416 SET_QUEUE_KEY,
27417 SET_ONCE_QUEUE_KEY,
27418 UNSET_QUEUE_KEY,
27419 ADD_QUEUE_KEY,
27420 APPEND_QUEUE_KEY,
27421 REMOVE_QUEUE_KEY,
27422 UNION_QUEUE_KEY,
27423 PEOPLE_DISTINCT_ID_KEY,
27424 ALIAS_ID_KEY,
27425 EVENT_TIMERS_KEY
27426 ];
27427
27428 /**
27429 * Mixpanel Persistence Object
27430 * @constructor
27431 */
27432 var MixpanelPersistence = function(config) {
27433 this['props'] = {};
27434 this.campaign_params_saved = false;
27435
27436 if (config['persistence_name']) {
27437 this.name = 'mp_' + config['persistence_name'];
27438 } else {
27439 this.name = 'mp_' + config['token'] + '_mixpanel';
27440 }
27441
27442 var storage_type = config['persistence'];
27443 if (storage_type !== 'cookie' && storage_type !== 'localStorage') {
27444 console$1.critical('Unknown persistence type ' + storage_type + '; falling back to cookie');
27445 storage_type = config['persistence'] = 'cookie';
27446 }
27447
27448 if (storage_type === 'localStorage' && _.localStorage.is_supported()) {
27449 this.storage = _.localStorage;
27450 } else {
27451 this.storage = _.cookie;
27452 }
27453
27454 this.load();
27455 this.update_config(config);
27456 this.upgrade();
27457 this.save();
27458 };
27459
27460 MixpanelPersistence.prototype.properties = function() {
27461 var p = {};
27462
27463 this.load();
27464
27465 // Filter out reserved properties
27466 _.each(this['props'], function(v, k) {
27467 if (!_.include(RESERVED_PROPERTIES, k)) {
27468 p[k] = v;
27469 }
27470 });
27471 return p;
27472 };
27473
27474 MixpanelPersistence.prototype.load = function() {
27475 if (this.disabled) { return; }
27476
27477 var entry = this.storage.parse(this.name);
27478
27479 if (entry) {
27480 this['props'] = _.extend({}, entry);
27481 }
27482 };
27483
27484 MixpanelPersistence.prototype.upgrade = function() {
27485 var old_cookie,
27486 old_localstorage;
27487
27488 // if transferring from cookie to localStorage or vice-versa, copy existing
27489 // super properties over to new storage mode
27490 if (this.storage === _.localStorage) {
27491 old_cookie = _.cookie.parse(this.name);
27492
27493 _.cookie.remove(this.name);
27494 _.cookie.remove(this.name, true);
27495
27496 if (old_cookie) {
27497 this.register_once(old_cookie);
27498 }
27499 } else if (this.storage === _.cookie) {
27500 old_localstorage = _.localStorage.parse(this.name);
27501
27502 _.localStorage.remove(this.name);
27503
27504 if (old_localstorage) {
27505 this.register_once(old_localstorage);
27506 }
27507 }
27508 };
27509
27510 MixpanelPersistence.prototype.save = function() {
27511 if (this.disabled) { return; }
27512
27513 this.storage.set(
27514 this.name,
27515 JSONStringify(this['props']),
27516 this.expire_days,
27517 this.cross_subdomain,
27518 this.secure,
27519 this.cross_site,
27520 this.cookie_domain
27521 );
27522 };
27523
27524 MixpanelPersistence.prototype.load_prop = function(key) {
27525 this.load();
27526 return this['props'][key];
27527 };
27528
27529 MixpanelPersistence.prototype.remove = function() {
27530 // remove both domain and subdomain cookies
27531 this.storage.remove(this.name, false, this.cookie_domain);
27532 this.storage.remove(this.name, true, this.cookie_domain);
27533 };
27534
27535 // removes the storage entry and deletes all loaded data
27536 // forced name for tests
27537 MixpanelPersistence.prototype.clear = function() {
27538 this.remove();
27539 this['props'] = {};
27540 };
27541
27542 /**
27543 * @param {Object} props
27544 * @param {*=} default_value
27545 * @param {number=} days
27546 */
27547 MixpanelPersistence.prototype.register_once = function(props, default_value, days) {
27548 if (_.isObject(props)) {
27549 if (typeof(default_value) === 'undefined') { default_value = 'None'; }
27550 this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
27551
27552 this.load();
27553
27554 _.each(props, function(val, prop) {
27555 if (!this['props'].hasOwnProperty(prop) || this['props'][prop] === default_value) {
27556 this['props'][prop] = val;
27557 }
27558 }, this);
27559
27560 this.save();
27561
27562 return true;
27563 }
27564 return false;
27565 };
27566
27567 /**
27568 * @param {Object} props
27569 * @param {number=} days
27570 */
27571 MixpanelPersistence.prototype.register = function(props, days) {
27572 if (_.isObject(props)) {
27573 this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
27574
27575 this.load();
27576 _.extend(this['props'], props);
27577 this.save();
27578
27579 return true;
27580 }
27581 return false;
27582 };
27583
27584 MixpanelPersistence.prototype.unregister = function(prop) {
27585 this.load();
27586 if (prop in this['props']) {
27587 delete this['props'][prop];
27588 this.save();
27589 }
27590 };
27591
27592 MixpanelPersistence.prototype.update_search_keyword = function(referrer) {
27593 this.register(_.info.searchInfo(referrer));
27594 };
27595
27596 // EXPORTED METHOD, we test this directly.
27597 MixpanelPersistence.prototype.update_referrer_info = function(referrer) {
27598 // If referrer doesn't exist, we want to note the fact that it was type-in traffic.
27599 this.register_once({
27600 '$initial_referrer': referrer || '$direct',
27601 '$initial_referring_domain': _.info.referringDomain(referrer) || '$direct'
27602 }, '');
27603 };
27604
27605 MixpanelPersistence.prototype.get_referrer_info = function() {
27606 return _.strip_empty_properties({
27607 '$initial_referrer': this['props']['$initial_referrer'],
27608 '$initial_referring_domain': this['props']['$initial_referring_domain']
27609 });
27610 };
27611
27612 MixpanelPersistence.prototype.update_config = function(config) {
27613 this.default_expiry = this.expire_days = config['cookie_expiration'];
27614 this.set_disabled(config['disable_persistence']);
27615 this.set_cookie_domain(config['cookie_domain']);
27616 this.set_cross_site(config['cross_site_cookie']);
27617 this.set_cross_subdomain(config['cross_subdomain_cookie']);
27618 this.set_secure(config['secure_cookie']);
27619 };
27620
27621 MixpanelPersistence.prototype.set_disabled = function(disabled) {
27622 this.disabled = disabled;
27623 if (this.disabled) {
27624 this.remove();
27625 } else {
27626 this.save();
27627 }
27628 };
27629
27630 MixpanelPersistence.prototype.set_cookie_domain = function(cookie_domain) {
27631 if (cookie_domain !== this.cookie_domain) {
27632 this.remove();
27633 this.cookie_domain = cookie_domain;
27634 this.save();
27635 }
27636 };
27637
27638 MixpanelPersistence.prototype.set_cross_site = function(cross_site) {
27639 if (cross_site !== this.cross_site) {
27640 this.cross_site = cross_site;
27641 this.remove();
27642 this.save();
27643 }
27644 };
27645
27646 MixpanelPersistence.prototype.set_cross_subdomain = function(cross_subdomain) {
27647 if (cross_subdomain !== this.cross_subdomain) {
27648 this.cross_subdomain = cross_subdomain;
27649 this.remove();
27650 this.save();
27651 }
27652 };
27653
27654 MixpanelPersistence.prototype.get_cross_subdomain = function() {
27655 return this.cross_subdomain;
27656 };
27657
27658 MixpanelPersistence.prototype.set_secure = function(secure) {
27659 if (secure !== this.secure) {
27660 this.secure = secure ? true : false;
27661 this.remove();
27662 this.save();
27663 }
27664 };
27665
27666 MixpanelPersistence.prototype._add_to_people_queue = function(queue, data) {
27667 var q_key = this._get_queue_key(queue),
27668 q_data = data[queue],
27669 set_q = this._get_or_create_queue(SET_ACTION),
27670 set_once_q = this._get_or_create_queue(SET_ONCE_ACTION),
27671 unset_q = this._get_or_create_queue(UNSET_ACTION),
27672 add_q = this._get_or_create_queue(ADD_ACTION),
27673 union_q = this._get_or_create_queue(UNION_ACTION),
27674 remove_q = this._get_or_create_queue(REMOVE_ACTION, []),
27675 append_q = this._get_or_create_queue(APPEND_ACTION, []);
27676
27677 if (q_key === SET_QUEUE_KEY) {
27678 // Update the set queue - we can override any existing values
27679 _.extend(set_q, q_data);
27680 // if there was a pending increment, override it
27681 // with the set.
27682 this._pop_from_people_queue(ADD_ACTION, q_data);
27683 // if there was a pending union, override it
27684 // with the set.
27685 this._pop_from_people_queue(UNION_ACTION, q_data);
27686 this._pop_from_people_queue(UNSET_ACTION, q_data);
27687 } else if (q_key === SET_ONCE_QUEUE_KEY) {
27688 // only queue the data if there is not already a set_once call for it.
27689 _.each(q_data, function(v, k) {
27690 if (!(k in set_once_q)) {
27691 set_once_q[k] = v;
27692 }
27693 });
27694 this._pop_from_people_queue(UNSET_ACTION, q_data);
27695 } else if (q_key === UNSET_QUEUE_KEY) {
27696 _.each(q_data, function(prop) {
27697
27698 // undo previously-queued actions on this key
27699 _.each([set_q, set_once_q, add_q, union_q], function(enqueued_obj) {
27700 if (prop in enqueued_obj) {
27701 delete enqueued_obj[prop];
27702 }
27703 });
27704 _.each(append_q, function(append_obj) {
27705 if (prop in append_obj) {
27706 delete append_obj[prop];
27707 }
27708 });
27709
27710 unset_q[prop] = true;
27711
27712 });
27713 } else if (q_key === ADD_QUEUE_KEY) {
27714 _.each(q_data, function(v, k) {
27715 // If it exists in the set queue, increment
27716 // the value
27717 if (k in set_q) {
27718 set_q[k] += v;
27719 } else {
27720 // If it doesn't exist, update the add
27721 // queue
27722 if (!(k in add_q)) {
27723 add_q[k] = 0;
27724 }
27725 add_q[k] += v;
27726 }
27727 }, this);
27728 this._pop_from_people_queue(UNSET_ACTION, q_data);
27729 } else if (q_key === UNION_QUEUE_KEY) {
27730 _.each(q_data, function(v, k) {
27731 if (_.isArray(v)) {
27732 if (!(k in union_q)) {
27733 union_q[k] = [];
27734 }
27735 // Prevent duplicate values
27736 _.each(v, function(item) {
27737 if (!_.include(union_q[k], item)) {
27738 union_q[k].push(item);
27739 }
27740 });
27741 }
27742 });
27743 this._pop_from_people_queue(UNSET_ACTION, q_data);
27744 } else if (q_key === REMOVE_QUEUE_KEY) {
27745 remove_q.push(q_data);
27746 this._pop_from_people_queue(APPEND_ACTION, q_data);
27747 } else if (q_key === APPEND_QUEUE_KEY) {
27748 append_q.push(q_data);
27749 this._pop_from_people_queue(UNSET_ACTION, q_data);
27750 }
27751
27752 console$1.log('MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):');
27753 console$1.log(data);
27754
27755 this.save();
27756 };
27757
27758 MixpanelPersistence.prototype._pop_from_people_queue = function(queue, data) {
27759 var q = this['props'][this._get_queue_key(queue)];
27760 if (!_.isUndefined(q)) {
27761 _.each(data, function(v, k) {
27762 if (queue === APPEND_ACTION || queue === REMOVE_ACTION) {
27763 // list actions: only remove if both k+v match
27764 // e.g. remove should not override append in a case like
27765 // append({foo: 'bar'}); remove({foo: 'qux'})
27766 _.each(q, function(queued_action) {
27767 if (queued_action[k] === v) {
27768 delete queued_action[k];
27769 }
27770 });
27771 } else {
27772 delete q[k];
27773 }
27774 }, this);
27775 }
27776 };
27777
27778 MixpanelPersistence.prototype.load_queue = function(queue) {
27779 return this.load_prop(this._get_queue_key(queue));
27780 };
27781
27782 MixpanelPersistence.prototype._get_queue_key = function(queue) {
27783 if (queue === SET_ACTION) {
27784 return SET_QUEUE_KEY;
27785 } else if (queue === SET_ONCE_ACTION) {
27786 return SET_ONCE_QUEUE_KEY;
27787 } else if (queue === UNSET_ACTION) {
27788 return UNSET_QUEUE_KEY;
27789 } else if (queue === ADD_ACTION) {
27790 return ADD_QUEUE_KEY;
27791 } else if (queue === APPEND_ACTION) {
27792 return APPEND_QUEUE_KEY;
27793 } else if (queue === REMOVE_ACTION) {
27794 return REMOVE_QUEUE_KEY;
27795 } else if (queue === UNION_ACTION) {
27796 return UNION_QUEUE_KEY;
27797 } else {
27798 console$1.error('Invalid queue:', queue);
27799 }
27800 };
27801
27802 MixpanelPersistence.prototype._get_or_create_queue = function(queue, default_val) {
27803 var key = this._get_queue_key(queue);
27804 default_val = _.isUndefined(default_val) ? {} : default_val;
27805 return this['props'][key] || (this['props'][key] = default_val);
27806 };
27807
27808 MixpanelPersistence.prototype.set_event_timer = function(event_name, timestamp) {
27809 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
27810 timers[event_name] = timestamp;
27811 this['props'][EVENT_TIMERS_KEY] = timers;
27812 this.save();
27813 };
27814
27815 MixpanelPersistence.prototype.remove_event_timer = function(event_name) {
27816 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
27817 var timestamp = timers[event_name];
27818 if (!_.isUndefined(timestamp)) {
27819 delete this['props'][EVENT_TIMERS_KEY][event_name];
27820 this.save();
27821 }
27822 return timestamp;
27823 };
27824
27825 /* eslint camelcase: "off" */
27826
27827 /*
27828 * Mixpanel JS Library
27829 *
27830 * Copyright 2012, Mixpanel, Inc. All Rights Reserved
27831 * http://mixpanel.com/
27832 *
27833 * Includes portions of Underscore.js
27834 * http://documentcloud.github.com/underscore/
27835 * (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
27836 * Released under the MIT License.
27837 */
27838
27839 /*
27840 SIMPLE STYLE GUIDE:
27841
27842 this.x === public function
27843 this._x === internal - only use within this file
27844 this.__x === private - only use within the class
27845
27846 Globals should be all caps
27847 */
27848
27849 var init_type; // MODULE or SNIPPET loader
27850 // allow bundlers to specify how extra code (recorder bundle) should be loaded
27851 // eslint-disable-next-line no-unused-vars
27852 var load_extra_bundle = function(src, _onload) {
27853 throw new Error(src + ' not available in this build.');
27854 };
27855
27856 var mixpanel_master; // main mixpanel instance / object
27857 var INIT_MODULE = 0;
27858 var INIT_SNIPPET = 1;
27859
27860 var IDENTITY_FUNC = function(x) {return x;};
27861
27862 /** @const */ var PRIMARY_INSTANCE_NAME = 'mixpanel';
27863 /** @const */ var PAYLOAD_TYPE_BASE64 = 'base64';
27864 /** @const */ var PAYLOAD_TYPE_JSON = 'json';
27865 /** @const */ var DEVICE_ID_PREFIX = '$device:';
27866
27867
27868 /*
27869 * Dynamic... constants? Is that an oxymoron?
27870 */
27871 // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
27872 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
27873 var USE_XHR = (win.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest());
27874
27875 // IE<10 does not support cross-origin XHR's but script tags
27876 // with defer won't block window.onload; ENQUEUE_REQUESTS
27877 // should only be true for Opera<12
27878 var ENQUEUE_REQUESTS = !USE_XHR && (userAgent.indexOf('MSIE') === -1) && (userAgent.indexOf('Mozilla') === -1);
27879
27880 // save reference to navigator.sendBeacon so it can be minified
27881 var sendBeacon = null;
27882 if (navigator['sendBeacon']) {
27883 sendBeacon = function() {
27884 // late reference to navigator.sendBeacon to allow patching/spying
27885 return navigator['sendBeacon'].apply(navigator, arguments);
27886 };
27887 }
27888
27889 var DEFAULT_API_ROUTES = {
27890 'track': 'track/',
27891 'engage': 'engage/',
27892 'groups': 'groups/',
27893 'record': 'record/',
27894 'flags': 'flags/'
27895 };
27896
27897 /*
27898 * Module-level globals
27899 */
27900 var DEFAULT_CONFIG = {
27901 'api_host': 'https://api-js.mixpanel.com',
27902 'api_hosts': {},
27903 'api_routes': DEFAULT_API_ROUTES,
27904 'api_extra_query_params': {},
27905 'api_method': 'POST',
27906 'api_transport': 'XHR',
27907 'api_payload_format': PAYLOAD_TYPE_BASE64,
27908 'app_host': 'https://mixpanel.com',
27909 'autocapture': false,
27910 'cdn': 'https://cdn.mxpnl.com',
27911 'cross_site_cookie': false,
27912 'cross_subdomain_cookie': true,
27913 'error_reporter': NOOP_FUNC,
27914 'flags': false,
27915 'persistence': 'cookie',
27916 'persistence_name': '',
27917 'cookie_domain': '',
27918 'cookie_name': '',
27919 'loaded': NOOP_FUNC,
27920 'mp_loader': null,
27921 'track_marketing': true,
27922 'track_pageview': false,
27923 'skip_first_touch_marketing': false,
27924 'store_google': true,
27925 'stop_utm_persistence': false,
27926 'save_referrer': true,
27927 'test': false,
27928 'verbose': false,
27929 'img': false,
27930 'debug': false,
27931 'track_links_timeout': 300,
27932 'cookie_expiration': 365,
27933 'upgrade': false,
27934 'disable_persistence': false,
27935 'disable_cookie': false,
27936 'secure_cookie': false,
27937 'ip': true,
27938 'opt_out_tracking_by_default': false,
27939 'opt_out_persistence_by_default': false,
27940 'opt_out_tracking_persistence_type': 'localStorage',
27941 'opt_out_tracking_cookie_prefix': null,
27942 'property_blacklist': [],
27943 'xhr_headers': {}, // { header: value, header2: value }
27944 'ignore_dnt': false,
27945 'batch_requests': true,
27946 'batch_size': 50,
27947 'batch_flush_interval_ms': 5000,
27948 'batch_request_timeout_ms': 90000,
27949 'batch_autostart': true,
27950 'hooks': {},
27951 'record_block_class': new RegExp('^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$'),
27952 'record_block_selector': 'img, video, audio',
27953 'record_canvas': false,
27954 'record_collect_fonts': false,
27955 'record_heatmap_data': false,
27956 'record_idle_timeout_ms': 30 * 60 * 1000, // 30 minutes
27957 'record_mask_text_class': new RegExp('^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$'),
27958 'record_mask_text_selector': '*',
27959 'record_max_ms': MAX_RECORDING_MS,
27960 'record_min_ms': 0,
27961 'record_sessions_percent': 0,
27962 'recorder_src': 'https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js'
27963 };
27964
27965 var DOM_LOADED = false;
27966
27967 /**
27968 * Mixpanel Library Object
27969 * @constructor
27970 */
27971 var MixpanelLib = function() {};
27972
27973
27974 /**
27975 * create_mplib(token:string, config:object, name:string)
27976 *
27977 * This function is used by the init method of MixpanelLib objects
27978 * as well as the main initializer at the end of the JSLib (that
27979 * initializes document.mixpanel as well as any additional instances
27980 * declared before this file has loaded).
27981 */
27982 var create_mplib = function(token, config, name) {
27983 var instance,
27984 target = (name === PRIMARY_INSTANCE_NAME) ? mixpanel_master : mixpanel_master[name];
27985
27986 if (target && init_type === INIT_MODULE) {
27987 instance = target;
27988 } else {
27989 if (target && !_.isArray(target)) {
27990 console$1.error('You have already initialized ' + name);
27991 return;
27992 }
27993 instance = new MixpanelLib();
27994 }
27995
27996 instance._cached_groups = {}; // cache groups in a pool
27997
27998 instance._init(token, config, name);
27999
28000 instance['people'] = new MixpanelPeople();
28001 instance['people']._init(instance);
28002
28003 if (!instance.get_config('skip_first_touch_marketing')) {
28004 // We need null UTM params in the object because
28005 // UTM parameters act as a tuple. If any UTM param
28006 // is present, then we set all UTM params including
28007 // empty ones together
28008 var utm_params = _.info.campaignParams(null);
28009 var initial_utm_params = {};
28010 var has_utm = false;
28011 _.each(utm_params, function(utm_value, utm_key) {
28012 initial_utm_params['initial_' + utm_key] = utm_value;
28013 if (utm_value) {
28014 has_utm = true;
28015 }
28016 });
28017 if (has_utm) {
28018 instance['people'].set_once(initial_utm_params);
28019 }
28020 }
28021
28022 // if any instance on the page has debug = true, we set the
28023 // global debug to be true
28024 Config.DEBUG = Config.DEBUG || instance.get_config('debug');
28025
28026 // if target is not defined, we called init after the lib already
28027 // loaded, so there won't be an array of things to execute
28028 if (!_.isUndefined(target) && _.isArray(target)) {
28029 // Crunch through the people queue first - we queue this data up &
28030 // flush on identify, so it's better to do all these operations first
28031 instance._execute_array.call(instance['people'], target['people']);
28032 instance._execute_array(target);
28033 }
28034
28035 return instance;
28036 };
28037
28038 // Initialization methods
28039
28040 /**
28041 * This function initializes a new instance of the Mixpanel tracking object.
28042 * All new instances are added to the main mixpanel object as sub properties (such as
28043 * mixpanel.library_name) and also returned by this function. To define a
28044 * second instance on the page, you would call:
28045 *
28046 * mixpanel.init('new token', { your: 'config' }, 'library_name');
28047 *
28048 * and use it like so:
28049 *
28050 * mixpanel.library_name.track(...);
28051 *
28052 * @param {String} token Your Mixpanel API token
28053 * @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>.
28054 * @param {String} [name] The name for the new mixpanel instance that you want created
28055 */
28056 MixpanelLib.prototype.init = function (token, config, name) {
28057 if (_.isUndefined(name)) {
28058 this.report_error('You must name your new library: init(token, config, name)');
28059 return;
28060 }
28061 if (name === PRIMARY_INSTANCE_NAME) {
28062 this.report_error('You must initialize the main mixpanel object right after you include the Mixpanel js snippet');
28063 return;
28064 }
28065
28066 var instance = create_mplib(token, config, name);
28067 mixpanel_master[name] = instance;
28068 instance._loaded();
28069
28070 return instance;
28071 };
28072
28073 // mixpanel._init(token:string, config:object, name:string)
28074 //
28075 // This function sets up the current instance of the mixpanel
28076 // library. The difference between this method and the init(...)
28077 // method is this one initializes the actual instance, whereas the
28078 // init(...) method sets up a new library and calls _init on it.
28079 //
28080 MixpanelLib.prototype._init = function(token, config, name) {
28081 config = config || {};
28082
28083 this['__loaded'] = true;
28084 this['config'] = {};
28085
28086 var variable_features = {};
28087
28088 // default to JSON payload for standard mixpanel.com API hosts
28089 if (!('api_payload_format' in config)) {
28090 var api_host = config['api_host'] || DEFAULT_CONFIG['api_host'];
28091 if (api_host.match(/\.mixpanel\.com/)) {
28092 variable_features['api_payload_format'] = PAYLOAD_TYPE_JSON;
28093 }
28094 }
28095
28096 this.set_config(_.extend({}, DEFAULT_CONFIG, variable_features, config, {
28097 'name': name,
28098 'token': token,
28099 'callback_fn': ((name === PRIMARY_INSTANCE_NAME) ? name : PRIMARY_INSTANCE_NAME + '.' + name) + '._jsc'
28100 }));
28101
28102 this['_jsc'] = NOOP_FUNC;
28103
28104 this.__dom_loaded_queue = [];
28105 this.__request_queue = [];
28106 this.__disabled_events = [];
28107 this._flags = {
28108 'disable_all_events': false,
28109 'identify_called': false
28110 };
28111
28112 // set up request queueing/batching
28113 this.request_batchers = {};
28114 this._batch_requests = this.get_config('batch_requests');
28115 if (this._batch_requests) {
28116 if (!_.localStorage.is_supported(true) || !USE_XHR) {
28117 this._batch_requests = false;
28118 console$1.log('Turning off Mixpanel request-queueing; needs XHR and localStorage support');
28119 _.each(this.get_batcher_configs(), function(batcher_config) {
28120 console$1.log('Clearing batch queue ' + batcher_config.queue_key);
28121 _.localStorage.remove(batcher_config.queue_key);
28122 });
28123 } else {
28124 this.init_batchers();
28125 if (sendBeacon && win.addEventListener) {
28126 // Before page closes or hides (user tabs away etc), attempt to flush any events
28127 // queued up via navigator.sendBeacon. Since sendBeacon doesn't report success/failure,
28128 // events will not be removed from the persistent store; if the site is loaded again,
28129 // the events will be flushed again on startup and deduplicated on the Mixpanel server
28130 // side.
28131 // There is no reliable way to capture only page close events, so we lean on the
28132 // visibilitychange and pagehide events as recommended at
28133 // https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event#usage_notes.
28134 // These events fire when the user clicks away from the current page/tab, so will occur
28135 // more frequently than page unload, but are the only mechanism currently for capturing
28136 // this scenario somewhat reliably.
28137 var flush_on_unload = _.bind(function() {
28138 if (!this.request_batchers.events.stopped) {
28139 this.request_batchers.events.flush({unloading: true});
28140 }
28141 }, this);
28142 win.addEventListener('pagehide', function(ev) {
28143 if (ev['persisted']) {
28144 flush_on_unload();
28145 }
28146 });
28147 win.addEventListener('visibilitychange', function() {
28148 if (document$1['visibilityState'] === 'hidden') {
28149 flush_on_unload();
28150 }
28151 });
28152 }
28153 }
28154 }
28155
28156 this['persistence'] = this['cookie'] = new MixpanelPersistence(this['config']);
28157 this.unpersisted_superprops = {};
28158 this._gdpr_init();
28159
28160 var uuid = _.UUID();
28161 if (!this.get_distinct_id()) {
28162 // There is no need to set the distinct id
28163 // or the device id if something was already stored
28164 // in the persitence
28165 this.register_once({
28166 'distinct_id': DEVICE_ID_PREFIX + uuid,
28167 '$device_id': uuid
28168 }, '');
28169 }
28170
28171 this.flags = new FeatureFlagManager({
28172 getFullApiRoute: _.bind(function() {
28173 return this.get_api_host('flags') + '/' + this.get_config('api_routes')['flags'];
28174 }, this),
28175 getConfigFunc: _.bind(this.get_config, this),
28176 setConfigFunc: _.bind(this.set_config, this),
28177 getPropertyFunc: _.bind(this.get_property, this),
28178 trackingFunc: _.bind(this.track, this)
28179 });
28180 this.flags.init();
28181 this['flags'] = this.flags;
28182
28183 this.autocapture = new Autocapture(this);
28184 this.autocapture.init();
28185
28186 this._init_tab_id();
28187 this._check_and_start_session_recording();
28188 };
28189
28190 /**
28191 * Assigns a unique UUID to this tab / window by leveraging sessionStorage.
28192 * This is primarily used for session recording, where data must be isolated to the current tab.
28193 */
28194 MixpanelLib.prototype._init_tab_id = function() {
28195 if (this.get_config('disable_persistence')) {
28196 console$1.log('Tab ID initialization skipped due to disable_persistence config');
28197 } else if (_.sessionStorage.is_supported()) {
28198 try {
28199 var key_suffix = this.get_config('name') + '_' + this.get_config('token');
28200 var tab_id_key = 'mp_tab_id_' + key_suffix;
28201
28202 // A flag is used to determine if sessionStorage is copied over and we need to generate a new tab ID.
28203 // This enforces a unique ID in the cases like duplicated tab, window.open(...)
28204 var should_generate_new_tab_id_key = 'mp_gen_new_tab_id_' + key_suffix;
28205 if (_.sessionStorage.get(should_generate_new_tab_id_key) || !_.sessionStorage.get(tab_id_key)) {
28206 _.sessionStorage.set(tab_id_key, '$tab-' + _.UUID());
28207 }
28208
28209 _.sessionStorage.set(should_generate_new_tab_id_key, '1');
28210 this.tab_id = _.sessionStorage.get(tab_id_key);
28211
28212 // 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,
28213 // but reliable in cases where the user remains in the tab e.g. a refresh or href navigation.
28214 // If the flag is absent, this indicates to the next SDK instance that we can reuse the stored tab_id.
28215 win.addEventListener('beforeunload', function () {
28216 _.sessionStorage.remove(should_generate_new_tab_id_key);
28217 });
28218 } catch(err) {
28219 this.report_error('Error initializing tab id', err);
28220 }
28221 } else {
28222 this.report_error('Session storage is not supported, cannot keep track of unique tab ID.');
28223 }
28224 };
28225
28226 MixpanelLib.prototype.get_tab_id = function () {
28227 return this.tab_id || null;
28228 };
28229
28230 MixpanelLib.prototype._should_load_recorder = function () {
28231 if (this.get_config('disable_persistence')) {
28232 console$1.log('Load recorder check skipped due to disable_persistence config');
28233 return Promise.resolve(false);
28234 }
28235
28236 var recording_registry_idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
28237 var tab_id = this.get_tab_id();
28238 return recording_registry_idb.init()
28239 .then(function () {
28240 return recording_registry_idb.getAll();
28241 })
28242 .then(function (recordings) {
28243 for (var i = 0; i < recordings.length; i++) {
28244 // if there are expired recordings in the registry, we should load the recorder to flush them
28245 // if there's a recording for this tab id, we should load the recorder to continue the recording
28246 if (isRecordingExpired(recordings[i]) || recordings[i]['tabId'] === tab_id) {
28247 return true;
28248 }
28249 }
28250 return false;
28251 })
28252 .catch(_.bind(function (err) {
28253 this.report_error('Error checking recording registry', err);
28254 }, this));
28255 };
28256
28257 MixpanelLib.prototype._check_and_start_session_recording = addOptOutCheckMixpanelLib(function(force_start) {
28258 if (!win['MutationObserver']) {
28259 console$1.critical('Browser does not support MutationObserver; skipping session recording');
28260 return;
28261 }
28262
28263 var loadRecorder = _.bind(function(startNewIfInactive) {
28264 var handleLoadedRecorder = _.bind(function() {
28265 this._recorder = this._recorder || new win['__mp_recorder'](this);
28266 this._recorder['resumeRecording'](startNewIfInactive);
28267 }, this);
28268
28269 if (_.isUndefined(win['__mp_recorder'])) {
28270 load_extra_bundle(this.get_config('recorder_src'), handleLoadedRecorder);
28271 } else {
28272 handleLoadedRecorder();
28273 }
28274 }, this);
28275
28276 /**
28277 * If the user is sampled or start_session_recording is called, we always load the recorder since it's guaranteed a recording should start.
28278 * 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.
28279 */
28280 var is_sampled = this.get_config('record_sessions_percent') > 0 && Math.random() * 100 <= this.get_config('record_sessions_percent');
28281 if (force_start || is_sampled) {
28282 loadRecorder(true);
28283 } else {
28284 this._should_load_recorder()
28285 .then(function (shouldLoad) {
28286 if (shouldLoad) {
28287 loadRecorder(false);
28288 }
28289 });
28290 }
28291 });
28292
28293 MixpanelLib.prototype.start_session_recording = function () {
28294 this._check_and_start_session_recording(true);
28295 };
28296
28297 MixpanelLib.prototype.stop_session_recording = function () {
28298 if (this._recorder) {
28299 return this._recorder['stopRecording']();
28300 }
28301 return Promise.resolve();
28302 };
28303
28304 MixpanelLib.prototype.pause_session_recording = function () {
28305 if (this._recorder) {
28306 return this._recorder['pauseRecording']();
28307 }
28308 return Promise.resolve();
28309 };
28310
28311 MixpanelLib.prototype.resume_session_recording = function () {
28312 if (this._recorder) {
28313 return this._recorder['resumeRecording']();
28314 }
28315 return Promise.resolve();
28316 };
28317
28318 MixpanelLib.prototype.is_recording_heatmap_data = function () {
28319 return this._get_session_replay_id() && this.get_config('record_heatmap_data');
28320 };
28321
28322 MixpanelLib.prototype.get_session_recording_properties = function () {
28323 var props = {};
28324 var replay_id = this._get_session_replay_id();
28325 if (replay_id) {
28326 props['$mp_replay_id'] = replay_id;
28327 }
28328 return props;
28329 };
28330
28331 MixpanelLib.prototype.get_session_replay_url = function () {
28332 var replay_url = null;
28333 var replay_id = this._get_session_replay_id();
28334 if (replay_id) {
28335 var query_params = _.HTTPBuildQuery({
28336 'replay_id': replay_id,
28337 'distinct_id': this.get_distinct_id(),
28338 'token': this.get_config('token')
28339 });
28340 replay_url = 'https://mixpanel.com/projects/replay-redirect?' + query_params;
28341 }
28342 return replay_url;
28343 };
28344
28345 MixpanelLib.prototype._get_session_replay_id = function () {
28346 var replay_id = null;
28347 if (this._recorder) {
28348 replay_id = this._recorder['replayId'];
28349 }
28350 return replay_id || null;
28351 };
28352
28353 // "private" public method to reach into the recorder in test cases
28354 MixpanelLib.prototype.__get_recorder = function () {
28355 return this._recorder;
28356 };
28357
28358 // Private methods
28359
28360 MixpanelLib.prototype._loaded = function() {
28361 this.get_config('loaded')(this);
28362 this._set_default_superprops();
28363 this['people'].set_once(this['persistence'].get_referrer_info());
28364
28365 // `store_google` is now deprecated and previously stored UTM parameters are cleared
28366 // from persistence by default.
28367 if (this.get_config('store_google') && this.get_config('stop_utm_persistence')) {
28368 var utm_params = _.info.campaignParams(null);
28369 _.each(utm_params, function(_utm_value, utm_key) {
28370 // We need to unregister persisted UTM parameters so old values
28371 // are not mixed with the new UTM parameters
28372 this.unregister(utm_key);
28373 }.bind(this));
28374 }
28375 };
28376
28377 // update persistence with info on referrer, UTM params, etc
28378 MixpanelLib.prototype._set_default_superprops = function() {
28379 this['persistence'].update_search_keyword(document$1.referrer);
28380 // Registering super properties for UTM persistence by 'store_google' is deprecated.
28381 if (this.get_config('store_google') && !this.get_config('stop_utm_persistence')) {
28382 this.register(_.info.campaignParams());
28383 }
28384 if (this.get_config('save_referrer')) {
28385 this['persistence'].update_referrer_info(document$1.referrer);
28386 }
28387 };
28388
28389 MixpanelLib.prototype._dom_loaded = function() {
28390 _.each(this.__dom_loaded_queue, function(item) {
28391 this._track_dom.apply(this, item);
28392 }, this);
28393
28394 if (!this.has_opted_out_tracking()) {
28395 _.each(this.__request_queue, function(item) {
28396 this._send_request.apply(this, item);
28397 }, this);
28398 }
28399
28400 delete this.__dom_loaded_queue;
28401 delete this.__request_queue;
28402 };
28403
28404 MixpanelLib.prototype._track_dom = function(DomClass, args) {
28405 if (this.get_config('img')) {
28406 this.report_error('You can\'t use DOM tracking functions with img = true.');
28407 return false;
28408 }
28409
28410 if (!DOM_LOADED) {
28411 this.__dom_loaded_queue.push([DomClass, args]);
28412 return false;
28413 }
28414
28415 var dt = new DomClass().init(this);
28416 return dt.track.apply(dt, args);
28417 };
28418
28419 /**
28420 * _prepare_callback() should be called by callers of _send_request for use
28421 * as the callback argument.
28422 *
28423 * If there is no callback, this returns null.
28424 * If we are going to make XHR/XDR requests, this returns a function.
28425 * If we are going to use script tags, this returns a string to use as the
28426 * callback GET param.
28427 */
28428 MixpanelLib.prototype._prepare_callback = function(callback, data) {
28429 if (_.isUndefined(callback)) {
28430 return null;
28431 }
28432
28433 if (USE_XHR) {
28434 var callback_function = function(response) {
28435 callback(response, data);
28436 };
28437 return callback_function;
28438 } else {
28439 // if the user gives us a callback, we store as a random
28440 // property on this instances jsc function and update our
28441 // callback string to reflect that.
28442 var jsc = this['_jsc'];
28443 var randomized_cb = '' + Math.floor(Math.random() * 100000000);
28444 var callback_string = this.get_config('callback_fn') + '[' + randomized_cb + ']';
28445 jsc[randomized_cb] = function(response) {
28446 delete jsc[randomized_cb];
28447 callback(response, data);
28448 };
28449 return callback_string;
28450 }
28451 };
28452
28453 MixpanelLib.prototype._send_request = function(url, data, options, callback) {
28454 var succeeded = true;
28455
28456 if (ENQUEUE_REQUESTS) {
28457 this.__request_queue.push(arguments);
28458 return succeeded;
28459 }
28460
28461 var DEFAULT_OPTIONS = {
28462 method: this.get_config('api_method'),
28463 transport: this.get_config('api_transport'),
28464 verbose: this.get_config('verbose')
28465 };
28466 var body_data = null;
28467
28468 if (!callback && (_.isFunction(options) || typeof options === 'string')) {
28469 callback = options;
28470 options = null;
28471 }
28472 options = _.extend(DEFAULT_OPTIONS, options || {});
28473 if (!USE_XHR) {
28474 options.method = 'GET';
28475 }
28476 var use_post = options.method === 'POST';
28477 var use_sendBeacon = sendBeacon && use_post && options.transport.toLowerCase() === 'sendbeacon';
28478
28479 // needed to correctly format responses
28480 var verbose_mode = options.verbose;
28481 if (data['verbose']) { verbose_mode = true; }
28482
28483 if (this.get_config('test')) { data['test'] = 1; }
28484 if (verbose_mode) { data['verbose'] = 1; }
28485 if (this.get_config('img')) { data['img'] = 1; }
28486 if (!USE_XHR) {
28487 if (callback) {
28488 data['callback'] = callback;
28489 } else if (verbose_mode || this.get_config('test')) {
28490 // Verbose output (from verbose mode, or an error in test mode) is a json blob,
28491 // which by itself is not valid javascript. Without a callback, this verbose output will
28492 // cause an error when returned via jsonp, so we force a no-op callback param.
28493 // See the ECMA script spec: http://www.ecma-international.org/ecma-262/5.1/#sec-12.4
28494 data['callback'] = '(function(){})';
28495 }
28496 }
28497
28498 data['ip'] = this.get_config('ip')?1:0;
28499 data['_'] = new Date().getTime().toString();
28500
28501 if (use_post) {
28502 body_data = 'data=' + encodeURIComponent(data['data']);
28503 delete data['data'];
28504 }
28505
28506 _.extend(data, this.get_config('api_extra_query_params'));
28507
28508 url += '?' + _.HTTPBuildQuery(data);
28509
28510 var lib = this;
28511 if ('img' in data) {
28512 var img = document$1.createElement('img');
28513 img.src = url;
28514 document$1.body.appendChild(img);
28515 } else if (use_sendBeacon) {
28516 try {
28517 succeeded = sendBeacon(url, body_data);
28518 } catch (e) {
28519 lib.report_error(e);
28520 succeeded = false;
28521 }
28522 try {
28523 if (callback) {
28524 callback(succeeded ? 1 : 0);
28525 }
28526 } catch (e) {
28527 lib.report_error(e);
28528 }
28529 } else if (USE_XHR) {
28530 try {
28531 var req = new XMLHttpRequest();
28532 req.open(options.method, url, true);
28533
28534 var headers = this.get_config('xhr_headers');
28535 if (use_post) {
28536 headers['Content-Type'] = 'application/x-www-form-urlencoded';
28537 }
28538 _.each(headers, function(headerValue, headerName) {
28539 req.setRequestHeader(headerName, headerValue);
28540 });
28541
28542 if (options.timeout_ms && typeof req.timeout !== 'undefined') {
28543 req.timeout = options.timeout_ms;
28544 var start_time = new Date().getTime();
28545 }
28546
28547 // send the mp_optout cookie
28548 // withCredentials cannot be modified until after calling .open on Android and Mobile Safari
28549 req.withCredentials = true;
28550 req.onreadystatechange = function () {
28551 if (req.readyState === 4) { // XMLHttpRequest.DONE == 4, except in safari 4
28552 if (req.status === 200) {
28553 if (callback) {
28554 if (verbose_mode) {
28555 var response;
28556 try {
28557 response = _.JSONDecode(req.responseText);
28558 } catch (e) {
28559 lib.report_error(e);
28560 if (options.ignore_json_errors) {
28561 response = req.responseText;
28562 } else {
28563 return;
28564 }
28565 }
28566 callback(response);
28567 } else {
28568 callback(Number(req.responseText));
28569 }
28570 }
28571 } else {
28572 var error;
28573 if (
28574 req.timeout &&
28575 !req.status &&
28576 new Date().getTime() - start_time >= req.timeout
28577 ) {
28578 error = 'timeout';
28579 } else {
28580 error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
28581 }
28582 lib.report_error(error);
28583 if (callback) {
28584 if (verbose_mode) {
28585 var response_headers = req['responseHeaders'] || {};
28586 callback({status: 0, httpStatusCode: req['status'], error: error, retryAfter: response_headers['Retry-After']});
28587 } else {
28588 callback(0);
28589 }
28590 }
28591 }
28592 }
28593 };
28594 req.send(body_data);
28595 } catch (e) {
28596 lib.report_error(e);
28597 succeeded = false;
28598 }
28599 } else {
28600 var script = document$1.createElement('script');
28601 script.type = 'text/javascript';
28602 script.async = true;
28603 script.defer = true;
28604 script.src = url;
28605 var s = document$1.getElementsByTagName('script')[0];
28606 s.parentNode.insertBefore(script, s);
28607 }
28608
28609 return succeeded;
28610 };
28611
28612 /**
28613 * _execute_array() deals with processing any mixpanel function
28614 * calls that were called before the Mixpanel library were loaded
28615 * (and are thus stored in an array so they can be called later)
28616 *
28617 * Note: we fire off all the mixpanel function calls && user defined
28618 * functions BEFORE we fire off mixpanel tracking calls. This is so
28619 * identify/register/set_config calls can properly modify early
28620 * tracking calls.
28621 *
28622 * @param {Array} array
28623 */
28624 MixpanelLib.prototype._execute_array = function(array) {
28625 var fn_name, alias_calls = [], other_calls = [], tracking_calls = [];
28626 _.each(array, function(item) {
28627 if (item) {
28628 fn_name = item[0];
28629 if (_.isArray(fn_name)) {
28630 tracking_calls.push(item); // chained call e.g. mixpanel.get_group().set()
28631 } else if (typeof(item) === 'function') {
28632 item.call(this);
28633 } else if (_.isArray(item) && fn_name === 'alias') {
28634 alias_calls.push(item);
28635 } else if (_.isArray(item) && fn_name.indexOf('track') !== -1 && typeof(this[fn_name]) === 'function') {
28636 tracking_calls.push(item);
28637 } else {
28638 other_calls.push(item);
28639 }
28640 }
28641 }, this);
28642
28643 var execute = function(calls, context) {
28644 _.each(calls, function(item) {
28645 if (_.isArray(item[0])) {
28646 // chained call
28647 var caller = context;
28648 _.each(item, function(call) {
28649 caller = caller[call[0]].apply(caller, call.slice(1));
28650 });
28651 } else {
28652 this[item[0]].apply(this, item.slice(1));
28653 }
28654 }, context);
28655 };
28656
28657 execute(alias_calls, this);
28658 execute(other_calls, this);
28659 execute(tracking_calls, this);
28660 };
28661
28662 // request queueing utils
28663
28664 MixpanelLib.prototype.are_batchers_initialized = function() {
28665 return !!this.request_batchers.events;
28666 };
28667
28668 MixpanelLib.prototype.get_batcher_configs = function() {
28669 var queue_prefix = '__mpq_' + this.get_config('token');
28670 this._batcher_configs = this._batcher_configs || {
28671 events: {type: 'events', api_name: 'track', queue_key: queue_prefix + '_ev'},
28672 people: {type: 'people', api_name: 'engage', queue_key: queue_prefix + '_pp'},
28673 groups: {type: 'groups', api_name: 'groups', queue_key: queue_prefix + '_gr'}
28674 };
28675 return this._batcher_configs;
28676 };
28677
28678 MixpanelLib.prototype.init_batchers = function() {
28679 if (!this.are_batchers_initialized()) {
28680 var batcher_for = _.bind(function(attrs) {
28681 return new RequestBatcher(
28682 attrs.queue_key,
28683 {
28684 libConfig: this['config'],
28685 errorReporter: this.get_config('error_reporter'),
28686 sendRequestFunc: _.bind(function(data, options, cb) {
28687 var api_routes = this.get_config('api_routes');
28688 this._send_request(
28689 this.get_api_host(attrs.api_name) + '/' + api_routes[attrs.api_name],
28690 this._encode_data_for_request(data),
28691 options,
28692 this._prepare_callback(cb, data)
28693 );
28694 }, this),
28695 beforeSendHook: _.bind(function(item) {
28696 return this._run_hook('before_send_' + attrs.type, item);
28697 }, this),
28698 stopAllBatchingFunc: _.bind(this.stop_batch_senders, this),
28699 usePersistence: true,
28700 }
28701 );
28702 }, this);
28703 var batcher_configs = this.get_batcher_configs();
28704 this.request_batchers = {
28705 events: batcher_for(batcher_configs.events),
28706 people: batcher_for(batcher_configs.people),
28707 groups: batcher_for(batcher_configs.groups)
28708 };
28709 }
28710 if (this.get_config('batch_autostart')) {
28711 this.start_batch_senders();
28712 }
28713 };
28714
28715 MixpanelLib.prototype.start_batch_senders = function() {
28716 this._batchers_were_started = true;
28717 if (this.are_batchers_initialized()) {
28718 this._batch_requests = true;
28719 _.each(this.request_batchers, function(batcher) {
28720 batcher.start();
28721 });
28722 }
28723 };
28724
28725 MixpanelLib.prototype.stop_batch_senders = function() {
28726 this._batch_requests = false;
28727 _.each(this.request_batchers, function(batcher) {
28728 batcher.stop();
28729 batcher.clear();
28730 });
28731 };
28732
28733 /**
28734 * push() keeps the standard async-array-push
28735 * behavior around after the lib is loaded.
28736 * This is only useful for external integrations that
28737 * do not wish to rely on our convenience methods
28738 * (created in the snippet).
28739 *
28740 * ### Usage:
28741 * mixpanel.push(['register', { a: 'b' }]);
28742 *
28743 * @param {Array} item A [function_name, args...] array to be executed
28744 */
28745 MixpanelLib.prototype.push = function(item) {
28746 this._execute_array([item]);
28747 };
28748
28749 /**
28750 * Disable events on the Mixpanel object. If passed no arguments,
28751 * this function disables tracking of any event. If passed an
28752 * array of event names, those events will be disabled, but other
28753 * events will continue to be tracked.
28754 *
28755 * Note: this function does not stop other mixpanel functions from
28756 * firing, such as register() or people.set().
28757 *
28758 * @param {Array} [events] An array of event names to disable
28759 */
28760 MixpanelLib.prototype.disable = function(events) {
28761 if (typeof(events) === 'undefined') {
28762 this._flags.disable_all_events = true;
28763 } else {
28764 this.__disabled_events = this.__disabled_events.concat(events);
28765 }
28766 };
28767
28768 MixpanelLib.prototype._encode_data_for_request = function(data) {
28769 var encoded_data = JSONStringify(data);
28770 if (this.get_config('api_payload_format') === PAYLOAD_TYPE_BASE64) {
28771 encoded_data = _.base64Encode(encoded_data);
28772 }
28773 return {'data': encoded_data};
28774 };
28775
28776 // internal method for handling track vs batch-enqueue logic
28777 MixpanelLib.prototype._track_or_batch = function(options, callback) {
28778 var truncated_data = _.truncate(options.data, 255);
28779 var endpoint = options.endpoint;
28780 var batcher = options.batcher;
28781 var should_send_immediately = options.should_send_immediately;
28782 var send_request_options = options.send_request_options || {};
28783 callback = callback || NOOP_FUNC;
28784
28785 var request_enqueued_or_initiated = true;
28786 var send_request_immediately = _.bind(function() {
28787 if (!send_request_options.skip_hooks) {
28788 truncated_data = this._run_hook('before_send_' + options.type, truncated_data);
28789 }
28790 if (truncated_data) {
28791 console$1.log('MIXPANEL REQUEST:');
28792 console$1.log(truncated_data);
28793 return this._send_request(
28794 endpoint,
28795 this._encode_data_for_request(truncated_data),
28796 send_request_options,
28797 this._prepare_callback(callback, truncated_data)
28798 );
28799 } else {
28800 return null;
28801 }
28802 }, this);
28803
28804 if (this._batch_requests && !should_send_immediately) {
28805 batcher.enqueue(truncated_data).then(function(succeeded) {
28806 if (succeeded) {
28807 callback(1, truncated_data);
28808 } else {
28809 send_request_immediately();
28810 }
28811 });
28812 } else {
28813 request_enqueued_or_initiated = send_request_immediately();
28814 }
28815
28816 return request_enqueued_or_initiated && truncated_data;
28817 };
28818
28819 /**
28820 * Track an event. This is the most important and
28821 * frequently used Mixpanel function.
28822 *
28823 * ### Usage:
28824 *
28825 * // track an event named 'Registered'
28826 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
28827 *
28828 * // track an event using navigator.sendBeacon
28829 * mixpanel.track('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});
28830 *
28831 * To track link clicks or form submissions, see track_links() or track_forms().
28832 *
28833 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
28834 * @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.
28835 * @param {Object} [options] Optional configuration for this track request.
28836 * @param {String} [options.transport] Transport method for network request ('xhr' or 'sendBeacon').
28837 * @param {Boolean} [options.send_immediately] Whether to bypass batching/queueing and send track request immediately.
28838 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
28839 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
28840 * with the tracking payload sent to the API server is returned; otherwise false.
28841 */
28842 MixpanelLib.prototype.track = addOptOutCheckMixpanelLib(function(event_name, properties, options, callback) {
28843 if (!callback && typeof options === 'function') {
28844 callback = options;
28845 options = null;
28846 }
28847 options = options || {};
28848 var transport = options['transport']; // external API, don't minify 'transport' prop
28849 if (transport) {
28850 options.transport = transport; // 'transport' prop name can be minified internally
28851 }
28852 var should_send_immediately = options['send_immediately'];
28853 if (typeof callback !== 'function') {
28854 callback = NOOP_FUNC;
28855 }
28856
28857 if (_.isUndefined(event_name)) {
28858 this.report_error('No event name provided to mixpanel.track');
28859 return;
28860 }
28861
28862 if (this._event_is_disabled(event_name)) {
28863 callback(0);
28864 return;
28865 }
28866
28867 // set defaults
28868 properties = _.extend({}, properties);
28869 properties['token'] = this.get_config('token');
28870
28871 // set $duration if time_event was previously called for this event
28872 var start_timestamp = this['persistence'].remove_event_timer(event_name);
28873 if (!_.isUndefined(start_timestamp)) {
28874 var duration_in_ms = new Date().getTime() - start_timestamp;
28875 properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));
28876 }
28877
28878 this._set_default_superprops();
28879
28880 var marketing_properties = this.get_config('track_marketing')
28881 ? _.info.marketingParams()
28882 : {};
28883
28884 // note: extend writes to the first object, so lets make sure we
28885 // don't write to the persistence properties object and info
28886 // properties object by passing in a new object
28887
28888 // update properties with pageview info and super-properties
28889 properties = _.extend(
28890 {},
28891 _.info.properties({'mp_loader': this.get_config('mp_loader')}),
28892 marketing_properties,
28893 this['persistence'].properties(),
28894 this.unpersisted_superprops,
28895 this.get_session_recording_properties(),
28896 properties
28897 );
28898
28899 var property_blacklist = this.get_config('property_blacklist');
28900 if (_.isArray(property_blacklist)) {
28901 _.each(property_blacklist, function(blacklisted_prop) {
28902 delete properties[blacklisted_prop];
28903 });
28904 } else {
28905 this.report_error('Invalid value for property_blacklist config: ' + property_blacklist);
28906 }
28907
28908 var data = {
28909 'event': event_name,
28910 'properties': properties
28911 };
28912 var ret = this._track_or_batch({
28913 type: 'events',
28914 data: data,
28915 endpoint: this.get_api_host('events') + '/' + this.get_config('api_routes')['track'],
28916 batcher: this.request_batchers.events,
28917 should_send_immediately: should_send_immediately,
28918 send_request_options: options
28919 }, callback);
28920
28921 return ret;
28922 });
28923
28924 /**
28925 * Register the current user into one/many groups.
28926 *
28927 * ### Usage:
28928 *
28929 * mixpanel.set_group('company', ['mixpanel', 'google']) // an array of IDs
28930 * mixpanel.set_group('company', 'mixpanel')
28931 * mixpanel.set_group('company', 128746312)
28932 *
28933 * @param {String} group_key Group key
28934 * @param {Array|String|Number} group_ids An array of group IDs, or a singular group ID
28935 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
28936 *
28937 */
28938 MixpanelLib.prototype.set_group = addOptOutCheckMixpanelLib(function(group_key, group_ids, callback) {
28939 if (!_.isArray(group_ids)) {
28940 group_ids = [group_ids];
28941 }
28942 var prop = {};
28943 prop[group_key] = group_ids;
28944 this.register(prop);
28945 return this['people'].set(group_key, group_ids, callback);
28946 });
28947
28948 /**
28949 * Add a new group for this user.
28950 *
28951 * ### Usage:
28952 *
28953 * mixpanel.add_group('company', 'mixpanel')
28954 *
28955 * @param {String} group_key Group key
28956 * @param {*} group_id A valid Mixpanel property type
28957 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
28958 */
28959 MixpanelLib.prototype.add_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
28960 var old_values = this.get_property(group_key);
28961 var prop = {};
28962 if (old_values === undefined) {
28963 prop[group_key] = [group_id];
28964 this.register(prop);
28965 } else {
28966 if (old_values.indexOf(group_id) === -1) {
28967 old_values.push(group_id);
28968 prop[group_key] = old_values;
28969 this.register(prop);
28970 }
28971 }
28972 return this['people'].union(group_key, group_id, callback);
28973 });
28974
28975 /**
28976 * Remove a group from this user.
28977 *
28978 * ### Usage:
28979 *
28980 * mixpanel.remove_group('company', 'mixpanel')
28981 *
28982 * @param {String} group_key Group key
28983 * @param {*} group_id A valid Mixpanel property type
28984 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
28985 */
28986 MixpanelLib.prototype.remove_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
28987 var old_value = this.get_property(group_key);
28988 // if the value doesn't exist, the persistent store is unchanged
28989 if (old_value !== undefined) {
28990 var idx = old_value.indexOf(group_id);
28991 if (idx > -1) {
28992 old_value.splice(idx, 1);
28993 this.register({group_key: old_value});
28994 }
28995 if (old_value.length === 0) {
28996 this.unregister(group_key);
28997 }
28998 }
28999 return this['people'].remove(group_key, group_id, callback);
29000 });
29001
29002 /**
29003 * Track an event with specific groups.
29004 *
29005 * ### Usage:
29006 *
29007 * mixpanel.track_with_groups('purchase', {'product': 'iphone'}, {'University': ['UCB', 'UCLA']})
29008 *
29009 * @param {String} event_name The name of the event (see `mixpanel.track()`)
29010 * @param {Object=} properties A set of properties to include with the event you're sending (see `mixpanel.track()`)
29011 * @param {Object=} groups An object mapping group name keys to one or more values
29012 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29013 */
29014 MixpanelLib.prototype.track_with_groups = addOptOutCheckMixpanelLib(function(event_name, properties, groups, callback) {
29015 var tracking_props = _.extend({}, properties || {});
29016 _.each(groups, function(v, k) {
29017 if (v !== null && v !== undefined) {
29018 tracking_props[k] = v;
29019 }
29020 });
29021 return this.track(event_name, tracking_props, callback);
29022 });
29023
29024 MixpanelLib.prototype._create_map_key = function (group_key, group_id) {
29025 return group_key + '_' + JSON.stringify(group_id);
29026 };
29027
29028 MixpanelLib.prototype._remove_group_from_cache = function (group_key, group_id) {
29029 delete this._cached_groups[this._create_map_key(group_key, group_id)];
29030 };
29031
29032 /**
29033 * Look up reference to a Mixpanel group
29034 *
29035 * ### Usage:
29036 *
29037 * mixpanel.get_group(group_key, group_id)
29038 *
29039 * @param {String} group_key Group key
29040 * @param {Object} group_id A valid Mixpanel property type
29041 * @returns {Object} A MixpanelGroup identifier
29042 */
29043 MixpanelLib.prototype.get_group = function (group_key, group_id) {
29044 var map_key = this._create_map_key(group_key, group_id);
29045 var group = this._cached_groups[map_key];
29046 if (group === undefined || group._group_key !== group_key || group._group_id !== group_id) {
29047 group = new MixpanelGroup();
29048 group._init(this, group_key, group_id);
29049 this._cached_groups[map_key] = group;
29050 }
29051 return group;
29052 };
29053
29054 /**
29055 * Track a default Mixpanel page view event, which includes extra default event properties to
29056 * improve page view data.
29057 *
29058 * ### Usage:
29059 *
29060 * // track a default $mp_web_page_view event
29061 * mixpanel.track_pageview();
29062 *
29063 * // track a page view event with additional event properties
29064 * mixpanel.track_pageview({'ab_test_variant': 'card-layout-b'});
29065 *
29066 * // example approach to track page views on different page types as event properties
29067 * mixpanel.track_pageview({'page': 'pricing'});
29068 * mixpanel.track_pageview({'page': 'homepage'});
29069 *
29070 * // UNCOMMON: Tracking a page view event with a custom event_name option. NOT expected to be used for
29071 * // individual pages on the same site or product. Use cases for custom event_name may be page
29072 * // views on different products or internal applications that are considered completely separate
29073 * mixpanel.track_pageview({'page': 'customer-search'}, {'event_name': '[internal] Admin Page View'});
29074 *
29075 * ### Notes:
29076 *
29077 * The `config.track_pageview` option for <a href="#mixpanelinit">mixpanel.init()</a>
29078 * may be turned on for tracking page loads automatically.
29079 *
29080 * // track only page loads
29081 * mixpanel.init(PROJECT_TOKEN, {track_pageview: true});
29082 *
29083 * // track when the URL changes in any manner
29084 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'full-url'});
29085 *
29086 * // track when the URL changes, ignoring any changes in the hash part
29087 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path-and-query-string'});
29088 *
29089 * // track when the path changes, ignoring any query parameter or hash changes
29090 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path'});
29091 *
29092 * @param {Object} [properties] An optional set of additional properties to send with the page view event
29093 * @param {Object} [options] Page view tracking options
29094 * @param {String} [options.event_name] - Alternate name for the tracking event
29095 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
29096 * with the tracking payload sent to the API server is returned; otherwise false.
29097 */
29098 MixpanelLib.prototype.track_pageview = addOptOutCheckMixpanelLib(function(properties, options) {
29099 if (typeof properties !== 'object') {
29100 properties = {};
29101 }
29102 options = options || {};
29103 var event_name = options['event_name'] || '$mp_web_page_view';
29104
29105 var default_page_properties = _.extend(
29106 _.info.mpPageViewProperties(),
29107 _.info.campaignParams(),
29108 _.info.clickParams()
29109 );
29110
29111 var event_properties = _.extend(
29112 {},
29113 default_page_properties,
29114 properties
29115 );
29116
29117 return this.track(event_name, event_properties);
29118 });
29119
29120 /**
29121 * Track clicks on a set of document elements. Selector must be a
29122 * valid query. Elements must exist on the page at the time track_links is called.
29123 *
29124 * ### Usage:
29125 *
29126 * // track click for link id #nav
29127 * mixpanel.track_links('#nav', 'Clicked Nav Link');
29128 *
29129 * ### Notes:
29130 *
29131 * This function will wait up to 300 ms for the Mixpanel
29132 * servers to respond. If they have not responded by that time
29133 * it will head to the link without ensuring that your event
29134 * has been tracked. To configure this timeout please see the
29135 * set_config() documentation below.
29136 *
29137 * If you pass a function in as the properties argument, the
29138 * function will receive the DOMElement that triggered the
29139 * event as an argument. You are expected to return an object
29140 * from the function; any properties defined on this object
29141 * will be sent to mixpanel as event properties.
29142 *
29143 * @type {Function}
29144 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
29145 * @param {String} event_name The name of the event to track
29146 * @param {Object|Function} [properties] A properties object or function that returns a dictionary of properties when passed a DOMElement
29147 */
29148 MixpanelLib.prototype.track_links = function() {
29149 return this._track_dom.call(this, LinkTracker, arguments);
29150 };
29151
29152 /**
29153 * Track form submissions. Selector must be a valid query.
29154 *
29155 * ### Usage:
29156 *
29157 * // track submission for form id 'register'
29158 * mixpanel.track_forms('#register', 'Created Account');
29159 *
29160 * ### Notes:
29161 *
29162 * This function will wait up to 300 ms for the mixpanel
29163 * servers to respond, if they have not responded by that time
29164 * it will head to the link without ensuring that your event
29165 * has been tracked. To configure this timeout please see the
29166 * set_config() documentation below.
29167 *
29168 * If you pass a function in as the properties argument, the
29169 * function will receive the DOMElement that triggered the
29170 * event as an argument. You are expected to return an object
29171 * from the function; any properties defined on this object
29172 * will be sent to mixpanel as event properties.
29173 *
29174 * @type {Function}
29175 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
29176 * @param {String} event_name The name of the event to track
29177 * @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
29178 */
29179 MixpanelLib.prototype.track_forms = function() {
29180 return this._track_dom.call(this, FormTracker, arguments);
29181 };
29182
29183 /**
29184 * Time an event by including the time between this call and a
29185 * later 'track' call for the same event in the properties sent
29186 * with the event.
29187 *
29188 * ### Usage:
29189 *
29190 * // time an event named 'Registered'
29191 * mixpanel.time_event('Registered');
29192 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
29193 *
29194 * When called for a particular event name, the next track call for that event
29195 * name will include the elapsed time between the 'time_event' and 'track'
29196 * calls. This value is stored as seconds in the '$duration' property.
29197 *
29198 * @param {String} event_name The name of the event.
29199 */
29200 MixpanelLib.prototype.time_event = function(event_name) {
29201 if (_.isUndefined(event_name)) {
29202 this.report_error('No event name provided to mixpanel.time_event');
29203 return;
29204 }
29205
29206 if (this._event_is_disabled(event_name)) {
29207 return;
29208 }
29209
29210 this['persistence'].set_event_timer(event_name, new Date().getTime());
29211 };
29212
29213 var REGISTER_DEFAULTS = {
29214 'persistent': true
29215 };
29216 /**
29217 * Helper to parse options param for register methods, maintaining
29218 * legacy support for plain "days" param instead of options object
29219 * @param {Number|Object} [days_or_options] 'days' option (Number), or Options object for register methods
29220 * @returns {Object} options object
29221 */
29222 var options_for_register = function(days_or_options) {
29223 var options;
29224 if (_.isObject(days_or_options)) {
29225 options = days_or_options;
29226 } else if (!_.isUndefined(days_or_options)) {
29227 options = {'days': days_or_options};
29228 } else {
29229 options = {};
29230 }
29231 return _.extend({}, REGISTER_DEFAULTS, options);
29232 };
29233
29234 /**
29235 * Register a set of super properties, which are included with all
29236 * events. This will overwrite previous super property values.
29237 *
29238 * ### Usage:
29239 *
29240 * // register 'Gender' as a super property
29241 * mixpanel.register({'Gender': 'Female'});
29242 *
29243 * // register several super properties when a user signs up
29244 * mixpanel.register({
29245 * 'Email': 'jdoe@example.com',
29246 * 'Account Type': 'Free'
29247 * });
29248 *
29249 * // register only for the current pageload
29250 * mixpanel.register({'Name': 'Pat'}, {persistent: false});
29251 *
29252 * @param {Object} properties An associative array of properties to store about the user
29253 * @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)
29254 * @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)
29255 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
29256 */
29257 MixpanelLib.prototype.register = function(props, days_or_options) {
29258 var options = options_for_register(days_or_options);
29259 if (options['persistent']) {
29260 this['persistence'].register(props, options['days']);
29261 } else {
29262 _.extend(this.unpersisted_superprops, props);
29263 }
29264 };
29265
29266 /**
29267 * Register a set of super properties only once. This will not
29268 * overwrite previous super property values, unlike register().
29269 *
29270 * ### Usage:
29271 *
29272 * // register a super property for the first time only
29273 * mixpanel.register_once({
29274 * 'First Login Date': new Date().toISOString()
29275 * });
29276 *
29277 * // register once, only for the current pageload
29278 * mixpanel.register_once({
29279 * 'First interaction time': new Date().toISOString()
29280 * }, 'None', {persistent: false});
29281 *
29282 * ### Notes:
29283 *
29284 * If default_value is specified, current super properties
29285 * with that value will be overwritten.
29286 *
29287 * @param {Object} properties An associative array of properties to store about the user
29288 * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'
29289 * @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)
29290 * @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)
29291 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
29292 */
29293 MixpanelLib.prototype.register_once = function(props, default_value, days_or_options) {
29294 var options = options_for_register(days_or_options);
29295 if (options['persistent']) {
29296 this['persistence'].register_once(props, default_value, options['days']);
29297 } else {
29298 if (typeof(default_value) === 'undefined') {
29299 default_value = 'None';
29300 }
29301 _.each(props, function(val, prop) {
29302 if (!this.unpersisted_superprops.hasOwnProperty(prop) || this.unpersisted_superprops[prop] === default_value) {
29303 this.unpersisted_superprops[prop] = val;
29304 }
29305 }, this);
29306 }
29307 };
29308
29309 /**
29310 * Delete a super property stored with the current user.
29311 *
29312 * @param {String} property The name of the super property to remove
29313 * @param {Object} [options]
29314 * @param {boolean} [options.persistent=true] - whether to look in persistent storage (cookie/localStorage)
29315 */
29316 MixpanelLib.prototype.unregister = function(property, options) {
29317 options = options_for_register(options);
29318 if (options['persistent']) {
29319 this['persistence'].unregister(property);
29320 } else {
29321 delete this.unpersisted_superprops[property];
29322 }
29323 };
29324
29325 MixpanelLib.prototype._register_single = function(prop, value) {
29326 var props = {};
29327 props[prop] = value;
29328 this.register(props);
29329 };
29330
29331 /**
29332 * Identify a user with a unique ID to track user activity across
29333 * devices, tie a user to their events, and create a user profile.
29334 * If you never call this method, unique visitors are tracked using
29335 * a UUID generated the first time they visit the site.
29336 *
29337 * Call identify when you know the identity of the current user,
29338 * typically after login or signup. We recommend against using
29339 * identify for anonymous visitors to your site.
29340 *
29341 * ### Notes:
29342 * If your project has
29343 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
29344 * enabled, the identify method will connect pre- and
29345 * post-authentication events when appropriate.
29346 *
29347 * If your project does not have ID Merge enabled, identify will
29348 * change the user's local distinct_id to the unique ID you pass.
29349 * Events tracked prior to authentication will not be connected
29350 * to the same user identity. If ID Merge is disabled, alias can
29351 * be used to connect pre- and post-registration events.
29352 *
29353 * @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.
29354 */
29355 MixpanelLib.prototype.identify = function(
29356 new_distinct_id, _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback
29357 ) {
29358 // Optional Parameters
29359 // _set_callback:function A callback to be run if and when the People set queue is flushed
29360 // _add_callback:function A callback to be run if and when the People add queue is flushed
29361 // _append_callback:function A callback to be run if and when the People append queue is flushed
29362 // _set_once_callback:function A callback to be run if and when the People set_once queue is flushed
29363 // _union_callback:function A callback to be run if and when the People union queue is flushed
29364 // _unset_callback:function A callback to be run if and when the People unset queue is flushed
29365
29366 var previous_distinct_id = this.get_distinct_id();
29367 if (new_distinct_id && previous_distinct_id !== new_distinct_id) {
29368 // we allow the following condition if previous distinct_id is same as new_distinct_id
29369 // so that you can force flush people updates for anonymous profiles.
29370 if (typeof new_distinct_id === 'string' && new_distinct_id.indexOf(DEVICE_ID_PREFIX) === 0) {
29371 this.report_error('distinct_id cannot have $device: prefix');
29372 return -1;
29373 }
29374 this.register({'$user_id': new_distinct_id});
29375 }
29376
29377 if (!this.get_property('$device_id')) {
29378 // The persisted distinct id might not actually be a device id at all
29379 // it might be a distinct id of the user from before
29380 var device_id = previous_distinct_id;
29381 this.register_once({
29382 '$had_persisted_distinct_id': true,
29383 '$device_id': device_id
29384 }, '');
29385 }
29386
29387 // identify only changes the distinct id if it doesn't match either the existing or the alias;
29388 // if it's new, blow away the alias as well.
29389 if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {
29390 this.unregister(ALIAS_ID_KEY);
29391 this.register({'distinct_id': new_distinct_id});
29392 }
29393 this._flags.identify_called = true;
29394 // Flush any queued up people requests
29395 this['people']._flush(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback);
29396
29397 // send an $identify event any time the distinct_id is changing - logic on the server
29398 // will determine whether or not to do anything with it.
29399 if (new_distinct_id !== previous_distinct_id) {
29400 this.track('$identify', {
29401 'distinct_id': new_distinct_id,
29402 '$anon_distinct_id': previous_distinct_id
29403 }, {skip_hooks: true});
29404 }
29405
29406 // check feature flags again if distinct id has changed
29407 if (new_distinct_id !== previous_distinct_id) {
29408 this.flags.fetchFlags();
29409 }
29410 };
29411
29412 /**
29413 * Clears super properties and generates a new random distinct_id for this instance.
29414 * Useful for clearing data when a user logs out.
29415 */
29416 MixpanelLib.prototype.reset = function() {
29417 this.stop_session_recording();
29418 this['persistence'].clear();
29419 this._flags.identify_called = false;
29420 var uuid = _.UUID();
29421 this.register_once({
29422 'distinct_id': DEVICE_ID_PREFIX + uuid,
29423 '$device_id': uuid
29424 }, '');
29425 this._check_and_start_session_recording();
29426 };
29427
29428 /**
29429 * Returns the current distinct id of the user. This is either the id automatically
29430 * generated by the library or the id that has been passed by a call to identify().
29431 *
29432 * ### Notes:
29433 *
29434 * get_distinct_id() can only be called after the Mixpanel library has finished loading.
29435 * init() has a loaded function available to handle this automatically. For example:
29436 *
29437 * // set distinct_id after the mixpanel library has loaded
29438 * mixpanel.init('YOUR PROJECT TOKEN', {
29439 * loaded: function(mixpanel) {
29440 * distinct_id = mixpanel.get_distinct_id();
29441 * }
29442 * });
29443 */
29444 MixpanelLib.prototype.get_distinct_id = function() {
29445 return this.get_property('distinct_id');
29446 };
29447
29448 /**
29449 * The alias method creates an alias which Mixpanel will use to
29450 * remap one id to another. Multiple aliases can point to the
29451 * same identifier.
29452 *
29453 * The following is a valid use of alias:
29454 *
29455 * mixpanel.alias('new_id', 'existing_id');
29456 * // You can add multiple id aliases to the existing ID
29457 * mixpanel.alias('newer_id', 'existing_id');
29458 *
29459 * Aliases can also be chained - the following is a valid example:
29460 *
29461 * mixpanel.alias('new_id', 'existing_id');
29462 * // chain newer_id - new_id - existing_id
29463 * mixpanel.alias('newer_id', 'new_id');
29464 *
29465 * Aliases cannot point to multiple identifiers - the following
29466 * example will not work:
29467 *
29468 * mixpanel.alias('new_id', 'existing_id');
29469 * // this is invalid as 'new_id' already points to 'existing_id'
29470 * mixpanel.alias('new_id', 'newer_id');
29471 *
29472 * ### Notes:
29473 *
29474 * If your project does not have
29475 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
29476 * enabled, the best practice is to call alias once when a unique
29477 * ID is first created for a user (e.g., when a user first registers
29478 * for an account). Do not use alias multiple times for a single
29479 * user without ID Merge enabled.
29480 *
29481 * @param {String} alias A unique identifier that you want to use for this user in the future.
29482 * @param {String} [original] The current identifier being used for this user.
29483 */
29484 MixpanelLib.prototype.alias = function(alias, original) {
29485 // If the $people_distinct_id key exists in persistence, there has been a previous
29486 // mixpanel.people.identify() call made for this user. It is VERY BAD to make an alias with
29487 // this ID, as it will duplicate users.
29488 if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {
29489 this.report_error('Attempting to create alias for existing People user - aborting.');
29490 return -2;
29491 }
29492
29493 var _this = this;
29494 if (_.isUndefined(original)) {
29495 original = this.get_distinct_id();
29496 }
29497 if (alias !== original) {
29498 this._register_single(ALIAS_ID_KEY, alias);
29499 return this.track('$create_alias', {
29500 'alias': alias,
29501 'distinct_id': original
29502 }, {
29503 skip_hooks: true
29504 }, function() {
29505 // Flush the people queue
29506 _this.identify(alias);
29507 });
29508 } else {
29509 this.report_error('alias matches current distinct_id - skipping api call.');
29510 this.identify(alias);
29511 return -1;
29512 }
29513 };
29514
29515 /**
29516 * Provide a string to recognize the user by. The string passed to
29517 * this method will appear in the Mixpanel Streams product rather
29518 * than an automatically generated name. Name tags do not have to
29519 * be unique.
29520 *
29521 * This value will only be included in Streams data.
29522 *
29523 * @param {String} name_tag A human readable name for the user
29524 * @deprecated
29525 */
29526 MixpanelLib.prototype.name_tag = function(name_tag) {
29527 this._register_single('mp_name_tag', name_tag);
29528 };
29529
29530 /**
29531 * Update the configuration of a mixpanel library instance.
29532 *
29533 * The default config is:
29534 *
29535 * {
29536 * // host for requests (customizable for e.g. a local proxy)
29537 * api_host: 'https://api-js.mixpanel.com',
29538 *
29539 * // endpoints for different types of requests
29540 * api_routes: {
29541 * track: 'track/',
29542 * engage: 'engage/',
29543 * groups: 'groups/',
29544 * }
29545 *
29546 * // HTTP method for tracking requests
29547 * api_method: 'POST'
29548 *
29549 * // transport for sending requests ('XHR' or 'sendBeacon')
29550 * // NB: sendBeacon should only be used for scenarios such as
29551 * // page unload where a "best-effort" attempt to send is
29552 * // acceptable; the sendBeacon API does not support callbacks
29553 * // or any way to know the result of the request. Mixpanel
29554 * // tracking via sendBeacon will not support any event-
29555 * // batching or retry mechanisms.
29556 * api_transport: 'XHR'
29557 *
29558 * // request-batching/queueing/retry
29559 * batch_requests: true,
29560 *
29561 * // maximum number of events/updates to send in a single
29562 * // network request
29563 * batch_size: 50,
29564 *
29565 * // milliseconds to wait between sending batch requests
29566 * batch_flush_interval_ms: 5000,
29567 *
29568 * // milliseconds to wait for network responses to batch requests
29569 * // before they are considered timed-out and retried
29570 * batch_request_timeout_ms: 90000,
29571 *
29572 * // override value for cookie domain, only useful for ensuring
29573 * // correct cross-subdomain cookies on unusual domains like
29574 * // subdomain.mainsite.avocat.fr; NB this cannot be used to
29575 * // set cookies on a different domain than the current origin
29576 * cookie_domain: ''
29577 *
29578 * // super properties cookie expiration (in days)
29579 * cookie_expiration: 365
29580 *
29581 * // if true, cookie will be set with SameSite=None; Secure
29582 * // this is only useful in special situations, like embedded
29583 * // 3rd-party iframes that set up a Mixpanel instance
29584 * cross_site_cookie: false
29585 *
29586 * // super properties span subdomains
29587 * cross_subdomain_cookie: true
29588 *
29589 * // debug mode
29590 * debug: false
29591 *
29592 * // if this is true, the mixpanel cookie or localStorage entry
29593 * // will be deleted, and no user persistence will take place
29594 * disable_persistence: false
29595 *
29596 * // if this is true, Mixpanel will automatically determine
29597 * // City, Region and Country data using the IP address of
29598 * //the client
29599 * ip: true
29600 *
29601 * // opt users out of tracking by this Mixpanel instance by default
29602 * opt_out_tracking_by_default: false
29603 *
29604 * // opt users out of browser data storage by this Mixpanel instance by default
29605 * opt_out_persistence_by_default: false
29606 *
29607 * // persistence mechanism used by opt-in/opt-out methods - cookie
29608 * // or localStorage - falls back to cookie if localStorage is unavailable
29609 * opt_out_tracking_persistence_type: 'localStorage'
29610 *
29611 * // customize the name of cookie/localStorage set by opt-in/opt-out methods
29612 * opt_out_tracking_cookie_prefix: null
29613 *
29614 * // type of persistent store for super properties (cookie/
29615 * // localStorage) if set to 'localStorage', any existing
29616 * // mixpanel cookie value with the same persistence_name
29617 * // will be transferred to localStorage and deleted
29618 * persistence: 'cookie'
29619 *
29620 * // name for super properties persistent store
29621 * persistence_name: ''
29622 *
29623 * // names of properties/superproperties which should never
29624 * // be sent with track() calls
29625 * property_blacklist: []
29626 *
29627 * // if this is true, mixpanel cookies will be marked as
29628 * // secure, meaning they will only be transmitted over https
29629 * secure_cookie: false
29630 *
29631 * // disables enriching user profiles with first touch marketing data
29632 * skip_first_touch_marketing: false
29633 *
29634 * // the amount of time track_links will
29635 * // wait for Mixpanel's servers to respond
29636 * track_links_timeout: 300
29637 *
29638 * // adds any UTM parameters and click IDs present on the page to any events fired
29639 * track_marketing: true
29640 *
29641 * // enables automatic page view tracking using default page view events through
29642 * // the track_pageview() method
29643 * track_pageview: false
29644 *
29645 * // if you set upgrade to be true, the library will check for
29646 * // a cookie from our old js library and import super
29647 * // properties from it, then the old cookie is deleted
29648 * // The upgrade config option only works in the initialization,
29649 * // so make sure you set it when you create the library.
29650 * upgrade: false
29651 *
29652 * // extra HTTP request headers to set for each API request, in
29653 * // the format {'Header-Name': value}
29654 * xhr_headers: {}
29655 *
29656 * // whether to ignore or respect the web browser's Do Not Track setting
29657 * ignore_dnt: false
29658 * }
29659 *
29660 *
29661 * @param {Object} config A dictionary of new configuration values to update
29662 */
29663 MixpanelLib.prototype.set_config = function(config) {
29664 if (_.isObject(config)) {
29665 _.extend(this['config'], config);
29666
29667 var new_batch_size = config['batch_size'];
29668 if (new_batch_size) {
29669 _.each(this.request_batchers, function(batcher) {
29670 batcher.resetBatchSize();
29671 });
29672 }
29673
29674 if (!this.get_config('persistence_name')) {
29675 this['config']['persistence_name'] = this['config']['cookie_name'];
29676 }
29677 if (!this.get_config('disable_persistence')) {
29678 this['config']['disable_persistence'] = this['config']['disable_cookie'];
29679 }
29680
29681 if (this['persistence']) {
29682 this['persistence'].update_config(this['config']);
29683 }
29684 Config.DEBUG = Config.DEBUG || this.get_config('debug');
29685
29686 if (('autocapture' in config || 'record_heatmap_data' in config) && this.autocapture) {
29687 this.autocapture.init();
29688 }
29689 }
29690 };
29691
29692 /**
29693 * returns the current config object for the library.
29694 */
29695 MixpanelLib.prototype.get_config = function(prop_name) {
29696 return this['config'][prop_name];
29697 };
29698
29699 /**
29700 * Fetch a hook function from config, with safe default, and run it
29701 * against the given arguments
29702 * @param {string} hook_name which hook to retrieve
29703 * @returns {any|null} return value of user-provided hook, or null if nothing was returned
29704 */
29705 MixpanelLib.prototype._run_hook = function(hook_name) {
29706 var ret = (this['config']['hooks'][hook_name] || IDENTITY_FUNC).apply(this, slice.call(arguments, 1));
29707 if (typeof ret === 'undefined') {
29708 this.report_error(hook_name + ' hook did not return a value');
29709 ret = null;
29710 }
29711 return ret;
29712 };
29713
29714 /**
29715 * Returns the value of the super property named property_name. If no such
29716 * property is set, get_property() will return the undefined value.
29717 *
29718 * ### Notes:
29719 *
29720 * get_property() can only be called after the Mixpanel library has finished loading.
29721 * init() has a loaded function available to handle this automatically. For example:
29722 *
29723 * // grab value for 'user_id' after the mixpanel library has loaded
29724 * mixpanel.init('YOUR PROJECT TOKEN', {
29725 * loaded: function(mixpanel) {
29726 * user_id = mixpanel.get_property('user_id');
29727 * }
29728 * });
29729 *
29730 * @param {String} property_name The name of the super property you want to retrieve
29731 */
29732 MixpanelLib.prototype.get_property = function(property_name) {
29733 return this['persistence'].load_prop([property_name]);
29734 };
29735
29736 /**
29737 * Get the API host for a specific endpoint type, falling back to the default api_host if not specified
29738 *
29739 * @param {String} endpoint_type The type of endpoint (e.g., "events", "people", "groups")
29740 * @returns {String} The API host to use for this endpoint
29741 */
29742 MixpanelLib.prototype.get_api_host = function(endpoint_type) {
29743 return this.get_config('api_hosts')[endpoint_type] || this.get_config('api_host');
29744 };
29745
29746 MixpanelLib.prototype.toString = function() {
29747 var name = this.get_config('name');
29748 if (name !== PRIMARY_INSTANCE_NAME) {
29749 name = PRIMARY_INSTANCE_NAME + '.' + name;
29750 }
29751 return name;
29752 };
29753
29754 MixpanelLib.prototype._event_is_disabled = function(event_name) {
29755 return _.isBlockedUA(userAgent) ||
29756 this._flags.disable_all_events ||
29757 _.include(this.__disabled_events, event_name);
29758 };
29759
29760 // perform some housekeeping around GDPR opt-in/out state
29761 MixpanelLib.prototype._gdpr_init = function() {
29762 var is_localStorage_requested = this.get_config('opt_out_tracking_persistence_type') === 'localStorage';
29763
29764 // try to convert opt-in/out cookies to localStorage if possible
29765 if (is_localStorage_requested && _.localStorage.is_supported()) {
29766 if (!this.has_opted_in_tracking() && this.has_opted_in_tracking({'persistence_type': 'cookie'})) {
29767 this.opt_in_tracking({'enable_persistence': false});
29768 }
29769 if (!this.has_opted_out_tracking() && this.has_opted_out_tracking({'persistence_type': 'cookie'})) {
29770 this.opt_out_tracking({'clear_persistence': false});
29771 }
29772 this.clear_opt_in_out_tracking({
29773 'persistence_type': 'cookie',
29774 'enable_persistence': false
29775 });
29776 }
29777
29778 // check whether the user has already opted out - if so, clear & disable persistence
29779 if (this.has_opted_out_tracking()) {
29780 this._gdpr_update_persistence({'clear_persistence': true});
29781
29782 // check whether we should opt out by default
29783 // note: we don't clear persistence here by default since opt-out default state is often
29784 // used as an initial state while GDPR information is being collected
29785 } else if (!this.has_opted_in_tracking() && (
29786 this.get_config('opt_out_tracking_by_default') || _.cookie.get('mp_optout')
29787 )) {
29788 _.cookie.remove('mp_optout');
29789 this.opt_out_tracking({
29790 'clear_persistence': this.get_config('opt_out_persistence_by_default')
29791 });
29792 }
29793 };
29794
29795 /**
29796 * Enable or disable persistence based on options
29797 * only enable/disable if persistence is not already in this state
29798 * @param {boolean} [options.clear_persistence] If true, will delete all data stored by the sdk in persistence and disable it
29799 * @param {boolean} [options.enable_persistence] If true, will re-enable sdk persistence
29800 */
29801 MixpanelLib.prototype._gdpr_update_persistence = function(options) {
29802 var disabled;
29803 if (options && options['clear_persistence']) {
29804 disabled = true;
29805 } else if (options && options['enable_persistence']) {
29806 disabled = false;
29807 } else {
29808 return;
29809 }
29810
29811 if (!this.get_config('disable_persistence') && this['persistence'].disabled !== disabled) {
29812 this['persistence'].set_disabled(disabled);
29813 }
29814
29815 if (disabled) {
29816 this.stop_batch_senders();
29817 this.stop_session_recording();
29818 } else {
29819 // only start batchers after opt-in if they have previously been started
29820 // in order to avoid unintentionally starting up batching for the first time
29821 if (this._batchers_were_started) {
29822 this.start_batch_senders();
29823 }
29824 }
29825 };
29826
29827 // call a base gdpr function after constructing the appropriate token and options args
29828 MixpanelLib.prototype._gdpr_call_func = function(func, options) {
29829 options = _.extend({
29830 'track': _.bind(this.track, this),
29831 'persistence_type': this.get_config('opt_out_tracking_persistence_type'),
29832 'cookie_prefix': this.get_config('opt_out_tracking_cookie_prefix'),
29833 'cookie_expiration': this.get_config('cookie_expiration'),
29834 'cross_site_cookie': this.get_config('cross_site_cookie'),
29835 'cross_subdomain_cookie': this.get_config('cross_subdomain_cookie'),
29836 'cookie_domain': this.get_config('cookie_domain'),
29837 'secure_cookie': this.get_config('secure_cookie'),
29838 'ignore_dnt': this.get_config('ignore_dnt')
29839 }, options);
29840
29841 // check if localStorage can be used for recording opt out status, fall back to cookie if not
29842 if (!_.localStorage.is_supported()) {
29843 options['persistence_type'] = 'cookie';
29844 }
29845
29846 return func(this.get_config('token'), {
29847 track: options['track'],
29848 trackEventName: options['track_event_name'],
29849 trackProperties: options['track_properties'],
29850 persistenceType: options['persistence_type'],
29851 persistencePrefix: options['cookie_prefix'],
29852 cookieDomain: options['cookie_domain'],
29853 cookieExpiration: options['cookie_expiration'],
29854 crossSiteCookie: options['cross_site_cookie'],
29855 crossSubdomainCookie: options['cross_subdomain_cookie'],
29856 secureCookie: options['secure_cookie'],
29857 ignoreDnt: options['ignore_dnt']
29858 });
29859 };
29860
29861 /**
29862 * Opt the user in to data tracking and cookies/localstorage for this Mixpanel instance
29863 *
29864 * ### Usage:
29865 *
29866 * // opt user in
29867 * mixpanel.opt_in_tracking();
29868 *
29869 * // opt user in with specific event name, properties, cookie configuration
29870 * mixpanel.opt_in_tracking({
29871 * track_event_name: 'User opted in',
29872 * track_event_properties: {
29873 * 'Email': 'jdoe@example.com'
29874 * },
29875 * cookie_expiration: 30,
29876 * secure_cookie: true
29877 * });
29878 *
29879 * @param {Object} [options] A dictionary of config options to override
29880 * @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)
29881 * @param {string} [options.track_event_name=$opt_in] Event name to be used for tracking the opt-in action
29882 * @param {Object} [options.track_properties] Set of properties to be tracked along with the opt-in action
29883 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
29884 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29885 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29886 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
29887 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
29888 * @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)
29889 * @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)
29890 * @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)
29891 */
29892 MixpanelLib.prototype.opt_in_tracking = function(options) {
29893 options = _.extend({
29894 'enable_persistence': true
29895 }, options);
29896
29897 this._gdpr_call_func(optIn, options);
29898 this._gdpr_update_persistence(options);
29899 };
29900
29901 /**
29902 * Opt the user out of data tracking and cookies/localstorage for this Mixpanel instance
29903 *
29904 * ### Usage:
29905 *
29906 * // opt user out
29907 * mixpanel.opt_out_tracking();
29908 *
29909 * // opt user out with different cookie configuration from Mixpanel instance
29910 * mixpanel.opt_out_tracking({
29911 * cookie_expiration: 30,
29912 * secure_cookie: true
29913 * });
29914 *
29915 * @param {Object} [options] A dictionary of config options to override
29916 * @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
29917 * @param {boolean} [options.clear_persistence=true] If true, will delete all data stored by the sdk in persistence
29918 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29919 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29920 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
29921 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
29922 * @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)
29923 * @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)
29924 * @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)
29925 */
29926 MixpanelLib.prototype.opt_out_tracking = function(options) {
29927 options = _.extend({
29928 'clear_persistence': true,
29929 'delete_user': true
29930 }, options);
29931
29932 // delete user and clear charges since these methods may be disabled by opt-out
29933 if (options['delete_user'] && this['people'] && this['people']._identify_called()) {
29934 this['people'].delete_user();
29935 this['people'].clear_charges();
29936 }
29937
29938 this._gdpr_call_func(optOut, options);
29939 this._gdpr_update_persistence(options);
29940 };
29941
29942 /**
29943 * Check whether the user has opted in to data tracking and cookies/localstorage for this Mixpanel instance
29944 *
29945 * ### Usage:
29946 *
29947 * var has_opted_in = mixpanel.has_opted_in_tracking();
29948 * // use has_opted_in value
29949 *
29950 * @param {Object} [options] A dictionary of config options to override
29951 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29952 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29953 * @returns {boolean} current opt-in status
29954 */
29955 MixpanelLib.prototype.has_opted_in_tracking = function(options) {
29956 return this._gdpr_call_func(hasOptedIn, options);
29957 };
29958
29959 /**
29960 * Check whether the user has opted out of data tracking and cookies/localstorage for this Mixpanel instance
29961 *
29962 * ### Usage:
29963 *
29964 * var has_opted_out = mixpanel.has_opted_out_tracking();
29965 * // use has_opted_out value
29966 *
29967 * @param {Object} [options] A dictionary of config options to override
29968 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29969 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29970 * @returns {boolean} current opt-out status
29971 */
29972 MixpanelLib.prototype.has_opted_out_tracking = function(options) {
29973 return this._gdpr_call_func(hasOptedOut, options);
29974 };
29975
29976 /**
29977 * Clear the user's opt in/out status of data tracking and cookies/localstorage for this Mixpanel instance
29978 *
29979 * ### Usage:
29980 *
29981 * // clear user's opt-in/out status
29982 * mixpanel.clear_opt_in_out_tracking();
29983 *
29984 * // clear user's opt-in/out status with specific cookie configuration - should match
29985 * // configuration used when opt_in_tracking/opt_out_tracking methods were called.
29986 * mixpanel.clear_opt_in_out_tracking({
29987 * cookie_expiration: 30,
29988 * secure_cookie: true
29989 * });
29990 *
29991 * @param {Object} [options] A dictionary of config options to override
29992 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
29993 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
29994 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
29995 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
29996 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
29997 * @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)
29998 * @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)
29999 * @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)
30000 */
30001 MixpanelLib.prototype.clear_opt_in_out_tracking = function(options) {
30002 options = _.extend({
30003 'enable_persistence': true
30004 }, options);
30005
30006 this._gdpr_call_func(clearOptInOut, options);
30007 this._gdpr_update_persistence(options);
30008 };
30009
30010 MixpanelLib.prototype.report_error = function(msg, err) {
30011 console$1.error.apply(console$1.error, arguments);
30012 try {
30013 if (!err && !(msg instanceof Error)) {
30014 msg = new Error(msg);
30015 }
30016 this.get_config('error_reporter')(msg, err);
30017 } catch(err) {
30018 console$1.error(err);
30019 }
30020 };
30021
30022 // EXPORTS (for closure compiler)
30023
30024 // MixpanelLib Exports
30025 MixpanelLib.prototype['init'] = MixpanelLib.prototype.init;
30026 MixpanelLib.prototype['reset'] = MixpanelLib.prototype.reset;
30027 MixpanelLib.prototype['disable'] = MixpanelLib.prototype.disable;
30028 MixpanelLib.prototype['time_event'] = MixpanelLib.prototype.time_event;
30029 MixpanelLib.prototype['track'] = MixpanelLib.prototype.track;
30030 MixpanelLib.prototype['track_links'] = MixpanelLib.prototype.track_links;
30031 MixpanelLib.prototype['track_forms'] = MixpanelLib.prototype.track_forms;
30032 MixpanelLib.prototype['track_pageview'] = MixpanelLib.prototype.track_pageview;
30033 MixpanelLib.prototype['register'] = MixpanelLib.prototype.register;
30034 MixpanelLib.prototype['register_once'] = MixpanelLib.prototype.register_once;
30035 MixpanelLib.prototype['unregister'] = MixpanelLib.prototype.unregister;
30036 MixpanelLib.prototype['identify'] = MixpanelLib.prototype.identify;
30037 MixpanelLib.prototype['alias'] = MixpanelLib.prototype.alias;
30038 MixpanelLib.prototype['name_tag'] = MixpanelLib.prototype.name_tag;
30039 MixpanelLib.prototype['set_config'] = MixpanelLib.prototype.set_config;
30040 MixpanelLib.prototype['get_config'] = MixpanelLib.prototype.get_config;
30041 MixpanelLib.prototype['get_api_host'] = MixpanelLib.prototype.get_api_host;
30042 MixpanelLib.prototype['get_property'] = MixpanelLib.prototype.get_property;
30043 MixpanelLib.prototype['get_distinct_id'] = MixpanelLib.prototype.get_distinct_id;
30044 MixpanelLib.prototype['toString'] = MixpanelLib.prototype.toString;
30045 MixpanelLib.prototype['opt_out_tracking'] = MixpanelLib.prototype.opt_out_tracking;
30046 MixpanelLib.prototype['opt_in_tracking'] = MixpanelLib.prototype.opt_in_tracking;
30047 MixpanelLib.prototype['has_opted_out_tracking'] = MixpanelLib.prototype.has_opted_out_tracking;
30048 MixpanelLib.prototype['has_opted_in_tracking'] = MixpanelLib.prototype.has_opted_in_tracking;
30049 MixpanelLib.prototype['clear_opt_in_out_tracking'] = MixpanelLib.prototype.clear_opt_in_out_tracking;
30050 MixpanelLib.prototype['get_group'] = MixpanelLib.prototype.get_group;
30051 MixpanelLib.prototype['set_group'] = MixpanelLib.prototype.set_group;
30052 MixpanelLib.prototype['add_group'] = MixpanelLib.prototype.add_group;
30053 MixpanelLib.prototype['remove_group'] = MixpanelLib.prototype.remove_group;
30054 MixpanelLib.prototype['track_with_groups'] = MixpanelLib.prototype.track_with_groups;
30055 MixpanelLib.prototype['start_batch_senders'] = MixpanelLib.prototype.start_batch_senders;
30056 MixpanelLib.prototype['stop_batch_senders'] = MixpanelLib.prototype.stop_batch_senders;
30057 MixpanelLib.prototype['start_session_recording'] = MixpanelLib.prototype.start_session_recording;
30058 MixpanelLib.prototype['stop_session_recording'] = MixpanelLib.prototype.stop_session_recording;
30059 MixpanelLib.prototype['pause_session_recording'] = MixpanelLib.prototype.pause_session_recording;
30060 MixpanelLib.prototype['resume_session_recording'] = MixpanelLib.prototype.resume_session_recording;
30061 MixpanelLib.prototype['get_session_recording_properties'] = MixpanelLib.prototype.get_session_recording_properties;
30062 MixpanelLib.prototype['get_session_replay_url'] = MixpanelLib.prototype.get_session_replay_url;
30063 MixpanelLib.prototype['get_tab_id'] = MixpanelLib.prototype.get_tab_id;
30064 MixpanelLib.prototype['DEFAULT_API_ROUTES'] = DEFAULT_API_ROUTES;
30065
30066 // Exports intended only for testing
30067 MixpanelLib.prototype['__get_recorder'] = MixpanelLib.prototype.__get_recorder;
30068
30069 // MixpanelPersistence Exports
30070 MixpanelPersistence.prototype['properties'] = MixpanelPersistence.prototype.properties;
30071 MixpanelPersistence.prototype['update_search_keyword'] = MixpanelPersistence.prototype.update_search_keyword;
30072 MixpanelPersistence.prototype['update_referrer_info'] = MixpanelPersistence.prototype.update_referrer_info;
30073 MixpanelPersistence.prototype['get_cross_subdomain'] = MixpanelPersistence.prototype.get_cross_subdomain;
30074 MixpanelPersistence.prototype['clear'] = MixpanelPersistence.prototype.clear;
30075
30076
30077 var instances = {};
30078 var extend_mp = function() {
30079 // add all the sub mixpanel instances
30080 _.each(instances, function(instance, name) {
30081 if (name !== PRIMARY_INSTANCE_NAME) { mixpanel_master[name] = instance; }
30082 });
30083
30084 // add private functions as _
30085 mixpanel_master['_'] = _;
30086 };
30087
30088 var override_mp_init_func = function() {
30089 // we override the snippets init function to handle the case where a
30090 // user initializes the mixpanel library after the script loads & runs
30091 mixpanel_master['init'] = function(token, config, name) {
30092 if (name) {
30093 // initialize a sub library
30094 if (!mixpanel_master[name]) {
30095 mixpanel_master[name] = instances[name] = create_mplib(token, config, name);
30096 mixpanel_master[name]._loaded();
30097 }
30098 return mixpanel_master[name];
30099 } else {
30100 var instance = mixpanel_master;
30101
30102 if (instances[PRIMARY_INSTANCE_NAME]) {
30103 // main mixpanel lib already initialized
30104 instance = instances[PRIMARY_INSTANCE_NAME];
30105 } else if (token) {
30106 // intialize the main mixpanel lib
30107 instance = create_mplib(token, config, PRIMARY_INSTANCE_NAME);
30108 instance._loaded();
30109 instances[PRIMARY_INSTANCE_NAME] = instance;
30110 }
30111
30112 mixpanel_master = instance;
30113 if (init_type === INIT_SNIPPET) {
30114 win[PRIMARY_INSTANCE_NAME] = mixpanel_master;
30115 }
30116 extend_mp();
30117 }
30118 };
30119 };
30120
30121 var add_dom_loaded_handler = function() {
30122 // Cross browser DOM Loaded support
30123 function dom_loaded_handler() {
30124 // function flag since we only want to execute this once
30125 if (dom_loaded_handler.done) { return; }
30126 dom_loaded_handler.done = true;
30127
30128 DOM_LOADED = true;
30129 ENQUEUE_REQUESTS = false;
30130
30131 _.each(instances, function(inst) {
30132 inst._dom_loaded();
30133 });
30134 }
30135
30136 function do_scroll_check() {
30137 try {
30138 document$1.documentElement.doScroll('left');
30139 } catch(e) {
30140 setTimeout(do_scroll_check, 1);
30141 return;
30142 }
30143
30144 dom_loaded_handler();
30145 }
30146
30147 if (document$1.addEventListener) {
30148 if (document$1.readyState === 'complete') {
30149 // safari 4 can fire the DOMContentLoaded event before loading all
30150 // external JS (including this file). you will see some copypasta
30151 // on the internet that checks for 'complete' and 'loaded', but
30152 // 'loaded' is an IE thing
30153 dom_loaded_handler();
30154 } else {
30155 document$1.addEventListener('DOMContentLoaded', dom_loaded_handler, false);
30156 }
30157 } else if (document$1.attachEvent) {
30158 // IE
30159 document$1.attachEvent('onreadystatechange', dom_loaded_handler);
30160
30161 // check to make sure we arn't in a frame
30162 var toplevel = false;
30163 try {
30164 toplevel = win.frameElement === null;
30165 } catch(e) {
30166 // noop
30167 }
30168
30169 if (document$1.documentElement.doScroll && toplevel) {
30170 do_scroll_check();
30171 }
30172 }
30173
30174 // fallback handler, always will work
30175 _.register_event(win, 'load', dom_loaded_handler, true);
30176 };
30177
30178 function init_as_module(bundle_loader) {
30179 load_extra_bundle = bundle_loader;
30180 init_type = INIT_MODULE;
30181 mixpanel_master = new MixpanelLib();
30182
30183 override_mp_init_func();
30184 mixpanel_master['init']();
30185 add_dom_loaded_handler();
30186
30187 return mixpanel_master;
30188 }
30189
30190 // For loading separate bundles asynchronously via script tag
30191 // so that we don't load them until they are needed at runtime.
30192
30193 // For builds that have everything in one bundle, no extra work.
30194 function loadNoop (_src, onload) {
30195 onload();
30196 }
30197
30198 /* eslint camelcase: "off" */
30199
30200 var mixpanel = init_as_module(loadNoop);
30201
30202
30203
30204
30205 /***/ }),
30206
30207 /***/ "@reduxjs/toolkit":
30208 /*!************************************************!*\
30209 !*** external "elementorVendors.reduxToolkit" ***!
30210 \************************************************/
30211 /***/ ((module) => {
30212
30213 "use strict";
30214 module.exports = elementorVendors.reduxToolkit;
30215
30216 /***/ }),
30217
30218 /***/ "@wordpress/i18n":
30219 /*!**************************!*\
30220 !*** external "wp.i18n" ***!
30221 \**************************/
30222 /***/ ((module) => {
30223
30224 "use strict";
30225 module.exports = wp.i18n;
30226
30227 /***/ })
30228
30229 /******/ });
30230 /************************************************************************/
30231 /******/ // The module cache
30232 /******/ var __webpack_module_cache__ = {};
30233 /******/
30234 /******/ // The require function
30235 /******/ function __webpack_require__(moduleId) {
30236 /******/ // Check if module is in cache
30237 /******/ var cachedModule = __webpack_module_cache__[moduleId];
30238 /******/ if (cachedModule !== undefined) {
30239 /******/ return cachedModule.exports;
30240 /******/ }
30241 /******/ // Create a new module (and put it into the cache)
30242 /******/ var module = __webpack_module_cache__[moduleId] = {
30243 /******/ // no module.id needed
30244 /******/ // no module.loaded needed
30245 /******/ exports: {}
30246 /******/ };
30247 /******/
30248 /******/ // Execute the module function
30249 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
30250 /******/
30251 /******/ // Return the exports of the module
30252 /******/ return module.exports;
30253 /******/ }
30254 /******/
30255 /************************************************************************/
30256 /******/ /* webpack/runtime/define property getters */
30257 /******/ (() => {
30258 /******/ // define getter functions for harmony exports
30259 /******/ __webpack_require__.d = (exports, definition) => {
30260 /******/ for(var key in definition) {
30261 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
30262 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
30263 /******/ }
30264 /******/ }
30265 /******/ };
30266 /******/ })();
30267 /******/
30268 /******/ /* webpack/runtime/hasOwnProperty shorthand */
30269 /******/ (() => {
30270 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
30271 /******/ })();
30272 /******/
30273 /******/ /* webpack/runtime/make namespace object */
30274 /******/ (() => {
30275 /******/ // define __esModule on exports
30276 /******/ __webpack_require__.r = (exports) => {
30277 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
30278 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
30279 /******/ }
30280 /******/ Object.defineProperty(exports, '__esModule', { value: true });
30281 /******/ };
30282 /******/ })();
30283 /******/
30284 /************************************************************************/
30285 var __webpack_exports__ = {};
30286 // This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
30287 (() => {
30288 "use strict";
30289 /*!******************************************!*\
30290 !*** ../core/common/assets/js/common.js ***!
30291 \******************************************/
30292
30293
30294 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
30295 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
30296 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
30297 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
30298 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
30299 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
30300 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
30301 var _helpers = _interopRequireDefault(__webpack_require__(/*! ./utils/helpers */ "../core/common/assets/js/utils/helpers.js"));
30302 var _storage = _interopRequireDefault(__webpack_require__(/*! ./utils/storage */ "../core/common/assets/js/utils/storage.js"));
30303 var _debug = _interopRequireDefault(__webpack_require__(/*! ./utils/debug */ "../core/common/assets/js/utils/debug.js"));
30304 var _ajax = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/ajax/assets/js/ajax */ "../core/common/modules/ajax/assets/js/ajax.js"));
30305 var _finder = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/finder/assets/js/finder */ "../core/common/modules/finder/assets/js/finder.js"));
30306 var _connect = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/connect/assets/js/connect */ "../core/common/modules/connect/assets/js/connect.js"));
30307 var _component = _interopRequireDefault(__webpack_require__(/*! ./components/wordpress/component */ "../core/common/assets/js/components/wordpress/component.js"));
30308 var _component2 = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/event-tracker/assets/js/data/component */ "../core/common/modules/event-tracker/assets/js/data/component.js"));
30309 var _events = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/event-tracker/assets/js/events */ "../core/common/modules/event-tracker/assets/js/events.js"));
30310 var _module = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/events-manager/assets/js/module */ "../core/common/modules/events-manager/assets/js/module.js"));
30311 var _notifications = _interopRequireDefault(__webpack_require__(/*! elementor-utils/notifications */ "../assets/dev/js/utils/notifications.js"));
30312 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)); }
30313 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
30314 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; }
30315 var ElementorCommonApp = /*#__PURE__*/function (_elementorModules$Vie) {
30316 function ElementorCommonApp() {
30317 (0, _classCallCheck2.default)(this, ElementorCommonApp);
30318 return _callSuper(this, ElementorCommonApp, arguments);
30319 }
30320 (0, _inherits2.default)(ElementorCommonApp, _elementorModules$Vie);
30321 return (0, _createClass2.default)(ElementorCommonApp, [{
30322 key: "setMarionetteTemplateCompiler",
30323 value: function setMarionetteTemplateCompiler() {
30324 Marionette.TemplateCache.prototype.compileTemplate = function (rawTemplate, options) {
30325 options = {
30326 evaluate: /<#([\s\S]+?)#>/g,
30327 interpolate: /{{{([\s\S]+?)}}}/g,
30328 escape: /{{([^}]+?)}}(?!})/g
30329 };
30330 return _.template(rawTemplate, options);
30331 };
30332 }
30333 }, {
30334 key: "getDefaultElements",
30335 value: function getDefaultElements() {
30336 return {
30337 $window: jQuery(window),
30338 $document: jQuery(document),
30339 $body: jQuery(document.body)
30340 };
30341 }
30342 }, {
30343 key: "initComponents",
30344 value: function initComponents() {
30345 this.events = new _events.default();
30346 this.eventsManager = new _module.default();
30347 this.debug = new _debug.default();
30348 this.helpers = new _helpers.default();
30349 this.storage = new _storage.default();
30350 this.dialogsManager = new DialogsManager.Instance();
30351 this.notifications = new _notifications.default();
30352 this.api = window.$e;
30353 $e.components.register(new _component2.default());
30354 elementorCommon.elements.$window.on('elementor:init-components', function () {
30355 $e.components.register(new _component.default());
30356 });
30357 this.initModules();
30358 }
30359 }, {
30360 key: "initModules",
30361 value: function initModules() {
30362 var _this = this;
30363 var activeModules = this.config.activeModules;
30364 var modules = {
30365 ajax: _ajax.default,
30366 finder: _finder.default,
30367 connect: _connect.default
30368 };
30369 activeModules.forEach(function (name) {
30370 if (modules[name]) {
30371 _this[name] = new modules[name](_this.config[name]);
30372 }
30373 });
30374 }
30375 }, {
30376 key: "compileArrayTemplateArgs",
30377 value: function compileArrayTemplateArgs(template, templateArgs) {
30378 return template.replace(/%(?:(\d+)\$)?s/g, function (match, number) {
30379 if (!number) {
30380 number = 1;
30381 }
30382 number--;
30383 return undefined !== templateArgs[number] ? templateArgs[number] : match;
30384 });
30385 }
30386 }, {
30387 key: "compileObjectTemplateArgs",
30388 value: function compileObjectTemplateArgs(template, templateArgs) {
30389 return template.replace(/{{(?:([ \w]+))}}/g, function (match, name) {
30390 return templateArgs[name] ? templateArgs[name] : match;
30391 });
30392 }
30393 }, {
30394 key: "compileTemplate",
30395 value: function compileTemplate(template, templateArgs) {
30396 return jQuery.isPlainObject(templateArgs) ? this.compileObjectTemplateArgs(template, templateArgs) : this.compileArrayTemplateArgs(template, templateArgs);
30397 }
30398 }, {
30399 key: "translate",
30400 value: function translate(stringKey, context, templateArgs, i18nStack) {
30401 if (context) {
30402 i18nStack = this.config[context].i18n;
30403 }
30404 if (!i18nStack) {
30405 i18nStack = this.config.i18n;
30406 }
30407 var string = i18nStack[stringKey];
30408 if (undefined === string) {
30409 string = stringKey;
30410 }
30411 if (templateArgs) {
30412 string = this.compileTemplate(string, templateArgs);
30413 }
30414 return string;
30415 }
30416 }, {
30417 key: "onInit",
30418 value: function onInit() {
30419 _superPropGet(ElementorCommonApp, "onInit", this, 3)([]);
30420 this.config = elementorCommonConfig;
30421 this.setMarionetteTemplateCompiler();
30422 }
30423 }]);
30424 }(elementorModules.ViewModule);
30425 window.elementorCommon = new ElementorCommonApp();
30426 elementorCommon.initComponents();
30427 })();
30428
30429 /******/ })()
30430 ;
30431 //# sourceMappingURL=common.js.map