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

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

33,787 lines 1.3 MB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (() => { // webpackBootstrap
2 /******/ var __webpack_modules__ = ({
3
4 /***/ "../assets/dev/js/editor/utils/editor-one-events.js":
5 /*!**********************************************************!*\
6 !*** ../assets/dev/js/editor/utils/editor-one-events.js ***!
7 \**********************************************************/
8 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
9
10 "use strict";
11
12
13 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
14 Object.defineProperty(exports, "__esModule", ({
15 value: true
16 }));
17 exports["default"] = exports.createDebouncedWidgetPanelSearch = exports.createDebouncedFinderSearch = exports.EditorOneEventManager = void 0;
18 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
19 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
20 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
21 function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
22 function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
23 var EditorOneEventManager = exports.EditorOneEventManager = /*#__PURE__*/function () {
24 function EditorOneEventManager() {
25 (0, _classCallCheck2.default)(this, EditorOneEventManager);
26 }
27 return (0, _createClass2.default)(EditorOneEventManager, null, [{
28 key: "getEventsManager",
29 value: function getEventsManager() {
30 var _elementorCommon;
31 return (_elementorCommon = elementorCommon) === null || _elementorCommon === void 0 ? void 0 : _elementorCommon.eventsManager;
32 }
33 }, {
34 key: "getConfig",
35 value: function getConfig() {
36 var _this$getEventsManage;
37 return (_this$getEventsManage = this.getEventsManager()) === null || _this$getEventsManage === void 0 ? void 0 : _this$getEventsManage.config;
38 }
39 }, {
40 key: "canSendEvents",
41 value: function canSendEvents() {
42 var _elementorCommon2;
43 return ((_elementorCommon2 = elementorCommon) === null || _elementorCommon2 === void 0 || (_elementorCommon2 = _elementorCommon2.config) === null || _elementorCommon2 === void 0 || (_elementorCommon2 = _elementorCommon2.editor_events) === null || _elementorCommon2 === void 0 ? void 0 : _elementorCommon2.can_send_events) || false;
44 }
45 }, {
46 key: "isEventsManagerAvailable",
47 value: function isEventsManagerAvailable() {
48 var eventsManager = this.getEventsManager();
49 return eventsManager && 'function' === typeof eventsManager.dispatchEvent;
50 }
51 }, {
52 key: "dispatchEvent",
53 value: function dispatchEvent(eventName, payload) {
54 if (!this.isEventsManagerAvailable() || !this.canSendEvents()) {
55 return false;
56 }
57 try {
58 return this.getEventsManager().dispatchEvent(eventName, payload);
59 } catch (error) {
60 return false;
61 }
62 }
63 }, {
64 key: "toLowerSnake",
65 value: function toLowerSnake(value) {
66 if (!value || 'string' !== typeof value) {
67 return value;
68 }
69 return value.replace(/\s+/g, '_').toLowerCase();
70 }
71 }, {
72 key: "decodeHtmlEntities",
73 value: function decodeHtmlEntities(text) {
74 if (!text || 'string' !== typeof text) {
75 return text;
76 }
77 var doc = new DOMParser().parseFromString(text, 'text/html');
78 return doc.body.textContent || text;
79 }
80 }, {
81 key: "isInEditorContext",
82 value: function isInEditorContext() {
83 var _window$elementor;
84 return 'undefined' !== typeof window.elementor && !!((_window$elementor = window.elementor) !== null && _window$elementor !== void 0 && _window$elementor.documents);
85 }
86 }, {
87 key: "getFinderContext",
88 value: function getFinderContext() {
89 var _config$appTypes, _config$appTypes2, _config$locations, _config$locations2;
90 var config = this.getConfig();
91 var isEditor = this.isInEditorContext();
92 return {
93 windowName: isEditor ? config === null || config === void 0 || (_config$appTypes = config.appTypes) === null || _config$appTypes === void 0 ? void 0 : _config$appTypes.editor : config === null || config === void 0 || (_config$appTypes2 = config.appTypes) === null || _config$appTypes2 === void 0 ? void 0 : _config$appTypes2.wpAdmin,
94 targetLocation: this.toLowerSnake(isEditor ? config === null || config === void 0 || (_config$locations = config.locations) === null || _config$locations === void 0 ? void 0 : _config$locations.topBar : config === null || config === void 0 || (_config$locations2 = config.locations) === null || _config$locations2 === void 0 ? void 0 : _config$locations2.sidebar)
95 };
96 }
97 }, {
98 key: "createBasePayload",
99 value: function createBasePayload() {
100 var _config$appTypes$edit, _config$appTypes3, _config$appTypes$edit2, _config$appTypes4;
101 var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
102 var config = this.getConfig();
103 return _objectSpread({
104 app_type: (_config$appTypes$edit = config === null || config === void 0 || (_config$appTypes3 = config.appTypes) === null || _config$appTypes3 === void 0 ? void 0 : _config$appTypes3.editor) !== null && _config$appTypes$edit !== void 0 ? _config$appTypes$edit : 'editor',
105 window_name: (_config$appTypes$edit2 = config === null || config === void 0 || (_config$appTypes4 = config.appTypes) === null || _config$appTypes4 === void 0 ? void 0 : _config$appTypes4.editor) !== null && _config$appTypes$edit2 !== void 0 ? _config$appTypes$edit2 : 'editor'
106 }, overrides);
107 }
108 }, {
109 key: "sendTopBarPublishDropdown",
110 value: function sendTopBarPublishDropdown(targetName) {
111 var _config$names, _config$triggers, _config$targetTypes, _config$interactionRe, _config$locations3, _config$secondaryLoca, _config$targetTypes2;
112 var config = this.getConfig();
113 return this.dispatchEvent(config === null || config === void 0 || (_config$names = config.names) === null || _config$names === void 0 || (_config$names = _config$names.editorOne) === null || _config$names === void 0 ? void 0 : _config$names.topBarPublishDropdown, this.createBasePayload({
114 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers = config.triggers) === null || _config$triggers === void 0 ? void 0 : _config$triggers.click),
115 target_type: config === null || config === void 0 || (_config$targetTypes = config.targetTypes) === null || _config$targetTypes === void 0 ? void 0 : _config$targetTypes.dropdownItem,
116 target_name: targetName,
117 interaction_result: config === null || config === void 0 || (_config$interactionRe = config.interactionResults) === null || _config$interactionRe === void 0 ? void 0 : _config$interactionRe.actionSelected,
118 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations3 = config.locations) === null || _config$locations3 === void 0 ? void 0 : _config$locations3.topBar),
119 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca = config.secondaryLocations) === null || _config$secondaryLoca === void 0 ? void 0 : _config$secondaryLoca.publishDropdown),
120 location_l2: config === null || config === void 0 || (_config$targetTypes2 = config.targetTypes) === null || _config$targetTypes2 === void 0 ? void 0 : _config$targetTypes2.dropdownItem,
121 interaction_description: 'User selected an action from the publish dropdown'
122 }));
123 }
124 }, {
125 key: "sendTopBarPageList",
126 value: function sendTopBarPageList(targetName) {
127 var _config$names2, _config$triggers2, _config$targetTypes3, _config$interactionRe2, _config$interactionRe3, _config$locations4, _config$secondaryLoca2, _config$targetTypes4;
128 var isCreate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
129 var config = this.getConfig();
130 return this.dispatchEvent(config === null || config === void 0 || (_config$names2 = config.names) === null || _config$names2 === void 0 || (_config$names2 = _config$names2.editorOne) === null || _config$names2 === void 0 ? void 0 : _config$names2.topBarPageList, this.createBasePayload({
131 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers2 = config.triggers) === null || _config$triggers2 === void 0 ? void 0 : _config$triggers2.click),
132 target_type: config === null || config === void 0 || (_config$targetTypes3 = config.targetTypes) === null || _config$targetTypes3 === void 0 ? void 0 : _config$targetTypes3.dropdownItem,
133 target_name: targetName,
134 interaction_result: isCreate ? config === null || config === void 0 || (_config$interactionRe2 = config.interactionResults) === null || _config$interactionRe2 === void 0 ? void 0 : _config$interactionRe2.create : config === null || config === void 0 || (_config$interactionRe3 = config.interactionResults) === null || _config$interactionRe3 === void 0 ? void 0 : _config$interactionRe3.navigate,
135 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations4 = config.locations) === null || _config$locations4 === void 0 ? void 0 : _config$locations4.topBar),
136 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca2 = config.secondaryLocations) === null || _config$secondaryLoca2 === void 0 ? void 0 : _config$secondaryLoca2.pageListDropdown),
137 location_l2: config === null || config === void 0 || (_config$targetTypes4 = config.targetTypes) === null || _config$targetTypes4 === void 0 ? void 0 : _config$targetTypes4.dropdownItem,
138 interaction_description: 'User selected an action from the page list dropdown'
139 }));
140 }
141 }, {
142 key: "sendSiteSettingsSession",
143 value: function sendSiteSettingsSession(_ref) {
144 var _config$names3, _config$triggers3, _config$interactionRe4, _config$locations5, _config$secondaryLoca3;
145 var targetType = _ref.targetType,
146 _ref$visitedItems = _ref.visitedItems,
147 visitedItems = _ref$visitedItems === void 0 ? [] : _ref$visitedItems,
148 _ref$savedItems = _ref.savedItems,
149 savedItems = _ref$savedItems === void 0 ? [] : _ref$savedItems,
150 state = _ref.state;
151 var config = this.getConfig();
152 return this.dispatchEvent(config === null || config === void 0 || (_config$names3 = config.names) === null || _config$names3 === void 0 || (_config$names3 = _config$names3.editorOne) === null || _config$names3 === void 0 ? void 0 : _config$names3.siteSettingsSession, this.createBasePayload({
153 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers3 = config.triggers) === null || _config$triggers3 === void 0 ? void 0 : _config$triggers3.click),
154 target_type: targetType,
155 target_name: 'site_settings',
156 interaction_result: config === null || config === void 0 || (_config$interactionRe4 = config.interactionResults) === null || _config$interactionRe4 === void 0 ? void 0 : _config$interactionRe4.sessionEnd,
157 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations5 = config.locations) === null || _config$locations5 === void 0 ? void 0 : _config$locations5.leftPanel),
158 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca3 = config.secondaryLocations) === null || _config$secondaryLoca3 === void 0 ? void 0 : _config$secondaryLoca3.siteSettings),
159 interaction_description: 'Records areas visited as part of the site setting session',
160 metadata: {
161 visited_items: visitedItems,
162 saved_items: savedItems
163 },
164 state: state
165 }));
166 }
167 }, {
168 key: "sendELibraryNav",
169 value: function sendELibraryNav(tabName) {
170 var _config$names4, _config$triggers4, _config$targetTypes5, _config$interactionRe5, _config$locations6, _config$secondaryLoca4;
171 var config = this.getConfig();
172 return this.dispatchEvent(config === null || config === void 0 || (_config$names4 = config.names) === null || _config$names4 === void 0 || (_config$names4 = _config$names4.editorOne) === null || _config$names4 === void 0 ? void 0 : _config$names4.eLibraryNav, this.createBasePayload({
173 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers4 = config.triggers) === null || _config$triggers4 === void 0 ? void 0 : _config$triggers4.tabSelect),
174 target_type: config === null || config === void 0 || (_config$targetTypes5 = config.targetTypes) === null || _config$targetTypes5 === void 0 ? void 0 : _config$targetTypes5.tab,
175 target_name: this.toLowerSnake(tabName),
176 interaction_result: config === null || config === void 0 || (_config$interactionRe5 = config.interactionResults) === null || _config$interactionRe5 === void 0 ? void 0 : _config$interactionRe5.tabChanged,
177 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations6 = config.locations) === null || _config$locations6 === void 0 ? void 0 : _config$locations6.elementorLibrary),
178 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca4 = config.secondaryLocations) === null || _config$secondaryLoca4 === void 0 ? void 0 : _config$secondaryLoca4.libraryTabs),
179 interaction_description: 'User navigates within elementor library'
180 }));
181 }
182 }, {
183 key: "sendELibraryInsert",
184 value: function sendELibraryInsert(_ref2) {
185 var _config$triggers5, _config$targetTypes6, _config$interactionRe6, _config$locations7, _config$secondaryLoca5, _config$names5;
186 var assetId = _ref2.assetId,
187 assetName = _ref2.assetName,
188 libraryType = _ref2.libraryType,
189 _ref2$proRequired = _ref2.proRequired,
190 proRequired = _ref2$proRequired === void 0 ? false : _ref2$proRequired;
191 var config = this.getConfig();
192 var payload = this.createBasePayload({
193 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers5 = config.triggers) === null || _config$triggers5 === void 0 ? void 0 : _config$triggers5.insert),
194 target_type: config === null || config === void 0 || (_config$targetTypes6 = config.targetTypes) === null || _config$targetTypes6 === void 0 ? void 0 : _config$targetTypes6.button,
195 target_name: String(assetId),
196 interaction_result: config === null || config === void 0 || (_config$interactionRe6 = config.interactionResults) === null || _config$interactionRe6 === void 0 ? void 0 : _config$interactionRe6.assetInserted,
197 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations7 = config.locations) === null || _config$locations7 === void 0 ? void 0 : _config$locations7.elementorLibrary),
198 location_l1: this.toLowerSnake(libraryType),
199 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca5 = config.secondaryLocations) === null || _config$secondaryLoca5 === void 0 ? void 0 : _config$secondaryLoca5.assetCard),
200 interaction_description: 'User inserts block/pages from elementor library',
201 metadata: {
202 template_id: String(assetId),
203 template_name: this.decodeHtmlEntities(assetName) || ''
204 }
205 });
206 if (proRequired) {
207 payload.state = 'pro_plan_required';
208 }
209 return this.dispatchEvent(config === null || config === void 0 || (_config$names5 = config.names) === null || _config$names5 === void 0 || (_config$names5 = _config$names5.editorOne) === null || _config$names5 === void 0 ? void 0 : _config$names5.eLibraryInsert, payload);
210 }
211 }, {
212 key: "sendELibraryFavorite",
213 value: function sendELibraryFavorite(_ref3) {
214 var _config$triggers6, _config$targetTypes7, _config$interactionRe7, _config$locations8, _config$secondaryLoca6, _config$names6;
215 var assetId = _ref3.assetId,
216 assetName = _ref3.assetName,
217 libraryType = _ref3.libraryType,
218 isFavorite = _ref3.isFavorite,
219 _ref3$proRequired = _ref3.proRequired,
220 proRequired = _ref3$proRequired === void 0 ? false : _ref3$proRequired;
221 var config = this.getConfig();
222 var payload = this.createBasePayload({
223 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers6 = config.triggers) === null || _config$triggers6 === void 0 ? void 0 : _config$triggers6.click),
224 target_type: config === null || config === void 0 || (_config$targetTypes7 = config.targetTypes) === null || _config$targetTypes7 === void 0 ? void 0 : _config$targetTypes7.toggle,
225 target_name: String(assetId),
226 interaction_result: config === null || config === void 0 || (_config$interactionRe7 = config.interactionResults) === null || _config$interactionRe7 === void 0 ? void 0 : _config$interactionRe7.assetFavorite,
227 target_value: Boolean(isFavorite),
228 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations8 = config.locations) === null || _config$locations8 === void 0 ? void 0 : _config$locations8.elementorLibrary),
229 location_l1: this.toLowerSnake(libraryType),
230 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca6 = config.secondaryLocations) === null || _config$secondaryLoca6 === void 0 ? void 0 : _config$secondaryLoca6.assetCard),
231 interaction_description: 'User favorite block/pages from elementor library',
232 metadata: {
233 template_id: String(assetId),
234 template_name: this.decodeHtmlEntities(assetName) || ''
235 }
236 });
237 if (proRequired) {
238 payload.state = 'pro_plan_required';
239 }
240 return this.dispatchEvent(config === null || config === void 0 || (_config$names6 = config.names) === null || _config$names6 === void 0 || (_config$names6 = _config$names6.editorOne) === null || _config$names6 === void 0 ? void 0 : _config$names6.eLibraryFavorite, payload);
241 }
242 }, {
243 key: "sendELibraryGenerateAi",
244 value: function sendELibraryGenerateAi(_ref4) {
245 var _config$names7, _config$triggers7, _config$targetTypes8, _config$interactionRe8, _config$locations9, _config$secondaryLoca7;
246 var assetId = _ref4.assetId,
247 assetName = _ref4.assetName,
248 libraryType = _ref4.libraryType;
249 var config = this.getConfig();
250 return this.dispatchEvent(config === null || config === void 0 || (_config$names7 = config.names) === null || _config$names7 === void 0 || (_config$names7 = _config$names7.editorOne) === null || _config$names7 === void 0 ? void 0 : _config$names7.eLibraryGenerateAi, this.createBasePayload({
251 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers7 = config.triggers) === null || _config$triggers7 === void 0 ? void 0 : _config$triggers7.click),
252 target_type: config === null || config === void 0 || (_config$targetTypes8 = config.targetTypes) === null || _config$targetTypes8 === void 0 ? void 0 : _config$targetTypes8.button,
253 target_name: String(assetId),
254 interaction_result: config === null || config === void 0 || (_config$interactionRe8 = config.interactionResults) === null || _config$interactionRe8 === void 0 ? void 0 : _config$interactionRe8.aiGenerate,
255 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations9 = config.locations) === null || _config$locations9 === void 0 ? void 0 : _config$locations9.elementorLibrary),
256 location_l1: this.toLowerSnake(libraryType),
257 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca7 = config.secondaryLocations) === null || _config$secondaryLoca7 === void 0 ? void 0 : _config$secondaryLoca7.assetCard),
258 interaction_description: 'User generated block/page based on a library asset',
259 metadata: {
260 template_id: String(assetId),
261 template_name: this.decodeHtmlEntities(assetName) || ''
262 }
263 }));
264 }
265 }, {
266 key: "sendFinderSearchInput",
267 value: function sendFinderSearchInput(_ref5) {
268 var _config$triggers8, _config$targetTypes9, _config$interactionRe9, _config$interactionRe0, _config$secondaryLoca8, _config$names8;
269 var resultsCount = _ref5.resultsCount,
270 _ref5$searchTerm = _ref5.searchTerm,
271 searchTerm = _ref5$searchTerm === void 0 ? null : _ref5$searchTerm;
272 var config = this.getConfig();
273 var hasResults = resultsCount > 0;
274 var finderContext = this.getFinderContext();
275 var payload = this.createBasePayload({
276 window_name: finderContext.windowName,
277 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers8 = config.triggers) === null || _config$triggers8 === void 0 ? void 0 : _config$triggers8.typing),
278 target_type: config === null || config === void 0 || (_config$targetTypes9 = config.targetTypes) === null || _config$targetTypes9 === void 0 ? void 0 : _config$targetTypes9.searchInput,
279 target_name: 'finder',
280 interaction_result: hasResults ? config === null || config === void 0 || (_config$interactionRe9 = config.interactionResults) === null || _config$interactionRe9 === void 0 ? void 0 : _config$interactionRe9.resultsUpdated : config === null || config === void 0 || (_config$interactionRe0 = config.interactionResults) === null || _config$interactionRe0 === void 0 ? void 0 : _config$interactionRe0.noResults,
281 target_location: finderContext.targetLocation,
282 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca8 = config.secondaryLocations) === null || _config$secondaryLoca8 === void 0 ? void 0 : _config$secondaryLoca8.finder),
283 interaction_description: 'Finder search input, follows debounce behavior',
284 metadata: {
285 results_count: resultsCount
286 }
287 });
288 if (!hasResults && searchTerm) {
289 payload.metadata.search_term = searchTerm;
290 }
291 return this.dispatchEvent(config === null || config === void 0 || (_config$names8 = config.names) === null || _config$names8 === void 0 || (_config$names8 = _config$names8.editorOne) === null || _config$names8 === void 0 ? void 0 : _config$names8.finderSearchInput, payload);
292 }
293 }, {
294 key: "sendFinderResultSelect",
295 value: function sendFinderResultSelect(choice) {
296 var _config$names9, _config$triggers9, _config$targetTypes0, _config$interactionRe1, _config$secondaryLoca9, _config$secondaryLoca0;
297 var config = this.getConfig();
298 var finderContext = this.getFinderContext();
299 return this.dispatchEvent(config === null || config === void 0 || (_config$names9 = config.names) === null || _config$names9 === void 0 || (_config$names9 = _config$names9.editorOne) === null || _config$names9 === void 0 ? void 0 : _config$names9.finderResultSelect, this.createBasePayload({
300 window_name: finderContext.windowName,
301 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers9 = config.triggers) === null || _config$triggers9 === void 0 ? void 0 : _config$triggers9.click),
302 target_type: config === null || config === void 0 || (_config$targetTypes0 = config.targetTypes) === null || _config$targetTypes0 === void 0 ? void 0 : _config$targetTypes0.searchResult,
303 target_name: choice,
304 interaction_result: config === null || config === void 0 || (_config$interactionRe1 = config.interactionResults) === null || _config$interactionRe1 === void 0 ? void 0 : _config$interactionRe1.selected,
305 target_location: finderContext.targetLocation,
306 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca9 = config.secondaryLocations) === null || _config$secondaryLoca9 === void 0 ? void 0 : _config$secondaryLoca9.finder),
307 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca0 = config.secondaryLocations) === null || _config$secondaryLoca0 === void 0 ? void 0 : _config$secondaryLoca0.finderResults),
308 interaction_description: 'Finder search results was selected'
309 }));
310 }
311 }, {
312 key: "sendCanvasEmptyBoxAction",
313 value: function sendCanvasEmptyBoxAction(_ref6) {
314 var _config$triggers0, _config$targetTypes1, _config$interactionRe10, _config$locations0, _config$secondaryLoca1, _config$names0;
315 var targetName = _ref6.targetName,
316 _ref6$metadata = _ref6.metadata,
317 metadata = _ref6$metadata === void 0 ? {} : _ref6$metadata,
318 _ref6$containerCreate = _ref6.containerCreated,
319 containerCreated = _ref6$containerCreate === void 0 ? null : _ref6$containerCreate;
320 var config = this.getConfig();
321 var payload = this.createBasePayload({
322 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers0 = config.triggers) === null || _config$triggers0 === void 0 ? void 0 : _config$triggers0.click),
323 target_type: config === null || config === void 0 || (_config$targetTypes1 = config.targetTypes) === null || _config$targetTypes1 === void 0 ? void 0 : _config$targetTypes1.buttons,
324 target_name: targetName,
325 interaction_result: config === null || config === void 0 || (_config$interactionRe10 = config.interactionResults) === null || _config$interactionRe10 === void 0 ? void 0 : _config$interactionRe10.selected,
326 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations0 = config.locations) === null || _config$locations0 === void 0 ? void 0 : _config$locations0.canvas),
327 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca1 = config.secondaryLocations) === null || _config$secondaryLoca1 === void 0 ? void 0 : _config$secondaryLoca1.emptyBox),
328 interaction_description: 'Empty box on canvas actions'
329 });
330 if (Object.keys(metadata).length > 0) {
331 payload.metadata = metadata;
332 }
333 if (containerCreated !== null) {
334 payload.state = containerCreated;
335 }
336 return this.dispatchEvent(config === null || config === void 0 || (_config$names0 = config.names) === null || _config$names0 === void 0 || (_config$names0 = _config$names0.editorOne) === null || _config$names0 === void 0 ? void 0 : _config$names0.canvasEmptyBoxAction, payload);
337 }
338 }, {
339 key: "sendWidgetPanelSearch",
340 value: function sendWidgetPanelSearch(_ref7) {
341 var _config$triggers1, _config$targetTypes10, _config$interactionRe11, _config$interactionRe12, _config$locations1, _config$locations10, _config$secondaryLoca10, _config$names1;
342 var resultsCount = _ref7.resultsCount,
343 _ref7$userInput = _ref7.userInput,
344 userInput = _ref7$userInput === void 0 ? null : _ref7$userInput;
345 var config = this.getConfig();
346 var hasResults = resultsCount > 0;
347 var payload = this.createBasePayload({
348 interaction_type: this.toLowerSnake(config === null || config === void 0 || (_config$triggers1 = config.triggers) === null || _config$triggers1 === void 0 ? void 0 : _config$triggers1.typing),
349 target_type: config === null || config === void 0 || (_config$targetTypes10 = config.targetTypes) === null || _config$targetTypes10 === void 0 ? void 0 : _config$targetTypes10.searchWidget,
350 target_name: 'search_widget',
351 interaction_result: hasResults ? config === null || config === void 0 || (_config$interactionRe11 = config.interactionResults) === null || _config$interactionRe11 === void 0 ? void 0 : _config$interactionRe11.resultsUpdated : config === null || config === void 0 || (_config$interactionRe12 = config.interactionResults) === null || _config$interactionRe12 === void 0 ? void 0 : _config$interactionRe12.noResults,
352 target_location: this.toLowerSnake(config === null || config === void 0 || (_config$locations1 = config.locations) === null || _config$locations1 === void 0 ? void 0 : _config$locations1.leftPanel),
353 location_l1: this.toLowerSnake(config === null || config === void 0 || (_config$locations10 = config.locations) === null || _config$locations10 === void 0 ? void 0 : _config$locations10.widgetPanel),
354 location_l2: this.toLowerSnake(config === null || config === void 0 || (_config$secondaryLoca10 = config.secondaryLocations) === null || _config$secondaryLoca10 === void 0 ? void 0 : _config$secondaryLoca10.searchBar),
355 interaction_description: 'Widget search input, follows debounce behavior'
356 });
357 if (!hasResults && userInput) {
358 payload.metadata = {
359 user_input: userInput
360 };
361 }
362 return this.dispatchEvent(config === null || config === void 0 || (_config$names1 = config.names) === null || _config$names1 === void 0 || (_config$names1 = _config$names1.editorOne) === null || _config$names1 === void 0 ? void 0 : _config$names1.widgetPanelSearch, payload);
363 }
364 }]);
365 }();
366 var createDebouncedFinderSearch = exports.createDebouncedFinderSearch = function createDebouncedFinderSearch() {
367 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300;
368 return _.debounce(function (resultsCount, searchTerm) {
369 EditorOneEventManager.sendFinderSearchInput({
370 resultsCount: resultsCount,
371 searchTerm: searchTerm
372 });
373 }, delay);
374 };
375 var createDebouncedWidgetPanelSearch = exports.createDebouncedWidgetPanelSearch = function createDebouncedWidgetPanelSearch() {
376 var delay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2000;
377 return _.debounce(function (resultsCount, userInput) {
378 EditorOneEventManager.sendWidgetPanelSearch({
379 resultsCount: resultsCount,
380 userInput: userInput
381 });
382 }, delay);
383 };
384 var _default = exports["default"] = EditorOneEventManager;
385
386 /***/ }),
387
388 /***/ "../assets/dev/js/editor/utils/files-upload-handler.js":
389 /*!*************************************************************!*\
390 !*** ../assets/dev/js/editor/utils/files-upload-handler.js ***!
391 \*************************************************************/
392 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
393
394 "use strict";
395 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
396
397
398 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
399 Object.defineProperty(exports, "__esModule", ({
400 value: true
401 }));
402 exports["default"] = void 0;
403 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
404 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
405 var FilesUploadHandler = exports["default"] = /*#__PURE__*/function () {
406 function FilesUploadHandler() {
407 (0, _classCallCheck2.default)(this, FilesUploadHandler);
408 }
409 return (0, _createClass2.default)(FilesUploadHandler, null, [{
410 key: "isUploadEnabled",
411 value: function isUploadEnabled(mediaType) {
412 var unfilteredFilesTypes = ['svg', 'application/json'];
413 if (!unfilteredFilesTypes.includes(mediaType)) {
414 return true;
415 }
416 return elementorCommon.config.filesUpload.unfilteredFiles;
417 }
418 }, {
419 key: "setUploadTypeCaller",
420 value: function setUploadTypeCaller(frame) {
421 frame.uploader.uploader.param('uploadTypeCaller', 'elementor-wp-media-upload');
422 }
423 }, {
424 key: "getUnfilteredFilesNonAdminDialog",
425 value: function getUnfilteredFilesNonAdminDialog() {
426 return elementorCommon.dialogsManager.createWidget('alert', {
427 id: 'e-unfiltered-files-disabled-dialog',
428 headerMessage: __('Sorry, you can\'t upload that file yet', 'elementor'),
429 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'),
430 strings: {
431 confirm: __('Got it', 'elementor')
432 }
433 });
434 }
435 }, {
436 key: "getUnfilteredFilesNotEnabledDialog",
437 value: function getUnfilteredFilesNotEnabledDialog(callback) {
438 var elementorInstance = window.elementorAdmin || window.elementor;
439 if (!elementorInstance.config.user.is_administrator) {
440 return this.getUnfilteredFilesNonAdminDialog();
441 }
442 var onConfirm = function onConfirm() {
443 elementorCommon.ajax.addRequest('enable_unfiltered_files_upload', {}, true);
444 elementorCommon.config.filesUpload.unfilteredFiles = true;
445 callback();
446 };
447 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);
448 }
449 }, {
450 key: "getUnfilteredFilesNotEnabledImportTemplateDialog",
451 value: function getUnfilteredFilesNotEnabledImportTemplateDialog(callback) {
452 if (!(window.elementorAdmin || window.elementor).config.user.is_administrator) {
453 return this.getUnfilteredFilesNonAdminDialog();
454 }
455 return elementorCommon.dialogsManager.createWidget('confirm', {
456 id: 'e-enable-unfiltered-files-dialog-import-template',
457 headerMessage: __('Enable Unfiltered File Uploads', 'elementor'),
458 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'),
459 position: {
460 my: 'center center',
461 at: 'center center'
462 },
463 strings: {
464 confirm: __('Enable and Import', 'elementor'),
465 cancel: __('Import Without Enabling', 'elementor')
466 },
467 onConfirm: function onConfirm() {
468 elementorCommon.ajax.addRequest('enable_unfiltered_files_upload', {
469 success: function success() {
470 // This utility is used in both the admin and the Editor.
471 elementorCommon.config.filesUpload.unfilteredFiles = true;
472 callback();
473 }
474 }, true);
475 },
476 onCancel: function onCancel() {
477 return callback();
478 }
479 });
480 }
481 }]);
482 }();
483
484 /***/ }),
485
486 /***/ "../assets/dev/js/editor/utils/is-instanceof.js":
487 /*!******************************************************!*\
488 !*** ../assets/dev/js/editor/utils/is-instanceof.js ***!
489 \******************************************************/
490 /***/ ((__unused_webpack_module, exports) => {
491
492 "use strict";
493
494
495 Object.defineProperty(exports, "__esModule", ({
496 value: true
497 }));
498 exports["default"] = void 0;
499 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; } } }; }
500 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; } }
501 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; }
502 /**
503 * Some FileAPI objects such as FileList, DataTransferItem and DataTransferItemList has inconsistency with the retrieved
504 * object (from events, etc.) and the actual JavaScript object so a regular instanceof doesn't work. This function can
505 * check whether it's instanceof by using the objects constructor and prototype names.
506 *
507 * @param object
508 * @param constructors
509 * @return {boolean}
510 */
511 var _default = exports["default"] = function _default(object, constructors) {
512 constructors = Array.isArray(constructors) ? constructors : [constructors];
513 var _iterator = _createForOfIteratorHelper(constructors),
514 _step;
515 try {
516 for (_iterator.s(); !(_step = _iterator.n()).done;) {
517 var constructor = _step.value;
518 if (object.constructor.name === constructor.prototype[Symbol.toStringTag]) {
519 return true;
520 }
521 }
522 } catch (err) {
523 _iterator.e(err);
524 } finally {
525 _iterator.f();
526 }
527 return false;
528 };
529
530 /***/ }),
531
532 /***/ "../assets/dev/js/modules/imports/args-object.js":
533 /*!*******************************************************!*\
534 !*** ../assets/dev/js/modules/imports/args-object.js ***!
535 \*******************************************************/
536 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
537
538 "use strict";
539
540
541 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
542 Object.defineProperty(exports, "__esModule", ({
543 value: true
544 }));
545 exports["default"] = void 0;
546 var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js"));
547 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
548 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
549 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
550 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
551 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
552 var _instanceType = _interopRequireDefault(__webpack_require__(/*! ./instance-type */ "../assets/dev/js/modules/imports/instance-type.js"));
553 var _isInstanceof = _interopRequireDefault(__webpack_require__(/*! ../../editor/utils/is-instanceof */ "../assets/dev/js/editor/utils/is-instanceof.js"));
554 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)); }
555 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
556 var ArgsObject = exports["default"] = /*#__PURE__*/function (_InstanceType) {
557 /**
558 * Function constructor().
559 *
560 * Create ArgsObject.
561 *
562 * @param {{}} args
563 */
564 function ArgsObject(args) {
565 var _this;
566 (0, _classCallCheck2.default)(this, ArgsObject);
567 _this = _callSuper(this, ArgsObject);
568 _this.args = args;
569 return _this;
570 }
571
572 /**
573 * Function requireArgument().
574 *
575 * Validate property in args.
576 *
577 * @param {string} property
578 * @param {{}} args
579 *
580 * @throws {Error}
581 */
582 (0, _inherits2.default)(ArgsObject, _InstanceType);
583 return (0, _createClass2.default)(ArgsObject, [{
584 key: "requireArgument",
585 value: function requireArgument(property) {
586 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.args;
587 if (!Object.prototype.hasOwnProperty.call(args, property)) {
588 throw Error("".concat(property, " is required."));
589 }
590 }
591
592 /**
593 * Function requireArgumentType().
594 *
595 * Validate property in args using `type === typeof(args.whatever)`.
596 *
597 * @param {string} property
598 * @param {string} type
599 * @param {{}} args
600 *
601 * @throws {Error}
602 */
603 }, {
604 key: "requireArgumentType",
605 value: function requireArgumentType(property, type) {
606 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
607 this.requireArgument(property, args);
608 if ((0, _typeof2.default)(args[property]) !== type) {
609 throw Error("".concat(property, " invalid type: ").concat(type, "."));
610 }
611 }
612
613 /**
614 * Function requireArgumentInstance().
615 *
616 * Validate property in args using `args.whatever instanceof instance`.
617 *
618 * @param {string} property
619 * @param {*} instance
620 * @param {{}} args
621 *
622 * @throws {Error}
623 */
624 }, {
625 key: "requireArgumentInstance",
626 value: function requireArgumentInstance(property, instance) {
627 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
628 this.requireArgument(property, args);
629 if (!(args[property] instanceof instance) && !(0, _isInstanceof.default)(args[property], instance)) {
630 throw Error("".concat(property, " invalid instance."));
631 }
632 }
633
634 /**
635 * Function requireArgumentConstructor().
636 *
637 * Validate property in args using `type === args.whatever.constructor`.
638 *
639 * @param {string} property
640 * @param {*} type
641 * @param {{}} args
642 *
643 * @throws {Error}
644 */
645 }, {
646 key: "requireArgumentConstructor",
647 value: function requireArgumentConstructor(property, type) {
648 var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.args;
649 this.requireArgument(property, args);
650
651 // Note: Converting the constructor to string in order to avoid equation issues
652 // due to different memory addresses between iframes (window.Object !== window.top.Object).
653 if (args[property].constructor.toString() !== type.prototype.constructor.toString()) {
654 throw Error("".concat(property, " invalid constructor type."));
655 }
656 }
657 }], [{
658 key: "getInstanceType",
659 value: function getInstanceType() {
660 return 'ArgsObject';
661 }
662 }]);
663 }(_instanceType.default);
664
665 /***/ }),
666
667 /***/ "../assets/dev/js/modules/imports/instance-type.js":
668 /*!*********************************************************!*\
669 !*** ../assets/dev/js/modules/imports/instance-type.js ***!
670 \*********************************************************/
671 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
672
673 "use strict";
674
675
676 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
677 Object.defineProperty(exports, "__esModule", ({
678 value: true
679 }));
680 exports["default"] = void 0;
681 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
682 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
683 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
684 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
685 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; }
686 var InstanceType = exports["default"] = /*#__PURE__*/function () {
687 function InstanceType() {
688 var _this = this;
689 (0, _classCallCheck2.default)(this, InstanceType);
690 // Since anonymous classes sometimes do not get validated by babel, do it manually.
691 var target = this instanceof InstanceType ? this.constructor : void 0;
692 var prototypes = [];
693 while (target.__proto__ && target.__proto__.name) {
694 prototypes.push(target.__proto__);
695 target = target.__proto__;
696 }
697 prototypes.reverse().forEach(function (proto) {
698 return _this instanceof proto;
699 });
700 }
701 return (0, _createClass2.default)(InstanceType, null, [{
702 key: Symbol.hasInstance,
703 value: function value(target) {
704 /**
705 * This is function extending being called each time JS uses instanceOf, since babel use it each time it create new class
706 * its give's opportunity to mange capabilities of instanceOf operator.
707 * saving current class each time will give option later to handle instanceOf manually.
708 */
709 var result = _superPropGet(InstanceType, Symbol.hasInstance, this, 2)([target]);
710
711 // Act normal when validate a class, which does not have instance type.
712 if (target && !target.constructor.getInstanceType) {
713 return result;
714 }
715 if (target) {
716 if (!target.instanceTypes) {
717 target.instanceTypes = [];
718 }
719 if (!result) {
720 if (this.getInstanceType() === target.constructor.getInstanceType()) {
721 result = true;
722 }
723 }
724 if (result) {
725 var name = this.getInstanceType === InstanceType.getInstanceType ? 'BaseInstanceType' : this.getInstanceType();
726 if (-1 === target.instanceTypes.indexOf(name)) {
727 target.instanceTypes.push(name);
728 }
729 }
730 }
731 if (!result && target) {
732 // Check if the given 'target', is instance of known types.
733 result = target.instanceTypes && Array.isArray(target.instanceTypes) && -1 !== target.instanceTypes.indexOf(this.getInstanceType());
734 }
735 return result;
736 }
737 }, {
738 key: "getInstanceType",
739 value: function getInstanceType() {
740 elementorModules.ForceMethodImplementation();
741 }
742 }]);
743 }();
744
745 /***/ }),
746
747 /***/ "../assets/dev/js/modules/imports/module.js":
748 /*!**************************************************!*\
749 !*** ../assets/dev/js/modules/imports/module.js ***!
750 \**************************************************/
751 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
752
753 "use strict";
754
755
756 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
757 var _typeof2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js"));
758 var Module = function Module() {
759 var $ = jQuery,
760 instanceParams = arguments,
761 self = this,
762 events = {};
763 var settings;
764 var ensureClosureMethods = function ensureClosureMethods() {
765 $.each(self, function (methodName) {
766 var oldMethod = self[methodName];
767 if ('function' !== typeof oldMethod) {
768 return;
769 }
770 self[methodName] = function () {
771 return oldMethod.apply(self, arguments);
772 };
773 });
774 };
775 var initSettings = function initSettings() {
776 settings = self.getDefaultSettings();
777 var instanceSettings = instanceParams[0];
778 if (instanceSettings) {
779 $.extend(true, settings, instanceSettings);
780 }
781 };
782 var init = function init() {
783 self.__construct.apply(self, instanceParams);
784 ensureClosureMethods();
785 initSettings();
786 self.trigger('init');
787 };
788 this.getItems = function (items, itemKey) {
789 if (itemKey) {
790 var keyStack = itemKey.split('.'),
791 currentKey = keyStack.splice(0, 1);
792 if (!keyStack.length) {
793 return items[currentKey];
794 }
795 if (!items[currentKey]) {
796 return;
797 }
798 return this.getItems(items[currentKey], keyStack.join('.'));
799 }
800 return items;
801 };
802 this.getSettings = function (setting) {
803 return this.getItems(settings, setting);
804 };
805 this.setSettings = function (settingKey, value, settingsContainer) {
806 if (!settingsContainer) {
807 settingsContainer = settings;
808 }
809 if ('object' === (0, _typeof2.default)(settingKey)) {
810 $.extend(settingsContainer, settingKey);
811 return self;
812 }
813 var keyStack = settingKey.split('.'),
814 currentKey = keyStack.splice(0, 1);
815 if (!keyStack.length) {
816 settingsContainer[currentKey] = value;
817 return self;
818 }
819 if (!settingsContainer[currentKey]) {
820 settingsContainer[currentKey] = {};
821 }
822 return self.setSettings(keyStack.join('.'), value, settingsContainer[currentKey]);
823 };
824 this.getErrorMessage = function (type, functionName) {
825 var message;
826 switch (type) {
827 case 'forceMethodImplementation':
828 message = "The method '".concat(functionName, "' must to be implemented in the inheritor child.");
829 break;
830 default:
831 message = 'An error occurs';
832 }
833 return message;
834 };
835
836 // TODO: This function should be deleted ?.
837 this.forceMethodImplementation = function (functionName) {
838 throw new Error(this.getErrorMessage('forceMethodImplementation', functionName));
839 };
840 this.on = function (eventName, callback) {
841 if ('object' === (0, _typeof2.default)(eventName)) {
842 $.each(eventName, function (singleEventName) {
843 self.on(singleEventName, this);
844 });
845 return self;
846 }
847 var eventNames = eventName.split(' ');
848 eventNames.forEach(function (singleEventName) {
849 if (!events[singleEventName]) {
850 events[singleEventName] = [];
851 }
852 events[singleEventName].push(callback);
853 });
854 return self;
855 };
856 this.off = function (eventName, callback) {
857 if (!events[eventName]) {
858 return self;
859 }
860 if (!callback) {
861 delete events[eventName];
862 return self;
863 }
864 var callbackIndex = events[eventName].indexOf(callback);
865 if (-1 !== callbackIndex) {
866 delete events[eventName][callbackIndex];
867
868 // Reset array index (for next off on same event).
869 events[eventName] = events[eventName].filter(function (val) {
870 return val;
871 });
872 }
873 return self;
874 };
875 this.trigger = function (eventName) {
876 var methodName = 'on' + eventName[0].toUpperCase() + eventName.slice(1),
877 params = Array.prototype.slice.call(arguments, 1);
878 if (self[methodName]) {
879 self[methodName].apply(self, params);
880 }
881 var callbacks = events[eventName];
882 if (!callbacks) {
883 return self;
884 }
885 $.each(callbacks, function (index, callback) {
886 callback.apply(self, params);
887 });
888 return self;
889 };
890 init();
891 };
892 Module.prototype.__construct = function () {};
893 Module.prototype.getDefaultSettings = function () {
894 return {};
895 };
896 Module.prototype.getConstructorID = function () {
897 return this.constructor.name;
898 };
899 Module.extend = function (properties) {
900 var $ = jQuery,
901 parent = this;
902 var child = function child() {
903 return parent.apply(this, arguments);
904 };
905 $.extend(child, parent);
906 child.prototype = Object.create($.extend({}, parent.prototype, properties));
907 child.prototype.constructor = child;
908 child.__super__ = parent.prototype;
909 return child;
910 };
911 module.exports = Module;
912
913 /***/ }),
914
915 /***/ "../assets/dev/js/utils/notifications.js":
916 /*!***********************************************!*\
917 !*** ../assets/dev/js/utils/notifications.js ***!
918 \***********************************************/
919 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
920
921 "use strict";
922
923
924 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
925 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
926 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; }
927 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; }
928 module.exports = elementorModules.Module.extend({
929 initToast: function initToast() {
930 var toast = elementorCommon.dialogsManager.createWidget('buttons', {
931 id: 'elementor-toast',
932 position: {
933 my: 'center bottom',
934 at: 'center bottom-10',
935 of: '#elementor-panel-inner',
936 autoRefresh: true
937 },
938 hide: {
939 onClick: true,
940 auto: true,
941 autoDelay: 10000
942 },
943 effects: {
944 show: function show() {
945 var $widget = toast.getElements('widget');
946 $widget.show();
947 toast.refreshPosition();
948 var top = parseInt($widget.css('top'), 10);
949 $widget.hide().css('top', top + 100);
950 $widget.animate({
951 opacity: 'show',
952 height: 'show',
953 paddingBottom: 'show',
954 paddingTop: 'show',
955 top: top
956 }, {
957 easing: 'linear',
958 duration: 300
959 });
960 },
961 hide: function hide() {
962 var $widget = toast.getElements('widget'),
963 top = parseInt($widget.css('top'), 10);
964 $widget.animate({
965 opacity: 'hide',
966 height: 'hide',
967 paddingBottom: 'hide',
968 paddingTop: 'hide',
969 top: top + 100
970 }, {
971 easing: 'linear',
972 duration: 300
973 });
974 }
975 },
976 button: {
977 tag: 'button'
978 }
979 });
980
981 // Add role="status" and aria-live for screen reader announcement
982 toast.getElements('widget').attr({
983 role: 'status',
984 'aria-live': 'polite',
985 'aria-atomic': 'true'
986 });
987 this.getToast = function () {
988 return toast;
989 };
990 },
991 showToast: function showToast(options) {
992 var toast = this.getToast();
993 toast.setMessage(options.message);
994 toast.getElements('buttonsWrapper').empty();
995 toast.focusedButton = null;
996 toast.buttons = [];
997 var isPositionValid = this.isPositionValid(options === null || options === void 0 ? void 0 : options.position);
998 if (!isPositionValid) {
999 this.positionToWindow();
1000 }
1001 if (options !== null && options !== void 0 && options.position && isPositionValid) {
1002 toast.setSettings('position', options.position);
1003 }
1004 if (options.buttons) {
1005 options.buttons.forEach(function (button) {
1006 toast.addButton(button);
1007 });
1008 }
1009 if (options.classes) {
1010 toast.getElements('widget').addClass(options.classes);
1011 }
1012 if (options.sticky) {
1013 toast.setSettings({
1014 hide: {
1015 auto: false,
1016 onClick: false
1017 }
1018 });
1019 }
1020 return toast.show();
1021 },
1022 isPositionValid: function isPositionValid(position) {
1023 var _position$of;
1024 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;
1025 if (!positionToCheck) {
1026 return false;
1027 }
1028 return !!document.querySelector(positionToCheck);
1029 },
1030 positionToWindow: function positionToWindow() {
1031 var toast = this.getToast();
1032 var position = _objectSpread(_objectSpread({}, toast.getSettings('position')), {}, {
1033 my: 'right top',
1034 at: 'right-10 top+42',
1035 // 42px is the default admin bar height + 10px
1036 of: ''
1037 });
1038 toast.setSettings('position', position);
1039 toast.getElements('widget').addClass('dialog-position-window');
1040 },
1041 onInit: function onInit() {
1042 this.initToast();
1043 }
1044 });
1045
1046 /***/ }),
1047
1048 /***/ "../assets/dev/js/utils/tiers.js":
1049 /*!***************************************!*\
1050 !*** ../assets/dev/js/utils/tiers.js ***!
1051 \***************************************/
1052 /***/ ((__unused_webpack_module, exports) => {
1053
1054 "use strict";
1055
1056
1057 Object.defineProperty(exports, "__esModule", ({
1058 value: true
1059 }));
1060 exports.isTierAtLeast = exports.TIERS_PRIORITY = exports.TIERS = void 0;
1061 var TIERS_PRIORITY = exports.TIERS_PRIORITY = Object.freeze(['free', 'essential', 'essential-oct2023', 'advanced', 'expert', 'agency']);
1062
1063 /**
1064 * @type {Readonly<{
1065 * free: string;
1066 * essential: string;
1067 * 'essential-oct2023': string;
1068 * advanced: string;
1069 * expert: string;
1070 * agency: string;
1071 * }>}
1072 */
1073 var TIERS = exports.TIERS = Object.freeze(TIERS_PRIORITY.reduce(function (acc, tier) {
1074 acc[tier] = tier;
1075 return acc;
1076 }, {}));
1077 var isTierAtLeast = exports.isTierAtLeast = function isTierAtLeast(currentTier, expectedTier) {
1078 var currentTierIndex = TIERS_PRIORITY.indexOf(currentTier);
1079 var expectedTierIndex = TIERS_PRIORITY.indexOf(expectedTier);
1080 if (-1 === currentTierIndex || -1 === expectedTierIndex) {
1081 return false;
1082 }
1083 return currentTierIndex >= expectedTierIndex;
1084 };
1085
1086 /***/ }),
1087
1088 /***/ "../assets/dev/js/utils/time.js":
1089 /*!**************************************!*\
1090 !*** ../assets/dev/js/utils/time.js ***!
1091 \**************************************/
1092 /***/ ((__unused_webpack_module, exports) => {
1093
1094 "use strict";
1095
1096
1097 Object.defineProperty(exports, "__esModule", ({
1098 value: true
1099 }));
1100 exports["default"] = getUserTimestamp;
1101 /**
1102 * Returns the timestamp in ISO8601 format with the UTC timezone offset.
1103 *
1104 * @since 3.6.0
1105 *
1106 * @param {Date} date
1107 * @return {Date} timestamp
1108 */
1109 function getUserTimestamp() {
1110 var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
1111 var timezoneOffset = date.getTimezoneOffset();
1112
1113 // Local time for the user
1114 var UTCTimestamp = new Date(date.getTime() - timezoneOffset * 60000).toISOString();
1115
1116 // Remove the Z suffix from the string.
1117 UTCTimestamp = UTCTimestamp.slice(0, -1);
1118
1119 // Create the offset string in the format `+HH:00` (or minus (-) prefix for negative offset instead of plus)
1120 var decimalTimezoneOffset = timezoneOffset / 60,
1121 // Negative offsets include a '-' sign in the getTimezoneOffset value, positive values need a '+' prefix (ISO8601).
1122 sign = 0 <= decimalTimezoneOffset ? '+' : '-',
1123 hours = Math.abs(Math.floor(decimalTimezoneOffset)),
1124 minutes = Math.abs(decimalTimezoneOffset % 1) * 60,
1125 addZeroToHour = 10 > hours ? '0' : '',
1126 addZeroToMinutes = 10 > minutes ? '0' : '';
1127 var formattedTimezoneOffset = sign + addZeroToHour + hours + ':' + addZeroToMinutes + minutes;
1128 return UTCTimestamp + formattedTimezoneOffset;
1129 }
1130
1131 /***/ }),
1132
1133 /***/ "../core/common/assets/js/components/wordpress/commands-data/index.js":
1134 /*!****************************************************************************!*\
1135 !*** ../core/common/assets/js/components/wordpress/commands-data/index.js ***!
1136 \****************************************************************************/
1137 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1138
1139 "use strict";
1140
1141
1142 Object.defineProperty(exports, "__esModule", ({
1143 value: true
1144 }));
1145 Object.defineProperty(exports, "Media", ({
1146 enumerable: true,
1147 get: function get() {
1148 return _media.Media;
1149 }
1150 }));
1151 var _media = __webpack_require__(/*! ./media */ "../core/common/assets/js/components/wordpress/commands-data/media.js");
1152
1153 /***/ }),
1154
1155 /***/ "../core/common/assets/js/components/wordpress/commands-data/media.js":
1156 /*!****************************************************************************!*\
1157 !*** ../core/common/assets/js/components/wordpress/commands-data/media.js ***!
1158 \****************************************************************************/
1159 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1160
1161 "use strict";
1162 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
1163
1164
1165 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1166 Object.defineProperty(exports, "__esModule", ({
1167 value: true
1168 }));
1169 exports.Media = void 0;
1170 var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "../node_modules/@babel/runtime/regenerator/index.js"));
1171 var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
1172 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1173 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1174 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1175 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1176 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
1177 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1178 var _commandData = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-data */ "../modules/web-cli/assets/js/modules/command-data.js"));
1179 var _filesUploadHandler = _interopRequireDefault(__webpack_require__(/*! elementor-editor/utils/files-upload-handler */ "../assets/dev/js/editor/utils/files-upload-handler.js"));
1180 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)); }
1181 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1182 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; }
1183 var Media = exports.Media = /*#__PURE__*/function (_CommandData) {
1184 function Media() {
1185 (0, _classCallCheck2.default)(this, Media);
1186 return _callSuper(this, Media, arguments);
1187 }
1188 (0, _inherits2.default)(Media, _CommandData);
1189 return (0, _createClass2.default)(Media, [{
1190 key: "validateArgs",
1191 value: function validateArgs() {
1192 this.requireArgumentInstance('file', File);
1193 }
1194 }, {
1195 key: "getRequestData",
1196 value: function getRequestData() {
1197 var requestData = _superPropGet(Media, "getRequestData", this, 3)([]);
1198 requestData.namespace = 'wp';
1199 requestData.version = '2';
1200 return requestData;
1201 }
1202 }, {
1203 key: "applyBeforeCreate",
1204 value: function applyBeforeCreate(args) {
1205 var _args$options;
1206 args.headers = {
1207 'Content-Disposition': "attachment; filename=".concat(this.file.name),
1208 'Content-Type': this.file.type
1209 };
1210 args.query = {
1211 uploadTypeCaller: 'elementor-wp-media-upload'
1212 };
1213 args.data = this.file;
1214 if ((_args$options = args.options) !== null && _args$options !== void 0 && _args$options.progress) {
1215 this.toast = elementor.notifications.showToast({
1216 // eslint-disable-next-line @wordpress/i18n-ellipsis
1217 message: __('Uploading...'),
1218 sticky: true
1219 });
1220 }
1221 return args;
1222 }
1223 }, {
1224 key: "applyAfterCreate",
1225 value: function applyAfterCreate(data, args) {
1226 var _args$options2;
1227 if ((_args$options2 = args.options) !== null && _args$options2 !== void 0 && _args$options2.progress) {
1228 this.toast.hide();
1229 }
1230 return data;
1231 }
1232 }, {
1233 key: "run",
1234 value: function () {
1235 var _run = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee() {
1236 return _regenerator.default.wrap(function (_context) {
1237 while (1) switch (_context.prev = _context.next) {
1238 case 0:
1239 this.file = this.args.file;
1240 if (!(this.file.size > parseInt(window._wpPluploadSettings.defaults.filters.max_file_size, 10))) {
1241 _context.next = 1;
1242 break;
1243 }
1244 throw new Error(__('The file exceeds the maximum upload size for this site.', 'elementor'));
1245 case 1:
1246 if (!(!window._wpPluploadSettings.defaults.filters.mime_types[0].extensions.split(',').includes(this.file.name.split('.').pop()) && !elementor.config.filesUpload.unfilteredFiles)) {
1247 _context.next = 2;
1248 break;
1249 }
1250 _filesUploadHandler.default.getUnfilteredFilesNotEnabledDialog(function () {}).show();
1251 return _context.abrupt("return");
1252 case 2:
1253 _context.next = 3;
1254 return _superPropGet(Media, "run", this, 3)([]);
1255 case 3:
1256 return _context.abrupt("return", _context.sent);
1257 case 4:
1258 case "end":
1259 return _context.stop();
1260 }
1261 }, _callee, this);
1262 }));
1263 function run() {
1264 return _run.apply(this, arguments);
1265 }
1266 return run;
1267 }()
1268 }], [{
1269 key: "getEndpointFormat",
1270 value: function getEndpointFormat() {
1271 // 'wp/media' to 'media' since `requestData.namespace` is 'wp'.
1272 return 'media';
1273 }
1274 }]);
1275 }(_commandData.default);
1276
1277 /***/ }),
1278
1279 /***/ "../core/common/assets/js/components/wordpress/component.js":
1280 /*!******************************************************************!*\
1281 !*** ../core/common/assets/js/components/wordpress/component.js ***!
1282 \******************************************************************/
1283 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1284
1285 "use strict";
1286
1287
1288 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1289 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
1290 Object.defineProperty(exports, "__esModule", ({
1291 value: true
1292 }));
1293 exports["default"] = void 0;
1294 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1295 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1296 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1297 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1298 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1299 var _componentBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
1300 var dataCommands = _interopRequireWildcard(__webpack_require__(/*! ./commands-data/ */ "../core/common/assets/js/components/wordpress/commands-data/index.js"));
1301 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); }
1302 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)); }
1303 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1304 var Component = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
1305 function Component() {
1306 (0, _classCallCheck2.default)(this, Component);
1307 return _callSuper(this, Component, arguments);
1308 }
1309 (0, _inherits2.default)(Component, _ComponentBase);
1310 return (0, _createClass2.default)(Component, [{
1311 key: "getNamespace",
1312 value: function getNamespace() {
1313 return 'wp';
1314 }
1315 }, {
1316 key: "defaultData",
1317 value: function defaultData() {
1318 return this.importCommands(dataCommands);
1319 }
1320 }]);
1321 }(_componentBase.default);
1322
1323 /***/ }),
1324
1325 /***/ "../core/common/assets/js/utils/debug.js":
1326 /*!***********************************************!*\
1327 !*** ../core/common/assets/js/utils/debug.js ***!
1328 \***********************************************/
1329 /***/ ((module) => {
1330
1331 "use strict";
1332
1333
1334 // Moved from assets/dev/js/editor/utils
1335 var Debug = function Debug() {
1336 var self = this,
1337 errorStack = [],
1338 settings = {},
1339 elements = {};
1340 var initSettings = function initSettings() {
1341 settings = {
1342 debounceDelay: 500,
1343 urlsToWatch: ['elementor/assets']
1344 };
1345 };
1346 var initElements = function initElements() {
1347 elements.$window = jQuery(window);
1348 };
1349 var onError = function onError(event) {
1350 var _event$originalEvent;
1351 var error = (_event$originalEvent = event.originalEvent) === null || _event$originalEvent === void 0 ? void 0 : _event$originalEvent.error;
1352 if (!error) {
1353 return;
1354 }
1355 var isInWatchList = false,
1356 urlsToWatch = settings.urlsToWatch;
1357 jQuery.each(urlsToWatch, function () {
1358 if (-1 !== error.stack.indexOf(this)) {
1359 isInWatchList = true;
1360 return false;
1361 }
1362 });
1363 if (!isInWatchList) {
1364 return;
1365 }
1366 self.addError({
1367 type: error.name,
1368 message: error.message,
1369 url: event.originalEvent.filename,
1370 line: event.originalEvent.lineno,
1371 column: event.originalEvent.colno
1372 });
1373 };
1374 var bindEvents = function bindEvents() {
1375 elements.$window.on('error', onError);
1376 };
1377 var init = function init() {
1378 initSettings();
1379 initElements();
1380 bindEvents();
1381 self.sendErrors = _.debounce(self.sendErrors, settings.debounceDelay);
1382 };
1383 this.addURLToWatch = function (url) {
1384 settings.urlsToWatch.push(url);
1385 };
1386 this.addCustomError = function (error, category, tag) {
1387 var errorInfo = {
1388 type: error.name,
1389 message: error.message,
1390 url: error.fileName || error.sourceURL,
1391 line: error.lineNumber || error.line,
1392 column: error.columnNumber || error.column,
1393 customFields: {
1394 category: category || 'general',
1395 tag: tag
1396 }
1397 };
1398 if (!errorInfo.url) {
1399 var stackInfo = error.stack.match(/\n {4}at (.*?(?=:(\d+):(\d+)))/);
1400 if (stackInfo) {
1401 errorInfo.url = stackInfo[1];
1402 errorInfo.line = stackInfo[2];
1403 errorInfo.column = stackInfo[3];
1404 }
1405 }
1406 this.addError(errorInfo);
1407 };
1408 this.addError = function (errorParams) {
1409 var defaultParams = {
1410 type: 'Error',
1411 timestamp: Math.floor(new Date().getTime() / 1000),
1412 message: null,
1413 url: null,
1414 line: null,
1415 column: null,
1416 customFields: {}
1417 };
1418 errorStack.push(jQuery.extend(true, defaultParams, errorParams));
1419 self.sendErrors();
1420 };
1421 this.sendErrors = function () {
1422 // Avoid recursions on errors in ajax
1423 elements.$window.off('error', onError);
1424 jQuery.ajax({
1425 url: elementorCommon.config.ajax.url,
1426 method: 'POST',
1427 data: {
1428 action: 'elementor_js_log',
1429 _nonce: elementorCommon.ajax.getSettings('nonce'),
1430 data: errorStack
1431 },
1432 success: function success() {
1433 errorStack = [];
1434
1435 // Restore error handler
1436 elements.$window.on('error', onError);
1437 }
1438 });
1439 };
1440 init();
1441 };
1442 module.exports = Debug;
1443
1444 /***/ }),
1445
1446 /***/ "../core/common/assets/js/utils/helpers.js":
1447 /*!*************************************************!*\
1448 !*** ../core/common/assets/js/utils/helpers.js ***!
1449 \*************************************************/
1450 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1451
1452 "use strict";
1453
1454
1455 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1456 Object.defineProperty(exports, "__esModule", ({
1457 value: true
1458 }));
1459 exports["default"] = void 0;
1460 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1461 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1462 var Helpers = exports["default"] = /*#__PURE__*/function () {
1463 function Helpers() {
1464 (0, _classCallCheck2.default)(this, Helpers);
1465 }
1466 return (0, _createClass2.default)(Helpers, [{
1467 key: "consoleWarn",
1468 value:
1469 /**
1470 * @param {*} args
1471 * @deprecated since 3.7.0, use `elementorDevTools.consoleWarn()` instead.
1472 */
1473 function consoleWarn() {
1474 var _elementorDevTools;
1475 (_elementorDevTools = elementorDevTools).consoleWarn.apply(_elementorDevTools, arguments);
1476
1477 // This is is self is deprecated.
1478 elementorDevTools.deprecation.deprecated('elementorCommon.helpers.consoleWarn()', '3.7.0', 'elementorDevTools.consoleWarn()');
1479 }
1480
1481 /**
1482 * @param {string} message
1483 * @deprecated since 3.7.0, use `console.error()` instead.
1484 */
1485 }, {
1486 key: "consoleError",
1487 value: function consoleError(message) {
1488 // eslint-disable-next-line no-console
1489 console.error(message);
1490
1491 // This is is self is deprecated.
1492 elementorDevTools.deprecation.deprecated('elementorCommon.helpers.consoleError()', '3.7.0', 'console.error()');
1493 }
1494 }, {
1495 key: "cloneObject",
1496 value: function cloneObject(object) {
1497 return JSON.parse(JSON.stringify(object));
1498 }
1499 }, {
1500 key: "upperCaseWords",
1501 value: function upperCaseWords(string) {
1502 return (string + '').replace(/^(.)|\s+(.)/g, function ($1) {
1503 return $1.toUpperCase();
1504 });
1505 }
1506 }, {
1507 key: "getUniqueId",
1508 value: function getUniqueId() {
1509 return Math.random().toString(16).substr(2, 7);
1510 }
1511 }]);
1512 }();
1513
1514 /***/ }),
1515
1516 /***/ "../core/common/assets/js/utils/storage.js":
1517 /*!*************************************************!*\
1518 !*** ../core/common/assets/js/utils/storage.js ***!
1519 \*************************************************/
1520 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1521
1522 "use strict";
1523
1524
1525 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1526 Object.defineProperty(exports, "__esModule", ({
1527 value: true
1528 }));
1529 exports["default"] = void 0;
1530 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1531 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1532 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1533 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1534 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1535 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)); }
1536 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1537 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
1538 function _default() {
1539 (0, _classCallCheck2.default)(this, _default);
1540 return _callSuper(this, _default, arguments);
1541 }
1542 (0, _inherits2.default)(_default, _elementorModules$Mod);
1543 return (0, _createClass2.default)(_default, [{
1544 key: "get",
1545 value: function get(key, options) {
1546 options = options || {};
1547 var storage;
1548 try {
1549 storage = options.session ? sessionStorage : localStorage;
1550 } catch (e) {
1551 return key ? undefined : {};
1552 }
1553 var elementorStorage = storage.getItem('elementor');
1554 if (elementorStorage) {
1555 elementorStorage = JSON.parse(elementorStorage);
1556 } else {
1557 elementorStorage = {};
1558 }
1559 if (!elementorStorage.__expiration) {
1560 elementorStorage.__expiration = {};
1561 }
1562 var expiration = elementorStorage.__expiration;
1563 var expirationToCheck = [];
1564 if (key) {
1565 if (expiration[key]) {
1566 expirationToCheck = [key];
1567 }
1568 } else {
1569 expirationToCheck = Object.keys(expiration);
1570 }
1571 var entryExpired = false;
1572 expirationToCheck.forEach(function (expirationKey) {
1573 if (new Date(expiration[expirationKey]) < new Date()) {
1574 delete elementorStorage[expirationKey];
1575 delete expiration[expirationKey];
1576 entryExpired = true;
1577 }
1578 });
1579 if (entryExpired) {
1580 this.save(elementorStorage, options.session);
1581 }
1582 if (key) {
1583 return elementorStorage[key];
1584 }
1585 return elementorStorage;
1586 }
1587 }, {
1588 key: "set",
1589 value: function set(key, value, options) {
1590 options = options || {};
1591 var elementorStorage = this.get(null, options);
1592 elementorStorage[key] = value;
1593 if (options.lifetimeInSeconds) {
1594 var date = new Date();
1595 date.setTime(date.getTime() + options.lifetimeInSeconds * 1000);
1596 elementorStorage.__expiration[key] = date.getTime();
1597 }
1598 this.save(elementorStorage, options.session);
1599 }
1600 }, {
1601 key: "save",
1602 value: function save(object, session) {
1603 var storage;
1604 try {
1605 storage = session ? sessionStorage : localStorage;
1606 } catch (e) {
1607 return;
1608 }
1609 storage.setItem('elementor', JSON.stringify(object));
1610 }
1611 }]);
1612 }(elementorModules.Module);
1613
1614 /***/ }),
1615
1616 /***/ "../core/common/modules/ajax/assets/js/ajax.js":
1617 /*!*****************************************************!*\
1618 !*** ../core/common/modules/ajax/assets/js/ajax.js ***!
1619 \*****************************************************/
1620 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1621
1622 "use strict";
1623
1624
1625 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1626 Object.defineProperty(exports, "__esModule", ({
1627 value: true
1628 }));
1629 exports["default"] = void 0;
1630 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
1631 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1632 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1633 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1634 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1635 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1636 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)); }
1637 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1638 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
1639 function _default() {
1640 var _this;
1641 (0, _classCallCheck2.default)(this, _default);
1642 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1643 args[_key] = arguments[_key];
1644 }
1645 _this = _callSuper(this, _default, [].concat(args));
1646 _this.requests = {};
1647 _this.cache = {};
1648 _this.initRequestConstants();
1649 _this.debounceSendBatch = _.debounce(_this.sendBatch.bind(_this), 500);
1650 return _this;
1651 }
1652 (0, _inherits2.default)(_default, _elementorModules$Mod);
1653 return (0, _createClass2.default)(_default, [{
1654 key: "getDefaultSettings",
1655 value: function getDefaultSettings() {
1656 return {
1657 ajaxParams: {
1658 type: 'POST',
1659 url: elementorCommon.config.ajax.url,
1660 data: {},
1661 dataType: 'json'
1662 },
1663 actionPrefix: 'elementor_'
1664 };
1665 }
1666 }, {
1667 key: "initRequestConstants",
1668 value: function initRequestConstants() {
1669 this.requestConstants = {
1670 _nonce: this.getSettings('nonce')
1671 };
1672 }
1673 }, {
1674 key: "addRequestConstant",
1675 value: function addRequestConstant(key, value) {
1676 this.requestConstants[key] = value;
1677 }
1678 }, {
1679 key: "getCacheKey",
1680 value: function getCacheKey(request) {
1681 return JSON.stringify({
1682 unique_id: request.unique_id,
1683 data: request.data
1684 });
1685 }
1686 }, {
1687 key: "loadObjects",
1688 value: function loadObjects(options) {
1689 var _this2 = this;
1690 var dataCollection = {};
1691 var deferredArray = [];
1692 if (options.before) {
1693 options.before();
1694 }
1695 options.ids.forEach(function (objectId) {
1696 deferredArray.push(_this2.load({
1697 action: options.action,
1698 unique_id: options.data.unique_id + objectId,
1699 data: jQuery.extend({
1700 id: objectId
1701 }, options.data)
1702 }).done(function (data) {
1703 return dataCollection = jQuery.extend(dataCollection, data);
1704 }));
1705 });
1706 jQuery.when.apply(jQuery, deferredArray).done(function () {
1707 return options.success(dataCollection);
1708 });
1709 }
1710 }, {
1711 key: "load",
1712 value: function load(request, immediately) {
1713 var _this3 = this;
1714 if (!request.unique_id) {
1715 request.unique_id = request.action;
1716 }
1717 if (request.before) {
1718 request.before();
1719 }
1720 var deferred;
1721 var cacheKey = this.getCacheKey(request);
1722 if (_.has(this.cache, cacheKey)) {
1723 deferred = jQuery.Deferred().done(request.success).resolve(this.cache[cacheKey]);
1724 } else {
1725 var _request$error;
1726 deferred = this.addRequest(request.action, {
1727 data: request.data,
1728 unique_id: request.unique_id,
1729 success: function success(data) {
1730 return _this3.cache[cacheKey] = data;
1731 },
1732 error: (_request$error = request.error) !== null && _request$error !== void 0 ? _request$error : function () {}
1733 }, immediately).done(request.success);
1734 }
1735 return deferred;
1736 }
1737 }, {
1738 key: "cancelRequest",
1739 value: function cancelRequest(requestId) {
1740 var request = this.requests[requestId];
1741 if (!request) {
1742 return null;
1743 }
1744 if (request.options.deferred.jqXhr) {
1745 return request.options.deferred.jqXhr.abort('Request canceled');
1746 }
1747 if (request.options.deferred) {
1748 return request.options.deferred.reject('Request canceled');
1749 }
1750 }
1751 }, {
1752 key: "addRequest",
1753 value: function addRequest(action, options, immediately) {
1754 options = options || {};
1755 if (!options.unique_id) {
1756 options.unique_id = action;
1757 }
1758 options.deferred = jQuery.Deferred().done(options.success).fail(options.error).always(options.complete);
1759 var request = {
1760 action: action,
1761 options: options
1762 };
1763 if (immediately) {
1764 var requests = {};
1765 requests[options.unique_id] = request;
1766 options.deferred.jqXhr = this.sendBatch(requests);
1767 } else {
1768 this.requests[options.unique_id] = request;
1769 this.debounceSendBatch();
1770 }
1771 return options.deferred;
1772 }
1773 }, {
1774 key: "sendBatch",
1775 value: function sendBatch(requests) {
1776 var actions = {};
1777 if (!requests) {
1778 requests = this.requests;
1779
1780 // Empty for next batch.
1781 this.requests = {};
1782 }
1783 Object.entries(requests).forEach(function (_ref) {
1784 var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
1785 id = _ref2[0],
1786 request = _ref2[1];
1787 return actions[id] = {
1788 action: request.action,
1789 data: request.options.data
1790 };
1791 });
1792 return this.send('ajax', {
1793 data: {
1794 actions: JSON.stringify(actions)
1795 },
1796 success: function success(data) {
1797 Object.entries(data.responses).forEach(function (_ref3) {
1798 var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
1799 id = _ref4[0],
1800 response = _ref4[1];
1801 var options = requests[id].options;
1802 if (options) {
1803 if (response.success) {
1804 options.deferred.resolve(response.data);
1805 } else if (!response.success) {
1806 options.deferred.reject(response.data);
1807 }
1808 }
1809 });
1810 },
1811 error: function error(data) {
1812 return Object.values(requests).forEach(function (args) {
1813 if (args.options) {
1814 args.options.deferred.reject(data);
1815 }
1816 });
1817 }
1818 });
1819 }
1820 }, {
1821 key: "prepareSend",
1822 value: function prepareSend(action, options) {
1823 var _this4 = this;
1824 var settings = this.getSettings(),
1825 ajaxParams = elementorCommon.helpers.cloneObject(settings.ajaxParams);
1826 options = options || {};
1827 action = settings.actionPrefix + action;
1828 jQuery.extend(ajaxParams, options);
1829 var requestConstants = elementorCommon.helpers.cloneObject(this.requestConstants);
1830 requestConstants.action = action;
1831 var isFormData = ajaxParams.data instanceof FormData;
1832 Object.entries(requestConstants).forEach(function (_ref5) {
1833 var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
1834 key = _ref6[0],
1835 value = _ref6[1];
1836 if (isFormData) {
1837 ajaxParams.data.append(key, value);
1838 } else {
1839 ajaxParams.data[key] = value;
1840 }
1841 });
1842 var successCallback = ajaxParams.success,
1843 errorCallback = ajaxParams.error;
1844 if (successCallback || errorCallback) {
1845 ajaxParams.success = function (response) {
1846 if (response.success && successCallback) {
1847 successCallback(response.data);
1848 }
1849 if (!response.success && errorCallback) {
1850 errorCallback(response.data);
1851 }
1852 };
1853 if (errorCallback) {
1854 ajaxParams.error = function (data) {
1855 return errorCallback(data);
1856 };
1857 } else {
1858 ajaxParams.error = function (xmlHttpRequest) {
1859 if (xmlHttpRequest.readyState || 'abort' !== xmlHttpRequest.statusText) {
1860 _this4.trigger('request:unhandledError', xmlHttpRequest);
1861 }
1862 };
1863 }
1864 }
1865 return ajaxParams;
1866 }
1867 }, {
1868 key: "send",
1869 value: function send(action, options) {
1870 return jQuery.ajax(this.prepareSend(action, options));
1871 }
1872 }, {
1873 key: "addRequestCache",
1874 value: function addRequestCache(request, data) {
1875 var cacheKey = this.getCacheKey(request);
1876 this.cache[cacheKey] = data;
1877 }
1878 }, {
1879 key: "invalidateCache",
1880 value: function invalidateCache(request) {
1881 var cacheKey = this.getCacheKey(request);
1882 delete this.cache[cacheKey];
1883 }
1884 }]);
1885 }(elementorModules.Module);
1886
1887 /***/ }),
1888
1889 /***/ "../core/common/modules/connect/assets/js/connect.js":
1890 /*!***********************************************************!*\
1891 !*** ../core/common/modules/connect/assets/js/connect.js ***!
1892 \***********************************************************/
1893 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
1894
1895 "use strict";
1896 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
1897
1898
1899 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
1900 Object.defineProperty(exports, "__esModule", ({
1901 value: true
1902 }));
1903 exports["default"] = void 0;
1904 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
1905 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
1906 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
1907 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
1908 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
1909 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
1910 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)); }
1911 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
1912 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; }
1913 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Vie) {
1914 function _default() {
1915 (0, _classCallCheck2.default)(this, _default);
1916 return _callSuper(this, _default, arguments);
1917 }
1918 (0, _inherits2.default)(_default, _elementorModules$Vie);
1919 return (0, _createClass2.default)(_default, [{
1920 key: "addPopupPlugin",
1921 value: function addPopupPlugin() {
1922 var counter = 0;
1923 jQuery.fn.elementorConnect = function (options) {
1924 var _this = this;
1925 // Open the Connect Dialog in a popup window.
1926 if (options !== null && options !== void 0 && options.popup) {
1927 jQuery(this).on('click', function (event) {
1928 var _options$popup, _options$popup2;
1929 event.preventDefault();
1930 var width = ((_options$popup = options.popup) === null || _options$popup === void 0 ? void 0 : _options$popup.width) || 600,
1931 height = ((_options$popup2 = options.popup) === null || _options$popup2 === void 0 ? void 0 : _options$popup2.height) || 700;
1932 window.open(jQuery(_this).attr('href') + '&mode=popup', 'elementorConnect', "toolbar=no, menubar=no, width=".concat(width, ", height=").concat(height, ", top=200, left=0"));
1933 });
1934 delete options.popup;
1935 }
1936 var settings = jQuery.extend({
1937 // These are the defaults.
1938 success: function success() {
1939 return location.reload();
1940 },
1941 error: function error() {
1942 elementor.notifications.showToast({
1943 message: __('Unable to connect', 'elementor')
1944 });
1945 },
1946 parseUrl: function parseUrl(url) {
1947 return url;
1948 } // Allow to change the url, e.g: replace placeholders like '%%template_type%%' with actual value.
1949 }, options);
1950 this.each(function () {
1951 counter++;
1952 var $this = jQuery(this),
1953 callbackId = 'cb' + counter;
1954 $this.attr({
1955 target: '_blank',
1956 rel: 'opener',
1957 href: settings.parseUrl($this.attr('href') + '&mode=popup&callback_id=' + callbackId)
1958 });
1959 elementorCommon.elements.$window.on('elementor/connect/success/' + callbackId, settings.success).on('elementor/connect/error/' + callbackId, settings.error);
1960 });
1961 return this;
1962 };
1963 }
1964 }, {
1965 key: "getDefaultSettings",
1966 value: function getDefaultSettings() {
1967 return {
1968 selectors: {
1969 connectButton: '#elementor-template-library-connect__button'
1970 }
1971 };
1972 }
1973 }, {
1974 key: "getDefaultElements",
1975 value: function getDefaultElements() {
1976 return {
1977 $connectButton: jQuery(this.getSettings('selectors.connectButton'))
1978 };
1979 }
1980 }, {
1981 key: "applyPopup",
1982 value: function applyPopup() {
1983 this.elements.$connectButton.elementorConnect();
1984 }
1985 }, {
1986 key: "onInit",
1987 value: function onInit() {
1988 _superPropGet(_default, "onInit", this, 3)([]);
1989 this.addPopupPlugin();
1990 this.applyPopup();
1991 }
1992 }]);
1993 }(elementorModules.ViewModule);
1994
1995 /***/ }),
1996
1997 /***/ "../core/common/modules/event-tracker/assets/js/data/commands-data/index.js":
1998 /*!**********************************************************************************!*\
1999 !*** ../core/common/modules/event-tracker/assets/js/data/commands-data/index.js ***!
2000 \**********************************************************************************/
2001 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2002
2003 "use strict";
2004
2005
2006 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2007 Object.defineProperty(exports, "__esModule", ({
2008 value: true
2009 }));
2010 exports.Index = void 0;
2011 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2012 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2013 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2014 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2015 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2016 var _commandData = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-data */ "../modules/web-cli/assets/js/modules/command-data.js"));
2017 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)); }
2018 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2019 var Index = exports.Index = /*#__PURE__*/function (_CommandData) {
2020 function Index() {
2021 (0, _classCallCheck2.default)(this, Index);
2022 return _callSuper(this, Index, arguments);
2023 }
2024 (0, _inherits2.default)(Index, _CommandData);
2025 return (0, _createClass2.default)(Index, null, [{
2026 key: "getEndpointFormat",
2027 value: function getEndpointFormat() {
2028 return 'send-event';
2029 }
2030 }]);
2031 }(_commandData.default);
2032
2033 /***/ }),
2034
2035 /***/ "../core/common/modules/event-tracker/assets/js/data/component.js":
2036 /*!************************************************************************!*\
2037 !*** ../core/common/modules/event-tracker/assets/js/data/component.js ***!
2038 \************************************************************************/
2039 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2040
2041 "use strict";
2042
2043
2044 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2045 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2046 Object.defineProperty(exports, "__esModule", ({
2047 value: true
2048 }));
2049 exports["default"] = void 0;
2050 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2051 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2052 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2053 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2054 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2055 var _componentBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
2056 var commandsData = _interopRequireWildcard(__webpack_require__(/*! ./commands-data/ */ "../core/common/modules/event-tracker/assets/js/data/commands-data/index.js"));
2057 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); }
2058 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)); }
2059 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2060 var Component = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
2061 function Component() {
2062 (0, _classCallCheck2.default)(this, Component);
2063 return _callSuper(this, Component, arguments);
2064 }
2065 (0, _inherits2.default)(Component, _ComponentBase);
2066 return (0, _createClass2.default)(Component, [{
2067 key: "getNamespace",
2068 value: function getNamespace() {
2069 return 'event-tracker';
2070 }
2071 }, {
2072 key: "defaultData",
2073 value: function defaultData() {
2074 return this.importCommands(commandsData);
2075 }
2076 }]);
2077 }(_componentBase.default);
2078
2079 /***/ }),
2080
2081 /***/ "../core/common/modules/event-tracker/assets/js/events.js":
2082 /*!****************************************************************!*\
2083 !*** ../core/common/modules/event-tracker/assets/js/events.js ***!
2084 \****************************************************************/
2085 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2086
2087 "use strict";
2088
2089
2090 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2091 Object.defineProperty(exports, "__esModule", ({
2092 value: true
2093 }));
2094 exports["default"] = void 0;
2095 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2096 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2097 var _time = _interopRequireDefault(__webpack_require__(/*! elementor-utils/time */ "../assets/dev/js/utils/time.js"));
2098 var Events = exports["default"] = /*#__PURE__*/function () {
2099 function Events() {
2100 (0, _classCallCheck2.default)(this, Events);
2101 }
2102 return (0, _createClass2.default)(Events, [{
2103 key: "dispatchEvent",
2104 value: function dispatchEvent(eventData) {
2105 if (!eventData) {
2106 return;
2107 }
2108 eventData.ts = (0, _time.default)();
2109
2110 // No need to wait for response, no need to block browser in any way.
2111 $e.data.create('event-tracker/index', {
2112 event_data: eventData
2113 });
2114 }
2115 }]);
2116 }();
2117
2118 /***/ }),
2119
2120 /***/ "../core/common/modules/events-manager/assets/js/events-config.js":
2121 /*!************************************************************************!*\
2122 !*** ../core/common/modules/events-manager/assets/js/events-config.js ***!
2123 \************************************************************************/
2124 /***/ ((__unused_webpack_module, exports) => {
2125
2126 "use strict";
2127
2128
2129 Object.defineProperty(exports, "__esModule", ({
2130 value: true
2131 }));
2132 exports["default"] = void 0;
2133 var eventsConfig = {
2134 appTypes: {
2135 editor: 'editor',
2136 wpAdmin: 'wpadmin'
2137 },
2138 targetTypes: {
2139 dropdownItem: 'dropdown_item',
2140 button: 'button',
2141 tab: 'tab',
2142 toggle: 'toggle',
2143 searchInput: 'search_input',
2144 searchResult: 'search_result',
2145 buttons: 'buttons',
2146 searchWidget: 'search_widget'
2147 },
2148 interactionResults: {
2149 actionSelected: 'action_selected',
2150 navigate: 'navigate',
2151 create: 'create',
2152 sessionEnd: 'session_end',
2153 tabChanged: 'tab_changed',
2154 assetInserted: 'asset_inserted',
2155 assetFavorite: 'asset_favorite',
2156 aiGenerate: 'ai_generate',
2157 resultsUpdated: 'results_updated',
2158 noResults: 'no_results',
2159 selected: 'selected',
2160 promotionViewed: 'promotion_viewed',
2161 upgradeNow: 'upgrade_now'
2162 },
2163 targetNames: {
2164 publishDropdown: {
2165 saveDraft: 'save_draft',
2166 saveAsTemplate: 'save_as_template',
2167 viewPage: 'view_page',
2168 copyAndShare: 'copy_and_share'
2169 },
2170 pageList: {
2171 addNewPage: 'add_new_page'
2172 }
2173 },
2174 triggers: {
2175 click: 'Click',
2176 rightClick: 'Right Click',
2177 doubleClick: 'Double Click',
2178 accordionClick: 'Accordion Click',
2179 toggleClick: 'Toggle Click',
2180 dropdownClick: 'Click Dropdown',
2181 editorLoaded: 'Editor Loaded',
2182 visible: 'Visible',
2183 pageLoaded: 'Page Loaded',
2184 typing: 'Typing',
2185 tabSelect: 'Tab Select',
2186 insert: 'Insert'
2187 },
2188 locations: {
2189 widgetPanel: 'Widget Panel',
2190 topBar: 'Top Bar',
2191 sidebar: 'Sidebar',
2192 elementorEditor: 'Elementor Editor',
2193 templatesLibrary: {
2194 library: 'Templates Library'
2195 },
2196 app: {
2197 import: 'Import Kit',
2198 export: 'Export Kit',
2199 kitLibrary: 'Kit Library',
2200 cloudKitLibrary: 'Cloud Kit Library'
2201 },
2202 variables: 'Variables Panel',
2203 variablesManager: 'Variables Manager',
2204 admin: 'WP admin',
2205 structurePanel: 'Structure Panel',
2206 canvas: 'Canvas',
2207 leftPanel: 'Left Panel',
2208 elementorLibrary: 'Elementor Library',
2209 components: {
2210 instanceEditingPanel: 'Instance Editing Panel'
2211 }
2212 },
2213 secondaryLocations: {
2214 layout: 'Layout Section',
2215 basic: 'Basic Section',
2216 'pro-elements': 'Pro Section',
2217 general: 'General Section',
2218 'theme-elements': 'Site Section',
2219 'theme-elements-single': 'Single Section',
2220 'woocommerce-elements': 'WooCommerce Section',
2221 wordpress: 'WordPress Section',
2222 categories: 'Widgets Tab',
2223 global: 'Globals Tab',
2224 'whats-new': 'What\'s New',
2225 'document-settings': 'Document Settings icon',
2226 'preview-page': 'Preview Page',
2227 'publish-button': 'Publish Button',
2228 'widget-panel': 'Widget Panel Icon',
2229 finder: 'Finder',
2230 help: 'Help',
2231 elementorLogoDropdown: 'top_bar_elementor_logo_dropdown',
2232 elementorLogo: 'Elementor Logo',
2233 eLogoMenu: 'E-logo Menu',
2234 notes: 'Notes',
2235 siteSettings: 'Site Settings',
2236 structure: 'Structure',
2237 documentNameDropdown: 'Document Name dropdown',
2238 responsiveControls: 'Responsive controls',
2239 launchpad: 'launchpad',
2240 checklistHeader: 'Checklist Header',
2241 checklistSteps: 'Checklist Steps',
2242 userPreferences: 'User Preferences',
2243 contextMenu: 'Context Menu',
2244 templateLibrary: {
2245 saveModal: 'Save to Modal',
2246 moveModal: 'Move to Modal',
2247 bulkMoveModal: 'Bulk Move to Modal',
2248 copyModal: 'Copy to Modal',
2249 bulkCopyModal: 'Bulk Copy to Modal',
2250 saveModalSelectFolder: 'Save to Modal - select folder',
2251 saveModalSelectConnect: 'Save to Modal - connect',
2252 saveModalSelectUpgrade: 'Save to Modal - upgrade',
2253 importModal: 'Import Modal',
2254 newFolderModal: 'New Folder Modal',
2255 deleteDialog: 'Delete Dialog',
2256 deleteFolderDialog: 'Delete Folder Dialog',
2257 renameDialog: 'Rename Dialog',
2258 createFolderDialog: 'Create Folder Dialog',
2259 applySettingsDialog: 'Apply Settings Dialog',
2260 cloudTab: 'Cloud Tab',
2261 siteTab: 'Site Tab',
2262 cloudTabFolder: 'Cloud Tab - Folder',
2263 cloudTabConnect: 'Cloud Tab - Connect',
2264 cloudTabUpgrade: 'Cloud Tab - Upgrade',
2265 morePopup: 'Context Menu',
2266 quotaBar: 'Quota Bar'
2267 },
2268 kitLibrary: {
2269 cloudKitLibrary: 'kits_cloud_library',
2270 cloudKitLibraryConnect: 'kits_cloud_library_connect',
2271 cloudKitLibraryUpgrade: 'kits_cloud_library_upgrade',
2272 kitExportCustomization: 'kit_export_customization',
2273 kitExport: 'kit_export',
2274 kitExportCustomizationEdit: 'kit_export_customization_edit',
2275 kitExportSummary: 'kit_export_summary',
2276 kitImportUploadBox: 'kit_import_upload_box',
2277 kitImportCustomization: 'kit_import_customization',
2278 kitImportSummary: 'kit_import_summary'
2279 },
2280 variablesPopover: 'Variables Popover',
2281 admin: {
2282 pluginToolsTab: 'plugin_tools_tab',
2283 pluginWebsiteTemplatesTab: 'plugin_website_templates_tab'
2284 },
2285 componentsTab: 'Components Tab',
2286 canvasElement: 'Canvas Element',
2287 publishDropdown: 'Publish Dropdown',
2288 pageListDropdown: 'Page List Dropdown',
2289 emptyBox: 'Empty Box',
2290 searchBar: 'Search Bar',
2291 finderResults: 'Finder Results',
2292 libraryTabs: 'Library Tabs',
2293 assetCard: 'Asset Card'
2294 },
2295 elements: {
2296 accordionSection: 'Accordion section',
2297 buttonIcon: 'Button Icon',
2298 mainCta: 'Main CTA',
2299 button: 'Button',
2300 link: 'Link',
2301 dropdown: 'Dropdown',
2302 toggle: 'Toggle',
2303 launchpadChecklist: 'Checklist popup'
2304 },
2305 names: {
2306 v1: {
2307 layout: 'v1_widgets_tab_layout_section',
2308 basic: 'v1_widgets_tab_basic_section',
2309 'pro-elements': 'v1_widgets_tab_pro_section',
2310 general: 'v1_widgets_tab_general_section',
2311 'theme-elements': 'v1_widgets_tab_site_section',
2312 'theme-elements-single': 'v1_widgets_tab_single_section',
2313 'woocommerce-elements': 'v1_widgets_tab_woocommerce_section',
2314 wordpress: 'v1_widgets_tab_wordpress_section',
2315 categories: 'v1_widgets_tab',
2316 global: 'v1_globals_tab'
2317 },
2318 topBar: {
2319 whatsNew: 'top_bar_whats_new',
2320 documentSettings: 'top_bar_document_settings_icon',
2321 previewPage: 'top_bar_preview_page',
2322 publishButton: 'top_bar_publish_button',
2323 widgetPanel: 'top_bar_widget_panel_icon',
2324 finder: 'top_bar_finder',
2325 help: 'top_bar_help',
2326 history: 'top_bar_elementor_logo_dropdown_history',
2327 userPreferences: 'top_bar_elementor_logo_dropdown_user_preferences',
2328 keyboardShortcuts: 'top_bar_elementor_logo_dropdown_keyboard_shortcuts',
2329 exitToWordpress: 'top_bar_elementor_logo_dropdown_exit_to_wordpress',
2330 themeBuilder: 'top_bar_elementor_logo_dropdown_theme_builder',
2331 notes: 'top_bar_notes',
2332 siteSettings: 'top_bar_site_setting',
2333 structure: 'top_bar_structure',
2334 documentNameDropdown: 'top_bar_document_name_dropdown',
2335 responsiveControls: 'top_bar_responsive_controls',
2336 launchpadOn: 'top_bar_checklist_icon_show',
2337 launchpadOff: 'top_bar_checklist_icon_hide',
2338 elementorLogoDropdown: 'open_e_menu',
2339 connectAccount: 'connect_account',
2340 accountConnected: 'account_connected'
2341 },
2342 // ChecklistSteps event names are generated dynamically, based on stepId and action type taken: title, action, done, undone, upgrade
2343 elementorEditor: {
2344 editorLoaded: 'editor_loaded',
2345 checklist: {
2346 checklistHeaderClose: 'checklist_header_close_icon',
2347 checklistFirstPopup: 'checklist popup triggered'
2348 },
2349 userPreferences: {
2350 checklistShow: 'checklist_userpreferences_toggle_show',
2351 checklistHide: 'checklist_userpreferences_toggle_hide'
2352 }
2353 },
2354 variables: {
2355 open: 'open_variables_popover',
2356 add: 'add_new_variable',
2357 connect: 'connect_variable',
2358 save: 'save_new_variable',
2359 openManager: 'open_variables_manager',
2360 saveChanges: 'save_variables_changes',
2361 delete: 'delete_variable',
2362 variableSyncToV3: 'variable_sync_to_v3'
2363 },
2364 design_system: {
2365 importOpened: 'design_system_import_opened',
2366 fileSelected: 'design_system_file_selected',
2367 validationFailed: 'design_system_validation_failed',
2368 conflictChoice: 'design_system_conflict_choice',
2369 confirmed: 'design_system_import_confirmed',
2370 imported: 'design_system_imported',
2371 importFailed: 'design_system_import_failed'
2372 },
2373 components: {
2374 createClicked: 'component_create_clicked',
2375 createCancelled: 'component_creation_cancelled',
2376 created: 'component_created',
2377 instanceAdded: 'component_instance_added',
2378 edited: 'component_edited',
2379 propertiesPanelOpened: 'component_properties_panel_opened',
2380 propertiesGroupCreated: 'component_properties_group_created',
2381 propertyExposed: 'component_property_exposed',
2382 propertyRemoved: 'component_property_removed',
2383 detached: 'component_detached'
2384 },
2385 global_classes: {
2386 classApplied: 'class_applied',
2387 classRemoved: 'class_removed',
2388 classManagerFilterCleared: 'class_manager_filter_cleared',
2389 classDeleted: 'class_deleted',
2390 classPublishConflict: 'class_publish_conflict',
2391 classRenamed: 'class_renamed',
2392 classCreated: 'class_created',
2393 classManagerSearched: 'class_manager_searched',
2394 classManagerFiltersOpened: 'class_manager_filters_opened',
2395 classManagerOpened: 'class_manager_opened',
2396 classManagerReorder: 'class_manager_reorder',
2397 classManagerFilterUsed: 'class_manager_filter_used',
2398 classUsageLocate: 'class_usage_locate',
2399 classUsageHovered: 'class_usage_hovered',
2400 classStyled: 'class_styled',
2401 classStateClicked: 'class_state_clicked',
2402 classUsageClicked: 'class_usage_clicked',
2403 classDuplicate: 'class_duplicate',
2404 classSyncToV3PopupShown: 'class_sync_to_v3_popup_shown',
2405 classSyncToV3: 'class_sync_to_v3',
2406 classSyncToV3PopupClick: 'class_sync_to_v3_popup_click'
2407 },
2408 editorOne: {
2409 topBarPublishDropdown: 'top_bar_publish_dropdown',
2410 topBarPageList: 'top_bar_page_list',
2411 siteSettingsSession: 'site_settings_session',
2412 eLibraryNav: 'e_library_nav',
2413 eLibraryInsert: 'e_library_insert',
2414 eLibraryFavorite: 'e_library_favorite',
2415 eLibraryGenerateAi: 'e_library_generate_ai',
2416 finderSearchInput: 'finder_search_input',
2417 finderResultSelect: 'finder_result_select',
2418 canvasEmptyBoxAction: 'canvas_empty_box_action',
2419 widgetPanelSearch: 'widget_panel_search'
2420 },
2421 interactions: {
2422 created: 'interactions_created'
2423 },
2424 promotions: {
2425 viewPromotion: 'view_promotion',
2426 upgradePromotionClick: 'upgrade_promotion_click'
2427 }
2428 }
2429 };
2430 var _default = exports["default"] = eventsConfig;
2431
2432 /***/ }),
2433
2434 /***/ "../core/common/modules/events-manager/assets/js/module.js":
2435 /*!*****************************************************************!*\
2436 !*** ../core/common/modules/events-manager/assets/js/module.js ***!
2437 \*****************************************************************/
2438 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2439
2440 "use strict";
2441
2442
2443 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2444 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2445 Object.defineProperty(exports, "__esModule", ({
2446 value: true
2447 }));
2448 exports["default"] = void 0;
2449 var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "../node_modules/@babel/runtime/regenerator/index.js"));
2450 var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js"));
2451 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2452 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2453 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2454 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2455 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2456 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
2457 var _eventsConfig = _interopRequireDefault(__webpack_require__(/*! ./events-config */ "../core/common/modules/events-manager/assets/js/events-config.js"));
2458 var _mixpanelBrowser = _interopRequireWildcard(__webpack_require__(/*! mixpanel-browser */ "../node_modules/mixpanel-browser/dist/mixpanel.module.js"));
2459 var _tiers = __webpack_require__(/*! elementor-utils/tiers */ "../assets/dev/js/utils/tiers.js");
2460 var _sessionRecording = __webpack_require__(/*! ./session-recording */ "../core/common/modules/events-manager/assets/js/session-recording.js");
2461 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); }
2462 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; }
2463 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; }
2464 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)); }
2465 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2466 /** @type {Mixpanel | null} */
2467 var mixpanelInstance = null;
2468 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
2469 function _default() {
2470 var _this;
2471 (0, _classCallCheck2.default)(this, _default);
2472 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2473 args[_key] = arguments[_key];
2474 }
2475 _this = _callSuper(this, _default, [].concat(args));
2476 (0, _defineProperty2.default)(_this, "trackingEnabled", false);
2477 (0, _defineProperty2.default)(_this, "availableExperiments", []);
2478 return _this;
2479 }
2480 (0, _inherits2.default)(_default, _elementorModules$Mod);
2481 return (0, _createClass2.default)(_default, [{
2482 key: "onInit",
2483 value: function onInit() {
2484 var _elementorCommon$conf,
2485 _this2 = this;
2486 this.config = _eventsConfig.default;
2487 if (!this.canSendEvents()) {
2488 return;
2489 }
2490 (0, _sessionRecording.configureSessionRecording)((_elementorCommon$conf = elementorCommon.config.editor_events) === null || _elementorCommon$conf === void 0 ? void 0 : _elementorCommon$conf.session_recording_events);
2491 this.initializeMixpanel(function () {
2492 return _this2.enableTracking();
2493 });
2494 }
2495 }, {
2496 key: "initializeMixpanel",
2497 value: function initializeMixpanel(onLoaded) {
2498 if (mixpanelInstance && mixpanelInstance.isInitialized) {
2499 onLoaded(mixpanelInstance);
2500 } else {
2501 var _elementorCommon$conf2;
2502 mixpanelInstance = _mixpanelBrowser.default.init((_elementorCommon$conf2 = elementorCommon.config.editor_events) === null || _elementorCommon$conf2 === void 0 ? void 0 : _elementorCommon$conf2.token, {
2503 persistence: 'localStorage',
2504 autocapture: false,
2505 flags: true,
2506 api_host: 'https://api-eu.mixpanel.com',
2507 loaded: onLoaded,
2508 record_sessions_percent: 0,
2509 record_idle_timeout_ms: 60 * 1000,
2510 // 60 Seconds
2511 record_min_ms: 5 * 1000,
2512 // 5 Seconds
2513 record_max_ms: 30 * 1000,
2514 // 30 Seconds
2515 record_mask_text_selector: ''
2516 }, 'elementor-editor');
2517 }
2518 elementorCommon.config.editor_events.mixpanelInstance = mixpanelInstance;
2519 }
2520 }, {
2521 key: "enableTracking",
2522 value: function enableTracking() {
2523 var _elementorCommon$conf3;
2524 if (!this.isMixpanelReady()) {
2525 return;
2526 }
2527 var userId = (_elementorCommon$conf3 = elementorCommon.config.editor_events) === null || _elementorCommon$conf3 === void 0 ? void 0 : _elementorCommon$conf3.user_id;
2528 mixpanelInstance.register({
2529 appType: 'Editor'
2530 });
2531 if (userId) {
2532 var _elementorCommon$conf4;
2533 mixpanelInstance.identify(userId);
2534 mixpanelInstance.people.set_once({
2535 $user_id: userId,
2536 $last_login: new Date().toISOString(),
2537 $plan_type: ((_elementorCommon$conf4 = elementorCommon.config.library_connect) === null || _elementorCommon$conf4 === void 0 ? void 0 : _elementorCommon$conf4.plan_type) || _tiers.TIERS.free
2538 });
2539 }
2540 this.trackingEnabled = true;
2541 this.availableExperiments = Object.keys(elementorCommon.config.experimentalFeatures || {});
2542 }
2543 }, {
2544 key: "dispatchEvent",
2545 value: function dispatchEvent(name, data) {
2546 var _elementorCommon$conf5, _elementorCommon$conf6, _elementorCommon$conf7, _elementorCommon$conf8, _elementorCommon$conf9, _elementorCommon$conf0, _elementorCommon$conf1, _elementorCommon$conf10, _elementorCommon$conf11;
2547 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2548 if (!this.canSendEvents()) {
2549 return;
2550 }
2551 if (!this.trackingEnabled) {
2552 this.enableTracking();
2553 }
2554 var eventData = _objectSpread({
2555 user_id: ((_elementorCommon$conf5 = elementorCommon.config.editor_events) === null || _elementorCommon$conf5 === void 0 ? void 0 : _elementorCommon$conf5.user_id) || null,
2556 user_roles: ((_elementorCommon$conf6 = elementorCommon.config.library_connect) === null || _elementorCommon$conf6 === void 0 ? void 0 : _elementorCommon$conf6.user_roles) || [],
2557 subscription_id: ((_elementorCommon$conf7 = elementorCommon.config.editor_events) === null || _elementorCommon$conf7 === void 0 ? void 0 : _elementorCommon$conf7.subscription_id) || null,
2558 user_tier: ((_elementorCommon$conf8 = elementorCommon.config.library_connect) === null || _elementorCommon$conf8 === void 0 ? void 0 : _elementorCommon$conf8.current_access_tier) || null,
2559 url: (_elementorCommon$conf9 = elementorCommon.config.editor_events) === null || _elementorCommon$conf9 === void 0 ? void 0 : _elementorCommon$conf9.site_url,
2560 wp_version: (_elementorCommon$conf0 = elementorCommon.config.editor_events) === null || _elementorCommon$conf0 === void 0 ? void 0 : _elementorCommon$conf0.wp_version,
2561 client_id: (_elementorCommon$conf1 = elementorCommon.config.editor_events) === null || _elementorCommon$conf1 === void 0 ? void 0 : _elementorCommon$conf1.site_key,
2562 app_version: (_elementorCommon$conf10 = elementorCommon.config.editor_events) === null || _elementorCommon$conf10 === void 0 ? void 0 : _elementorCommon$conf10.elementor_version,
2563 site_language: (_elementorCommon$conf11 = elementorCommon.config.editor_events) === null || _elementorCommon$conf11 === void 0 ? void 0 : _elementorCommon$conf11.site_language,
2564 experiments: this.availableExperiments
2565 }, data);
2566 mixpanelInstance.track(name, eventData, options);
2567 var recordingDecision = (0, _sessionRecording.handleSessionRecording)(name, mixpanelInstance);
2568 if (recordingDecision) {
2569 mixpanelInstance.track(recordingDecision, eventData);
2570 }
2571 }
2572 }, {
2573 key: "featureFlagIsActive",
2574 value: function () {
2575 var _featureFlagIsActive = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee(flagName) {
2576 var _mixpanelInstance;
2577 var isEnabled;
2578 return _regenerator.default.wrap(function (_context) {
2579 while (1) switch (_context.prev = _context.next) {
2580 case 0:
2581 if (!('function' !== typeof ((_mixpanelInstance = mixpanelInstance) === null || _mixpanelInstance === void 0 || (_mixpanelInstance = _mixpanelInstance.flags) === null || _mixpanelInstance === void 0 ? void 0 : _mixpanelInstance.is_enabled))) {
2582 _context.next = 1;
2583 break;
2584 }
2585 return _context.abrupt("return", false);
2586 case 1:
2587 _context.next = 2;
2588 return mixpanelInstance.flags.is_enabled(flagName, false);
2589 case 2:
2590 isEnabled = _context.sent;
2591 return _context.abrupt("return", true === isEnabled);
2592 case 3:
2593 case "end":
2594 return _context.stop();
2595 }
2596 }, _callee);
2597 }));
2598 function featureFlagIsActive(_x) {
2599 return _featureFlagIsActive.apply(this, arguments);
2600 }
2601 return featureFlagIsActive;
2602 }()
2603 }, {
2604 key: "getExperimentVariant",
2605 value: function () {
2606 var _getExperimentVariant = (0, _asyncToGenerator2.default)(/*#__PURE__*/_regenerator.default.mark(function _callee2(experimentName) {
2607 var defaultValue,
2608 _elementorCommon$conf12,
2609 _elementorCommon$conf13,
2610 isAbTestingEnabled,
2611 variant,
2612 _args2 = arguments,
2613 _t;
2614 return _regenerator.default.wrap(function (_context2) {
2615 while (1) switch (_context2.prev = _context2.next) {
2616 case 0:
2617 defaultValue = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 'control';
2618 _context2.prev = 1;
2619 if (this.canSendEvents()) {
2620 _context2.next = 2;
2621 break;
2622 }
2623 return _context2.abrupt("return", defaultValue);
2624 case 2:
2625 isAbTestingEnabled = (_elementorCommon$conf12 = (_elementorCommon$conf13 = elementorCommon.config.editor_events) === null || _elementorCommon$conf13 === void 0 ? void 0 : _elementorCommon$conf13.flags_enabled) !== null && _elementorCommon$conf12 !== void 0 ? _elementorCommon$conf12 : false;
2626 if (isAbTestingEnabled) {
2627 _context2.next = 3;
2628 break;
2629 }
2630 return _context2.abrupt("return", defaultValue);
2631 case 3:
2632 if (mixpanelInstance) {
2633 _context2.next = 4;
2634 break;
2635 }
2636 return _context2.abrupt("return", defaultValue);
2637 case 4:
2638 if (!this.trackingEnabled) {
2639 this.enableTracking();
2640 }
2641 if (mixpanelInstance.flags) {
2642 _context2.next = 5;
2643 break;
2644 }
2645 return _context2.abrupt("return", defaultValue);
2646 case 5:
2647 if (!('function' !== typeof mixpanelInstance.flags.get_variant_value)) {
2648 _context2.next = 6;
2649 break;
2650 }
2651 return _context2.abrupt("return", defaultValue);
2652 case 6:
2653 _context2.next = 7;
2654 return mixpanelInstance.flags.get_variant_value(experimentName, defaultValue);
2655 case 7:
2656 variant = _context2.sent;
2657 if (!(undefined === variant || null === variant)) {
2658 _context2.next = 8;
2659 break;
2660 }
2661 return _context2.abrupt("return", defaultValue);
2662 case 8:
2663 return _context2.abrupt("return", variant);
2664 case 9:
2665 _context2.prev = 9;
2666 _t = _context2["catch"](1);
2667 return _context2.abrupt("return", defaultValue);
2668 case 10:
2669 case "end":
2670 return _context2.stop();
2671 }
2672 }, _callee2, this, [[1, 9]]);
2673 }));
2674 function getExperimentVariant(_x2) {
2675 return _getExperimentVariant.apply(this, arguments);
2676 }
2677 return getExperimentVariant;
2678 }()
2679 }, {
2680 key: "startExperiment",
2681 value: function startExperiment(experimentName, experimentVariant) {
2682 if (!this.trackingEnabled) {
2683 return;
2684 }
2685 mixpanelInstance.track('$experiment_started', {
2686 'Experiment name': experimentName,
2687 'Variant name': experimentVariant
2688 });
2689 }
2690 }, {
2691 key: "isMixpanelReady",
2692 value: function isMixpanelReady() {
2693 if ('undefined' === typeof mixpanelInstance || !mixpanelInstance) {
2694 return false;
2695 }
2696 try {
2697 var distinctId = mixpanelInstance.get_distinct_id();
2698 return distinctId !== undefined && distinctId !== null;
2699 } catch (error) {
2700 return false;
2701 }
2702 }
2703 }, {
2704 key: "canSendEvents",
2705 value: function canSendEvents() {
2706 var _elementorCommon;
2707 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);
2708 }
2709 }, {
2710 key: "getMixpanelInstance",
2711 value: function getMixpanelInstance() {
2712 return this.isMixpanelReady() ? mixpanelInstance : undefined;
2713 }
2714 }]);
2715 }(elementorModules.Module);
2716
2717 /***/ }),
2718
2719 /***/ "../core/common/modules/events-manager/assets/js/session-recording.js":
2720 /*!****************************************************************************!*\
2721 !*** ../core/common/modules/events-manager/assets/js/session-recording.js ***!
2722 \****************************************************************************/
2723 /***/ ((__unused_webpack_module, exports) => {
2724
2725 "use strict";
2726
2727
2728 Object.defineProperty(exports, "__esModule", ({
2729 value: true
2730 }));
2731 exports.configureSessionRecording = configureSessionRecording;
2732 exports.getIsRecording = getIsRecording;
2733 exports.handleSessionRecording = handleSessionRecording;
2734 var RECORD_SESSION_PERCENT = 1;
2735 var sessionRecordingPairs = [];
2736 var activeEndEvent = null;
2737 var isRecording = false;
2738 function shouldRecordSession(distinctId, percent) {
2739 var fraction = Math.min(Math.max(percent / 100, 0), 1);
2740 var hash = 0;
2741 for (var i = 0; i < distinctId.length; i++) {
2742 // eslint-disable-next-line no-bitwise
2743 hash = hash * 31 + distinctId.charCodeAt(i) >>> 0;
2744 }
2745 return hash / 4294967295 < fraction;
2746 }
2747
2748 /**
2749 * @param {Array<{start: string, end?: string|null}>} pairs
2750 */
2751 function configureSessionRecording(pairs) {
2752 if (!Array.isArray(pairs)) {
2753 return;
2754 }
2755 sessionRecordingPairs = pairs.filter(function (pair) {
2756 return 'string' === typeof (pair === null || pair === void 0 ? void 0 : pair.start) && pair.start;
2757 });
2758 }
2759
2760 /**
2761 * Evaluates whether to start/stop recording based on the event name.
2762 *
2763 * @param {string} name
2764 * @param {import('mixpanel-browser').Mixpanel} mixpanelInstance
2765 * @return {'recording_started'|'recording_skipped'|'recording_stopped'|null} The recording decision, or null if no action taken.
2766 */
2767 function handleSessionRecording(name, mixpanelInstance) {
2768 var matchedPair = sessionRecordingPairs.find(function (pair) {
2769 return pair.start === name;
2770 });
2771 if (matchedPair) {
2772 var distinctId = mixpanelInstance.get_distinct_id();
2773 if (shouldRecordSession(distinctId, RECORD_SESSION_PERCENT)) {
2774 var _matchedPair$end;
2775 mixpanelInstance.start_session_recording();
2776 isRecording = true;
2777 activeEndEvent = (_matchedPair$end = matchedPair.end) !== null && _matchedPair$end !== void 0 ? _matchedPair$end : null;
2778 return 'recording_started';
2779 }
2780 isRecording = false;
2781 activeEndEvent = null;
2782 return 'recording_skipped';
2783 }
2784 if (activeEndEvent && name === activeEndEvent) {
2785 mixpanelInstance.stop_session_recording();
2786 isRecording = false;
2787 activeEndEvent = null;
2788 return 'recording_stopped';
2789 }
2790 return null;
2791 }
2792 function getIsRecording() {
2793 return isRecording;
2794 }
2795
2796 /***/ }),
2797
2798 /***/ "../core/common/modules/finder/assets/js/commands/index.js":
2799 /*!*****************************************************************!*\
2800 !*** ../core/common/modules/finder/assets/js/commands/index.js ***!
2801 \*****************************************************************/
2802 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2803
2804 "use strict";
2805
2806
2807 Object.defineProperty(exports, "__esModule", ({
2808 value: true
2809 }));
2810 Object.defineProperty(exports, "NavigateDown", ({
2811 enumerable: true,
2812 get: function get() {
2813 return _navigateDown.NavigateDown;
2814 }
2815 }));
2816 Object.defineProperty(exports, "NavigateSelect", ({
2817 enumerable: true,
2818 get: function get() {
2819 return _navigateSelect.NavigateSelect;
2820 }
2821 }));
2822 Object.defineProperty(exports, "NavigateUp", ({
2823 enumerable: true,
2824 get: function get() {
2825 return _navigateUp.NavigateUp;
2826 }
2827 }));
2828 var _navigateDown = __webpack_require__(/*! ./navigate-down */ "../core/common/modules/finder/assets/js/commands/navigate-down.js");
2829 var _navigateSelect = __webpack_require__(/*! ./navigate-select */ "../core/common/modules/finder/assets/js/commands/navigate-select.js");
2830 var _navigateUp = __webpack_require__(/*! ./navigate-up */ "../core/common/modules/finder/assets/js/commands/navigate-up.js");
2831
2832 /***/ }),
2833
2834 /***/ "../core/common/modules/finder/assets/js/commands/navigate-down.js":
2835 /*!*************************************************************************!*\
2836 !*** ../core/common/modules/finder/assets/js/commands/navigate-down.js ***!
2837 \*************************************************************************/
2838 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2839
2840 "use strict";
2841
2842
2843 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2844 Object.defineProperty(exports, "__esModule", ({
2845 value: true
2846 }));
2847 exports["default"] = exports.NavigateDown = void 0;
2848 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2849 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2850 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2851 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2852 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2853 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2854 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)); }
2855 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2856 var NavigateDown = exports.NavigateDown = /*#__PURE__*/function (_CommandBase) {
2857 function NavigateDown() {
2858 (0, _classCallCheck2.default)(this, NavigateDown);
2859 return _callSuper(this, NavigateDown, arguments);
2860 }
2861 (0, _inherits2.default)(NavigateDown, _CommandBase);
2862 return (0, _createClass2.default)(NavigateDown, [{
2863 key: "apply",
2864 value: function apply() {
2865 this.component.getItemsView().activateNextItem();
2866 }
2867 }]);
2868 }(_commandBase.default);
2869 var _default = exports["default"] = NavigateDown;
2870
2871 /***/ }),
2872
2873 /***/ "../core/common/modules/finder/assets/js/commands/navigate-select.js":
2874 /*!***************************************************************************!*\
2875 !*** ../core/common/modules/finder/assets/js/commands/navigate-select.js ***!
2876 \***************************************************************************/
2877 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2878
2879 "use strict";
2880
2881
2882 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2883 Object.defineProperty(exports, "__esModule", ({
2884 value: true
2885 }));
2886 exports["default"] = exports.NavigateSelect = void 0;
2887 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2888 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2889 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2890 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2891 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2892 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2893 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)); }
2894 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2895 var NavigateSelect = exports.NavigateSelect = /*#__PURE__*/function (_CommandBase) {
2896 function NavigateSelect() {
2897 (0, _classCallCheck2.default)(this, NavigateSelect);
2898 return _callSuper(this, NavigateSelect, arguments);
2899 }
2900 (0, _inherits2.default)(NavigateSelect, _CommandBase);
2901 return (0, _createClass2.default)(NavigateSelect, [{
2902 key: "apply",
2903 value: function apply(args) {
2904 this.component.getItemsView().goToActiveItem(args);
2905 }
2906 }]);
2907 }(_commandBase.default);
2908 var _default = exports["default"] = NavigateSelect;
2909
2910 /***/ }),
2911
2912 /***/ "../core/common/modules/finder/assets/js/commands/navigate-up.js":
2913 /*!***********************************************************************!*\
2914 !*** ../core/common/modules/finder/assets/js/commands/navigate-up.js ***!
2915 \***********************************************************************/
2916 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2917
2918 "use strict";
2919
2920
2921 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2922 Object.defineProperty(exports, "__esModule", ({
2923 value: true
2924 }));
2925 exports["default"] = exports.NavigateUp = void 0;
2926 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2927 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2928 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2929 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2930 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2931 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
2932 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)); }
2933 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2934 var NavigateUp = exports.NavigateUp = /*#__PURE__*/function (_CommandBase) {
2935 function NavigateUp() {
2936 (0, _classCallCheck2.default)(this, NavigateUp);
2937 return _callSuper(this, NavigateUp, arguments);
2938 }
2939 (0, _inherits2.default)(NavigateUp, _CommandBase);
2940 return (0, _createClass2.default)(NavigateUp, [{
2941 key: "apply",
2942 value: function apply() {
2943 this.component.getItemsView().activateNextItem(true);
2944 }
2945 }]);
2946 }(_commandBase.default);
2947 var _default = exports["default"] = NavigateUp;
2948
2949 /***/ }),
2950
2951 /***/ "../core/common/modules/finder/assets/js/component.js":
2952 /*!************************************************************!*\
2953 !*** ../core/common/modules/finder/assets/js/component.js ***!
2954 \************************************************************/
2955 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
2956
2957 "use strict";
2958
2959
2960 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
2961 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
2962 Object.defineProperty(exports, "__esModule", ({
2963 value: true
2964 }));
2965 exports["default"] = void 0;
2966 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
2967 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
2968 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
2969 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
2970 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
2971 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
2972 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
2973 var _componentModalBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/component-modal-base */ "../modules/web-cli/assets/js/modules/component-modal-base.js"));
2974 var _layout = _interopRequireDefault(__webpack_require__(/*! ./modal/views/layout */ "../core/common/modules/finder/assets/js/modal/views/layout.js"));
2975 var commands = _interopRequireWildcard(__webpack_require__(/*! ./commands/ */ "../core/common/modules/finder/assets/js/commands/index.js"));
2976 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); }
2977 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; }
2978 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; }
2979 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)); }
2980 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
2981 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; }
2982 var Component = exports["default"] = /*#__PURE__*/function (_ComponentModalBase) {
2983 function Component() {
2984 (0, _classCallCheck2.default)(this, Component);
2985 return _callSuper(this, Component, arguments);
2986 }
2987 (0, _inherits2.default)(Component, _ComponentModalBase);
2988 return (0, _createClass2.default)(Component, [{
2989 key: "getNamespace",
2990 value: function getNamespace() {
2991 return 'finder';
2992 }
2993 }, {
2994 key: "defaultShortcuts",
2995 value: function defaultShortcuts() {
2996 var _this = this;
2997 return {
2998 '': {
2999 keys: 'ctrl+e'
3000 },
3001 'navigate-down': {
3002 keys: 'down',
3003 scopes: [this.getNamespace()],
3004 dependency: function dependency() {
3005 return _this.getItemsView();
3006 }
3007 },
3008 'navigate-up': {
3009 keys: 'up',
3010 scopes: [this.getNamespace()],
3011 dependency: function dependency() {
3012 return _this.getItemsView();
3013 }
3014 },
3015 'navigate-select': {
3016 keys: 'enter',
3017 scopes: [this.getNamespace()],
3018 dependency: function dependency() {
3019 return _this.getItemsView().$activeItem;
3020 }
3021 }
3022 };
3023 }
3024 }, {
3025 key: "defaultCommands",
3026 value: function defaultCommands() {
3027 var modalCommands = _superPropGet(Component, "defaultCommands", this, 3)([]);
3028 return _objectSpread(_objectSpread({
3029 'navigate/down': function navigate_down() {
3030 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/down' )", '3.0.0', "$e.run( 'finder/navigate-down' )");
3031 $e.run('finder/navigate-down');
3032 },
3033 'navigate/up': function navigate_up() {
3034 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/up' )", '3.0.0', "$e.run( 'finder/navigate-up' )");
3035 $e.run('finder/navigate-up');
3036 },
3037 'navigate/select': function navigate_select(event) {
3038 elementorDevTools.deprecation.deprecated("$e.run( 'finder/navigate/select', event )", '3.0.0', "$e.run( 'finder/navigate-select', event )");
3039
3040 // TODO: Fix $e.shortcuts use args. ( args.event ).
3041 $e.run('finder/navigate-select', event);
3042 }
3043 }, modalCommands), this.importCommands(commands));
3044 }
3045 }, {
3046 key: "getModalLayout",
3047 value: function getModalLayout() {
3048 return _layout.default;
3049 }
3050 }, {
3051 key: "getItemsView",
3052 value: function getItemsView() {
3053 return this.layout.modalContent.currentView.content.currentView;
3054 }
3055 }]);
3056 }(_componentModalBase.default);
3057
3058 /***/ }),
3059
3060 /***/ "../core/common/modules/finder/assets/js/finder.js":
3061 /*!*********************************************************!*\
3062 !*** ../core/common/modules/finder/assets/js/finder.js ***!
3063 \*********************************************************/
3064 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3065
3066 "use strict";
3067
3068
3069 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3070 Object.defineProperty(exports, "__esModule", ({
3071 value: true
3072 }));
3073 exports["default"] = void 0;
3074 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3075 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3076 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3077 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3078 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3079 var _component = _interopRequireDefault(__webpack_require__(/*! ./component */ "../core/common/modules/finder/assets/js/component.js"));
3080 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)); }
3081 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3082 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$Mod) {
3083 function _default() {
3084 (0, _classCallCheck2.default)(this, _default);
3085 return _callSuper(this, _default, arguments);
3086 }
3087 (0, _inherits2.default)(_default, _elementorModules$Mod);
3088 return (0, _createClass2.default)(_default, [{
3089 key: "onInit",
3090 value: function onInit() {
3091 // TODO: Temp fix, do not load finder in theme-builder.
3092 // Better to pass into '$e' constructor the app owner. ( admin, editor, preview, iframe ).
3093 if (window.top !== window) {
3094 return;
3095 }
3096 this.channel = Backbone.Radio.channel('ELEMENTOR:finder');
3097 $e.components.register(new _component.default({
3098 manager: this
3099 }));
3100 }
3101 }]);
3102 }(elementorModules.Module);
3103
3104 /***/ }),
3105
3106 /***/ "../core/common/modules/finder/assets/js/modal/model/item.js":
3107 /*!*******************************************************************!*\
3108 !*** ../core/common/modules/finder/assets/js/modal/model/item.js ***!
3109 \*******************************************************************/
3110 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3111
3112 "use strict";
3113
3114
3115 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3116 Object.defineProperty(exports, "__esModule", ({
3117 value: true
3118 }));
3119 exports["default"] = void 0;
3120 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3121 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3122 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3123 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3124 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3125 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)); }
3126 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3127 var _default = exports["default"] = /*#__PURE__*/function (_Backbone$Model) {
3128 function _default() {
3129 (0, _classCallCheck2.default)(this, _default);
3130 return _callSuper(this, _default, arguments);
3131 }
3132 (0, _inherits2.default)(_default, _Backbone$Model);
3133 return (0, _createClass2.default)(_default, [{
3134 key: "defaults",
3135 value: function defaults() {
3136 return {
3137 description: '',
3138 icon: 'settings',
3139 url: '',
3140 keywords: [],
3141 actions: [],
3142 lock: null
3143 };
3144 }
3145 }]);
3146 }(Backbone.Model);
3147
3148 /***/ }),
3149
3150 /***/ "../core/common/modules/finder/assets/js/modal/views/categories.js":
3151 /*!*************************************************************************!*\
3152 !*** ../core/common/modules/finder/assets/js/modal/views/categories.js ***!
3153 \*************************************************************************/
3154 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3155
3156 "use strict";
3157
3158
3159 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3160 Object.defineProperty(exports, "__esModule", ({
3161 value: true
3162 }));
3163 exports["default"] = void 0;
3164 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3165 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3166 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3167 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3168 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3169 var _category = _interopRequireDefault(__webpack_require__(/*! ./category */ "../core/common/modules/finder/assets/js/modal/views/category.js"));
3170 var _dynamicCategory = _interopRequireDefault(__webpack_require__(/*! ./dynamic-category */ "../core/common/modules/finder/assets/js/modal/views/dynamic-category.js"));
3171 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)); }
3172 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3173 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$Composite) {
3174 function _default() {
3175 (0, _classCallCheck2.default)(this, _default);
3176 return _callSuper(this, _default, arguments);
3177 }
3178 (0, _inherits2.default)(_default, _Marionette$Composite);
3179 return (0, _createClass2.default)(_default, [{
3180 key: "id",
3181 value: function id() {
3182 return 'elementor-finder__results-container';
3183 }
3184 }, {
3185 key: "ui",
3186 value: function ui() {
3187 this.selectors = {
3188 noResults: '#elementor-finder__no-results',
3189 categoryItem: '.elementor-finder__results__item'
3190 };
3191 return this.selectors;
3192 }
3193 }, {
3194 key: "events",
3195 value: function events() {
3196 return {
3197 'mouseenter @ui.categoryItem': 'onCategoryItemMouseEnter'
3198 };
3199 }
3200 }, {
3201 key: "getTemplate",
3202 value: function getTemplate() {
3203 return '#tmpl-elementor-finder-results-container';
3204 }
3205 }, {
3206 key: "getChildView",
3207 value: function getChildView(childModel) {
3208 return childModel.get('dynamic') ? _dynamicCategory.default : _category.default;
3209 }
3210 }, {
3211 key: "initialize",
3212 value: function initialize() {
3213 this.$activeItem = null;
3214 this.childViewContainer = '#elementor-finder__results';
3215 this.collection = new Backbone.Collection(Object.values(elementorCommon.finder.getSettings('data')));
3216 }
3217 }, {
3218 key: "activateItem",
3219 value: function activateItem($item) {
3220 if (this.$activeItem) {
3221 this.$activeItem.removeClass('elementor-active');
3222 }
3223 $item.addClass('elementor-active');
3224 this.$activeItem = $item;
3225 }
3226 }, {
3227 key: "activateNextItem",
3228 value: function activateNextItem(reverse) {
3229 var $allItems = jQuery(this.selectors.categoryItem);
3230 var nextItemIndex = 0;
3231 if (this.$activeItem) {
3232 nextItemIndex = $allItems.index(this.$activeItem) + (reverse ? -1 : 1);
3233 if (nextItemIndex >= $allItems.length) {
3234 nextItemIndex = 0;
3235 } else if (nextItemIndex < 0) {
3236 nextItemIndex = $allItems.length - 1;
3237 }
3238 }
3239 var $nextItem = $allItems.eq(nextItemIndex);
3240 this.activateItem($nextItem);
3241 $nextItem[0].scrollIntoView({
3242 block: 'nearest'
3243 });
3244 }
3245 }, {
3246 key: "goToActiveItem",
3247 value: function goToActiveItem(event) {
3248 var $a = this.$activeItem.children('a'),
3249 isControlClicked = $e.shortcuts.isControlEvent(event);
3250 if (isControlClicked) {
3251 $a.attr('target', '_blank');
3252 }
3253 $a[0].click();
3254 if (isControlClicked) {
3255 $a.removeAttr('target');
3256 }
3257 }
3258 }, {
3259 key: "onCategoryItemMouseEnter",
3260 value: function onCategoryItemMouseEnter(event) {
3261 this.activateItem(jQuery(event.currentTarget));
3262 }
3263 }, {
3264 key: "onChildviewToggleVisibility",
3265 value: function onChildviewToggleVisibility() {
3266 var allCategoriesAreEmpty = this.children.every(function (child) {
3267 return !child.isVisible;
3268 });
3269 this.ui.noResults.toggle(allCategoriesAreEmpty);
3270 }
3271 }]);
3272 }(Marionette.CompositeView);
3273
3274 /***/ }),
3275
3276 /***/ "../core/common/modules/finder/assets/js/modal/views/category.js":
3277 /*!***********************************************************************!*\
3278 !*** ../core/common/modules/finder/assets/js/modal/views/category.js ***!
3279 \***********************************************************************/
3280 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3281
3282 "use strict";
3283
3284
3285 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3286 Object.defineProperty(exports, "__esModule", ({
3287 value: true
3288 }));
3289 exports["default"] = void 0;
3290 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3291 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3292 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3293 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3294 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3295 var _item = _interopRequireDefault(__webpack_require__(/*! ./item */ "../core/common/modules/finder/assets/js/modal/views/item.js"));
3296 var _item2 = _interopRequireDefault(__webpack_require__(/*! ../model/item */ "../core/common/modules/finder/assets/js/modal/model/item.js"));
3297 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)); }
3298 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3299 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$Composite) {
3300 function _default() {
3301 (0, _classCallCheck2.default)(this, _default);
3302 return _callSuper(this, _default, arguments);
3303 }
3304 (0, _inherits2.default)(_default, _Marionette$Composite);
3305 return (0, _createClass2.default)(_default, [{
3306 key: "className",
3307 value: function className() {
3308 return 'elementor-finder__results__category';
3309 }
3310 }, {
3311 key: "getTemplate",
3312 value: function getTemplate() {
3313 return '#tmpl-elementor-finder__results__category';
3314 }
3315 }, {
3316 key: "getChildView",
3317 value: function getChildView() {
3318 return _item.default;
3319 }
3320 }, {
3321 key: "initialize",
3322 value: function initialize() {
3323 this.childViewContainer = '.elementor-finder__results__category__items';
3324 this.isVisible = true;
3325 var items = this.model.get('items');
3326 if (items) {
3327 items = Object.values(items);
3328 }
3329 this.collection = new Backbone.Collection(items, {
3330 model: _item2.default
3331 });
3332 }
3333 }, {
3334 key: "filter",
3335 value: function filter(childModel) {
3336 var textFilter = this.getTextFilter();
3337 if (childModel.get('title').toLowerCase().indexOf(textFilter) >= 0) {
3338 return true;
3339 }
3340 return childModel.get('keywords').some(function (keyword) {
3341 return keyword.indexOf(textFilter) >= 0;
3342 });
3343 }
3344 }, {
3345 key: "getTextFilter",
3346 value: function getTextFilter() {
3347 return elementorCommon.finder.channel.request('filter:text').trim().toLowerCase();
3348 }
3349 }, {
3350 key: "toggleElement",
3351 value: function toggleElement() {
3352 var isCurrentlyVisible = !!this.children.length;
3353 if (isCurrentlyVisible !== this.isVisible) {
3354 this.isVisible = isCurrentlyVisible;
3355 this.$el.toggle(isCurrentlyVisible);
3356 this.triggerMethod('toggle:visibility');
3357 }
3358 }
3359 }, {
3360 key: "onRender",
3361 value: function onRender() {
3362 this.listenTo(elementorCommon.finder.channel, 'filter:change', this.onFilterChange.bind(this));
3363 }
3364 }, {
3365 key: "onFilterChange",
3366 value: function onFilterChange() {
3367 this._renderChildren();
3368 }
3369 }, {
3370 key: "onRenderCollection",
3371 value: function onRenderCollection() {
3372 this.toggleElement();
3373 }
3374 }]);
3375 }(Marionette.CompositeView);
3376
3377 /***/ }),
3378
3379 /***/ "../core/common/modules/finder/assets/js/modal/views/content.js":
3380 /*!**********************************************************************!*\
3381 !*** ../core/common/modules/finder/assets/js/modal/views/content.js ***!
3382 \**********************************************************************/
3383 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3384
3385 "use strict";
3386
3387
3388 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3389 Object.defineProperty(exports, "__esModule", ({
3390 value: true
3391 }));
3392 exports["default"] = void 0;
3393 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3394 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3395 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3396 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3397 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3398 var _categories = _interopRequireDefault(__webpack_require__(/*! ./categories */ "../core/common/modules/finder/assets/js/modal/views/categories.js"));
3399 var _editorOneEvents = __webpack_require__(/*! elementor-editor-utils/editor-one-events */ "../assets/dev/js/editor/utils/editor-one-events.js");
3400 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)); }
3401 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3402 var FINDER_SEARCH_DEBOUNCE_MS = 300;
3403 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$LayoutVie) {
3404 function _default() {
3405 (0, _classCallCheck2.default)(this, _default);
3406 return _callSuper(this, _default, arguments);
3407 }
3408 (0, _inherits2.default)(_default, _Marionette$LayoutVie);
3409 return (0, _createClass2.default)(_default, [{
3410 key: "id",
3411 value: function id() {
3412 return 'elementor-finder';
3413 }
3414 }, {
3415 key: "getTemplate",
3416 value: function getTemplate() {
3417 return '#tmpl-elementor-finder';
3418 }
3419 }, {
3420 key: "ui",
3421 value: function ui() {
3422 return {
3423 searchInput: '#elementor-finder__search__input'
3424 };
3425 }
3426 }, {
3427 key: "events",
3428 value: function events() {
3429 return {
3430 'input @ui.searchInput': 'onSearchInputInput'
3431 };
3432 }
3433 }, {
3434 key: "regions",
3435 value: function regions() {
3436 return {
3437 content: '#elementor-finder__content'
3438 };
3439 }
3440 }, {
3441 key: "initialize",
3442 value: function initialize() {
3443 this.debouncedTrackSearch = (0, _editorOneEvents.createDebouncedFinderSearch)(FINDER_SEARCH_DEBOUNCE_MS);
3444 }
3445 }, {
3446 key: "showCategoriesView",
3447 value: function showCategoriesView() {
3448 this.content.show(new _categories.default());
3449 }
3450 }, {
3451 key: "getResultsCount",
3452 value: function getResultsCount() {
3453 if (!this.content.currentView) {
3454 return 0;
3455 }
3456 var $visibleItems = this.content.currentView.$el.find('.elementor-finder__results__item:visible');
3457 return $visibleItems.length;
3458 }
3459 }, {
3460 key: "onSearchInputInput",
3461 value: function onSearchInputInput() {
3462 var _this = this;
3463 var value = this.ui.searchInput.val();
3464 if (value) {
3465 elementorCommon.finder.channel.reply('filter:text', value).trigger('filter:change');
3466 if (!(this.content.currentView instanceof _categories.default)) {
3467 this.showCategoriesView();
3468 }
3469 setTimeout(function () {
3470 var resultsCount = _this.getResultsCount();
3471 _this.debouncedTrackSearch(resultsCount, value);
3472 }, 50);
3473 }
3474 this.content.currentView.$el.toggle(!!value);
3475 }
3476 }, {
3477 key: "onDestroy",
3478 value: function onDestroy() {
3479 var _this$debouncedTrackS;
3480 if ((_this$debouncedTrackS = this.debouncedTrackSearch) !== null && _this$debouncedTrackS !== void 0 && _this$debouncedTrackS.cancel) {
3481 this.debouncedTrackSearch.cancel();
3482 }
3483 }
3484 }]);
3485 }(Marionette.LayoutView);
3486
3487 /***/ }),
3488
3489 /***/ "../core/common/modules/finder/assets/js/modal/views/dynamic-category.js":
3490 /*!*******************************************************************************!*\
3491 !*** ../core/common/modules/finder/assets/js/modal/views/dynamic-category.js ***!
3492 \*******************************************************************************/
3493 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3494
3495 "use strict";
3496
3497
3498 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3499 Object.defineProperty(exports, "__esModule", ({
3500 value: true
3501 }));
3502 exports["default"] = void 0;
3503 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3504 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3505 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3506 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3507 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
3508 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3509 var _category = _interopRequireDefault(__webpack_require__(/*! ./category */ "../core/common/modules/finder/assets/js/modal/views/category.js"));
3510 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)); }
3511 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3512 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; }
3513 var _default = exports["default"] = /*#__PURE__*/function (_Category) {
3514 function _default() {
3515 (0, _classCallCheck2.default)(this, _default);
3516 return _callSuper(this, _default, arguments);
3517 }
3518 (0, _inherits2.default)(_default, _Category);
3519 return (0, _createClass2.default)(_default, [{
3520 key: "className",
3521 value: function className() {
3522 return _superPropGet(_default, "className", this, 3)([]) + ' elementor-finder__results__category--dynamic';
3523 }
3524 }, {
3525 key: "ui",
3526 value: function ui() {
3527 return {
3528 title: '.elementor-finder__results__category__title'
3529 };
3530 }
3531 }, {
3532 key: "fetchData",
3533 value: function fetchData() {
3534 var _this = this;
3535 this.ui.loadingIcon.show();
3536 elementorCommon.ajax.addRequest('finder_get_category_items', {
3537 data: {
3538 category: this.model.get('name'),
3539 filter: this.getTextFilter()
3540 },
3541 success: function success(data) {
3542 if (_this.isDestroyed) {
3543 return;
3544 }
3545 _this.collection.set(data);
3546 _this.toggleElement();
3547 _this.ui.loadingIcon.hide();
3548 }
3549 });
3550 }
3551 }, {
3552 key: "filter",
3553 value: function filter() {
3554 return true;
3555 }
3556 }, {
3557 key: "onFilterChange",
3558 value: function onFilterChange() {
3559 this.fetchData();
3560 }
3561 }, {
3562 key: "onRender",
3563 value: function onRender() {
3564 _superPropGet(_default, "onRender", this, 3)([]);
3565 this.ui.loadingIcon = jQuery('<i>', {
3566 class: 'eicon-loading eicon-animation-spin'
3567 });
3568 this.ui.title.after(this.ui.loadingIcon);
3569 this.fetchData();
3570 }
3571 }]);
3572 }(_category.default);
3573
3574 /***/ }),
3575
3576 /***/ "../core/common/modules/finder/assets/js/modal/views/item.js":
3577 /*!*******************************************************************!*\
3578 !*** ../core/common/modules/finder/assets/js/modal/views/item.js ***!
3579 \*******************************************************************/
3580 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3581
3582 "use strict";
3583 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
3584
3585
3586 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3587 Object.defineProperty(exports, "__esModule", ({
3588 value: true
3589 }));
3590 exports["default"] = void 0;
3591 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3592 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3593 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3594 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3595 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3596 var _editorOneEvents = __webpack_require__(/*! elementor-editor-utils/editor-one-events */ "../assets/dev/js/editor/utils/editor-one-events.js");
3597 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)); }
3598 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3599 var _default = exports["default"] = /*#__PURE__*/function (_Marionette$ItemView) {
3600 function _default() {
3601 (0, _classCallCheck2.default)(this, _default);
3602 return _callSuper(this, _default, arguments);
3603 }
3604 (0, _inherits2.default)(_default, _Marionette$ItemView);
3605 return (0, _createClass2.default)(_default, [{
3606 key: "className",
3607 value: function className() {
3608 return 'elementor-finder__results__item';
3609 }
3610 }, {
3611 key: "getTemplate",
3612 value: function getTemplate() {
3613 return '#tmpl-elementor-finder__results__item';
3614 }
3615 }, {
3616 key: "events",
3617 value: function events() {
3618 this.$el[0].addEventListener('click', this.onClick.bind(this), true);
3619 }
3620 }, {
3621 key: "trackResultSelect",
3622 value: function trackResultSelect() {
3623 var title = this.model.get('title');
3624 _editorOneEvents.EditorOneEventManager.sendFinderResultSelect(title);
3625 }
3626 }, {
3627 key: "onClick",
3628 value: function onClick(e) {
3629 var _this = this;
3630 var lockOptions = this.model.get('lock');
3631 if (!(lockOptions !== null && lockOptions !== void 0 && lockOptions.is_locked)) {
3632 this.trackResultSelect();
3633 return;
3634 }
3635 e.preventDefault();
3636 e.stopImmediatePropagation();
3637 elementorCommon.dialogsManager.createWidget('confirm', {
3638 id: 'elementor-finder__lock-dialog',
3639 headerMessage: lockOptions.content.heading,
3640 message: lockOptions.content.description,
3641 position: {
3642 my: 'center center',
3643 at: 'center center'
3644 },
3645 strings: {
3646 confirm: lockOptions.button.text,
3647 cancel: __('Cancel', 'elementor')
3648 },
3649 onConfirm: function onConfirm() {
3650 _this.trackResultSelect();
3651 var link = _this.replaceLockLinkPlaceholders(lockOptions.button.url);
3652 window.open(link, '_blank');
3653 }
3654 }).show();
3655 }
3656 }, {
3657 key: "replaceLockLinkPlaceholders",
3658 value: function replaceLockLinkPlaceholders(link) {
3659 return link.replace(/%%utm_source%%/g, 'finder').replace(/%%utm_medium%%/g, 'wp-dash');
3660 }
3661 }]);
3662 }(Marionette.ItemView);
3663
3664 /***/ }),
3665
3666 /***/ "../core/common/modules/finder/assets/js/modal/views/layout.js":
3667 /*!*********************************************************************!*\
3668 !*** ../core/common/modules/finder/assets/js/modal/views/layout.js ***!
3669 \*********************************************************************/
3670 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3671
3672 "use strict";
3673 /* provided dependency */ var __ = __webpack_require__(/*! @wordpress/i18n */ "@wordpress/i18n")["__"];
3674
3675
3676 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3677 Object.defineProperty(exports, "__esModule", ({
3678 value: true
3679 }));
3680 exports["default"] = void 0;
3681 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3682 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3683 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3684 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3685 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
3686 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3687 var _content = _interopRequireDefault(__webpack_require__(/*! ./content */ "../core/common/modules/finder/assets/js/modal/views/content.js"));
3688 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)); }
3689 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3690 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; }
3691 var _default = exports["default"] = /*#__PURE__*/function (_elementorModules$com) {
3692 function _default() {
3693 (0, _classCallCheck2.default)(this, _default);
3694 return _callSuper(this, _default, arguments);
3695 }
3696 (0, _inherits2.default)(_default, _elementorModules$com);
3697 return (0, _createClass2.default)(_default, [{
3698 key: "getModalOptions",
3699 value: function getModalOptions() {
3700 return {
3701 id: 'elementor-finder__modal',
3702 draggable: true,
3703 effects: {
3704 show: 'show',
3705 hide: 'hide'
3706 },
3707 position: {
3708 enable: false
3709 }
3710 };
3711 }
3712 }, {
3713 key: "getLogoOptions",
3714 value: function getLogoOptions() {
3715 return {
3716 title: __('Finder', 'elementor')
3717 };
3718 }
3719 }, {
3720 key: "initialize",
3721 value: function initialize() {
3722 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
3723 args[_key] = arguments[_key];
3724 }
3725 _superPropGet(_default, "initialize", this, 3)(args);
3726 this.showLogo();
3727 this.showContentView();
3728 }
3729 }, {
3730 key: "showContentView",
3731 value: function showContentView() {
3732 this.modalContent.show(new _content.default());
3733 }
3734 }, {
3735 key: "showModal",
3736 value: function showModal() {
3737 for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
3738 args[_key2] = arguments[_key2];
3739 }
3740 _superPropGet(_default, "showModal", this, 3)(args);
3741 this.modalContent.currentView.ui.searchInput.focus();
3742 }
3743 }]);
3744 }(elementorModules.common.views.modal.Layout);
3745
3746 /***/ }),
3747
3748 /***/ "../modules/web-cli/assets/js/core/data/errors/base-error.js":
3749 /*!*******************************************************************!*\
3750 !*** ../modules/web-cli/assets/js/core/data/errors/base-error.js ***!
3751 \*******************************************************************/
3752 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3753
3754 "use strict";
3755
3756
3757 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3758 Object.defineProperty(exports, "__esModule", ({
3759 value: true
3760 }));
3761 exports["default"] = void 0;
3762 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3763 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3764 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3765 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3766 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3767 var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js"));
3768 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
3769 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
3770 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../../../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
3771 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; }
3772 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; }
3773 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)); }
3774 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3775 var BaseError = exports["default"] = /*#__PURE__*/function (_Error) {
3776 /**
3777 * Error constructor.
3778 *
3779 * @param {string} message
3780 * @param {string} code
3781 * @param {*} data
3782 */
3783 function BaseError() {
3784 var _this;
3785 var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
3786 var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
3787 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
3788 (0, _classCallCheck2.default)(this, BaseError);
3789 _this = _callSuper(this, BaseError, [message]);
3790 /**
3791 * The server error code.
3792 *
3793 * @type {string}
3794 */
3795 (0, _defineProperty2.default)(_this, "code", '');
3796 /**
3797 * Additional data about the current error.
3798 *
3799 * @type {*[]}
3800 */
3801 (0, _defineProperty2.default)(_this, "data", []);
3802 _this.code = code;
3803 _this.data = data;
3804 return _this;
3805 }
3806
3807 /**
3808 * Notify a message when the error occurs.
3809 */
3810 (0, _inherits2.default)(BaseError, _Error);
3811 return (0, _createClass2.default)(BaseError, [{
3812 key: "notify",
3813 value: function notify() {
3814 _console.default.error(_objectSpread({
3815 message: this.message
3816 }, this));
3817 }
3818 }], [{
3819 key: "create",
3820 value:
3821 /**
3822 * Static helper function to create the error.
3823 *
3824 * @param {string} message
3825 * @param {string} code
3826 * @param {*} data
3827 * @return {BaseError} error
3828 */
3829 function create(message) {
3830 var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
3831 var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
3832 return new this(message, code, data);
3833 }
3834
3835 /**
3836 * Returns the status code of the error.
3837 */
3838 }, {
3839 key: "getHTTPErrorCode",
3840 value: function getHTTPErrorCode() {
3841 (0, _forceMethodImplementation.default)();
3842 }
3843 }]);
3844 }(/*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
3845
3846 /***/ }),
3847
3848 /***/ "../modules/web-cli/assets/js/core/data/errors/default-error.js":
3849 /*!**********************************************************************!*\
3850 !*** ../modules/web-cli/assets/js/core/data/errors/default-error.js ***!
3851 \**********************************************************************/
3852 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3853
3854 "use strict";
3855
3856
3857 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3858 Object.defineProperty(exports, "__esModule", ({
3859 value: true
3860 }));
3861 exports["default"] = exports.DefaultError = void 0;
3862 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3863 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3864 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3865 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3866 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3867 var _baseError = _interopRequireDefault(__webpack_require__(/*! ./base-error */ "../modules/web-cli/assets/js/core/data/errors/base-error.js"));
3868 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)); }
3869 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3870 var DefaultError = exports.DefaultError = /*#__PURE__*/function (_BaseError) {
3871 function DefaultError() {
3872 (0, _classCallCheck2.default)(this, DefaultError);
3873 return _callSuper(this, DefaultError, arguments);
3874 }
3875 (0, _inherits2.default)(DefaultError, _BaseError);
3876 return (0, _createClass2.default)(DefaultError, null, [{
3877 key: "getHTTPErrorCode",
3878 value: function getHTTPErrorCode() {
3879 return 501;
3880 }
3881 }]);
3882 }(_baseError.default);
3883 var _default = exports["default"] = DefaultError;
3884
3885 /***/ }),
3886
3887 /***/ "../modules/web-cli/assets/js/core/data/errors/error-404.js":
3888 /*!******************************************************************!*\
3889 !*** ../modules/web-cli/assets/js/core/data/errors/error-404.js ***!
3890 \******************************************************************/
3891 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3892
3893 "use strict";
3894
3895
3896 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3897 Object.defineProperty(exports, "__esModule", ({
3898 value: true
3899 }));
3900 exports["default"] = exports.Error404 = void 0;
3901 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3902 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3903 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3904 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3905 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3906 var _baseError = _interopRequireDefault(__webpack_require__(/*! ./base-error */ "../modules/web-cli/assets/js/core/data/errors/base-error.js"));
3907 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
3908 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)); }
3909 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3910 var Error404 = exports.Error404 = /*#__PURE__*/function (_BaseError) {
3911 function Error404() {
3912 (0, _classCallCheck2.default)(this, Error404);
3913 return _callSuper(this, Error404, arguments);
3914 }
3915 (0, _inherits2.default)(Error404, _BaseError);
3916 return (0, _createClass2.default)(Error404, [{
3917 key: "notify",
3918 value: function notify() {
3919 _console.default.warn(this.message);
3920 }
3921 }], [{
3922 key: "getHTTPErrorCode",
3923 value: function getHTTPErrorCode() {
3924 return 404;
3925 }
3926 }]);
3927 }(_baseError.default);
3928 var _default = exports["default"] = Error404;
3929
3930 /***/ }),
3931
3932 /***/ "../modules/web-cli/assets/js/core/data/errors/index.js":
3933 /*!**************************************************************!*\
3934 !*** ../modules/web-cli/assets/js/core/data/errors/index.js ***!
3935 \**************************************************************/
3936 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3937
3938 "use strict";
3939
3940
3941 Object.defineProperty(exports, "__esModule", ({
3942 value: true
3943 }));
3944 Object.defineProperty(exports, "DefaultError", ({
3945 enumerable: true,
3946 get: function get() {
3947 return _defaultError.DefaultError;
3948 }
3949 }));
3950 Object.defineProperty(exports, "Error404", ({
3951 enumerable: true,
3952 get: function get() {
3953 return _error.Error404;
3954 }
3955 }));
3956 var _defaultError = __webpack_require__(/*! ./default-error */ "../modules/web-cli/assets/js/core/data/errors/default-error.js");
3957 var _error = __webpack_require__(/*! ./error-404 */ "../modules/web-cli/assets/js/core/data/errors/error-404.js");
3958
3959 /***/ }),
3960
3961 /***/ "../modules/web-cli/assets/js/modules/command-base.js":
3962 /*!************************************************************!*\
3963 !*** ../modules/web-cli/assets/js/modules/command-base.js ***!
3964 \************************************************************/
3965 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
3966
3967 "use strict";
3968
3969
3970 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
3971 Object.defineProperty(exports, "__esModule", ({
3972 value: true
3973 }));
3974 exports["default"] = void 0;
3975 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
3976 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
3977 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
3978 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
3979 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
3980 var _commandInfra = _interopRequireDefault(__webpack_require__(/*! ./command-infra */ "../modules/web-cli/assets/js/modules/command-infra.js"));
3981 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
3982 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)); }
3983 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
3984 /**
3985 * @name $e.modules.CommandBase
3986 */
3987 var CommandBase = exports["default"] = /*#__PURE__*/function (_CommandInfra) {
3988 function CommandBase() {
3989 (0, _classCallCheck2.default)(this, CommandBase);
3990 return _callSuper(this, CommandBase, arguments);
3991 }
3992 (0, _inherits2.default)(CommandBase, _CommandInfra);
3993 return (0, _createClass2.default)(CommandBase, [{
3994 key: "onBeforeRun",
3995 value: function onBeforeRun() {
3996 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3997 $e.hooks.runUIBefore(this.command, args);
3998 }
3999 }, {
4000 key: "onAfterRun",
4001 value: function onAfterRun() {
4002 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4003 var result = arguments.length > 1 ? arguments[1] : undefined;
4004 $e.hooks.runUIAfter(this.command, args, result);
4005 }
4006 }, {
4007 key: "onBeforeApply",
4008 value: function onBeforeApply() {
4009 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4010 $e.hooks.runDataDependency(this.command, args);
4011 }
4012 }, {
4013 key: "onAfterApply",
4014 value: function onAfterApply() {
4015 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4016 var result = arguments.length > 1 ? arguments[1] : undefined;
4017 return $e.hooks.runDataAfter(this.command, args, result);
4018 }
4019 }, {
4020 key: "onCatchApply",
4021 value: function onCatchApply(e) {
4022 this.runCatchHooks(e);
4023 }
4024
4025 /**
4026 * Run all the catch hooks.
4027 *
4028 * @param {Error} e
4029 */
4030 }, {
4031 key: "runCatchHooks",
4032 value: function runCatchHooks(e) {
4033 $e.hooks.runDataCatch(this.command, this.args, e);
4034 $e.hooks.runUICatch(this.command, this.args, e);
4035 }
4036
4037 /**
4038 * TODO - Remove - Backwards compatibility.
4039 *
4040 * Function requireContainer().
4041 *
4042 * Validate `arg.container` & `arg.containers`.
4043 *
4044 * @param {{}} args
4045 * @deprecated since 3.7.0, extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase` instead.
4046 *
4047 * @throws {Error}
4048 */
4049 }, {
4050 key: "requireContainer",
4051 value: function requireContainer() {
4052 var _this = this;
4053 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.args;
4054 _deprecation.default.deprecated('requireContainer()', '3.7.0', 'Extend `$e.modules.editor.CommandContainerBase` or `$e.modules.editor.CommandContainerInternalBase`');
4055 if (!args.container && !args.containers) {
4056 throw Error('container or containers are required.');
4057 }
4058 if (args.container && args.containers) {
4059 throw Error('container and containers cannot go together please select one of them.');
4060 }
4061 var containers = args.containers || [args.container];
4062 containers.forEach(function (container) {
4063 _this.requireArgumentInstance('container', elementorModules.editor.Container, {
4064 container: container
4065 });
4066 });
4067 }
4068 }], [{
4069 key: "getInstanceType",
4070 value: function getInstanceType() {
4071 return 'CommandBase';
4072 }
4073 }]);
4074 }(_commandInfra.default);
4075
4076 /***/ }),
4077
4078 /***/ "../modules/web-cli/assets/js/modules/command-callback-base.js":
4079 /*!*********************************************************************!*\
4080 !*** ../modules/web-cli/assets/js/modules/command-callback-base.js ***!
4081 \*********************************************************************/
4082 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4083
4084 "use strict";
4085
4086
4087 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4088 Object.defineProperty(exports, "__esModule", ({
4089 value: true
4090 }));
4091 exports["default"] = void 0;
4092 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4093 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4094 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4095 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4096 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4097 var _commandBase = _interopRequireDefault(__webpack_require__(/*! ./command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4098 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)); }
4099 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4100 /**
4101 * To support pure callbacks in the API(commands.js), to ensure they have registered with the proper context.
4102 */
4103 var CommandCallbackBase = exports["default"] = /*#__PURE__*/function (_CommandBase) {
4104 function CommandCallbackBase() {
4105 (0, _classCallCheck2.default)(this, CommandCallbackBase);
4106 return _callSuper(this, CommandCallbackBase, arguments);
4107 }
4108 (0, _inherits2.default)(CommandCallbackBase, _CommandBase);
4109 return (0, _createClass2.default)(CommandCallbackBase, [{
4110 key: "apply",
4111 value: function apply() {
4112 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4113 return this.constructor.getCallback()(args);
4114 }
4115 }], [{
4116 key: "getInstanceType",
4117 value: function getInstanceType() {
4118 return 'CommandCallbackBase';
4119 }
4120
4121 /**
4122 * Get original callback of the command.
4123 *
4124 * Support pure callbacks ( Non command-base ).
4125 *
4126 * @return {()=>{}} Command Results.
4127 */
4128 }, {
4129 key: "getCallback",
4130 value: function getCallback() {
4131 return this.registerConfig.callback;
4132 }
4133 }]);
4134 }(_commandBase.default);
4135
4136 /***/ }),
4137
4138 /***/ "../modules/web-cli/assets/js/modules/command-data.js":
4139 /*!************************************************************!*\
4140 !*** ../modules/web-cli/assets/js/modules/command-data.js ***!
4141 \************************************************************/
4142 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4143
4144 "use strict";
4145
4146
4147 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4148 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
4149 Object.defineProperty(exports, "__esModule", ({
4150 value: true
4151 }));
4152 exports["default"] = void 0;
4153 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4154 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4155 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4156 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4157 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4158 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4159 var _commandBase = _interopRequireDefault(__webpack_require__(/*! ./command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4160 var errors = _interopRequireWildcard(__webpack_require__(/*! ../core/data/errors/ */ "../modules/web-cli/assets/js/core/data/errors/index.js"));
4161 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); }
4162 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)); }
4163 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4164 /**
4165 * @name $e.modules.CommandData
4166 */
4167 /**
4168 * @typedef {('create'|'delete'|'get'|'update'|'options')} DataTypes
4169 */
4170 /**
4171 * @typedef {{}} RequestData
4172 */
4173 /**
4174 * @typedef {import('../core/data/errors/base-error')} BaseError
4175 */
4176 var CommandData = exports["default"] = /*#__PURE__*/function (_CommandBase) {
4177 function CommandData(args) {
4178 var _this$args$options;
4179 var _this;
4180 var commandsAPI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : $e.data;
4181 (0, _classCallCheck2.default)(this, CommandData);
4182 _this = _callSuper(this, CommandData, [args, commandsAPI]);
4183 /**
4184 * Data returned from remote.
4185 *
4186 * @type {*}
4187 */
4188 (0, _defineProperty2.default)(_this, "data", void 0);
4189 /**
4190 * Fetch type.
4191 *
4192 * @type {DataTypes}
4193 */
4194 (0, _defineProperty2.default)(_this, "type", void 0);
4195 if ((_this$args$options = _this.args.options) !== null && _this$args$options !== void 0 && _this$args$options.type) {
4196 _this.type = _this.args.options.type;
4197 }
4198 return _this;
4199 }
4200
4201 /**
4202 * Function getEndpointFormat().
4203 *
4204 * @return {null|string} endpoint format
4205 */
4206 (0, _inherits2.default)(CommandData, _CommandBase);
4207 return (0, _createClass2.default)(CommandData, [{
4208 key: "getApplyMethods",
4209 value:
4210 /**
4211 * @param {DataTypes} type
4212 *
4213 * @return {boolean|{before: (function(*=): {}), after: (function({}, *=): {})}} apply methods
4214 */
4215 function getApplyMethods() {
4216 var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.type;
4217 var before, after;
4218 switch (type) {
4219 case 'create':
4220 before = this.applyBeforeCreate;
4221 after = this.applyAfterCreate;
4222 break;
4223 case 'delete':
4224 before = this.applyBeforeDelete;
4225 after = this.applyAfterDelete;
4226 break;
4227 case 'get':
4228 before = this.applyBeforeGet;
4229 after = this.applyAfterGet;
4230 break;
4231 case 'update':
4232 before = this.applyBeforeUpdate;
4233 after = this.applyAfterUpdate;
4234 break;
4235 case 'options':
4236 before = this.applyBeforeOptions;
4237 after = this.applyAfterOptions;
4238 break;
4239 default:
4240 return false;
4241 }
4242 return {
4243 before: before.bind(this),
4244 after: after.bind(this)
4245 };
4246 }
4247
4248 /**
4249 * Function getRequestData().
4250 *
4251 * @return {RequestData} request data
4252 */
4253 }, {
4254 key: "getRequestData",
4255 value: function getRequestData() {
4256 return {
4257 type: this.type,
4258 args: this.args,
4259 timestamp: new Date().getTime(),
4260 component: this.component,
4261 command: this.command,
4262 endpoint: $e.data.commandToEndpoint(this.command, JSON.parse(JSON.stringify(this.args)), this.constructor.getEndpointFormat())
4263 };
4264 }
4265 }, {
4266 key: "apply",
4267 value: function apply() {
4268 var _this2 = this;
4269 var applyMethods = this.getApplyMethods();
4270
4271 // Run 'before' method.
4272 this.args = applyMethods.before(this.args);
4273 var requestData = this.getRequestData();
4274 return $e.data.fetch(requestData).then(function (data) {
4275 _this2.data = data;
4276
4277 // Run 'after' method.
4278 _this2.data = applyMethods.after(data, _this2.args);
4279 _this2.data = {
4280 data: _this2.data
4281 };
4282
4283 // Append requestData.
4284 _this2.data = Object.assign({
4285 __requestData__: requestData
4286 }, _this2.data);
4287 return _this2.data;
4288 });
4289 }
4290
4291 /**
4292 * @param {*} [args={}]
4293 * @return {{}} filtered args
4294 */
4295 }, {
4296 key: "applyBeforeCreate",
4297 value: function applyBeforeCreate() {
4298 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4299 return args;
4300 }
4301
4302 /**
4303 * @param {{}} data
4304 * @param {*} [args={}]
4305 * @return {{}} filtered result
4306 */
4307 }, {
4308 key: "applyAfterCreate",
4309 value: function applyAfterCreate(data) {
4310 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4311 // eslint-disable-line no-unused-vars
4312 return data;
4313 }
4314
4315 /**
4316 * @param {*} [args={}]
4317 * @return {{}} filtered args
4318 */
4319 }, {
4320 key: "applyBeforeDelete",
4321 value: function applyBeforeDelete() {
4322 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4323 return args;
4324 }
4325
4326 /**
4327 * @param {{}} data
4328 * @param {*} [args={}]
4329 * @return {{}} filtered result
4330 */
4331 }, {
4332 key: "applyAfterDelete",
4333 value: function applyAfterDelete(data) {
4334 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4335 // eslint-disable-line no-unused-vars
4336 return data;
4337 }
4338
4339 /**
4340 * @param {*} [args={}]
4341 * @return {{}} filtered args
4342 */
4343 }, {
4344 key: "applyBeforeGet",
4345 value: function applyBeforeGet() {
4346 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4347 return args;
4348 }
4349
4350 /**
4351 * @param {{}} data
4352 * @param {*} [args={}]
4353 * @return {{}} filtered result
4354 */
4355 }, {
4356 key: "applyAfterGet",
4357 value: function applyAfterGet(data) {
4358 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4359 // eslint-disable-line no-unused-vars
4360 return data;
4361 }
4362
4363 /**
4364 * @param {*} [args={}]
4365 * @return {{}} filtered args
4366 */
4367 }, {
4368 key: "applyBeforeUpdate",
4369 value: function applyBeforeUpdate() {
4370 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4371 return args;
4372 }
4373
4374 /**
4375 * @param {{}} data
4376 * @param {*} [args={}]
4377 * @return {{}} filtered result
4378 */
4379 }, {
4380 key: "applyAfterUpdate",
4381 value: function applyAfterUpdate(data) {
4382 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4383 // eslint-disable-line no-unused-vars
4384 return data;
4385 }
4386
4387 /**
4388 * @param {*} [args={}]
4389 * @return {{}} filtered args
4390 */
4391 }, {
4392 key: "applyBeforeOptions",
4393 value: function applyBeforeOptions() {
4394 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4395 return args;
4396 }
4397
4398 /**
4399 * @param {{}} data
4400 * @param {*} [args={}]
4401 * @return {{}} filtered result
4402 */
4403 }, {
4404 key: "applyAfterOptions",
4405 value: function applyAfterOptions(data) {
4406 var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4407 // eslint-disable-line no-unused-vars
4408 return data;
4409 }
4410
4411 /**
4412 * @param {BaseError} e
4413 */
4414 }, {
4415 key: "applyAfterCatch",
4416 value: function applyAfterCatch(e) {
4417 e.notify();
4418 }
4419 }, {
4420 key: "onCatchApply",
4421 value: function onCatchApply(e) {
4422 var _e;
4423 // TODO: If the errors that returns from the server is consistent remove the '?' from 'e'
4424 var httpErrorCode = ((_e = e) === null || _e === void 0 || (_e = _e.data) === null || _e === void 0 ? void 0 : _e.status) || 501;
4425 var dataError = Object.values(errors).find(function (error) {
4426 return error.getHTTPErrorCode() === httpErrorCode;
4427 });
4428 if (!dataError) {
4429 dataError = errors.DefaultError;
4430 }
4431 e = dataError.create(e.message, e.code, e.data || []);
4432 this.runCatchHooks(e);
4433 this.applyAfterCatch(e);
4434 }
4435 }], [{
4436 key: "getInstanceType",
4437 value: function getInstanceType() {
4438 return 'CommandData';
4439 }
4440 }, {
4441 key: "getEndpointFormat",
4442 value: function getEndpointFormat() {
4443 return null;
4444 }
4445 }]);
4446 }(_commandBase.default);
4447
4448 /***/ }),
4449
4450 /***/ "../modules/web-cli/assets/js/modules/command-infra.js":
4451 /*!*************************************************************!*\
4452 !*** ../modules/web-cli/assets/js/modules/command-infra.js ***!
4453 \*************************************************************/
4454 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4455
4456 "use strict";
4457
4458
4459 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4460 Object.defineProperty(exports, "__esModule", ({
4461 value: true
4462 }));
4463 exports["default"] = void 0;
4464 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4465 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4466 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4467 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4468 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4469 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4470 var _argsObject = _interopRequireDefault(__webpack_require__(/*! elementor-assets-js/modules/imports/args-object */ "../assets/dev/js/modules/imports/args-object.js"));
4471 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
4472 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)); }
4473 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4474 /**
4475 * @typedef {import('../modules/component-base')} ComponentBase
4476 */
4477 var CommandInfra = exports["default"] = /*#__PURE__*/function (_ArgsObject) {
4478 /**
4479 * Function constructor().
4480 *
4481 * Create Commands Base.
4482 *
4483 * @param {{}} args
4484 */
4485 function CommandInfra() {
4486 var _this;
4487 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4488 (0, _classCallCheck2.default)(this, CommandInfra);
4489 _this = _callSuper(this, CommandInfra, [args]);
4490 if (!_this.constructor.registerConfig) {
4491 throw RangeError('Doing it wrong: Each command type should have `registerConfig`.');
4492 }
4493
4494 // Acknowledge self about which command it run.
4495 _this.command = _this.constructor.getCommand();
4496
4497 // Assign instance of current component.
4498 _this.component = _this.constructor.getComponent();
4499
4500 // Who ever need do something before without `super` the constructor can use `initialize` method.
4501 _this.initialize(args);
4502
4503 // Refresh args, maybe the changed via `initialize`.
4504 args = _this.args;
4505
4506 // Validate args before run.
4507 _this.validateArgs(args);
4508 return _this;
4509 }
4510
4511 /**
4512 * Function initialize().
4513 *
4514 * Initialize command, called after construction.
4515 *
4516 * @param {{}} args
4517 */
4518 (0, _inherits2.default)(CommandInfra, _ArgsObject);
4519 return (0, _createClass2.default)(CommandInfra, [{
4520 key: "currentCommand",
4521 get:
4522 /**
4523 * @deprecated since 3.7.0, use `this.command` instead.
4524 */
4525 function get() {
4526 _deprecation.default.deprecated('this.currentCommand', '3.7.0', 'this.command');
4527 return this.command;
4528 }
4529 }, {
4530 key: "initialize",
4531 value: function initialize() {
4532 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4533 } // eslint-disable-line no-unused-vars
4534
4535 /**
4536 * Function validateArgs().
4537 *
4538 * Validate command arguments.
4539 *
4540 * @param {{}} args
4541 */
4542 }, {
4543 key: "validateArgs",
4544 value: function validateArgs() {
4545 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4546 } // eslint-disable-line no-unused-vars
4547
4548 // eslint-disable-next-line jsdoc/require-returns-check
4549 /**
4550 * Function apply().
4551 *
4552 * Do the actual command.
4553 *
4554 * @param {{}} args
4555 *
4556 * @return {*} Command results.
4557 */
4558 }, {
4559 key: "apply",
4560 value: function apply() {
4561 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4562 // eslint-disable-line no-unused-vars
4563 elementorModules.ForceMethodImplementation();
4564 }
4565
4566 /**
4567 * Function run().
4568 *
4569 * Run command with history & hooks.
4570 *
4571 * @return {*} Command results.
4572 */
4573 }, {
4574 key: "run",
4575 value: function run() {
4576 return this.apply(this.args);
4577 }
4578
4579 /**
4580 * Function onBeforeRun.
4581 *
4582 * Called before run().
4583 *
4584 * @param {{}} args
4585 */
4586 }, {
4587 key: "onBeforeRun",
4588 value: function onBeforeRun() {
4589 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4590 } // eslint-disable-line no-unused-vars
4591
4592 /**
4593 * Function onAfterRun.
4594 *
4595 * Called after run().
4596 *
4597 * @param {{}} args
4598 * @param {*} result
4599 */
4600 }, {
4601 key: "onAfterRun",
4602 value: function onAfterRun() {
4603 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4604 var result = arguments.length > 1 ? arguments[1] : undefined;
4605 } // eslint-disable-line no-unused-vars
4606
4607 /**
4608 * Function onBeforeApply.
4609 *
4610 * Called before apply().
4611 *
4612 * @param {{}} args
4613 */
4614 }, {
4615 key: "onBeforeApply",
4616 value: function onBeforeApply() {
4617 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4618 } // eslint-disable-line no-unused-vars
4619
4620 /**
4621 * Function onAfterApply.
4622 *
4623 * Called after apply().
4624 *
4625 * @param {{}} args
4626 * @param {*} result
4627 */
4628 }, {
4629 key: "onAfterApply",
4630 value: function onAfterApply() {
4631 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4632 var result = arguments.length > 1 ? arguments[1] : undefined;
4633 } // eslint-disable-line no-unused-vars
4634
4635 /**
4636 * Function onCatchApply.
4637 *
4638 * Called after apply() failed.
4639 *
4640 * @param {Error} e
4641 */
4642 }, {
4643 key: "onCatchApply",
4644 value: function onCatchApply(e) {} // eslint-disable-line no-unused-vars
4645 }], [{
4646 key: "getInstanceType",
4647 value: function getInstanceType() {
4648 return 'CommandInfra';
4649 }
4650
4651 /**
4652 * Get info of command.
4653 *
4654 * @return {Object} Extra information about the command.
4655 */
4656 }, {
4657 key: "getInfo",
4658 value: function getInfo() {
4659 return {};
4660 }
4661
4662 /**
4663 * @return {string} Self command name.
4664 */
4665 }, {
4666 key: "getCommand",
4667 value: function getCommand() {
4668 return this.registerConfig.command;
4669 }
4670
4671 /**
4672 * @return {ComponentBase} Self component
4673 */
4674 }, {
4675 key: "getComponent",
4676 value: function getComponent() {
4677 return this.registerConfig.component;
4678 }
4679 }, {
4680 key: "setRegisterConfig",
4681 value: function setRegisterConfig(config) {
4682 this.registerConfig = Object.freeze(config);
4683 }
4684 }]);
4685 }(_argsObject.default);
4686 /**
4687 * @type {Object}
4688 */
4689 (0, _defineProperty2.default)(CommandInfra, "registerConfig", null);
4690
4691 /***/ }),
4692
4693 /***/ "../modules/web-cli/assets/js/modules/commands/close.js":
4694 /*!**************************************************************!*\
4695 !*** ../modules/web-cli/assets/js/modules/commands/close.js ***!
4696 \**************************************************************/
4697 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4698
4699 "use strict";
4700
4701
4702 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4703 Object.defineProperty(exports, "__esModule", ({
4704 value: true
4705 }));
4706 exports["default"] = exports.Close = void 0;
4707 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4708 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4709 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4710 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4711 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4712 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4713 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)); }
4714 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4715 var Close = exports.Close = /*#__PURE__*/function (_CommandBase) {
4716 function Close() {
4717 (0, _classCallCheck2.default)(this, Close);
4718 return _callSuper(this, Close, arguments);
4719 }
4720 (0, _inherits2.default)(Close, _CommandBase);
4721 return (0, _createClass2.default)(Close, [{
4722 key: "apply",
4723 value: function apply() {
4724 this.component.close();
4725 }
4726 }]);
4727 }(_commandBase.default);
4728 var _default = exports["default"] = Close;
4729
4730 /***/ }),
4731
4732 /***/ "../modules/web-cli/assets/js/modules/commands/index.js":
4733 /*!**************************************************************!*\
4734 !*** ../modules/web-cli/assets/js/modules/commands/index.js ***!
4735 \**************************************************************/
4736 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4737
4738 "use strict";
4739
4740
4741 Object.defineProperty(exports, "__esModule", ({
4742 value: true
4743 }));
4744 Object.defineProperty(exports, "Close", ({
4745 enumerable: true,
4746 get: function get() {
4747 return _close.Close;
4748 }
4749 }));
4750 Object.defineProperty(exports, "Open", ({
4751 enumerable: true,
4752 get: function get() {
4753 return _open.Open;
4754 }
4755 }));
4756 Object.defineProperty(exports, "Toggle", ({
4757 enumerable: true,
4758 get: function get() {
4759 return _toggle.Toggle;
4760 }
4761 }));
4762 var _close = __webpack_require__(/*! ./close */ "../modules/web-cli/assets/js/modules/commands/close.js");
4763 var _open = __webpack_require__(/*! ./open */ "../modules/web-cli/assets/js/modules/commands/open.js");
4764 var _toggle = __webpack_require__(/*! ./toggle */ "../modules/web-cli/assets/js/modules/commands/toggle.js");
4765
4766 /***/ }),
4767
4768 /***/ "../modules/web-cli/assets/js/modules/commands/open.js":
4769 /*!*************************************************************!*\
4770 !*** ../modules/web-cli/assets/js/modules/commands/open.js ***!
4771 \*************************************************************/
4772 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4773
4774 "use strict";
4775
4776
4777 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4778 Object.defineProperty(exports, "__esModule", ({
4779 value: true
4780 }));
4781 exports["default"] = exports.Open = void 0;
4782 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4783 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4784 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4785 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4786 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4787 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4788 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)); }
4789 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4790 var Open = exports.Open = /*#__PURE__*/function (_CommandBase) {
4791 function Open() {
4792 (0, _classCallCheck2.default)(this, Open);
4793 return _callSuper(this, Open, arguments);
4794 }
4795 (0, _inherits2.default)(Open, _CommandBase);
4796 return (0, _createClass2.default)(Open, [{
4797 key: "apply",
4798 value: function apply() {
4799 $e.route(this.component.getNamespace());
4800 }
4801 }]);
4802 }(_commandBase.default);
4803 var _default = exports["default"] = Open;
4804
4805 /***/ }),
4806
4807 /***/ "../modules/web-cli/assets/js/modules/commands/toggle.js":
4808 /*!***************************************************************!*\
4809 !*** ../modules/web-cli/assets/js/modules/commands/toggle.js ***!
4810 \***************************************************************/
4811 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4812
4813 "use strict";
4814
4815
4816 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4817 Object.defineProperty(exports, "__esModule", ({
4818 value: true
4819 }));
4820 exports["default"] = exports.Toggle = void 0;
4821 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4822 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4823 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4824 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4825 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4826 var _commandBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-base */ "../modules/web-cli/assets/js/modules/command-base.js"));
4827 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)); }
4828 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4829 var Toggle = exports.Toggle = /*#__PURE__*/function (_CommandBase) {
4830 function Toggle() {
4831 (0, _classCallCheck2.default)(this, Toggle);
4832 return _callSuper(this, Toggle, arguments);
4833 }
4834 (0, _inherits2.default)(Toggle, _CommandBase);
4835 return (0, _createClass2.default)(Toggle, [{
4836 key: "apply",
4837 value: function apply() {
4838 if (this.component.isOpen) {
4839 this.component.close();
4840 } else {
4841 $e.route(this.component.getNamespace());
4842 }
4843 }
4844 }]);
4845 }(_commandBase.default);
4846 var _default = exports["default"] = Toggle;
4847
4848 /***/ }),
4849
4850 /***/ "../modules/web-cli/assets/js/modules/component-base.js":
4851 /*!**************************************************************!*\
4852 !*** ../modules/web-cli/assets/js/modules/component-base.js ***!
4853 \**************************************************************/
4854 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
4855
4856 "use strict";
4857
4858
4859 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
4860 Object.defineProperty(exports, "__esModule", ({
4861 value: true
4862 }));
4863 exports["default"] = void 0;
4864 var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../node_modules/@babel/runtime/helpers/defineProperty.js"));
4865 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
4866 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
4867 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
4868 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
4869 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
4870 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
4871 var _commandCallbackBase = _interopRequireDefault(__webpack_require__(/*! elementor-api/modules/command-callback-base */ "../modules/web-cli/assets/js/modules/command-callback-base.js"));
4872 var _toolkit = __webpack_require__(/*! @reduxjs/toolkit */ "../node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js");
4873 var _module = _interopRequireDefault(__webpack_require__(/*! elementor/assets/dev/js/modules/imports/module.js */ "../assets/dev/js/modules/imports/module.js"));
4874 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
4875 var _deprecation = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/deprecation */ "../modules/web-cli/assets/js/utils/deprecation.js"));
4876 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; }
4877 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; }
4878 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)); }
4879 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
4880 /**
4881 * @typedef {import('./command-infra')} CommandInfra
4882 * @typedef {import('./hook-base')} HookBase
4883 * @typedef {import('../core/states/ui-state-base')} UiStateBase
4884 */
4885 var ComponentBase = exports["default"] = /*#__PURE__*/function (_Module) {
4886 function ComponentBase() {
4887 (0, _classCallCheck2.default)(this, ComponentBase);
4888 return _callSuper(this, ComponentBase, arguments);
4889 }
4890 (0, _inherits2.default)(ComponentBase, _Module);
4891 return (0, _createClass2.default)(ComponentBase, [{
4892 key: "__construct",
4893 value: function __construct() {
4894 var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
4895 if (args.manager) {
4896 this.manager = args.manager;
4897 }
4898 this.commands = this.defaultCommands();
4899 this.commandsInternal = this.defaultCommandsInternal();
4900 this.hooks = this.defaultHooks();
4901 this.routes = this.defaultRoutes();
4902 this.tabs = this.defaultTabs();
4903 this.shortcuts = this.defaultShortcuts();
4904 this.utils = this.defaultUtils();
4905 this.data = this.defaultData();
4906 this.uiStates = this.defaultUiStates();
4907 this.states = this.defaultStates();
4908 this.defaultRoute = '';
4909 this.currentTab = '';
4910 }
4911 }, {
4912 key: "registerAPI",
4913 value: function registerAPI() {
4914 var _this = this;
4915 Object.entries(this.getTabs()).forEach(function (tab) {
4916 return _this.registerTabRoute(tab[0]);
4917 });
4918 Object.entries(this.getRoutes()).forEach(function (_ref) {
4919 var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
4920 route = _ref2[0],
4921 callback = _ref2[1];
4922 return _this.registerRoute(route, callback);
4923 });
4924 Object.entries(this.getCommands()).forEach(function (_ref3) {
4925 var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
4926 command = _ref4[0],
4927 callback = _ref4[1];
4928 return _this.registerCommand(command, callback);
4929 });
4930 Object.entries(this.getCommandsInternal()).forEach(function (_ref5) {
4931 var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
4932 command = _ref6[0],
4933 callback = _ref6[1];
4934 return _this.registerCommandInternal(command, callback);
4935 });
4936 Object.values(this.getHooks()).forEach(function (instance) {
4937 return _this.registerHook(instance);
4938 });
4939 Object.entries(this.getData()).forEach(function (_ref7) {
4940 var _ref8 = (0, _slicedToArray2.default)(_ref7, 2),
4941 command = _ref8[0],
4942 callback = _ref8[1];
4943 return _this.registerData(command, callback);
4944 });
4945 Object.values(this.getUiStates()).forEach(function (instance) {
4946 return _this.registerUiState(instance);
4947 });
4948 Object.entries(this.getStates()).forEach(function (_ref9) {
4949 var _ref0 = (0, _slicedToArray2.default)(_ref9, 2),
4950 id = _ref0[0],
4951 state = _ref0[1];
4952 return _this.registerState(id, state);
4953 });
4954 }
4955
4956 // eslint-disable-next-line jsdoc/require-returns-check
4957 /**
4958 * @return {string} namespace
4959 */
4960 }, {
4961 key: "getNamespace",
4962 value: function getNamespace() {
4963 (0, _forceMethodImplementation.default)();
4964 }
4965
4966 /**
4967 * @deprecated since 3.7.0, use `getServiceName()` instead.
4968 */
4969 }, {
4970 key: "getRootContainer",
4971 value: function getRootContainer() {
4972 _deprecation.default.deprecated('getRootContainer()', '3.7.0', 'getServiceName()');
4973 return this.getServiceName();
4974 }
4975 }, {
4976 key: "getServiceName",
4977 value: function getServiceName() {
4978 return this.getNamespace().split('/')[0];
4979 }
4980 }, {
4981 key: "store",
4982 get: function get() {
4983 return $e.store.get(this.getNamespace());
4984 }
4985 }, {
4986 key: "defaultTabs",
4987 value: function defaultTabs() {
4988 return {};
4989 }
4990 }, {
4991 key: "defaultRoutes",
4992 value: function defaultRoutes() {
4993 return {};
4994 }
4995 }, {
4996 key: "defaultCommands",
4997 value: function defaultCommands() {
4998 return {};
4999 }
5000 }, {
5001 key: "defaultCommandsInternal",
5002 value: function defaultCommandsInternal() {
5003 return {};
5004 }
5005 }, {
5006 key: "defaultHooks",
5007 value: function defaultHooks() {
5008 return {};
5009 }
5010
5011 /**
5012 * Get the component's default UI states.
5013 *
5014 * @return {Object} default UI states
5015 */
5016 }, {
5017 key: "defaultUiStates",
5018 value: function defaultUiStates() {
5019 return {};
5020 }
5021
5022 /**
5023 * Get the component's Redux slice settings.
5024 *
5025 * @return {Object} Redux slice settings
5026 */
5027 }, {
5028 key: "defaultStates",
5029 value: function defaultStates() {
5030 return {};
5031 }
5032 }, {
5033 key: "defaultShortcuts",
5034 value: function defaultShortcuts() {
5035 return {};
5036 }
5037 }, {
5038 key: "defaultUtils",
5039 value: function defaultUtils() {
5040 return {};
5041 }
5042 }, {
5043 key: "defaultData",
5044 value: function defaultData() {
5045 return {};
5046 }
5047 }, {
5048 key: "getCommands",
5049 value: function getCommands() {
5050 return this.commands;
5051 }
5052 }, {
5053 key: "getCommandsInternal",
5054 value: function getCommandsInternal() {
5055 return this.commandsInternal;
5056 }
5057 }, {
5058 key: "getHooks",
5059 value: function getHooks() {
5060 return this.hooks;
5061 }
5062
5063 /**
5064 * Retrieve the component's UI states.
5065 *
5066 * @return {Object} UI states
5067 */
5068 }, {
5069 key: "getUiStates",
5070 value: function getUiStates() {
5071 return this.uiStates;
5072 }
5073
5074 /**
5075 * Retrieve the component's Redux Slice.
5076 *
5077 * @return {Object} Redux Slice
5078 */
5079 }, {
5080 key: "getStates",
5081 value: function getStates() {
5082 return this.states;
5083 }
5084 }, {
5085 key: "getRoutes",
5086 value: function getRoutes() {
5087 return this.routes;
5088 }
5089 }, {
5090 key: "getTabs",
5091 value: function getTabs() {
5092 return this.tabs;
5093 }
5094 }, {
5095 key: "getShortcuts",
5096 value: function getShortcuts() {
5097 return this.shortcuts;
5098 }
5099 }, {
5100 key: "getData",
5101 value: function getData() {
5102 return this.data;
5103 }
5104
5105 /**
5106 * @param {string} command
5107 * @param {(()=>{}|CommandInfra)} context
5108 * @param {'default'|'internal'|'data'} commandsType
5109 */
5110 }, {
5111 key: "registerCommand",
5112 value: function registerCommand(command, context) {
5113 var commandsType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'default';
5114 var commandsManager;
5115 switch (commandsType) {
5116 case 'default':
5117 commandsManager = $e.commands;
5118 break;
5119 case 'internal':
5120 commandsManager = $e.commandsInternal;
5121 break;
5122 case 'data':
5123 commandsManager = $e.data;
5124 break;
5125 default:
5126 throw new Error("Invalid commands type: '".concat(command, "'"));
5127 }
5128 var fullCommand = this.getNamespace() + '/' + command,
5129 instanceType = context.getInstanceType ? context.getInstanceType() : false,
5130 registerConfig = {
5131 command: fullCommand,
5132 component: this
5133 };
5134
5135 // Support pure callback.
5136 if (!instanceType) {
5137 if ($e.devTools) {
5138 $e.devTools.log.warn("Attach command-callback-base, on command: '".concat(fullCommand, "', context is unknown type."));
5139 }
5140 registerConfig.callback = context;
5141
5142 // Unique class.
5143 context = /*#__PURE__*/function (_CommandCallbackBase) {
5144 function context() {
5145 (0, _classCallCheck2.default)(this, context);
5146 return _callSuper(this, context, arguments);
5147 }
5148 (0, _inherits2.default)(context, _CommandCallbackBase);
5149 return (0, _createClass2.default)(context);
5150 }(_commandCallbackBase.default);
5151 }
5152 context.setRegisterConfig(registerConfig);
5153 commandsManager.register(this, command, context);
5154 }
5155
5156 /**
5157 * @param {HookBase} instance
5158 */
5159 }, {
5160 key: "registerHook",
5161 value: function registerHook(instance) {
5162 return instance.register();
5163 }
5164 }, {
5165 key: "registerCommandInternal",
5166 value: function registerCommandInternal(command, context) {
5167 this.registerCommand(command, context, 'internal');
5168 }
5169
5170 /**
5171 * Register a UI state.
5172 *
5173 * @param {UiStateBase} instance - UI state instance.
5174 *
5175 * @return {void}
5176 */
5177 }, {
5178 key: "registerUiState",
5179 value: function registerUiState(instance) {
5180 $e.uiStates.register(instance);
5181 }
5182
5183 /**
5184 * Register a Redux Slice.
5185 *
5186 * @param {string} id - State id.
5187 * @param {Object} stateConfig - The state config.
5188 *
5189 * @return {void}
5190 */
5191 }, {
5192 key: "registerState",
5193 value: function registerState(id, stateConfig) {
5194 id = this.getNamespace() + (id ? "/".concat(id) : '');
5195 var slice = (0, _toolkit.createSlice)(_objectSpread(_objectSpread({}, stateConfig), {}, {
5196 name: id
5197 }));
5198 $e.store.register(id, slice);
5199 }
5200 }, {
5201 key: "registerRoute",
5202 value: function registerRoute(route, callback) {
5203 $e.routes.register(this, route, callback);
5204 }
5205 }, {
5206 key: "registerData",
5207 value: function registerData(command, context) {
5208 this.registerCommand(command, context, 'data');
5209 }
5210 }, {
5211 key: "unregisterRoute",
5212 value: function unregisterRoute(route) {
5213 $e.routes.unregister(this, route);
5214 }
5215 }, {
5216 key: "registerTabRoute",
5217 value: function registerTabRoute(tab) {
5218 var _this2 = this;
5219 this.registerRoute(tab, function (args) {
5220 return _this2.activateTab(tab, args);
5221 });
5222 }
5223 }, {
5224 key: "dependency",
5225 value: function dependency() {
5226 return true;
5227 }
5228 }, {
5229 key: "open",
5230 value: function open() {
5231 return true;
5232 }
5233 }, {
5234 key: "close",
5235 value: function close() {
5236 if (!this.isOpen) {
5237 return false;
5238 }
5239 this.isOpen = false;
5240 this.inactivate();
5241 $e.routes.clearCurrent(this.getNamespace());
5242 $e.routes.clearHistory(this.getServiceName());
5243 return true;
5244 }
5245 }, {
5246 key: "activate",
5247 value: function activate() {
5248 $e.components.activate(this.getNamespace());
5249 }
5250 }, {
5251 key: "inactivate",
5252 value: function inactivate() {
5253 $e.components.inactivate(this.getNamespace());
5254 }
5255 }, {
5256 key: "isActive",
5257 value: function isActive() {
5258 return $e.components.isActive(this.getNamespace());
5259 }
5260 }, {
5261 key: "onRoute",
5262 value: function onRoute(route) {
5263 this.toggleRouteClass(route, true);
5264 this.toggleHistoryClass();
5265 this.activate();
5266 this.trigger('route/open', route);
5267 }
5268 }, {
5269 key: "onCloseRoute",
5270 value: function onCloseRoute(route) {
5271 this.toggleRouteClass(route, false);
5272 this.inactivate();
5273 this.trigger('route/close', route);
5274 }
5275 }, {
5276 key: "setDefaultRoute",
5277 value: function setDefaultRoute(route) {
5278 this.defaultRoute = this.getNamespace() + '/' + route;
5279 }
5280 }, {
5281 key: "getDefaultRoute",
5282 value: function getDefaultRoute() {
5283 return this.defaultRoute;
5284 }
5285 }, {
5286 key: "removeTab",
5287 value: function removeTab(tab) {
5288 delete this.tabs[tab];
5289 this.unregisterRoute(tab);
5290 }
5291 }, {
5292 key: "hasTab",
5293 value: function hasTab(tab) {
5294 return !!this.tabs[tab];
5295 }
5296 }, {
5297 key: "addTab",
5298 value: function addTab(tab, args, position) {
5299 var _this3 = this;
5300 this.tabs[tab] = args;
5301 // It can be 0.
5302 if ('undefined' !== typeof position) {
5303 var newTabs = {};
5304 var ids = Object.keys(this.tabs);
5305 // Remove new tab
5306 ids.pop();
5307
5308 // Add it to position.
5309 ids.splice(position, 0, tab);
5310 ids.forEach(function (id) {
5311 newTabs[id] = _this3.tabs[id];
5312 });
5313 this.tabs = newTabs;
5314 }
5315 this.registerTabRoute(tab);
5316 }
5317 }, {
5318 key: "getTabsWrapperSelector",
5319 value: function getTabsWrapperSelector() {
5320 return '';
5321 }
5322 }, {
5323 key: "getTabRoute",
5324 value: function getTabRoute(tab) {
5325 return this.getNamespace() + '/' + tab;
5326 }
5327 }, {
5328 key: "renderTab",
5329 value: function renderTab(tab) {} // eslint-disable-line
5330 }, {
5331 key: "activateTab",
5332 value: function activateTab(tab, args) {
5333 var _this4 = this;
5334 this.renderTab(tab, args);
5335 jQuery(this.getTabsWrapperSelector() + ' .elementor-component-tab').off('click').on('click', function (event) {
5336 $e.route(_this4.getTabRoute(event.currentTarget.dataset.tab), args);
5337 }).removeClass('elementor-active').filter('[data-tab="' + tab + '"]').addClass('elementor-active');
5338 }
5339 }, {
5340 key: "getActiveTabConfig",
5341 value: function getActiveTabConfig() {
5342 return this.tabs[this.currentTab] || {};
5343 }
5344 }, {
5345 key: "getBodyClass",
5346 value: function getBodyClass(route) {
5347 return 'e-route-' + route.replace(/\//g, '-');
5348 }
5349
5350 /**
5351 * If command includes uppercase character convert it to lowercase and add `-`.
5352 * e.g: `CopyAll` is converted to `copy-all`.
5353 *
5354 * @param {string} commandName
5355 */
5356 }, {
5357 key: "normalizeCommandName",
5358 value: function normalizeCommandName(commandName) {
5359 return commandName.replace(/[A-Z]/g, function (match, offset) {
5360 return (offset > 0 ? '-' : '') + match.toLowerCase();
5361 });
5362 }
5363
5364 /**
5365 * @param {{}} commandsFromImport
5366 * @return {{}} imported commands
5367 */
5368 }, {
5369 key: "importCommands",
5370 value: function importCommands(commandsFromImport) {
5371 var _this5 = this;
5372 var commands = {};
5373
5374 // Convert `Commands` to `ComponentBase` workable format.
5375 Object.entries(commandsFromImport).forEach(function (_ref1) {
5376 var _ref10 = (0, _slicedToArray2.default)(_ref1, 2),
5377 className = _ref10[0],
5378 Class = _ref10[1];
5379 var command = _this5.normalizeCommandName(className);
5380 commands[command] = Class;
5381 });
5382 return commands;
5383 }
5384 }, {
5385 key: "importHooks",
5386 value: function importHooks(hooksFromImport) {
5387 var hooks = {};
5388 for (var key in hooksFromImport) {
5389 var hook = new hooksFromImport[key]();
5390 hooks[hook.getId()] = hook;
5391 }
5392 return hooks;
5393 }
5394
5395 /**
5396 * Import & initialize the component's UI states.
5397 * Should be used inside `defaultUiState()`.
5398 *
5399 * @param {Object} statesFromImport - UI states from import.
5400 *
5401 * @return {Object} UI States
5402 */
5403 }, {
5404 key: "importUiStates",
5405 value: function importUiStates(statesFromImport) {
5406 var _this6 = this;
5407 var uiStates = {};
5408 Object.values(statesFromImport).forEach(function (className) {
5409 var uiState = new className(_this6);
5410 uiStates[uiState.getId()] = uiState;
5411 });
5412 return uiStates;
5413 }
5414
5415 /**
5416 * Set a UI state value.
5417 * TODO: Should we provide such function? Maybe the developer should implicitly pass the full state ID?
5418 *
5419 * @param {string} state - Non-prefixed state ID.
5420 * @param {*} value - New state value.
5421 *
5422 * @return {void}
5423 */
5424 }, {
5425 key: "setUiState",
5426 value: function setUiState(state, value) {
5427 $e.uiStates.set("".concat(this.getNamespace(), "/").concat(state), value);
5428 }
5429 }, {
5430 key: "toggleRouteClass",
5431 value: function toggleRouteClass(route, state) {
5432 document.body.classList.toggle(this.getBodyClass(route), state);
5433 }
5434 }, {
5435 key: "toggleHistoryClass",
5436 value: function toggleHistoryClass() {
5437 document.body.classList.toggle('e-routes-has-history', !!$e.routes.getHistory(this.getServiceName()).length);
5438 }
5439 }]);
5440 }(_module.default);
5441
5442 /***/ }),
5443
5444 /***/ "../modules/web-cli/assets/js/modules/component-modal-base.js":
5445 /*!********************************************************************!*\
5446 !*** ../modules/web-cli/assets/js/modules/component-modal-base.js ***!
5447 \********************************************************************/
5448 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5449
5450 "use strict";
5451
5452
5453 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5454 var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../node_modules/@babel/runtime/helpers/typeof.js");
5455 Object.defineProperty(exports, "__esModule", ({
5456 value: true
5457 }));
5458 exports["default"] = void 0;
5459 var _readOnlyError2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/readOnlyError */ "../node_modules/@babel/runtime/helpers/readOnlyError.js"));
5460 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5461 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5462 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
5463 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
5464 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
5465 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
5466 var _componentBase = _interopRequireDefault(__webpack_require__(/*! ./component-base */ "../modules/web-cli/assets/js/modules/component-base.js"));
5467 var commands = _interopRequireWildcard(__webpack_require__(/*! ./commands/ */ "../modules/web-cli/assets/js/modules/commands/index.js"));
5468 var _forceMethodImplementation = _interopRequireDefault(__webpack_require__(/*! ../utils/force-method-implementation */ "../modules/web-cli/assets/js/utils/force-method-implementation.js"));
5469 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); }
5470 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)); }
5471 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
5472 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; }
5473 var ComponentModalBase = exports["default"] = /*#__PURE__*/function (_ComponentBase) {
5474 function ComponentModalBase() {
5475 (0, _classCallCheck2.default)(this, ComponentModalBase);
5476 return _callSuper(this, ComponentModalBase, arguments);
5477 }
5478 (0, _inherits2.default)(ComponentModalBase, _ComponentBase);
5479 return (0, _createClass2.default)(ComponentModalBase, [{
5480 key: "registerAPI",
5481 value: function registerAPI() {
5482 var _this = this;
5483 _superPropGet(ComponentModalBase, "registerAPI", this, 3)([]);
5484 $e.shortcuts.register('esc', {
5485 scopes: [this.getNamespace()],
5486 callback: function callback() {
5487 return _this.close();
5488 }
5489 });
5490 }
5491 }, {
5492 key: "defaultCommands",
5493 value: function defaultCommands() {
5494 return this.importCommands(commands);
5495 }
5496 }, {
5497 key: "defaultRoutes",
5498 value: function defaultRoutes() {
5499 return {
5500 '': function _() {/* Nothing to do, it's already rendered. */}
5501 };
5502 }
5503 }, {
5504 key: "open",
5505 value: function open() {
5506 var _this2 = this;
5507 if (!this.layout) {
5508 var layout = this.getModalLayout();
5509 this.layout = new layout({
5510 component: this
5511 });
5512 this.layout.getModal().on('hide', function () {
5513 return _this2.close();
5514 });
5515 }
5516 this.layout.showModal();
5517 return true;
5518 }
5519 }, {
5520 key: "close",
5521 value: function close() {
5522 if (!_superPropGet(ComponentModalBase, "close", this, 3)([])) {
5523 return false;
5524 }
5525 var close = elementor.hooks.applyFilters('component/modal/close', this.layout.getModal().hide.bind(this.layout.getModal()), this);
5526 close();
5527 return true;
5528 }
5529 }, {
5530 key: "getModalLayout",
5531 value: function getModalLayout() {
5532 (0, _forceMethodImplementation.default)();
5533 }
5534 }]);
5535 }(_componentBase.default);
5536
5537 /***/ }),
5538
5539 /***/ "../modules/web-cli/assets/js/utils/console.js":
5540 /*!*****************************************************!*\
5541 !*** ../modules/web-cli/assets/js/utils/console.js ***!
5542 \*****************************************************/
5543 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5544
5545 "use strict";
5546
5547
5548 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5549 Object.defineProperty(exports, "__esModule", ({
5550 value: true
5551 }));
5552 exports["default"] = void 0;
5553 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5554 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5555 var Console = exports["default"] = /*#__PURE__*/function () {
5556 function Console() {
5557 (0, _classCallCheck2.default)(this, Console);
5558 }
5559 return (0, _createClass2.default)(Console, null, [{
5560 key: "error",
5561 value: function error(message) {
5562 // Show an error if devTools is available.
5563 if ($e.devTools) {
5564 $e.devTools.log.error(message);
5565 }
5566
5567 // If not a 'Hook-Break' then show error.
5568 if (!(message instanceof $e.modules.HookBreak)) {
5569 // eslint-disable-next-line no-console
5570 console.error(message);
5571 }
5572 }
5573 }, {
5574 key: "warn",
5575 value: function warn() {
5576 var _console;
5577 var style = "font-size: 12px; background-image: url(\"".concat(elementorWebCliConfig.urls.assets, "images/logo-icon.png\"); background-repeat: no-repeat; background-size: contain;");
5578 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
5579 args[_key] = arguments[_key];
5580 }
5581 args.unshift('%c %c', style, '');
5582 (_console = console).warn.apply(_console, args); // eslint-disable-line no-console
5583 }
5584 }]);
5585 }();
5586
5587 /***/ }),
5588
5589 /***/ "../modules/web-cli/assets/js/utils/deprecation.js":
5590 /*!*********************************************************!*\
5591 !*** ../modules/web-cli/assets/js/utils/deprecation.js ***!
5592 \*********************************************************/
5593 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5594
5595 "use strict";
5596
5597
5598 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5599 Object.defineProperty(exports, "__esModule", ({
5600 value: true
5601 }));
5602 exports["default"] = void 0;
5603 var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "../node_modules/@babel/runtime/helpers/slicedToArray.js"));
5604 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5605 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5606 var _console = _interopRequireDefault(__webpack_require__(/*! elementor-api/utils/console */ "../modules/web-cli/assets/js/utils/console.js"));
5607 // Copied from `modules/dev-tools/assets/js/deprecation.js`
5608 /**
5609 * @typedef {Object} Version
5610 * @property {number} major1 The first number
5611 * @property {number} major2 The second number
5612 * @property {number} minor The third number
5613 * @property {string} build The fourth number
5614 */
5615
5616 var softDeprecated = function softDeprecated(name, version, replacement) {
5617 if (elementorWebCliConfig.isDebug) {
5618 deprecatedMessage('soft', name, version, replacement);
5619 }
5620 };
5621 var hardDeprecated = function hardDeprecated(name, version, replacement) {
5622 deprecatedMessage('hard', name, version, replacement);
5623 };
5624 var deprecatedMessage = function deprecatedMessage(type, name, version, replacement) {
5625 var message = "`".concat(name, "` is ").concat(type, " deprecated since ").concat(version);
5626 if (replacement) {
5627 message += " - Use `".concat(replacement, "` instead");
5628 }
5629 _console.default.warn(message);
5630 };
5631 var Deprecation = exports["default"] = /*#__PURE__*/function () {
5632 function Deprecation() {
5633 (0, _classCallCheck2.default)(this, Deprecation);
5634 }
5635 return (0, _createClass2.default)(Deprecation, null, [{
5636 key: "deprecated",
5637 value: function deprecated(name, version, replacement) {
5638 if (this.isHardDeprecated(version)) {
5639 hardDeprecated(name, version, replacement);
5640 } else {
5641 softDeprecated(name, version, replacement);
5642 }
5643 }
5644
5645 /**
5646 * @param {string} version
5647 *
5648 * @return {Version}
5649 */
5650 }, {
5651 key: "parseVersion",
5652 value: function parseVersion(version) {
5653 var versionParts = version.split('.');
5654 if (versionParts.length < 3 || versionParts.length > 4) {
5655 throw new RangeError('Invalid Semantic Version string provided');
5656 }
5657 var _versionParts = (0, _slicedToArray2.default)(versionParts, 4),
5658 major1 = _versionParts[0],
5659 major2 = _versionParts[1],
5660 minor = _versionParts[2],
5661 _versionParts$ = _versionParts[3],
5662 build = _versionParts$ === void 0 ? '' : _versionParts$;
5663 return {
5664 major1: parseInt(major1),
5665 major2: parseInt(major2),
5666 minor: parseInt(minor),
5667 build: build
5668 };
5669 }
5670
5671 /**
5672 * Get total of major.
5673 *
5674 * 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,
5675 * versions with major2 more then 9 will be added to total.
5676 *
5677 * @param {Version} versionObj
5678 *
5679 * @return {number}
5680 */
5681 }, {
5682 key: "getTotalMajor",
5683 value: function getTotalMajor(versionObj) {
5684 var total = parseInt("".concat(versionObj.major1).concat(versionObj.major2, "0"));
5685 total = Number((total / 10).toFixed(0));
5686 if (versionObj.major2 > 9) {
5687 total = versionObj.major2 - 9;
5688 }
5689 return total;
5690 }
5691
5692 /**
5693 * @param {string} version1
5694 * @param {string} version2
5695 *
5696 * @return {number}
5697 */
5698 }, {
5699 key: "compareVersion",
5700 value: function compareVersion(version1, version2) {
5701 var _this = this;
5702 return [this.parseVersion(version1), this.parseVersion(version2)].map(function (versionObj) {
5703 return _this.getTotalMajor(versionObj);
5704 }).reduce(function (acc, major) {
5705 return acc - major;
5706 });
5707 }
5708
5709 /**
5710 * @param {string} version
5711 *
5712 * @return {boolean}
5713 */
5714 }, {
5715 key: "isSoftDeprecated",
5716 value: function isSoftDeprecated(version) {
5717 var total = this.compareVersion(version, elementorWebCliConfig.version);
5718 return total <= 4;
5719 }
5720
5721 /**
5722 * @param {string} version
5723 * @return {boolean}
5724 */
5725 }, {
5726 key: "isHardDeprecated",
5727 value: function isHardDeprecated(version) {
5728 var total = this.compareVersion(version, elementorWebCliConfig.version);
5729 return total < 0 || total >= 8;
5730 }
5731 }]);
5732 }();
5733
5734 /***/ }),
5735
5736 /***/ "../modules/web-cli/assets/js/utils/force-method-implementation.js":
5737 /*!*************************************************************************!*\
5738 !*** ../modules/web-cli/assets/js/utils/force-method-implementation.js ***!
5739 \*************************************************************************/
5740 /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
5741
5742 "use strict";
5743
5744
5745 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
5746 Object.defineProperty(exports, "__esModule", ({
5747 value: true
5748 }));
5749 exports["default"] = exports.ForceMethodImplementation = void 0;
5750 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
5751 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
5752 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
5753 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
5754 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
5755 var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js"));
5756 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)); }
5757 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
5758 // TODO: Copied from `assets/dev/js/modules/imports/force-method-implementation.js`;
5759 var ForceMethodImplementation = exports.ForceMethodImplementation = /*#__PURE__*/function (_Error) {
5760 function ForceMethodImplementation() {
5761 var _this;
5762 var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
5763 (0, _classCallCheck2.default)(this, ForceMethodImplementation);
5764 _this = _callSuper(this, ForceMethodImplementation, ["".concat(info.isStatic ? 'static ' : '').concat(info.fullName, "() should be implemented, please provide '").concat(info.functionName || info.fullName, "' functionality.")]);
5765 Error.captureStackTrace(_this, ForceMethodImplementation);
5766 return _this;
5767 }
5768 (0, _inherits2.default)(ForceMethodImplementation, _Error);
5769 return (0, _createClass2.default)(ForceMethodImplementation);
5770 }(/*#__PURE__*/(0, _wrapNativeSuper2.default)(Error));
5771 var _default = exports["default"] = function _default() {
5772 var stack = Error().stack,
5773 caller = stack.split('\n')[2].trim(),
5774 callerName = caller.startsWith('at new') ? 'constructor' : caller.split(' ')[1],
5775 info = {};
5776 info.functionName = callerName;
5777 info.fullName = callerName;
5778 if (info.functionName.includes('.')) {
5779 var parts = info.functionName.split('.');
5780 info.className = parts[0];
5781 info.functionName = parts[1];
5782 } else {
5783 info.isStatic = true;
5784 }
5785 throw new ForceMethodImplementation(info);
5786 };
5787
5788 /***/ }),
5789
5790 /***/ "../node_modules/@babel/runtime/helpers/OverloadYield.js":
5791 /*!***************************************************************!*\
5792 !*** ../node_modules/@babel/runtime/helpers/OverloadYield.js ***!
5793 \***************************************************************/
5794 /***/ ((module) => {
5795
5796 function _OverloadYield(e, d) {
5797 this.v = e, this.k = d;
5798 }
5799 module.exports = _OverloadYield, module.exports.__esModule = true, module.exports["default"] = module.exports;
5800
5801 /***/ }),
5802
5803 /***/ "../node_modules/@babel/runtime/helpers/arrayLikeToArray.js":
5804 /*!******************************************************************!*\
5805 !*** ../node_modules/@babel/runtime/helpers/arrayLikeToArray.js ***!
5806 \******************************************************************/
5807 /***/ ((module) => {
5808
5809 function _arrayLikeToArray(r, a) {
5810 (null == a || a > r.length) && (a = r.length);
5811 for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
5812 return n;
5813 }
5814 module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
5815
5816 /***/ }),
5817
5818 /***/ "../node_modules/@babel/runtime/helpers/arrayWithHoles.js":
5819 /*!****************************************************************!*\
5820 !*** ../node_modules/@babel/runtime/helpers/arrayWithHoles.js ***!
5821 \****************************************************************/
5822 /***/ ((module) => {
5823
5824 function _arrayWithHoles(r) {
5825 if (Array.isArray(r)) return r;
5826 }
5827 module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
5828
5829 /***/ }),
5830
5831 /***/ "../node_modules/@babel/runtime/helpers/assertThisInitialized.js":
5832 /*!***********************************************************************!*\
5833 !*** ../node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
5834 \***********************************************************************/
5835 /***/ ((module) => {
5836
5837 function _assertThisInitialized(e) {
5838 if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
5839 return e;
5840 }
5841 module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
5842
5843 /***/ }),
5844
5845 /***/ "../node_modules/@babel/runtime/helpers/asyncToGenerator.js":
5846 /*!******************************************************************!*\
5847 !*** ../node_modules/@babel/runtime/helpers/asyncToGenerator.js ***!
5848 \******************************************************************/
5849 /***/ ((module) => {
5850
5851 function asyncGeneratorStep(n, t, e, r, o, a, c) {
5852 try {
5853 var i = n[a](c),
5854 u = i.value;
5855 } catch (n) {
5856 return void e(n);
5857 }
5858 i.done ? t(u) : Promise.resolve(u).then(r, o);
5859 }
5860 function _asyncToGenerator(n) {
5861 return function () {
5862 var t = this,
5863 e = arguments;
5864 return new Promise(function (r, o) {
5865 var a = n.apply(t, e);
5866 function _next(n) {
5867 asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
5868 }
5869 function _throw(n) {
5870 asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
5871 }
5872 _next(void 0);
5873 });
5874 };
5875 }
5876 module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
5877
5878 /***/ }),
5879
5880 /***/ "../node_modules/@babel/runtime/helpers/classCallCheck.js":
5881 /*!****************************************************************!*\
5882 !*** ../node_modules/@babel/runtime/helpers/classCallCheck.js ***!
5883 \****************************************************************/
5884 /***/ ((module) => {
5885
5886 function _classCallCheck(a, n) {
5887 if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
5888 }
5889 module.exports = _classCallCheck, module.exports.__esModule = true, module.exports["default"] = module.exports;
5890
5891 /***/ }),
5892
5893 /***/ "../node_modules/@babel/runtime/helpers/construct.js":
5894 /*!***********************************************************!*\
5895 !*** ../node_modules/@babel/runtime/helpers/construct.js ***!
5896 \***********************************************************/
5897 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5898
5899 var isNativeReflectConstruct = __webpack_require__(/*! ./isNativeReflectConstruct.js */ "../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js");
5900 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
5901 function _construct(t, e, r) {
5902 if (isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
5903 var o = [null];
5904 o.push.apply(o, e);
5905 var p = new (t.bind.apply(t, o))();
5906 return r && setPrototypeOf(p, r.prototype), p;
5907 }
5908 module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports;
5909
5910 /***/ }),
5911
5912 /***/ "../node_modules/@babel/runtime/helpers/createClass.js":
5913 /*!*************************************************************!*\
5914 !*** ../node_modules/@babel/runtime/helpers/createClass.js ***!
5915 \*************************************************************/
5916 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5917
5918 var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/toPropertyKey.js");
5919 function _defineProperties(e, r) {
5920 for (var t = 0; t < r.length; t++) {
5921 var o = r[t];
5922 o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);
5923 }
5924 }
5925 function _createClass(e, r, t) {
5926 return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
5927 writable: !1
5928 }), e;
5929 }
5930 module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
5931
5932 /***/ }),
5933
5934 /***/ "../node_modules/@babel/runtime/helpers/defineProperty.js":
5935 /*!****************************************************************!*\
5936 !*** ../node_modules/@babel/runtime/helpers/defineProperty.js ***!
5937 \****************************************************************/
5938 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
5939
5940 var toPropertyKey = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/toPropertyKey.js");
5941 function _defineProperty(e, r, t) {
5942 return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
5943 value: t,
5944 enumerable: !0,
5945 configurable: !0,
5946 writable: !0
5947 }) : e[r] = t, e;
5948 }
5949 module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
5950
5951 /***/ }),
5952
5953 /***/ "../node_modules/@babel/runtime/helpers/esm/defineProperty.js":
5954 /*!********************************************************************!*\
5955 !*** ../node_modules/@babel/runtime/helpers/esm/defineProperty.js ***!
5956 \********************************************************************/
5957 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5958
5959 "use strict";
5960 __webpack_require__.r(__webpack_exports__);
5961 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5962 /* harmony export */ "default": () => (/* binding */ _defineProperty)
5963 /* harmony export */ });
5964 /* harmony import */ var _toPropertyKey_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./toPropertyKey.js */ "../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js");
5965
5966 function _defineProperty(e, r, t) {
5967 return (r = (0,_toPropertyKey_js__WEBPACK_IMPORTED_MODULE_0__["default"])(r)) in e ? Object.defineProperty(e, r, {
5968 value: t,
5969 enumerable: !0,
5970 configurable: !0,
5971 writable: !0
5972 }) : e[r] = t, e;
5973 }
5974
5975
5976 /***/ }),
5977
5978 /***/ "../node_modules/@babel/runtime/helpers/esm/objectSpread2.js":
5979 /*!*******************************************************************!*\
5980 !*** ../node_modules/@babel/runtime/helpers/esm/objectSpread2.js ***!
5981 \*******************************************************************/
5982 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5983
5984 "use strict";
5985 __webpack_require__.r(__webpack_exports__);
5986 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5987 /* harmony export */ "default": () => (/* binding */ _objectSpread2)
5988 /* harmony export */ });
5989 /* harmony import */ var _defineProperty_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./defineProperty.js */ "../node_modules/@babel/runtime/helpers/esm/defineProperty.js");
5990
5991 function ownKeys(e, r) {
5992 var t = Object.keys(e);
5993 if (Object.getOwnPropertySymbols) {
5994 var o = Object.getOwnPropertySymbols(e);
5995 r && (o = o.filter(function (r) {
5996 return Object.getOwnPropertyDescriptor(e, r).enumerable;
5997 })), t.push.apply(t, o);
5998 }
5999 return t;
6000 }
6001 function _objectSpread2(e) {
6002 for (var r = 1; r < arguments.length; r++) {
6003 var t = null != arguments[r] ? arguments[r] : {};
6004 r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
6005 (0,_defineProperty_js__WEBPACK_IMPORTED_MODULE_0__["default"])(e, r, t[r]);
6006 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
6007 Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
6008 });
6009 }
6010 return e;
6011 }
6012
6013
6014 /***/ }),
6015
6016 /***/ "../node_modules/@babel/runtime/helpers/esm/toPrimitive.js":
6017 /*!*****************************************************************!*\
6018 !*** ../node_modules/@babel/runtime/helpers/esm/toPrimitive.js ***!
6019 \*****************************************************************/
6020 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6021
6022 "use strict";
6023 __webpack_require__.r(__webpack_exports__);
6024 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6025 /* harmony export */ "default": () => (/* binding */ toPrimitive)
6026 /* harmony export */ });
6027 /* harmony import */ var _typeof_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/esm/typeof.js");
6028
6029 function toPrimitive(t, r) {
6030 if ("object" != (0,_typeof_js__WEBPACK_IMPORTED_MODULE_0__["default"])(t) || !t) return t;
6031 var e = t[Symbol.toPrimitive];
6032 if (void 0 !== e) {
6033 var i = e.call(t, r || "default");
6034 if ("object" != (0,_typeof_js__WEBPACK_IMPORTED_MODULE_0__["default"])(i)) return i;
6035 throw new TypeError("@@toPrimitive must return a primitive value.");
6036 }
6037 return ("string" === r ? String : Number)(t);
6038 }
6039
6040
6041 /***/ }),
6042
6043 /***/ "../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js":
6044 /*!*******************************************************************!*\
6045 !*** ../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js ***!
6046 \*******************************************************************/
6047 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6048
6049 "use strict";
6050 __webpack_require__.r(__webpack_exports__);
6051 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6052 /* harmony export */ "default": () => (/* binding */ toPropertyKey)
6053 /* harmony export */ });
6054 /* harmony import */ var _typeof_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/esm/typeof.js");
6055 /* harmony import */ var _toPrimitive_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./toPrimitive.js */ "../node_modules/@babel/runtime/helpers/esm/toPrimitive.js");
6056
6057
6058 function toPropertyKey(t) {
6059 var i = (0,_toPrimitive_js__WEBPACK_IMPORTED_MODULE_1__["default"])(t, "string");
6060 return "symbol" == (0,_typeof_js__WEBPACK_IMPORTED_MODULE_0__["default"])(i) ? i : i + "";
6061 }
6062
6063
6064 /***/ }),
6065
6066 /***/ "../node_modules/@babel/runtime/helpers/esm/typeof.js":
6067 /*!************************************************************!*\
6068 !*** ../node_modules/@babel/runtime/helpers/esm/typeof.js ***!
6069 \************************************************************/
6070 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6071
6072 "use strict";
6073 __webpack_require__.r(__webpack_exports__);
6074 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6075 /* harmony export */ "default": () => (/* binding */ _typeof)
6076 /* harmony export */ });
6077 function _typeof(o) {
6078 "@babel/helpers - typeof";
6079
6080 return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
6081 return typeof o;
6082 } : function (o) {
6083 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
6084 }, _typeof(o);
6085 }
6086
6087
6088 /***/ }),
6089
6090 /***/ "../node_modules/@babel/runtime/helpers/get.js":
6091 /*!*****************************************************!*\
6092 !*** ../node_modules/@babel/runtime/helpers/get.js ***!
6093 \*****************************************************/
6094 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6095
6096 var superPropBase = __webpack_require__(/*! ./superPropBase.js */ "../node_modules/@babel/runtime/helpers/superPropBase.js");
6097 function _get() {
6098 return module.exports = _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
6099 var p = superPropBase(e, t);
6100 if (p) {
6101 var n = Object.getOwnPropertyDescriptor(p, t);
6102 return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
6103 }
6104 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _get.apply(null, arguments);
6105 }
6106 module.exports = _get, module.exports.__esModule = true, module.exports["default"] = module.exports;
6107
6108 /***/ }),
6109
6110 /***/ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js":
6111 /*!****************************************************************!*\
6112 !*** ../node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
6113 \****************************************************************/
6114 /***/ ((module) => {
6115
6116 function _getPrototypeOf(t) {
6117 return module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
6118 return t.__proto__ || Object.getPrototypeOf(t);
6119 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _getPrototypeOf(t);
6120 }
6121 module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
6122
6123 /***/ }),
6124
6125 /***/ "../node_modules/@babel/runtime/helpers/inherits.js":
6126 /*!**********************************************************!*\
6127 !*** ../node_modules/@babel/runtime/helpers/inherits.js ***!
6128 \**********************************************************/
6129 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6130
6131 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
6132 function _inherits(t, e) {
6133 if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
6134 t.prototype = Object.create(e && e.prototype, {
6135 constructor: {
6136 value: t,
6137 writable: !0,
6138 configurable: !0
6139 }
6140 }), Object.defineProperty(t, "prototype", {
6141 writable: !1
6142 }), e && setPrototypeOf(t, e);
6143 }
6144 module.exports = _inherits, module.exports.__esModule = true, module.exports["default"] = module.exports;
6145
6146 /***/ }),
6147
6148 /***/ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js":
6149 /*!***********************************************************************!*\
6150 !*** ../node_modules/@babel/runtime/helpers/interopRequireDefault.js ***!
6151 \***********************************************************************/
6152 /***/ ((module) => {
6153
6154 function _interopRequireDefault(e) {
6155 return e && e.__esModule ? e : {
6156 "default": e
6157 };
6158 }
6159 module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports;
6160
6161 /***/ }),
6162
6163 /***/ "../node_modules/@babel/runtime/helpers/isNativeFunction.js":
6164 /*!******************************************************************!*\
6165 !*** ../node_modules/@babel/runtime/helpers/isNativeFunction.js ***!
6166 \******************************************************************/
6167 /***/ ((module) => {
6168
6169 function _isNativeFunction(t) {
6170 try {
6171 return -1 !== Function.toString.call(t).indexOf("[native code]");
6172 } catch (n) {
6173 return "function" == typeof t;
6174 }
6175 }
6176 module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports;
6177
6178 /***/ }),
6179
6180 /***/ "../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js":
6181 /*!**************************************************************************!*\
6182 !*** ../node_modules/@babel/runtime/helpers/isNativeReflectConstruct.js ***!
6183 \**************************************************************************/
6184 /***/ ((module) => {
6185
6186 function _isNativeReflectConstruct() {
6187 try {
6188 var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
6189 } catch (t) {}
6190 return (module.exports = _isNativeReflectConstruct = function _isNativeReflectConstruct() {
6191 return !!t;
6192 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6193 }
6194 module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports;
6195
6196 /***/ }),
6197
6198 /***/ "../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js":
6199 /*!**********************************************************************!*\
6200 !*** ../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js ***!
6201 \**********************************************************************/
6202 /***/ ((module) => {
6203
6204 function _iterableToArrayLimit(r, l) {
6205 var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
6206 if (null != t) {
6207 var e,
6208 n,
6209 i,
6210 u,
6211 a = [],
6212 f = !0,
6213 o = !1;
6214 try {
6215 if (i = (t = t.call(r)).next, 0 === l) {
6216 if (Object(t) !== t) return;
6217 f = !1;
6218 } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
6219 } catch (r) {
6220 o = !0, n = r;
6221 } finally {
6222 try {
6223 if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
6224 } finally {
6225 if (o) throw n;
6226 }
6227 }
6228 return a;
6229 }
6230 }
6231 module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
6232
6233 /***/ }),
6234
6235 /***/ "../node_modules/@babel/runtime/helpers/nonIterableRest.js":
6236 /*!*****************************************************************!*\
6237 !*** ../node_modules/@babel/runtime/helpers/nonIterableRest.js ***!
6238 \*****************************************************************/
6239 /***/ ((module) => {
6240
6241 function _nonIterableRest() {
6242 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
6243 }
6244 module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
6245
6246 /***/ }),
6247
6248 /***/ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js":
6249 /*!***************************************************************************!*\
6250 !*** ../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
6251 \***************************************************************************/
6252 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6253
6254 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6255 var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized.js */ "../node_modules/@babel/runtime/helpers/assertThisInitialized.js");
6256 function _possibleConstructorReturn(t, e) {
6257 if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
6258 if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
6259 return assertThisInitialized(t);
6260 }
6261 module.exports = _possibleConstructorReturn, module.exports.__esModule = true, module.exports["default"] = module.exports;
6262
6263 /***/ }),
6264
6265 /***/ "../node_modules/@babel/runtime/helpers/readOnlyError.js":
6266 /*!***************************************************************!*\
6267 !*** ../node_modules/@babel/runtime/helpers/readOnlyError.js ***!
6268 \***************************************************************/
6269 /***/ ((module) => {
6270
6271 function _readOnlyError(r) {
6272 throw new TypeError('"' + r + '" is read-only');
6273 }
6274 module.exports = _readOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports;
6275
6276 /***/ }),
6277
6278 /***/ "../node_modules/@babel/runtime/helpers/regenerator.js":
6279 /*!*************************************************************!*\
6280 !*** ../node_modules/@babel/runtime/helpers/regenerator.js ***!
6281 \*************************************************************/
6282 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6283
6284 var regeneratorDefine = __webpack_require__(/*! ./regeneratorDefine.js */ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js");
6285 function _regenerator() {
6286 /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
6287 var e,
6288 t,
6289 r = "function" == typeof Symbol ? Symbol : {},
6290 n = r.iterator || "@@iterator",
6291 o = r.toStringTag || "@@toStringTag";
6292 function i(r, n, o, i) {
6293 var c = n && n.prototype instanceof Generator ? n : Generator,
6294 u = Object.create(c.prototype);
6295 return regeneratorDefine(u, "_invoke", function (r, n, o) {
6296 var i,
6297 c,
6298 u,
6299 f = 0,
6300 p = o || [],
6301 y = !1,
6302 G = {
6303 p: 0,
6304 n: 0,
6305 v: e,
6306 a: d,
6307 f: d.bind(e, 4),
6308 d: function d(t, r) {
6309 return i = t, c = 0, u = e, G.n = r, a;
6310 }
6311 };
6312 function d(r, n) {
6313 for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
6314 var o,
6315 i = p[t],
6316 d = G.p,
6317 l = i[2];
6318 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));
6319 }
6320 if (o || r > 1) return a;
6321 throw y = !0, n;
6322 }
6323 return function (o, p, l) {
6324 if (f > 1) throw TypeError("Generator is already running");
6325 for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
6326 i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
6327 try {
6328 if (f = 2, i) {
6329 if (c || (o = "next"), t = i[o]) {
6330 if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
6331 if (!t.done) return t;
6332 u = t.value, c < 2 && (c = 0);
6333 } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
6334 i = e;
6335 } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
6336 } catch (t) {
6337 i = e, c = 1, u = t;
6338 } finally {
6339 f = 1;
6340 }
6341 }
6342 return {
6343 value: t,
6344 done: y
6345 };
6346 };
6347 }(r, o, i), !0), u;
6348 }
6349 var a = {};
6350 function Generator() {}
6351 function GeneratorFunction() {}
6352 function GeneratorFunctionPrototype() {}
6353 t = Object.getPrototypeOf;
6354 var c = [][n] ? t(t([][n]())) : (regeneratorDefine(t = {}, n, function () {
6355 return this;
6356 }), t),
6357 u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
6358 function f(e) {
6359 return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
6360 }
6361 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 () {
6362 return this;
6363 }), regeneratorDefine(u, "toString", function () {
6364 return "[object Generator]";
6365 }), (module.exports = _regenerator = function _regenerator() {
6366 return {
6367 w: i,
6368 m: f
6369 };
6370 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6371 }
6372 module.exports = _regenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
6373
6374 /***/ }),
6375
6376 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsync.js":
6377 /*!******************************************************************!*\
6378 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsync.js ***!
6379 \******************************************************************/
6380 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6381
6382 var regeneratorAsyncGen = __webpack_require__(/*! ./regeneratorAsyncGen.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");
6383 function _regeneratorAsync(n, e, r, t, o) {
6384 var a = regeneratorAsyncGen(n, e, r, t, o);
6385 return a.next().then(function (n) {
6386 return n.done ? n.value : a.next();
6387 });
6388 }
6389 module.exports = _regeneratorAsync, module.exports.__esModule = true, module.exports["default"] = module.exports;
6390
6391 /***/ }),
6392
6393 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js":
6394 /*!*********************************************************************!*\
6395 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js ***!
6396 \*********************************************************************/
6397 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6398
6399 var regenerator = __webpack_require__(/*! ./regenerator.js */ "../node_modules/@babel/runtime/helpers/regenerator.js");
6400 var regeneratorAsyncIterator = __webpack_require__(/*! ./regeneratorAsyncIterator.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");
6401 function _regeneratorAsyncGen(r, e, t, o, n) {
6402 return new regeneratorAsyncIterator(regenerator().w(r, e, t, o), n || Promise);
6403 }
6404 module.exports = _regeneratorAsyncGen, module.exports.__esModule = true, module.exports["default"] = module.exports;
6405
6406 /***/ }),
6407
6408 /***/ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js":
6409 /*!**************************************************************************!*\
6410 !*** ../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js ***!
6411 \**************************************************************************/
6412 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6413
6414 var OverloadYield = __webpack_require__(/*! ./OverloadYield.js */ "../node_modules/@babel/runtime/helpers/OverloadYield.js");
6415 var regeneratorDefine = __webpack_require__(/*! ./regeneratorDefine.js */ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js");
6416 function AsyncIterator(t, e) {
6417 function n(r, o, i, f) {
6418 try {
6419 var c = t[r](o),
6420 u = c.value;
6421 return u instanceof OverloadYield ? e.resolve(u.v).then(function (t) {
6422 n("next", t, i, f);
6423 }, function (t) {
6424 n("throw", t, i, f);
6425 }) : e.resolve(u).then(function (t) {
6426 c.value = t, i(c);
6427 }, function (t) {
6428 return n("throw", t, i, f);
6429 });
6430 } catch (t) {
6431 f(t);
6432 }
6433 }
6434 var r;
6435 this.next || (regeneratorDefine(AsyncIterator.prototype), regeneratorDefine(AsyncIterator.prototype, "function" == typeof Symbol && Symbol.asyncIterator || "@asyncIterator", function () {
6436 return this;
6437 })), regeneratorDefine(this, "_invoke", function (t, o, i) {
6438 function f() {
6439 return new e(function (e, r) {
6440 n(t, i, e, r);
6441 });
6442 }
6443 return r = r ? r.then(f, f) : f();
6444 }, !0);
6445 }
6446 module.exports = AsyncIterator, module.exports.__esModule = true, module.exports["default"] = module.exports;
6447
6448 /***/ }),
6449
6450 /***/ "../node_modules/@babel/runtime/helpers/regeneratorDefine.js":
6451 /*!*******************************************************************!*\
6452 !*** ../node_modules/@babel/runtime/helpers/regeneratorDefine.js ***!
6453 \*******************************************************************/
6454 /***/ ((module) => {
6455
6456 function _regeneratorDefine(e, r, n, t) {
6457 var i = Object.defineProperty;
6458 try {
6459 i({}, "", {});
6460 } catch (e) {
6461 i = 0;
6462 }
6463 module.exports = _regeneratorDefine = function regeneratorDefine(e, r, n, t) {
6464 function o(r, n) {
6465 _regeneratorDefine(e, r, function (e) {
6466 return this._invoke(r, n, e);
6467 });
6468 }
6469 r ? i ? i(e, r, {
6470 value: n,
6471 enumerable: !t,
6472 configurable: !t,
6473 writable: !t
6474 }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
6475 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _regeneratorDefine(e, r, n, t);
6476 }
6477 module.exports = _regeneratorDefine, module.exports.__esModule = true, module.exports["default"] = module.exports;
6478
6479 /***/ }),
6480
6481 /***/ "../node_modules/@babel/runtime/helpers/regeneratorKeys.js":
6482 /*!*****************************************************************!*\
6483 !*** ../node_modules/@babel/runtime/helpers/regeneratorKeys.js ***!
6484 \*****************************************************************/
6485 /***/ ((module) => {
6486
6487 function _regeneratorKeys(e) {
6488 var n = Object(e),
6489 r = [];
6490 for (var t in n) r.unshift(t);
6491 return function e() {
6492 for (; r.length;) if ((t = r.pop()) in n) return e.value = t, e.done = !1, e;
6493 return e.done = !0, e;
6494 };
6495 }
6496 module.exports = _regeneratorKeys, module.exports.__esModule = true, module.exports["default"] = module.exports;
6497
6498 /***/ }),
6499
6500 /***/ "../node_modules/@babel/runtime/helpers/regeneratorRuntime.js":
6501 /*!********************************************************************!*\
6502 !*** ../node_modules/@babel/runtime/helpers/regeneratorRuntime.js ***!
6503 \********************************************************************/
6504 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6505
6506 var OverloadYield = __webpack_require__(/*! ./OverloadYield.js */ "../node_modules/@babel/runtime/helpers/OverloadYield.js");
6507 var regenerator = __webpack_require__(/*! ./regenerator.js */ "../node_modules/@babel/runtime/helpers/regenerator.js");
6508 var regeneratorAsync = __webpack_require__(/*! ./regeneratorAsync.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsync.js");
6509 var regeneratorAsyncGen = __webpack_require__(/*! ./regeneratorAsyncGen.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncGen.js");
6510 var regeneratorAsyncIterator = __webpack_require__(/*! ./regeneratorAsyncIterator.js */ "../node_modules/@babel/runtime/helpers/regeneratorAsyncIterator.js");
6511 var regeneratorKeys = __webpack_require__(/*! ./regeneratorKeys.js */ "../node_modules/@babel/runtime/helpers/regeneratorKeys.js");
6512 var regeneratorValues = __webpack_require__(/*! ./regeneratorValues.js */ "../node_modules/@babel/runtime/helpers/regeneratorValues.js");
6513 function _regeneratorRuntime() {
6514 "use strict";
6515
6516 var r = regenerator(),
6517 e = r.m(_regeneratorRuntime),
6518 t = (Object.getPrototypeOf ? Object.getPrototypeOf(e) : e.__proto__).constructor;
6519 function n(r) {
6520 var e = "function" == typeof r && r.constructor;
6521 return !!e && (e === t || "GeneratorFunction" === (e.displayName || e.name));
6522 }
6523 var o = {
6524 "throw": 1,
6525 "return": 2,
6526 "break": 3,
6527 "continue": 3
6528 };
6529 function a(r) {
6530 var e, t;
6531 return function (n) {
6532 e || (e = {
6533 stop: function stop() {
6534 return t(n.a, 2);
6535 },
6536 "catch": function _catch() {
6537 return n.v;
6538 },
6539 abrupt: function abrupt(r, e) {
6540 return t(n.a, o[r], e);
6541 },
6542 delegateYield: function delegateYield(r, o, a) {
6543 return e.resultName = o, t(n.d, regeneratorValues(r), a);
6544 },
6545 finish: function finish(r) {
6546 return t(n.f, r);
6547 }
6548 }, t = function t(r, _t, o) {
6549 n.p = e.prev, n.n = e.next;
6550 try {
6551 return r(_t, o);
6552 } finally {
6553 e.next = n.n;
6554 }
6555 }), e.resultName && (e[e.resultName] = n.v, e.resultName = void 0), e.sent = n.v, e.next = n.n;
6556 try {
6557 return r.call(this, e);
6558 } finally {
6559 n.p = e.prev, n.n = e.next;
6560 }
6561 };
6562 }
6563 return (module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
6564 return {
6565 wrap: function wrap(e, t, n, o) {
6566 return r.w(a(e), t, n, o && o.reverse());
6567 },
6568 isGeneratorFunction: n,
6569 mark: r.m,
6570 awrap: function awrap(r, e) {
6571 return new OverloadYield(r, e);
6572 },
6573 AsyncIterator: regeneratorAsyncIterator,
6574 async: function async(r, e, t, o, u) {
6575 return (n(e) ? regeneratorAsyncGen : regeneratorAsync)(a(r), e, t, o, u);
6576 },
6577 keys: regeneratorKeys,
6578 values: regeneratorValues
6579 };
6580 }, module.exports.__esModule = true, module.exports["default"] = module.exports)();
6581 }
6582 module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
6583
6584 /***/ }),
6585
6586 /***/ "../node_modules/@babel/runtime/helpers/regeneratorValues.js":
6587 /*!*******************************************************************!*\
6588 !*** ../node_modules/@babel/runtime/helpers/regeneratorValues.js ***!
6589 \*******************************************************************/
6590 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6591
6592 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6593 function _regeneratorValues(e) {
6594 if (null != e) {
6595 var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
6596 r = 0;
6597 if (t) return t.call(e);
6598 if ("function" == typeof e.next) return e;
6599 if (!isNaN(e.length)) return {
6600 next: function next() {
6601 return e && r >= e.length && (e = void 0), {
6602 value: e && e[r++],
6603 done: !e
6604 };
6605 }
6606 };
6607 }
6608 throw new TypeError(_typeof(e) + " is not iterable");
6609 }
6610 module.exports = _regeneratorValues, module.exports.__esModule = true, module.exports["default"] = module.exports;
6611
6612 /***/ }),
6613
6614 /***/ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js":
6615 /*!****************************************************************!*\
6616 !*** ../node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
6617 \****************************************************************/
6618 /***/ ((module) => {
6619
6620 function _setPrototypeOf(t, e) {
6621 return module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
6622 return t.__proto__ = e, t;
6623 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _setPrototypeOf(t, e);
6624 }
6625 module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
6626
6627 /***/ }),
6628
6629 /***/ "../node_modules/@babel/runtime/helpers/slicedToArray.js":
6630 /*!***************************************************************!*\
6631 !*** ../node_modules/@babel/runtime/helpers/slicedToArray.js ***!
6632 \***************************************************************/
6633 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6634
6635 var arrayWithHoles = __webpack_require__(/*! ./arrayWithHoles.js */ "../node_modules/@babel/runtime/helpers/arrayWithHoles.js");
6636 var iterableToArrayLimit = __webpack_require__(/*! ./iterableToArrayLimit.js */ "../node_modules/@babel/runtime/helpers/iterableToArrayLimit.js");
6637 var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray.js */ "../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js");
6638 var nonIterableRest = __webpack_require__(/*! ./nonIterableRest.js */ "../node_modules/@babel/runtime/helpers/nonIterableRest.js");
6639 function _slicedToArray(r, e) {
6640 return arrayWithHoles(r) || iterableToArrayLimit(r, e) || unsupportedIterableToArray(r, e) || nonIterableRest();
6641 }
6642 module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
6643
6644 /***/ }),
6645
6646 /***/ "../node_modules/@babel/runtime/helpers/superPropBase.js":
6647 /*!***************************************************************!*\
6648 !*** ../node_modules/@babel/runtime/helpers/superPropBase.js ***!
6649 \***************************************************************/
6650 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6651
6652 var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js");
6653 function _superPropBase(t, o) {
6654 for (; !{}.hasOwnProperty.call(t, o) && null !== (t = getPrototypeOf(t)););
6655 return t;
6656 }
6657 module.exports = _superPropBase, module.exports.__esModule = true, module.exports["default"] = module.exports;
6658
6659 /***/ }),
6660
6661 /***/ "../node_modules/@babel/runtime/helpers/toPrimitive.js":
6662 /*!*************************************************************!*\
6663 !*** ../node_modules/@babel/runtime/helpers/toPrimitive.js ***!
6664 \*************************************************************/
6665 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6666
6667 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6668 function toPrimitive(t, r) {
6669 if ("object" != _typeof(t) || !t) return t;
6670 var e = t[Symbol.toPrimitive];
6671 if (void 0 !== e) {
6672 var i = e.call(t, r || "default");
6673 if ("object" != _typeof(i)) return i;
6674 throw new TypeError("@@toPrimitive must return a primitive value.");
6675 }
6676 return ("string" === r ? String : Number)(t);
6677 }
6678 module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
6679
6680 /***/ }),
6681
6682 /***/ "../node_modules/@babel/runtime/helpers/toPropertyKey.js":
6683 /*!***************************************************************!*\
6684 !*** ../node_modules/@babel/runtime/helpers/toPropertyKey.js ***!
6685 \***************************************************************/
6686 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6687
6688 var _typeof = (__webpack_require__(/*! ./typeof.js */ "../node_modules/@babel/runtime/helpers/typeof.js")["default"]);
6689 var toPrimitive = __webpack_require__(/*! ./toPrimitive.js */ "../node_modules/@babel/runtime/helpers/toPrimitive.js");
6690 function toPropertyKey(t) {
6691 var i = toPrimitive(t, "string");
6692 return "symbol" == _typeof(i) ? i : i + "";
6693 }
6694 module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
6695
6696 /***/ }),
6697
6698 /***/ "../node_modules/@babel/runtime/helpers/typeof.js":
6699 /*!********************************************************!*\
6700 !*** ../node_modules/@babel/runtime/helpers/typeof.js ***!
6701 \********************************************************/
6702 /***/ ((module) => {
6703
6704 function _typeof(o) {
6705 "@babel/helpers - typeof";
6706
6707 return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
6708 return typeof o;
6709 } : function (o) {
6710 return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
6711 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o);
6712 }
6713 module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
6714
6715 /***/ }),
6716
6717 /***/ "../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js":
6718 /*!****************************************************************************!*\
6719 !*** ../node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js ***!
6720 \****************************************************************************/
6721 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6722
6723 var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray.js */ "../node_modules/@babel/runtime/helpers/arrayLikeToArray.js");
6724 function _unsupportedIterableToArray(r, a) {
6725 if (r) {
6726 if ("string" == typeof r) return arrayLikeToArray(r, a);
6727 var t = {}.toString.call(r).slice(8, -1);
6728 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;
6729 }
6730 }
6731 module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
6732
6733 /***/ }),
6734
6735 /***/ "../node_modules/@babel/runtime/helpers/wrapNativeSuper.js":
6736 /*!*****************************************************************!*\
6737 !*** ../node_modules/@babel/runtime/helpers/wrapNativeSuper.js ***!
6738 \*****************************************************************/
6739 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6740
6741 var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js");
6742 var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf.js */ "../node_modules/@babel/runtime/helpers/setPrototypeOf.js");
6743 var isNativeFunction = __webpack_require__(/*! ./isNativeFunction.js */ "../node_modules/@babel/runtime/helpers/isNativeFunction.js");
6744 var construct = __webpack_require__(/*! ./construct.js */ "../node_modules/@babel/runtime/helpers/construct.js");
6745 function _wrapNativeSuper(t) {
6746 var r = "function" == typeof Map ? new Map() : void 0;
6747 return module.exports = _wrapNativeSuper = function _wrapNativeSuper(t) {
6748 if (null === t || !isNativeFunction(t)) return t;
6749 if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
6750 if (void 0 !== r) {
6751 if (r.has(t)) return r.get(t);
6752 r.set(t, Wrapper);
6753 }
6754 function Wrapper() {
6755 return construct(t, arguments, getPrototypeOf(this).constructor);
6756 }
6757 return Wrapper.prototype = Object.create(t.prototype, {
6758 constructor: {
6759 value: Wrapper,
6760 enumerable: !1,
6761 writable: !0,
6762 configurable: !0
6763 }
6764 }), setPrototypeOf(Wrapper, t);
6765 }, module.exports.__esModule = true, module.exports["default"] = module.exports, _wrapNativeSuper(t);
6766 }
6767 module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports;
6768
6769 /***/ }),
6770
6771 /***/ "../node_modules/@babel/runtime/regenerator/index.js":
6772 /*!***********************************************************!*\
6773 !*** ../node_modules/@babel/runtime/regenerator/index.js ***!
6774 \***********************************************************/
6775 /***/ ((module, __unused_webpack_exports, __webpack_require__) => {
6776
6777 // TODO(Babel 8): Remove this file.
6778
6779 var runtime = __webpack_require__(/*! ../helpers/regeneratorRuntime */ "../node_modules/@babel/runtime/helpers/regeneratorRuntime.js")();
6780 module.exports = runtime;
6781
6782 // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
6783 try {
6784 regeneratorRuntime = runtime;
6785 } catch (accidentalStrictMode) {
6786 if (typeof globalThis === "object") {
6787 globalThis.regeneratorRuntime = runtime;
6788 } else {
6789 Function("r", "regeneratorRuntime = r")(runtime);
6790 }
6791 }
6792
6793
6794 /***/ }),
6795
6796 /***/ "../node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js":
6797 /*!******************************************************************!*\
6798 !*** ../node_modules/@reduxjs/toolkit/dist/redux-toolkit.esm.js ***!
6799 \******************************************************************/
6800 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
6801
6802 "use strict";
6803 __webpack_require__.r(__webpack_exports__);
6804 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6805 /* harmony export */ EnhancerArray: () => (/* binding */ EnhancerArray),
6806 /* harmony export */ MiddlewareArray: () => (/* binding */ MiddlewareArray),
6807 /* harmony export */ SHOULD_AUTOBATCH: () => (/* binding */ SHOULD_AUTOBATCH),
6808 /* harmony export */ TaskAbortError: () => (/* binding */ TaskAbortError),
6809 /* harmony export */ __DO_NOT_USE__ActionTypes: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.__DO_NOT_USE__ActionTypes),
6810 /* harmony export */ addListener: () => (/* binding */ addListener),
6811 /* harmony export */ applyMiddleware: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.applyMiddleware),
6812 /* harmony export */ autoBatchEnhancer: () => (/* binding */ autoBatchEnhancer),
6813 /* harmony export */ bindActionCreators: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.bindActionCreators),
6814 /* harmony export */ clearAllListeners: () => (/* binding */ clearAllListeners),
6815 /* harmony export */ combineReducers: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.combineReducers),
6816 /* harmony export */ compose: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.compose),
6817 /* harmony export */ configureStore: () => (/* binding */ configureStore),
6818 /* harmony export */ createAction: () => (/* binding */ createAction),
6819 /* harmony export */ createActionCreatorInvariantMiddleware: () => (/* binding */ createActionCreatorInvariantMiddleware),
6820 /* harmony export */ createAsyncThunk: () => (/* binding */ createAsyncThunk),
6821 /* harmony export */ createDraftSafeSelector: () => (/* binding */ createDraftSafeSelector),
6822 /* harmony export */ createEntityAdapter: () => (/* binding */ createEntityAdapter),
6823 /* harmony export */ createImmutableStateInvariantMiddleware: () => (/* binding */ createImmutableStateInvariantMiddleware),
6824 /* harmony export */ createListenerMiddleware: () => (/* binding */ createListenerMiddleware),
6825 /* harmony export */ createNextState: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__["default"]),
6826 /* harmony export */ createReducer: () => (/* binding */ createReducer),
6827 /* harmony export */ createSelector: () => (/* reexport safe */ reselect__WEBPACK_IMPORTED_MODULE_2__.createSelector),
6828 /* harmony export */ createSerializableStateInvariantMiddleware: () => (/* binding */ createSerializableStateInvariantMiddleware),
6829 /* harmony export */ createSlice: () => (/* binding */ createSlice),
6830 /* harmony export */ createStore: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.createStore),
6831 /* harmony export */ current: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__.current),
6832 /* harmony export */ findNonSerializableValue: () => (/* binding */ findNonSerializableValue),
6833 /* harmony export */ freeze: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__.freeze),
6834 /* harmony export */ getDefaultMiddleware: () => (/* binding */ getDefaultMiddleware),
6835 /* harmony export */ getType: () => (/* binding */ getType),
6836 /* harmony export */ isAction: () => (/* binding */ isAction),
6837 /* harmony export */ isActionCreator: () => (/* binding */ isActionCreator),
6838 /* harmony export */ isAllOf: () => (/* binding */ isAllOf),
6839 /* harmony export */ isAnyOf: () => (/* binding */ isAnyOf),
6840 /* harmony export */ isAsyncThunkAction: () => (/* binding */ isAsyncThunkAction),
6841 /* harmony export */ isDraft: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__.isDraft),
6842 /* harmony export */ isFluxStandardAction: () => (/* binding */ isFSA),
6843 /* harmony export */ isFulfilled: () => (/* binding */ isFulfilled),
6844 /* harmony export */ isImmutableDefault: () => (/* binding */ isImmutableDefault),
6845 /* harmony export */ isPending: () => (/* binding */ isPending),
6846 /* harmony export */ isPlain: () => (/* binding */ isPlain),
6847 /* harmony export */ isPlainObject: () => (/* binding */ isPlainObject),
6848 /* harmony export */ isRejected: () => (/* binding */ isRejected),
6849 /* harmony export */ isRejectedWithValue: () => (/* binding */ isRejectedWithValue),
6850 /* harmony export */ legacy_createStore: () => (/* reexport safe */ redux__WEBPACK_IMPORTED_MODULE_1__.legacy_createStore),
6851 /* harmony export */ miniSerializeError: () => (/* binding */ miniSerializeError),
6852 /* harmony export */ nanoid: () => (/* binding */ nanoid),
6853 /* harmony export */ original: () => (/* reexport safe */ immer__WEBPACK_IMPORTED_MODULE_0__.original),
6854 /* harmony export */ prepareAutoBatched: () => (/* binding */ prepareAutoBatched),
6855 /* harmony export */ removeListener: () => (/* binding */ removeListener),
6856 /* harmony export */ unwrapResult: () => (/* binding */ unwrapResult)
6857 /* harmony export */ });
6858 /* harmony import */ var immer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! immer */ "../node_modules/immer/dist/immer.esm.mjs");
6859 /* harmony import */ var redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! redux */ "../node_modules/redux/es/redux.js");
6860 /* harmony import */ var reselect__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! reselect */ "../node_modules/reselect/es/index.js");
6861 /* harmony import */ var redux_thunk__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! redux-thunk */ "../node_modules/redux-thunk/es/index.js");
6862 var __extends = (undefined && undefined.__extends) || (function () {
6863 var extendStatics = function (d, b) {
6864 extendStatics = Object.setPrototypeOf ||
6865 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6866 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6867 return extendStatics(d, b);
6868 };
6869 return function (d, b) {
6870 if (typeof b !== "function" && b !== null)
6871 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
6872 extendStatics(d, b);
6873 function __() { this.constructor = d; }
6874 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
6875 };
6876 })();
6877 var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
6878 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
6879 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
6880 function verb(n) { return function (v) { return step([n, v]); }; }
6881 function step(op) {
6882 if (f) throw new TypeError("Generator is already executing.");
6883 while (_) try {
6884 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;
6885 if (y = 0, t) op = [op[0] & 2, t.value];
6886 switch (op[0]) {
6887 case 0: case 1: t = op; break;
6888 case 4: _.label++; return { value: op[1], done: false };
6889 case 5: _.label++; y = op[1]; op = [0]; continue;
6890 case 7: op = _.ops.pop(); _.trys.pop(); continue;
6891 default:
6892 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
6893 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
6894 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
6895 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
6896 if (t[2]) _.ops.pop();
6897 _.trys.pop(); continue;
6898 }
6899 op = body.call(thisArg, _);
6900 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
6901 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
6902 }
6903 };
6904 var __spreadArray = (undefined && undefined.__spreadArray) || function (to, from) {
6905 for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
6906 to[j] = from[i];
6907 return to;
6908 };
6909 var __defProp = Object.defineProperty;
6910 var __defProps = Object.defineProperties;
6911 var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6912 var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6913 var __hasOwnProp = Object.prototype.hasOwnProperty;
6914 var __propIsEnum = Object.prototype.propertyIsEnumerable;
6915 var __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };
6916 var __spreadValues = function (a, b) {
6917 for (var prop in b || (b = {}))
6918 if (__hasOwnProp.call(b, prop))
6919 __defNormalProp(a, prop, b[prop]);
6920 if (__getOwnPropSymbols)
6921 for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {
6922 var prop = _c[_i];
6923 if (__propIsEnum.call(b, prop))
6924 __defNormalProp(a, prop, b[prop]);
6925 }
6926 return a;
6927 };
6928 var __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };
6929 var __async = function (__this, __arguments, generator) {
6930 return new Promise(function (resolve, reject) {
6931 var fulfilled = function (value) {
6932 try {
6933 step(generator.next(value));
6934 }
6935 catch (e) {
6936 reject(e);
6937 }
6938 };
6939 var rejected = function (value) {
6940 try {
6941 step(generator.throw(value));
6942 }
6943 catch (e) {
6944 reject(e);
6945 }
6946 };
6947 var step = function (x) { return x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); };
6948 step((generator = generator.apply(__this, __arguments)).next());
6949 });
6950 };
6951 // src/index.ts
6952
6953
6954
6955
6956 // src/createDraftSafeSelector.ts
6957
6958
6959 var createDraftSafeSelector = function () {
6960 var args = [];
6961 for (var _i = 0; _i < arguments.length; _i++) {
6962 args[_i] = arguments[_i];
6963 }
6964 var selector = reselect__WEBPACK_IMPORTED_MODULE_2__.createSelector.apply(void 0, args);
6965 var wrappedSelector = function (value) {
6966 var rest = [];
6967 for (var _i = 1; _i < arguments.length; _i++) {
6968 rest[_i - 1] = arguments[_i];
6969 }
6970 return selector.apply(void 0, __spreadArray([(0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraft)(value) ? (0,immer__WEBPACK_IMPORTED_MODULE_0__.current)(value) : value], rest));
6971 };
6972 return wrappedSelector;
6973 };
6974 // src/configureStore.ts
6975
6976 // src/devtoolsExtension.ts
6977
6978 var composeWithDevTools = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function () {
6979 if (arguments.length === 0)
6980 return void 0;
6981 if (typeof arguments[0] === "object")
6982 return redux__WEBPACK_IMPORTED_MODULE_1__.compose;
6983 return redux__WEBPACK_IMPORTED_MODULE_1__.compose.apply(null, arguments);
6984 };
6985 var devToolsEnhancer = typeof window !== "undefined" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function () {
6986 return function (noop2) {
6987 return noop2;
6988 };
6989 };
6990 // src/isPlainObject.ts
6991 function isPlainObject(value) {
6992 if (typeof value !== "object" || value === null)
6993 return false;
6994 var proto = Object.getPrototypeOf(value);
6995 if (proto === null)
6996 return true;
6997 var baseProto = proto;
6998 while (Object.getPrototypeOf(baseProto) !== null) {
6999 baseProto = Object.getPrototypeOf(baseProto);
7000 }
7001 return proto === baseProto;
7002 }
7003 // src/getDefaultMiddleware.ts
7004
7005 // src/tsHelpers.ts
7006 var hasMatchFunction = function (v) {
7007 return v && typeof v.match === "function";
7008 };
7009 // src/createAction.ts
7010 function createAction(type, prepareAction) {
7011 function actionCreator() {
7012 var args = [];
7013 for (var _i = 0; _i < arguments.length; _i++) {
7014 args[_i] = arguments[_i];
7015 }
7016 if (prepareAction) {
7017 var prepared = prepareAction.apply(void 0, args);
7018 if (!prepared) {
7019 throw new Error("prepareAction did not return an object");
7020 }
7021 return __spreadValues(__spreadValues({
7022 type: type,
7023 payload: prepared.payload
7024 }, "meta" in prepared && { meta: prepared.meta }), "error" in prepared && { error: prepared.error });
7025 }
7026 return { type: type, payload: args[0] };
7027 }
7028 actionCreator.toString = function () { return "" + type; };
7029 actionCreator.type = type;
7030 actionCreator.match = function (action) { return action.type === type; };
7031 return actionCreator;
7032 }
7033 function isAction(action) {
7034 return isPlainObject(action) && "type" in action;
7035 }
7036 function isActionCreator(action) {
7037 return typeof action === "function" && "type" in action && hasMatchFunction(action);
7038 }
7039 function isFSA(action) {
7040 return isAction(action) && typeof action.type === "string" && Object.keys(action).every(isValidKey);
7041 }
7042 function isValidKey(key) {
7043 return ["type", "payload", "error", "meta"].indexOf(key) > -1;
7044 }
7045 function getType(actionCreator) {
7046 return "" + actionCreator;
7047 }
7048 // src/actionCreatorInvariantMiddleware.ts
7049 function getMessage(type) {
7050 var splitType = type ? ("" + type).split("/") : [];
7051 var actionName = splitType[splitType.length - 1] || "actionCreator";
7052 return "Detected an action creator with type \"" + (type || "unknown") + "\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. `dispatch(" + actionName + "())` instead of `dispatch(" + actionName + ")`. This is necessary even if the action has no payload.";
7053 }
7054 function createActionCreatorInvariantMiddleware(options) {
7055 if (options === void 0) { options = {}; }
7056 if (false) // removed by dead control flow
7057 {}
7058 var _c = options.isActionCreator, isActionCreator2 = _c === void 0 ? isActionCreator : _c;
7059 return function () { return function (next) { return function (action) {
7060 if (isActionCreator2(action)) {
7061 console.warn(getMessage(action.type));
7062 }
7063 return next(action);
7064 }; }; };
7065 }
7066 // src/utils.ts
7067
7068 function getTimeMeasureUtils(maxDelay, fnName) {
7069 var elapsed = 0;
7070 return {
7071 measureTime: function (fn) {
7072 var started = Date.now();
7073 try {
7074 return fn();
7075 }
7076 finally {
7077 var finished = Date.now();
7078 elapsed += finished - started;
7079 }
7080 },
7081 warnIfExceeded: function () {
7082 if (elapsed > maxDelay) {
7083 console.warn(fnName + " took " + elapsed + "ms, which is more than the warning threshold of " + maxDelay + "ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.");
7084 }
7085 }
7086 };
7087 }
7088 var MiddlewareArray = /** @class */ (function (_super) {
7089 __extends(MiddlewareArray, _super);
7090 function MiddlewareArray() {
7091 var args = [];
7092 for (var _i = 0; _i < arguments.length; _i++) {
7093 args[_i] = arguments[_i];
7094 }
7095 var _this = _super.apply(this, args) || this;
7096 Object.setPrototypeOf(_this, MiddlewareArray.prototype);
7097 return _this;
7098 }
7099 Object.defineProperty(MiddlewareArray, Symbol.species, {
7100 get: function () {
7101 return MiddlewareArray;
7102 },
7103 enumerable: false,
7104 configurable: true
7105 });
7106 MiddlewareArray.prototype.concat = function () {
7107 var arr = [];
7108 for (var _i = 0; _i < arguments.length; _i++) {
7109 arr[_i] = arguments[_i];
7110 }
7111 return _super.prototype.concat.apply(this, arr);
7112 };
7113 MiddlewareArray.prototype.prepend = function () {
7114 var arr = [];
7115 for (var _i = 0; _i < arguments.length; _i++) {
7116 arr[_i] = arguments[_i];
7117 }
7118 if (arr.length === 1 && Array.isArray(arr[0])) {
7119 return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr[0].concat(this))))();
7120 }
7121 return new (MiddlewareArray.bind.apply(MiddlewareArray, __spreadArray([void 0], arr.concat(this))))();
7122 };
7123 return MiddlewareArray;
7124 }(Array));
7125 var EnhancerArray = /** @class */ (function (_super) {
7126 __extends(EnhancerArray, _super);
7127 function EnhancerArray() {
7128 var args = [];
7129 for (var _i = 0; _i < arguments.length; _i++) {
7130 args[_i] = arguments[_i];
7131 }
7132 var _this = _super.apply(this, args) || this;
7133 Object.setPrototypeOf(_this, EnhancerArray.prototype);
7134 return _this;
7135 }
7136 Object.defineProperty(EnhancerArray, Symbol.species, {
7137 get: function () {
7138 return EnhancerArray;
7139 },
7140 enumerable: false,
7141 configurable: true
7142 });
7143 EnhancerArray.prototype.concat = function () {
7144 var arr = [];
7145 for (var _i = 0; _i < arguments.length; _i++) {
7146 arr[_i] = arguments[_i];
7147 }
7148 return _super.prototype.concat.apply(this, arr);
7149 };
7150 EnhancerArray.prototype.prepend = function () {
7151 var arr = [];
7152 for (var _i = 0; _i < arguments.length; _i++) {
7153 arr[_i] = arguments[_i];
7154 }
7155 if (arr.length === 1 && Array.isArray(arr[0])) {
7156 return new (EnhancerArray.bind.apply(EnhancerArray, __spreadArray([void 0], arr[0].concat(this))))();
7157 }
7158 return new (EnhancerArray.bind.apply(EnhancerArray, __spreadArray([void 0], arr.concat(this))))();
7159 };
7160 return EnhancerArray;
7161 }(Array));
7162 function freezeDraftable(val) {
7163 return (0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraftable)(val) ? (0,immer__WEBPACK_IMPORTED_MODULE_0__["default"])(val, function () {
7164 }) : val;
7165 }
7166 // src/immutableStateInvariantMiddleware.ts
7167 var isProduction = "development" === "production";
7168 var prefix = "Invariant failed";
7169 function invariant(condition, message) {
7170 if (condition) {
7171 return;
7172 }
7173 if (isProduction) {
7174 throw new Error(prefix);
7175 }
7176 throw new Error(prefix + ": " + (message || ""));
7177 }
7178 function stringify(obj, serializer, indent, decycler) {
7179 return JSON.stringify(obj, getSerialize(serializer, decycler), indent);
7180 }
7181 function getSerialize(serializer, decycler) {
7182 var stack = [], keys = [];
7183 if (!decycler)
7184 decycler = function (_, value) {
7185 if (stack[0] === value)
7186 return "[Circular ~]";
7187 return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]";
7188 };
7189 return function (key, value) {
7190 if (stack.length > 0) {
7191 var thisPos = stack.indexOf(this);
7192 ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
7193 ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
7194 if (~stack.indexOf(value))
7195 value = decycler.call(this, key, value);
7196 }
7197 else
7198 stack.push(value);
7199 return serializer == null ? value : serializer.call(this, key, value);
7200 };
7201 }
7202 function isImmutableDefault(value) {
7203 return typeof value !== "object" || value == null || Object.isFrozen(value);
7204 }
7205 function trackForMutations(isImmutable, ignorePaths, obj) {
7206 var trackedProperties = trackProperties(isImmutable, ignorePaths, obj);
7207 return {
7208 detectMutations: function () {
7209 return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);
7210 }
7211 };
7212 }
7213 function trackProperties(isImmutable, ignorePaths, obj, path, checkedObjects) {
7214 if (ignorePaths === void 0) { ignorePaths = []; }
7215 if (path === void 0) { path = ""; }
7216 if (checkedObjects === void 0) { checkedObjects = new Set(); }
7217 var tracked = { value: obj };
7218 if (!isImmutable(obj) && !checkedObjects.has(obj)) {
7219 checkedObjects.add(obj);
7220 tracked.children = {};
7221 for (var key in obj) {
7222 var childPath = path ? path + "." + key : key;
7223 if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {
7224 continue;
7225 }
7226 tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);
7227 }
7228 }
7229 return tracked;
7230 }
7231 function detectMutations(isImmutable, ignoredPaths, trackedProperty, obj, sameParentRef, path) {
7232 if (ignoredPaths === void 0) { ignoredPaths = []; }
7233 if (sameParentRef === void 0) { sameParentRef = false; }
7234 if (path === void 0) { path = ""; }
7235 var prevObj = trackedProperty ? trackedProperty.value : void 0;
7236 var sameRef = prevObj === obj;
7237 if (sameParentRef && !sameRef && !Number.isNaN(obj)) {
7238 return { wasMutated: true, path: path };
7239 }
7240 if (isImmutable(prevObj) || isImmutable(obj)) {
7241 return { wasMutated: false };
7242 }
7243 var keysToDetect = {};
7244 for (var key in trackedProperty.children) {
7245 keysToDetect[key] = true;
7246 }
7247 for (var key in obj) {
7248 keysToDetect[key] = true;
7249 }
7250 var hasIgnoredPaths = ignoredPaths.length > 0;
7251 var _loop_1 = function (key) {
7252 var nestedPath = path ? path + "." + key : key;
7253 if (hasIgnoredPaths) {
7254 var hasMatches = ignoredPaths.some(function (ignored) {
7255 if (ignored instanceof RegExp) {
7256 return ignored.test(nestedPath);
7257 }
7258 return nestedPath === ignored;
7259 });
7260 if (hasMatches) {
7261 return "continue";
7262 }
7263 }
7264 var result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);
7265 if (result.wasMutated) {
7266 return { value: result };
7267 }
7268 };
7269 for (var key in keysToDetect) {
7270 var state_1 = _loop_1(key);
7271 if (typeof state_1 === "object")
7272 return state_1.value;
7273 }
7274 return { wasMutated: false };
7275 }
7276 function createImmutableStateInvariantMiddleware(options) {
7277 if (options === void 0) { options = {}; }
7278 if (false) // removed by dead control flow
7279 {}
7280 var _c = options.isImmutable, isImmutable = _c === void 0 ? isImmutableDefault : _c, ignoredPaths = options.ignoredPaths, _d = options.warnAfter, warnAfter = _d === void 0 ? 32 : _d, ignore = options.ignore;
7281 ignoredPaths = ignoredPaths || ignore;
7282 var track = trackForMutations.bind(null, isImmutable, ignoredPaths);
7283 return function (_c) {
7284 var getState = _c.getState;
7285 var state = getState();
7286 var tracker = track(state);
7287 var result;
7288 return function (next) { return function (action) {
7289 var measureUtils = getTimeMeasureUtils(warnAfter, "ImmutableStateInvariantMiddleware");
7290 measureUtils.measureTime(function () {
7291 state = getState();
7292 result = tracker.detectMutations();
7293 tracker = track(state);
7294 invariant(!result.wasMutated, "A state mutation was detected between dispatches, in the path '" + (result.path || "") + "'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)");
7295 });
7296 var dispatchedAction = next(action);
7297 measureUtils.measureTime(function () {
7298 state = getState();
7299 result = tracker.detectMutations();
7300 tracker = track(state);
7301 result.wasMutated && invariant(!result.wasMutated, "A state mutation was detected inside a dispatch, in the path: " + (result.path || "") + ". Take a look at the reducer(s) handling the action " + stringify(action) + ". (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)");
7302 });
7303 measureUtils.warnIfExceeded();
7304 return dispatchedAction;
7305 }; };
7306 };
7307 }
7308 // src/serializableStateInvariantMiddleware.ts
7309 function isPlain(val) {
7310 var type = typeof val;
7311 return val == null || type === "string" || type === "boolean" || type === "number" || Array.isArray(val) || isPlainObject(val);
7312 }
7313 function findNonSerializableValue(value, path, isSerializable, getEntries, ignoredPaths, cache) {
7314 if (path === void 0) { path = ""; }
7315 if (isSerializable === void 0) { isSerializable = isPlain; }
7316 if (ignoredPaths === void 0) { ignoredPaths = []; }
7317 var foundNestedSerializable;
7318 if (!isSerializable(value)) {
7319 return {
7320 keyPath: path || "<root>",
7321 value: value
7322 };
7323 }
7324 if (typeof value !== "object" || value === null) {
7325 return false;
7326 }
7327 if (cache == null ? void 0 : cache.has(value))
7328 return false;
7329 var entries = getEntries != null ? getEntries(value) : Object.entries(value);
7330 var hasIgnoredPaths = ignoredPaths.length > 0;
7331 var _loop_2 = function (key, nestedValue) {
7332 var nestedPath = path ? path + "." + key : key;
7333 if (hasIgnoredPaths) {
7334 var hasMatches = ignoredPaths.some(function (ignored) {
7335 if (ignored instanceof RegExp) {
7336 return ignored.test(nestedPath);
7337 }
7338 return nestedPath === ignored;
7339 });
7340 if (hasMatches) {
7341 return "continue";
7342 }
7343 }
7344 if (!isSerializable(nestedValue)) {
7345 return { value: {
7346 keyPath: nestedPath,
7347 value: nestedValue
7348 } };
7349 }
7350 if (typeof nestedValue === "object") {
7351 foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);
7352 if (foundNestedSerializable) {
7353 return { value: foundNestedSerializable };
7354 }
7355 }
7356 };
7357 for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
7358 var _c = entries_1[_i], key = _c[0], nestedValue = _c[1];
7359 var state_2 = _loop_2(key, nestedValue);
7360 if (typeof state_2 === "object")
7361 return state_2.value;
7362 }
7363 if (cache && isNestedFrozen(value))
7364 cache.add(value);
7365 return false;
7366 }
7367 function isNestedFrozen(value) {
7368 if (!Object.isFrozen(value))
7369 return false;
7370 for (var _i = 0, _c = Object.values(value); _i < _c.length; _i++) {
7371 var nestedValue = _c[_i];
7372 if (typeof nestedValue !== "object" || nestedValue === null)
7373 continue;
7374 if (!isNestedFrozen(nestedValue))
7375 return false;
7376 }
7377 return true;
7378 }
7379 function createSerializableStateInvariantMiddleware(options) {
7380 if (options === void 0) { options = {}; }
7381 if (false) // removed by dead control flow
7382 {}
7383 var _c = options.isSerializable, isSerializable = _c === void 0 ? isPlain : _c, getEntries = options.getEntries, _d = options.ignoredActions, ignoredActions = _d === void 0 ? [] : _d, _e = options.ignoredActionPaths, ignoredActionPaths = _e === void 0 ? ["meta.arg", "meta.baseQueryMeta"] : _e, _f = options.ignoredPaths, ignoredPaths = _f === void 0 ? [] : _f, _g = options.warnAfter, warnAfter = _g === void 0 ? 32 : _g, _h = options.ignoreState, ignoreState = _h === void 0 ? false : _h, _j = options.ignoreActions, ignoreActions = _j === void 0 ? false : _j, _k = options.disableCache, disableCache = _k === void 0 ? false : _k;
7384 var cache = !disableCache && WeakSet ? new WeakSet() : void 0;
7385 return function (storeAPI) { return function (next) { return function (action) {
7386 var result = next(action);
7387 var measureUtils = getTimeMeasureUtils(warnAfter, "SerializableStateInvariantMiddleware");
7388 if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {
7389 measureUtils.measureTime(function () {
7390 var foundActionNonSerializableValue = findNonSerializableValue(action, "", isSerializable, getEntries, ignoredActionPaths, cache);
7391 if (foundActionNonSerializableValue) {
7392 var keyPath = foundActionNonSerializableValue.keyPath, value = foundActionNonSerializableValue.value;
7393 console.error("A non-serializable value was detected in an action, in the path: `" + keyPath + "`. Value:", value, "\nTake a look at the logic that dispatched this action: ", action, "\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)", "\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)");
7394 }
7395 });
7396 }
7397 if (!ignoreState) {
7398 measureUtils.measureTime(function () {
7399 var state = storeAPI.getState();
7400 var foundStateNonSerializableValue = findNonSerializableValue(state, "", isSerializable, getEntries, ignoredPaths, cache);
7401 if (foundStateNonSerializableValue) {
7402 var keyPath = foundStateNonSerializableValue.keyPath, value = foundStateNonSerializableValue.value;
7403 console.error("A non-serializable value was detected in the state, in the path: `" + keyPath + "`. Value:", value, "\nTake a look at the reducer(s) handling this action type: " + action.type + ".\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)");
7404 }
7405 });
7406 measureUtils.warnIfExceeded();
7407 }
7408 return result;
7409 }; }; };
7410 }
7411 // src/getDefaultMiddleware.ts
7412 function isBoolean(x) {
7413 return typeof x === "boolean";
7414 }
7415 function curryGetDefaultMiddleware() {
7416 return function curriedGetDefaultMiddleware(options) {
7417 return getDefaultMiddleware(options);
7418 };
7419 }
7420 function getDefaultMiddleware(options) {
7421 if (options === void 0) { options = {}; }
7422 var _c = options.thunk, thunk = _c === void 0 ? true : _c, _d = options.immutableCheck, immutableCheck = _d === void 0 ? true : _d, _e = options.serializableCheck, serializableCheck = _e === void 0 ? true : _e, _f = options.actionCreatorCheck, actionCreatorCheck = _f === void 0 ? true : _f;
7423 var middlewareArray = new MiddlewareArray();
7424 if (thunk) {
7425 if (isBoolean(thunk)) {
7426 middlewareArray.push(redux_thunk__WEBPACK_IMPORTED_MODULE_3__["default"]);
7427 }
7428 else {
7429 middlewareArray.push(redux_thunk__WEBPACK_IMPORTED_MODULE_3__["default"].withExtraArgument(thunk.extraArgument));
7430 }
7431 }
7432 if (true) {
7433 if (immutableCheck) {
7434 var immutableOptions = {};
7435 if (!isBoolean(immutableCheck)) {
7436 immutableOptions = immutableCheck;
7437 }
7438 middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));
7439 }
7440 if (serializableCheck) {
7441 var serializableOptions = {};
7442 if (!isBoolean(serializableCheck)) {
7443 serializableOptions = serializableCheck;
7444 }
7445 middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));
7446 }
7447 if (actionCreatorCheck) {
7448 var actionCreatorOptions = {};
7449 if (!isBoolean(actionCreatorCheck)) {
7450 actionCreatorOptions = actionCreatorCheck;
7451 }
7452 middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));
7453 }
7454 }
7455 return middlewareArray;
7456 }
7457 // src/configureStore.ts
7458 var IS_PRODUCTION = "development" === "production";
7459 function configureStore(options) {
7460 var curriedGetDefaultMiddleware = curryGetDefaultMiddleware();
7461 var _c = options || {}, _d = _c.reducer, reducer = _d === void 0 ? void 0 : _d, _e = _c.middleware, middleware = _e === void 0 ? curriedGetDefaultMiddleware() : _e, _f = _c.devTools, devTools = _f === void 0 ? true : _f, _g = _c.preloadedState, preloadedState = _g === void 0 ? void 0 : _g, _h = _c.enhancers, enhancers = _h === void 0 ? void 0 : _h;
7462 var rootReducer;
7463 if (typeof reducer === "function") {
7464 rootReducer = reducer;
7465 }
7466 else if (isPlainObject(reducer)) {
7467 rootReducer = (0,redux__WEBPACK_IMPORTED_MODULE_1__.combineReducers)(reducer);
7468 }
7469 else {
7470 throw new Error('"reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers');
7471 }
7472 var finalMiddleware = middleware;
7473 if (typeof finalMiddleware === "function") {
7474 finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware);
7475 if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {
7476 throw new Error("when using a middleware builder function, an array of middleware must be returned");
7477 }
7478 }
7479 if (!IS_PRODUCTION && finalMiddleware.some(function (item) { return typeof item !== "function"; })) {
7480 throw new Error("each middleware provided to configureStore must be a function");
7481 }
7482 var middlewareEnhancer = redux__WEBPACK_IMPORTED_MODULE_1__.applyMiddleware.apply(void 0, finalMiddleware);
7483 var finalCompose = redux__WEBPACK_IMPORTED_MODULE_1__.compose;
7484 if (devTools) {
7485 finalCompose = composeWithDevTools(__spreadValues({
7486 trace: !IS_PRODUCTION
7487 }, typeof devTools === "object" && devTools));
7488 }
7489 var defaultEnhancers = new EnhancerArray(middlewareEnhancer);
7490 var storeEnhancers = defaultEnhancers;
7491 if (Array.isArray(enhancers)) {
7492 storeEnhancers = __spreadArray([middlewareEnhancer], enhancers);
7493 }
7494 else if (typeof enhancers === "function") {
7495 storeEnhancers = enhancers(defaultEnhancers);
7496 }
7497 var composedEnhancer = finalCompose.apply(void 0, storeEnhancers);
7498 return (0,redux__WEBPACK_IMPORTED_MODULE_1__.createStore)(rootReducer, preloadedState, composedEnhancer);
7499 }
7500 // src/createReducer.ts
7501
7502 // src/mapBuilders.ts
7503 function executeReducerBuilderCallback(builderCallback) {
7504 var actionsMap = {};
7505 var actionMatchers = [];
7506 var defaultCaseReducer;
7507 var builder = {
7508 addCase: function (typeOrActionCreator, reducer) {
7509 if (true) {
7510 if (actionMatchers.length > 0) {
7511 throw new Error("`builder.addCase` should only be called before calling `builder.addMatcher`");
7512 }
7513 if (defaultCaseReducer) {
7514 throw new Error("`builder.addCase` should only be called before calling `builder.addDefaultCase`");
7515 }
7516 }
7517 var type = typeof typeOrActionCreator === "string" ? typeOrActionCreator : typeOrActionCreator.type;
7518 if (!type) {
7519 throw new Error("`builder.addCase` cannot be called with an empty action type");
7520 }
7521 if (type in actionsMap) {
7522 throw new Error("`builder.addCase` cannot be called with two reducers for the same action type");
7523 }
7524 actionsMap[type] = reducer;
7525 return builder;
7526 },
7527 addMatcher: function (matcher, reducer) {
7528 if (true) {
7529 if (defaultCaseReducer) {
7530 throw new Error("`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");
7531 }
7532 }
7533 actionMatchers.push({ matcher: matcher, reducer: reducer });
7534 return builder;
7535 },
7536 addDefaultCase: function (reducer) {
7537 if (true) {
7538 if (defaultCaseReducer) {
7539 throw new Error("`builder.addDefaultCase` can only be called once");
7540 }
7541 }
7542 defaultCaseReducer = reducer;
7543 return builder;
7544 }
7545 };
7546 builderCallback(builder);
7547 return [actionsMap, actionMatchers, defaultCaseReducer];
7548 }
7549 // src/createReducer.ts
7550 function isStateFunction(x) {
7551 return typeof x === "function";
7552 }
7553 var hasWarnedAboutObjectNotation = false;
7554 function createReducer(initialState, mapOrBuilderCallback, actionMatchers, defaultCaseReducer) {
7555 if (actionMatchers === void 0) { actionMatchers = []; }
7556 if (true) {
7557 if (typeof mapOrBuilderCallback === "object") {
7558 if (!hasWarnedAboutObjectNotation) {
7559 hasWarnedAboutObjectNotation = true;
7560 console.warn("The object notation for `createReducer` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");
7561 }
7562 }
7563 }
7564 var _c = typeof mapOrBuilderCallback === "function" ? executeReducerBuilderCallback(mapOrBuilderCallback) : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer], actionsMap = _c[0], finalActionMatchers = _c[1], finalDefaultCaseReducer = _c[2];
7565 var getInitialState;
7566 if (isStateFunction(initialState)) {
7567 getInitialState = function () { return freezeDraftable(initialState()); };
7568 }
7569 else {
7570 var frozenInitialState_1 = freezeDraftable(initialState);
7571 getInitialState = function () { return frozenInitialState_1; };
7572 }
7573 function reducer(state, action) {
7574 if (state === void 0) { state = getInitialState(); }
7575 var caseReducers = __spreadArray([
7576 actionsMap[action.type]
7577 ], finalActionMatchers.filter(function (_c) {
7578 var matcher = _c.matcher;
7579 return matcher(action);
7580 }).map(function (_c) {
7581 var reducer2 = _c.reducer;
7582 return reducer2;
7583 }));
7584 if (caseReducers.filter(function (cr) { return !!cr; }).length === 0) {
7585 caseReducers = [finalDefaultCaseReducer];
7586 }
7587 return caseReducers.reduce(function (previousState, caseReducer) {
7588 if (caseReducer) {
7589 if ((0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraft)(previousState)) {
7590 var draft = previousState;
7591 var result = caseReducer(draft, action);
7592 if (result === void 0) {
7593 return previousState;
7594 }
7595 return result;
7596 }
7597 else if (!(0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraftable)(previousState)) {
7598 var result = caseReducer(previousState, action);
7599 if (result === void 0) {
7600 if (previousState === null) {
7601 return previousState;
7602 }
7603 throw Error("A case reducer on a non-draftable value must not return undefined");
7604 }
7605 return result;
7606 }
7607 else {
7608 return (0,immer__WEBPACK_IMPORTED_MODULE_0__["default"])(previousState, function (draft) {
7609 return caseReducer(draft, action);
7610 });
7611 }
7612 }
7613 return previousState;
7614 }, state);
7615 }
7616 reducer.getInitialState = getInitialState;
7617 return reducer;
7618 }
7619 // src/createSlice.ts
7620 var hasWarnedAboutObjectNotation2 = false;
7621 function getType2(slice, actionKey) {
7622 return slice + "/" + actionKey;
7623 }
7624 function createSlice(options) {
7625 var name = options.name;
7626 if (!name) {
7627 throw new Error("`name` is a required option for createSlice");
7628 }
7629 if (typeof process !== "undefined" && "development" === "development") {
7630 if (options.initialState === void 0) {
7631 console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");
7632 }
7633 }
7634 var initialState = typeof options.initialState == "function" ? options.initialState : freezeDraftable(options.initialState);
7635 var reducers = options.reducers || {};
7636 var reducerNames = Object.keys(reducers);
7637 var sliceCaseReducersByName = {};
7638 var sliceCaseReducersByType = {};
7639 var actionCreators = {};
7640 reducerNames.forEach(function (reducerName) {
7641 var maybeReducerWithPrepare = reducers[reducerName];
7642 var type = getType2(name, reducerName);
7643 var caseReducer;
7644 var prepareCallback;
7645 if ("reducer" in maybeReducerWithPrepare) {
7646 caseReducer = maybeReducerWithPrepare.reducer;
7647 prepareCallback = maybeReducerWithPrepare.prepare;
7648 }
7649 else {
7650 caseReducer = maybeReducerWithPrepare;
7651 }
7652 sliceCaseReducersByName[reducerName] = caseReducer;
7653 sliceCaseReducersByType[type] = caseReducer;
7654 actionCreators[reducerName] = prepareCallback ? createAction(type, prepareCallback) : createAction(type);
7655 });
7656 function buildReducer() {
7657 if (true) {
7658 if (typeof options.extraReducers === "object") {
7659 if (!hasWarnedAboutObjectNotation2) {
7660 hasWarnedAboutObjectNotation2 = true;
7661 console.warn("The object notation for `createSlice.extraReducers` is deprecated, and will be removed in RTK 2.0. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");
7662 }
7663 }
7664 }
7665 var _c = typeof options.extraReducers === "function" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers], _d = _c[0], extraReducers = _d === void 0 ? {} : _d, _e = _c[1], actionMatchers = _e === void 0 ? [] : _e, _f = _c[2], defaultCaseReducer = _f === void 0 ? void 0 : _f;
7666 var finalCaseReducers = __spreadValues(__spreadValues({}, extraReducers), sliceCaseReducersByType);
7667 return createReducer(initialState, function (builder) {
7668 for (var key in finalCaseReducers) {
7669 builder.addCase(key, finalCaseReducers[key]);
7670 }
7671 for (var _i = 0, actionMatchers_1 = actionMatchers; _i < actionMatchers_1.length; _i++) {
7672 var m = actionMatchers_1[_i];
7673 builder.addMatcher(m.matcher, m.reducer);
7674 }
7675 if (defaultCaseReducer) {
7676 builder.addDefaultCase(defaultCaseReducer);
7677 }
7678 });
7679 }
7680 var _reducer;
7681 return {
7682 name: name,
7683 reducer: function (state, action) {
7684 if (!_reducer)
7685 _reducer = buildReducer();
7686 return _reducer(state, action);
7687 },
7688 actions: actionCreators,
7689 caseReducers: sliceCaseReducersByName,
7690 getInitialState: function () {
7691 if (!_reducer)
7692 _reducer = buildReducer();
7693 return _reducer.getInitialState();
7694 }
7695 };
7696 }
7697 // src/entities/entity_state.ts
7698 function getInitialEntityState() {
7699 return {
7700 ids: [],
7701 entities: {}
7702 };
7703 }
7704 function createInitialStateFactory() {
7705 function getInitialState(additionalState) {
7706 if (additionalState === void 0) { additionalState = {}; }
7707 return Object.assign(getInitialEntityState(), additionalState);
7708 }
7709 return { getInitialState: getInitialState };
7710 }
7711 // src/entities/state_selectors.ts
7712 function createSelectorsFactory() {
7713 function getSelectors(selectState) {
7714 var selectIds = function (state) { return state.ids; };
7715 var selectEntities = function (state) { return state.entities; };
7716 var selectAll = createDraftSafeSelector(selectIds, selectEntities, function (ids, entities) { return ids.map(function (id) { return entities[id]; }); });
7717 var selectId = function (_, id) { return id; };
7718 var selectById = function (entities, id) { return entities[id]; };
7719 var selectTotal = createDraftSafeSelector(selectIds, function (ids) { return ids.length; });
7720 if (!selectState) {
7721 return {
7722 selectIds: selectIds,
7723 selectEntities: selectEntities,
7724 selectAll: selectAll,
7725 selectTotal: selectTotal,
7726 selectById: createDraftSafeSelector(selectEntities, selectId, selectById)
7727 };
7728 }
7729 var selectGlobalizedEntities = createDraftSafeSelector(selectState, selectEntities);
7730 return {
7731 selectIds: createDraftSafeSelector(selectState, selectIds),
7732 selectEntities: selectGlobalizedEntities,
7733 selectAll: createDraftSafeSelector(selectState, selectAll),
7734 selectTotal: createDraftSafeSelector(selectState, selectTotal),
7735 selectById: createDraftSafeSelector(selectGlobalizedEntities, selectId, selectById)
7736 };
7737 }
7738 return { getSelectors: getSelectors };
7739 }
7740 // src/entities/state_adapter.ts
7741
7742 function createSingleArgumentStateOperator(mutator) {
7743 var operator = createStateOperator(function (_, state) { return mutator(state); });
7744 return function operation(state) {
7745 return operator(state, void 0);
7746 };
7747 }
7748 function createStateOperator(mutator) {
7749 return function operation(state, arg) {
7750 function isPayloadActionArgument(arg2) {
7751 return isFSA(arg2);
7752 }
7753 var runMutator = function (draft) {
7754 if (isPayloadActionArgument(arg)) {
7755 mutator(arg.payload, draft);
7756 }
7757 else {
7758 mutator(arg, draft);
7759 }
7760 };
7761 if ((0,immer__WEBPACK_IMPORTED_MODULE_0__.isDraft)(state)) {
7762 runMutator(state);
7763 return state;
7764 }
7765 else {
7766 return (0,immer__WEBPACK_IMPORTED_MODULE_0__["default"])(state, runMutator);
7767 }
7768 };
7769 }
7770 // src/entities/utils.ts
7771 function selectIdValue(entity, selectId) {
7772 var key = selectId(entity);
7773 if ( true && key === void 0) {
7774 console.warn("The entity passed to the `selectId` implementation returned undefined.", "You should probably provide your own `selectId` implementation.", "The entity that was passed:", entity, "The `selectId` implementation:", selectId.toString());
7775 }
7776 return key;
7777 }
7778 function ensureEntitiesArray(entities) {
7779 if (!Array.isArray(entities)) {
7780 entities = Object.values(entities);
7781 }
7782 return entities;
7783 }
7784 function splitAddedUpdatedEntities(newEntities, selectId, state) {
7785 newEntities = ensureEntitiesArray(newEntities);
7786 var added = [];
7787 var updated = [];
7788 for (var _i = 0, newEntities_1 = newEntities; _i < newEntities_1.length; _i++) {
7789 var entity = newEntities_1[_i];
7790 var id = selectIdValue(entity, selectId);
7791 if (id in state.entities) {
7792 updated.push({ id: id, changes: entity });
7793 }
7794 else {
7795 added.push(entity);
7796 }
7797 }
7798 return [added, updated];
7799 }
7800 // src/entities/unsorted_state_adapter.ts
7801 function createUnsortedStateAdapter(selectId) {
7802 function addOneMutably(entity, state) {
7803 var key = selectIdValue(entity, selectId);
7804 if (key in state.entities) {
7805 return;
7806 }
7807 state.ids.push(key);
7808 state.entities[key] = entity;
7809 }
7810 function addManyMutably(newEntities, state) {
7811 newEntities = ensureEntitiesArray(newEntities);
7812 for (var _i = 0, newEntities_2 = newEntities; _i < newEntities_2.length; _i++) {
7813 var entity = newEntities_2[_i];
7814 addOneMutably(entity, state);
7815 }
7816 }
7817 function setOneMutably(entity, state) {
7818 var key = selectIdValue(entity, selectId);
7819 if (!(key in state.entities)) {
7820 state.ids.push(key);
7821 }
7822 state.entities[key] = entity;
7823 }
7824 function setManyMutably(newEntities, state) {
7825 newEntities = ensureEntitiesArray(newEntities);
7826 for (var _i = 0, newEntities_3 = newEntities; _i < newEntities_3.length; _i++) {
7827 var entity = newEntities_3[_i];
7828 setOneMutably(entity, state);
7829 }
7830 }
7831 function setAllMutably(newEntities, state) {
7832 newEntities = ensureEntitiesArray(newEntities);
7833 state.ids = [];
7834 state.entities = {};
7835 addManyMutably(newEntities, state);
7836 }
7837 function removeOneMutably(key, state) {
7838 return removeManyMutably([key], state);
7839 }
7840 function removeManyMutably(keys, state) {
7841 var didMutate = false;
7842 keys.forEach(function (key) {
7843 if (key in state.entities) {
7844 delete state.entities[key];
7845 didMutate = true;
7846 }
7847 });
7848 if (didMutate) {
7849 state.ids = state.ids.filter(function (id) { return id in state.entities; });
7850 }
7851 }
7852 function removeAllMutably(state) {
7853 Object.assign(state, {
7854 ids: [],
7855 entities: {}
7856 });
7857 }
7858 function takeNewKey(keys, update, state) {
7859 var original2 = state.entities[update.id];
7860 var updated = Object.assign({}, original2, update.changes);
7861 var newKey = selectIdValue(updated, selectId);
7862 var hasNewKey = newKey !== update.id;
7863 if (hasNewKey) {
7864 keys[update.id] = newKey;
7865 delete state.entities[update.id];
7866 }
7867 state.entities[newKey] = updated;
7868 return hasNewKey;
7869 }
7870 function updateOneMutably(update, state) {
7871 return updateManyMutably([update], state);
7872 }
7873 function updateManyMutably(updates, state) {
7874 var newKeys = {};
7875 var updatesPerEntity = {};
7876 updates.forEach(function (update) {
7877 if (update.id in state.entities) {
7878 updatesPerEntity[update.id] = {
7879 id: update.id,
7880 changes: __spreadValues(__spreadValues({}, updatesPerEntity[update.id] ? updatesPerEntity[update.id].changes : null), update.changes)
7881 };
7882 }
7883 });
7884 updates = Object.values(updatesPerEntity);
7885 var didMutateEntities = updates.length > 0;
7886 if (didMutateEntities) {
7887 var didMutateIds = updates.filter(function (update) { return takeNewKey(newKeys, update, state); }).length > 0;
7888 if (didMutateIds) {
7889 state.ids = Object.keys(state.entities);
7890 }
7891 }
7892 }
7893 function upsertOneMutably(entity, state) {
7894 return upsertManyMutably([entity], state);
7895 }
7896 function upsertManyMutably(newEntities, state) {
7897 var _c = splitAddedUpdatedEntities(newEntities, selectId, state), added = _c[0], updated = _c[1];
7898 updateManyMutably(updated, state);
7899 addManyMutably(added, state);
7900 }
7901 return {
7902 removeAll: createSingleArgumentStateOperator(removeAllMutably),
7903 addOne: createStateOperator(addOneMutably),
7904 addMany: createStateOperator(addManyMutably),
7905 setOne: createStateOperator(setOneMutably),
7906 setMany: createStateOperator(setManyMutably),
7907 setAll: createStateOperator(setAllMutably),
7908 updateOne: createStateOperator(updateOneMutably),
7909 updateMany: createStateOperator(updateManyMutably),
7910 upsertOne: createStateOperator(upsertOneMutably),
7911 upsertMany: createStateOperator(upsertManyMutably),
7912 removeOne: createStateOperator(removeOneMutably),
7913 removeMany: createStateOperator(removeManyMutably)
7914 };
7915 }
7916 // src/entities/sorted_state_adapter.ts
7917 function createSortedStateAdapter(selectId, sort) {
7918 var _c = createUnsortedStateAdapter(selectId), removeOne = _c.removeOne, removeMany = _c.removeMany, removeAll = _c.removeAll;
7919 function addOneMutably(entity, state) {
7920 return addManyMutably([entity], state);
7921 }
7922 function addManyMutably(newEntities, state) {
7923 newEntities = ensureEntitiesArray(newEntities);
7924 var models = newEntities.filter(function (model) { return !(selectIdValue(model, selectId) in state.entities); });
7925 if (models.length !== 0) {
7926 merge(models, state);
7927 }
7928 }
7929 function setOneMutably(entity, state) {
7930 return setManyMutably([entity], state);
7931 }
7932 function setManyMutably(newEntities, state) {
7933 newEntities = ensureEntitiesArray(newEntities);
7934 if (newEntities.length !== 0) {
7935 merge(newEntities, state);
7936 }
7937 }
7938 function setAllMutably(newEntities, state) {
7939 newEntities = ensureEntitiesArray(newEntities);
7940 state.entities = {};
7941 state.ids = [];
7942 addManyMutably(newEntities, state);
7943 }
7944 function updateOneMutably(update, state) {
7945 return updateManyMutably([update], state);
7946 }
7947 function updateManyMutably(updates, state) {
7948 var appliedUpdates = false;
7949 for (var _i = 0, updates_1 = updates; _i < updates_1.length; _i++) {
7950 var update = updates_1[_i];
7951 var entity = state.entities[update.id];
7952 if (!entity) {
7953 continue;
7954 }
7955 appliedUpdates = true;
7956 Object.assign(entity, update.changes);
7957 var newId = selectId(entity);
7958 if (update.id !== newId) {
7959 delete state.entities[update.id];
7960 state.entities[newId] = entity;
7961 }
7962 }
7963 if (appliedUpdates) {
7964 resortEntities(state);
7965 }
7966 }
7967 function upsertOneMutably(entity, state) {
7968 return upsertManyMutably([entity], state);
7969 }
7970 function upsertManyMutably(newEntities, state) {
7971 var _c = splitAddedUpdatedEntities(newEntities, selectId, state), added = _c[0], updated = _c[1];
7972 updateManyMutably(updated, state);
7973 addManyMutably(added, state);
7974 }
7975 function areArraysEqual(a, b) {
7976 if (a.length !== b.length) {
7977 return false;
7978 }
7979 for (var i = 0; i < a.length && i < b.length; i++) {
7980 if (a[i] === b[i]) {
7981 continue;
7982 }
7983 return false;
7984 }
7985 return true;
7986 }
7987 function merge(models, state) {
7988 models.forEach(function (model) {
7989 state.entities[selectId(model)] = model;
7990 });
7991 resortEntities(state);
7992 }
7993 function resortEntities(state) {
7994 var allEntities = Object.values(state.entities);
7995 allEntities.sort(sort);
7996 var newSortedIds = allEntities.map(selectId);
7997 var ids = state.ids;
7998 if (!areArraysEqual(ids, newSortedIds)) {
7999 state.ids = newSortedIds;
8000 }
8001 }
8002 return {
8003 removeOne: removeOne,
8004 removeMany: removeMany,
8005 removeAll: removeAll,
8006 addOne: createStateOperator(addOneMutably),
8007 updateOne: createStateOperator(updateOneMutably),
8008 upsertOne: createStateOperator(upsertOneMutably),
8009 setOne: createStateOperator(setOneMutably),
8010 setMany: createStateOperator(setManyMutably),
8011 setAll: createStateOperator(setAllMutably),
8012 addMany: createStateOperator(addManyMutably),
8013 updateMany: createStateOperator(updateManyMutably),
8014 upsertMany: createStateOperator(upsertManyMutably)
8015 };
8016 }
8017 // src/entities/create_adapter.ts
8018 function createEntityAdapter(options) {
8019 if (options === void 0) { options = {}; }
8020 var _c = __spreadValues({
8021 sortComparer: false,
8022 selectId: function (instance) { return instance.id; }
8023 }, options), selectId = _c.selectId, sortComparer = _c.sortComparer;
8024 var stateFactory = createInitialStateFactory();
8025 var selectorsFactory = createSelectorsFactory();
8026 var stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);
8027 return __spreadValues(__spreadValues(__spreadValues({
8028 selectId: selectId,
8029 sortComparer: sortComparer
8030 }, stateFactory), selectorsFactory), stateAdapter);
8031 }
8032 // src/nanoid.ts
8033 var urlAlphabet = "ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW";
8034 var nanoid = function (size) {
8035 if (size === void 0) { size = 21; }
8036 var id = "";
8037 var i = size;
8038 while (i--) {
8039 id += urlAlphabet[Math.random() * 64 | 0];
8040 }
8041 return id;
8042 };
8043 // src/createAsyncThunk.ts
8044 var commonProperties = [
8045 "name",
8046 "message",
8047 "stack",
8048 "code"
8049 ];
8050 var RejectWithValue = /** @class */ (function () {
8051 function RejectWithValue(payload, meta) {
8052 this.payload = payload;
8053 this.meta = meta;
8054 }
8055 return RejectWithValue;
8056 }());
8057 var FulfillWithMeta = /** @class */ (function () {
8058 function FulfillWithMeta(payload, meta) {
8059 this.payload = payload;
8060 this.meta = meta;
8061 }
8062 return FulfillWithMeta;
8063 }());
8064 var miniSerializeError = function (value) {
8065 if (typeof value === "object" && value !== null) {
8066 var simpleError = {};
8067 for (var _i = 0, commonProperties_1 = commonProperties; _i < commonProperties_1.length; _i++) {
8068 var property = commonProperties_1[_i];
8069 if (typeof value[property] === "string") {
8070 simpleError[property] = value[property];
8071 }
8072 }
8073 return simpleError;
8074 }
8075 return { message: String(value) };
8076 };
8077 var createAsyncThunk = (function () {
8078 function createAsyncThunk2(typePrefix, payloadCreator, options) {
8079 var fulfilled = createAction(typePrefix + "/fulfilled", function (payload, requestId, arg, meta) { return ({
8080 payload: payload,
8081 meta: __spreadProps(__spreadValues({}, meta || {}), {
8082 arg: arg,
8083 requestId: requestId,
8084 requestStatus: "fulfilled"
8085 })
8086 }); });
8087 var pending = createAction(typePrefix + "/pending", function (requestId, arg, meta) { return ({
8088 payload: void 0,
8089 meta: __spreadProps(__spreadValues({}, meta || {}), {
8090 arg: arg,
8091 requestId: requestId,
8092 requestStatus: "pending"
8093 })
8094 }); });
8095 var rejected = createAction(typePrefix + "/rejected", function (error, requestId, arg, payload, meta) { return ({
8096 payload: payload,
8097 error: (options && options.serializeError || miniSerializeError)(error || "Rejected"),
8098 meta: __spreadProps(__spreadValues({}, meta || {}), {
8099 arg: arg,
8100 requestId: requestId,
8101 rejectedWithValue: !!payload,
8102 requestStatus: "rejected",
8103 aborted: (error == null ? void 0 : error.name) === "AbortError",
8104 condition: (error == null ? void 0 : error.name) === "ConditionError"
8105 })
8106 }); });
8107 var displayedWarning = false;
8108 var AC = typeof AbortController !== "undefined" ? AbortController : /** @class */ (function () {
8109 function class_1() {
8110 this.signal = {
8111 aborted: false,
8112 addEventListener: function () {
8113 },
8114 dispatchEvent: function () {
8115 return false;
8116 },
8117 onabort: function () {
8118 },
8119 removeEventListener: function () {
8120 },
8121 reason: void 0,
8122 throwIfAborted: function () {
8123 }
8124 };
8125 }
8126 class_1.prototype.abort = function () {
8127 if (true) {
8128 if (!displayedWarning) {
8129 displayedWarning = true;
8130 console.info("This platform does not implement AbortController. \nIf you want to use the AbortController to react to `abort` events, please consider importing a polyfill like 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'.");
8131 }
8132 }
8133 };
8134 return class_1;
8135 }());
8136 function actionCreator(arg) {
8137 return function (dispatch, getState, extra) {
8138 var requestId = (options == null ? void 0 : options.idGenerator) ? options.idGenerator(arg) : nanoid();
8139 var abortController = new AC();
8140 var abortReason;
8141 var started = false;
8142 function abort(reason) {
8143 abortReason = reason;
8144 abortController.abort();
8145 }
8146 var promise2 = function () {
8147 return __async(this, null, function () {
8148 var _a, _b, finalAction, conditionResult, abortedPromise, err_1, skipDispatch;
8149 return __generator(this, function (_c) {
8150 switch (_c.label) {
8151 case 0:
8152 _c.trys.push([0, 4, , 5]);
8153 conditionResult = (_a = options == null ? void 0 : options.condition) == null ? void 0 : _a.call(options, arg, { getState: getState, extra: extra });
8154 if (!isThenable(conditionResult)) return [3 /*break*/, 2];
8155 return [4 /*yield*/, conditionResult];
8156 case 1:
8157 conditionResult = _c.sent();
8158 _c.label = 2;
8159 case 2:
8160 if (conditionResult === false || abortController.signal.aborted) {
8161 throw {
8162 name: "ConditionError",
8163 message: "Aborted due to condition callback returning false."
8164 };
8165 }
8166 started = true;
8167 abortedPromise = new Promise(function (_, reject) { return abortController.signal.addEventListener("abort", function () { return reject({
8168 name: "AbortError",
8169 message: abortReason || "Aborted"
8170 }); }); });
8171 dispatch(pending(requestId, arg, (_b = options == null ? void 0 : options.getPendingMeta) == null ? void 0 : _b.call(options, { requestId: requestId, arg: arg }, { getState: getState, extra: extra })));
8172 return [4 /*yield*/, Promise.race([
8173 abortedPromise,
8174 Promise.resolve(payloadCreator(arg, {
8175 dispatch: dispatch,
8176 getState: getState,
8177 extra: extra,
8178 requestId: requestId,
8179 signal: abortController.signal,
8180 abort: abort,
8181 rejectWithValue: function (value, meta) {
8182 return new RejectWithValue(value, meta);
8183 },
8184 fulfillWithValue: function (value, meta) {
8185 return new FulfillWithMeta(value, meta);
8186 }
8187 })).then(function (result) {
8188 if (result instanceof RejectWithValue) {
8189 throw result;
8190 }
8191 if (result instanceof FulfillWithMeta) {
8192 return fulfilled(result.payload, requestId, arg, result.meta);
8193 }
8194 return fulfilled(result, requestId, arg);
8195 })
8196 ])];
8197 case 3:
8198 finalAction = _c.sent();
8199 return [3 /*break*/, 5];
8200 case 4:
8201 err_1 = _c.sent();
8202 finalAction = err_1 instanceof RejectWithValue ? rejected(null, requestId, arg, err_1.payload, err_1.meta) : rejected(err_1, requestId, arg);
8203 return [3 /*break*/, 5];
8204 case 5:
8205 skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;
8206 if (!skipDispatch) {
8207 dispatch(finalAction);
8208 }
8209 return [2 /*return*/, finalAction];
8210 }
8211 });
8212 });
8213 }();
8214 return Object.assign(promise2, {
8215 abort: abort,
8216 requestId: requestId,
8217 arg: arg,
8218 unwrap: function () {
8219 return promise2.then(unwrapResult);
8220 }
8221 });
8222 };
8223 }
8224 return Object.assign(actionCreator, {
8225 pending: pending,
8226 rejected: rejected,
8227 fulfilled: fulfilled,
8228 typePrefix: typePrefix
8229 });
8230 }
8231 createAsyncThunk2.withTypes = function () { return createAsyncThunk2; };
8232 return createAsyncThunk2;
8233 })();
8234 function unwrapResult(action) {
8235 if (action.meta && action.meta.rejectedWithValue) {
8236 throw action.payload;
8237 }
8238 if (action.error) {
8239 throw action.error;
8240 }
8241 return action.payload;
8242 }
8243 function isThenable(value) {
8244 return value !== null && typeof value === "object" && typeof value.then === "function";
8245 }
8246 // src/matchers.ts
8247 var matches = function (matcher, action) {
8248 if (hasMatchFunction(matcher)) {
8249 return matcher.match(action);
8250 }
8251 else {
8252 return matcher(action);
8253 }
8254 };
8255 function isAnyOf() {
8256 var matchers = [];
8257 for (var _i = 0; _i < arguments.length; _i++) {
8258 matchers[_i] = arguments[_i];
8259 }
8260 return function (action) {
8261 return matchers.some(function (matcher) { return matches(matcher, action); });
8262 };
8263 }
8264 function isAllOf() {
8265 var matchers = [];
8266 for (var _i = 0; _i < arguments.length; _i++) {
8267 matchers[_i] = arguments[_i];
8268 }
8269 return function (action) {
8270 return matchers.every(function (matcher) { return matches(matcher, action); });
8271 };
8272 }
8273 function hasExpectedRequestMetadata(action, validStatus) {
8274 if (!action || !action.meta)
8275 return false;
8276 var hasValidRequestId = typeof action.meta.requestId === "string";
8277 var hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;
8278 return hasValidRequestId && hasValidRequestStatus;
8279 }
8280 function isAsyncThunkArray(a) {
8281 return typeof a[0] === "function" && "pending" in a[0] && "fulfilled" in a[0] && "rejected" in a[0];
8282 }
8283 function isPending() {
8284 var asyncThunks = [];
8285 for (var _i = 0; _i < arguments.length; _i++) {
8286 asyncThunks[_i] = arguments[_i];
8287 }
8288 if (asyncThunks.length === 0) {
8289 return function (action) { return hasExpectedRequestMetadata(action, ["pending"]); };
8290 }
8291 if (!isAsyncThunkArray(asyncThunks)) {
8292 return isPending()(asyncThunks[0]);
8293 }
8294 return function (action) {
8295 var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.pending; });
8296 var combinedMatcher = isAnyOf.apply(void 0, matchers);
8297 return combinedMatcher(action);
8298 };
8299 }
8300 function isRejected() {
8301 var asyncThunks = [];
8302 for (var _i = 0; _i < arguments.length; _i++) {
8303 asyncThunks[_i] = arguments[_i];
8304 }
8305 if (asyncThunks.length === 0) {
8306 return function (action) { return hasExpectedRequestMetadata(action, ["rejected"]); };
8307 }
8308 if (!isAsyncThunkArray(asyncThunks)) {
8309 return isRejected()(asyncThunks[0]);
8310 }
8311 return function (action) {
8312 var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.rejected; });
8313 var combinedMatcher = isAnyOf.apply(void 0, matchers);
8314 return combinedMatcher(action);
8315 };
8316 }
8317 function isRejectedWithValue() {
8318 var asyncThunks = [];
8319 for (var _i = 0; _i < arguments.length; _i++) {
8320 asyncThunks[_i] = arguments[_i];
8321 }
8322 var hasFlag = function (action) {
8323 return action && action.meta && action.meta.rejectedWithValue;
8324 };
8325 if (asyncThunks.length === 0) {
8326 return function (action) {
8327 var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);
8328 return combinedMatcher(action);
8329 };
8330 }
8331 if (!isAsyncThunkArray(asyncThunks)) {
8332 return isRejectedWithValue()(asyncThunks[0]);
8333 }
8334 return function (action) {
8335 var combinedMatcher = isAllOf(isRejected.apply(void 0, asyncThunks), hasFlag);
8336 return combinedMatcher(action);
8337 };
8338 }
8339 function isFulfilled() {
8340 var asyncThunks = [];
8341 for (var _i = 0; _i < arguments.length; _i++) {
8342 asyncThunks[_i] = arguments[_i];
8343 }
8344 if (asyncThunks.length === 0) {
8345 return function (action) { return hasExpectedRequestMetadata(action, ["fulfilled"]); };
8346 }
8347 if (!isAsyncThunkArray(asyncThunks)) {
8348 return isFulfilled()(asyncThunks[0]);
8349 }
8350 return function (action) {
8351 var matchers = asyncThunks.map(function (asyncThunk) { return asyncThunk.fulfilled; });
8352 var combinedMatcher = isAnyOf.apply(void 0, matchers);
8353 return combinedMatcher(action);
8354 };
8355 }
8356 function isAsyncThunkAction() {
8357 var asyncThunks = [];
8358 for (var _i = 0; _i < arguments.length; _i++) {
8359 asyncThunks[_i] = arguments[_i];
8360 }
8361 if (asyncThunks.length === 0) {
8362 return function (action) { return hasExpectedRequestMetadata(action, ["pending", "fulfilled", "rejected"]); };
8363 }
8364 if (!isAsyncThunkArray(asyncThunks)) {
8365 return isAsyncThunkAction()(asyncThunks[0]);
8366 }
8367 return function (action) {
8368 var matchers = [];
8369 for (var _i = 0, asyncThunks_1 = asyncThunks; _i < asyncThunks_1.length; _i++) {
8370 var asyncThunk = asyncThunks_1[_i];
8371 matchers.push(asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled);
8372 }
8373 var combinedMatcher = isAnyOf.apply(void 0, matchers);
8374 return combinedMatcher(action);
8375 };
8376 }
8377 // src/listenerMiddleware/utils.ts
8378 var assertFunction = function (func, expected) {
8379 if (typeof func !== "function") {
8380 throw new TypeError(expected + " is not a function");
8381 }
8382 };
8383 var noop = function () {
8384 };
8385 var catchRejection = function (promise2, onError) {
8386 if (onError === void 0) { onError = noop; }
8387 promise2.catch(onError);
8388 return promise2;
8389 };
8390 var addAbortSignalListener = function (abortSignal, callback) {
8391 abortSignal.addEventListener("abort", callback, { once: true });
8392 return function () { return abortSignal.removeEventListener("abort", callback); };
8393 };
8394 var abortControllerWithReason = function (abortController, reason) {
8395 var signal = abortController.signal;
8396 if (signal.aborted) {
8397 return;
8398 }
8399 if (!("reason" in signal)) {
8400 Object.defineProperty(signal, "reason", {
8401 enumerable: true,
8402 value: reason,
8403 configurable: true,
8404 writable: true
8405 });
8406 }
8407 ;
8408 abortController.abort(reason);
8409 };
8410 // src/listenerMiddleware/exceptions.ts
8411 var task = "task";
8412 var listener = "listener";
8413 var completed = "completed";
8414 var cancelled = "cancelled";
8415 var taskCancelled = "task-" + cancelled;
8416 var taskCompleted = "task-" + completed;
8417 var listenerCancelled = listener + "-" + cancelled;
8418 var listenerCompleted = listener + "-" + completed;
8419 var TaskAbortError = /** @class */ (function () {
8420 function TaskAbortError(code) {
8421 this.code = code;
8422 this.name = "TaskAbortError";
8423 this.message = task + " " + cancelled + " (reason: " + code + ")";
8424 }
8425 return TaskAbortError;
8426 }());
8427 // src/listenerMiddleware/task.ts
8428 var validateActive = function (signal) {
8429 if (signal.aborted) {
8430 throw new TaskAbortError(signal.reason);
8431 }
8432 };
8433 function raceWithSignal(signal, promise2) {
8434 var cleanup = noop;
8435 return new Promise(function (resolve, reject) {
8436 var notifyRejection = function () { return reject(new TaskAbortError(signal.reason)); };
8437 if (signal.aborted) {
8438 notifyRejection();
8439 return;
8440 }
8441 cleanup = addAbortSignalListener(signal, notifyRejection);
8442 promise2.finally(function () { return cleanup(); }).then(resolve, reject);
8443 }).finally(function () {
8444 cleanup = noop;
8445 });
8446 }
8447 var runTask = function (task2, cleanUp) { return __async(void 0, null, function () {
8448 var value, error_1;
8449 return __generator(this, function (_c) {
8450 switch (_c.label) {
8451 case 0:
8452 _c.trys.push([0, 3, 4, 5]);
8453 return [4 /*yield*/, Promise.resolve()];
8454 case 1:
8455 _c.sent();
8456 return [4 /*yield*/, task2()];
8457 case 2:
8458 value = _c.sent();
8459 return [2 /*return*/, {
8460 status: "ok",
8461 value: value
8462 }];
8463 case 3:
8464 error_1 = _c.sent();
8465 return [2 /*return*/, {
8466 status: error_1 instanceof TaskAbortError ? "cancelled" : "rejected",
8467 error: error_1
8468 }];
8469 case 4:
8470 cleanUp == null ? void 0 : cleanUp();
8471 return [7 /*endfinally*/];
8472 case 5: return [2 /*return*/];
8473 }
8474 });
8475 }); };
8476 var createPause = function (signal) {
8477 return function (promise2) {
8478 return catchRejection(raceWithSignal(signal, promise2).then(function (output) {
8479 validateActive(signal);
8480 return output;
8481 }));
8482 };
8483 };
8484 var createDelay = function (signal) {
8485 var pause = createPause(signal);
8486 return function (timeoutMs) {
8487 return pause(new Promise(function (resolve) { return setTimeout(resolve, timeoutMs); }));
8488 };
8489 };
8490 // src/listenerMiddleware/index.ts
8491 var assign = Object.assign;
8492 var INTERNAL_NIL_TOKEN = {};
8493 var alm = "listenerMiddleware";
8494 var createFork = function (parentAbortSignal, parentBlockingPromises) {
8495 var linkControllers = function (controller) { return addAbortSignalListener(parentAbortSignal, function () { return abortControllerWithReason(controller, parentAbortSignal.reason); }); };
8496 return function (taskExecutor, opts) {
8497 assertFunction(taskExecutor, "taskExecutor");
8498 var childAbortController = new AbortController();
8499 linkControllers(childAbortController);
8500 var result = runTask(function () { return __async(void 0, null, function () {
8501 var result2;
8502 return __generator(this, function (_c) {
8503 switch (_c.label) {
8504 case 0:
8505 validateActive(parentAbortSignal);
8506 validateActive(childAbortController.signal);
8507 return [4 /*yield*/, taskExecutor({
8508 pause: createPause(childAbortController.signal),
8509 delay: createDelay(childAbortController.signal),
8510 signal: childAbortController.signal
8511 })];
8512 case 1:
8513 result2 = _c.sent();
8514 validateActive(childAbortController.signal);
8515 return [2 /*return*/, result2];
8516 }
8517 });
8518 }); }, function () { return abortControllerWithReason(childAbortController, taskCompleted); });
8519 if (opts == null ? void 0 : opts.autoJoin) {
8520 parentBlockingPromises.push(result);
8521 }
8522 return {
8523 result: createPause(parentAbortSignal)(result),
8524 cancel: function () {
8525 abortControllerWithReason(childAbortController, taskCancelled);
8526 }
8527 };
8528 };
8529 };
8530 var createTakePattern = function (startListening, signal) {
8531 var take = function (predicate, timeout) { return __async(void 0, null, function () {
8532 var unsubscribe, tuplePromise, promises, output;
8533 return __generator(this, function (_c) {
8534 switch (_c.label) {
8535 case 0:
8536 validateActive(signal);
8537 unsubscribe = function () {
8538 };
8539 tuplePromise = new Promise(function (resolve, reject) {
8540 var stopListening = startListening({
8541 predicate: predicate,
8542 effect: function (action, listenerApi) {
8543 listenerApi.unsubscribe();
8544 resolve([
8545 action,
8546 listenerApi.getState(),
8547 listenerApi.getOriginalState()
8548 ]);
8549 }
8550 });
8551 unsubscribe = function () {
8552 stopListening();
8553 reject();
8554 };
8555 });
8556 promises = [
8557 tuplePromise
8558 ];
8559 if (timeout != null) {
8560 promises.push(new Promise(function (resolve) { return setTimeout(resolve, timeout, null); }));
8561 }
8562 _c.label = 1;
8563 case 1:
8564 _c.trys.push([1, , 3, 4]);
8565 return [4 /*yield*/, raceWithSignal(signal, Promise.race(promises))];
8566 case 2:
8567 output = _c.sent();
8568 validateActive(signal);
8569 return [2 /*return*/, output];
8570 case 3:
8571 unsubscribe();
8572 return [7 /*endfinally*/];
8573 case 4: return [2 /*return*/];
8574 }
8575 });
8576 }); };
8577 return function (predicate, timeout) { return catchRejection(take(predicate, timeout)); };
8578 };
8579 var getListenerEntryPropsFrom = function (options) {
8580 var type = options.type, actionCreator = options.actionCreator, matcher = options.matcher, predicate = options.predicate, effect = options.effect;
8581 if (type) {
8582 predicate = createAction(type).match;
8583 }
8584 else if (actionCreator) {
8585 type = actionCreator.type;
8586 predicate = actionCreator.match;
8587 }
8588 else if (matcher) {
8589 predicate = matcher;
8590 }
8591 else if (predicate) {
8592 }
8593 else {
8594 throw new Error("Creating or removing a listener requires one of the known fields for matching an action");
8595 }
8596 assertFunction(effect, "options.listener");
8597 return { predicate: predicate, type: type, effect: effect };
8598 };
8599 var createListenerEntry = function (options) {
8600 var _c = getListenerEntryPropsFrom(options), type = _c.type, predicate = _c.predicate, effect = _c.effect;
8601 var id = nanoid();
8602 var entry = {
8603 id: id,
8604 effect: effect,
8605 type: type,
8606 predicate: predicate,
8607 pending: new Set(),
8608 unsubscribe: function () {
8609 throw new Error("Unsubscribe not initialized");
8610 }
8611 };
8612 return entry;
8613 };
8614 var cancelActiveListeners = function (entry) {
8615 entry.pending.forEach(function (controller) {
8616 abortControllerWithReason(controller, listenerCancelled);
8617 });
8618 };
8619 var createClearListenerMiddleware = function (listenerMap) {
8620 return function () {
8621 listenerMap.forEach(cancelActiveListeners);
8622 listenerMap.clear();
8623 };
8624 };
8625 var safelyNotifyError = function (errorHandler, errorToNotify, errorInfo) {
8626 try {
8627 errorHandler(errorToNotify, errorInfo);
8628 }
8629 catch (errorHandlerError) {
8630 setTimeout(function () {
8631 throw errorHandlerError;
8632 }, 0);
8633 }
8634 };
8635 var addListener = createAction(alm + "/add");
8636 var clearAllListeners = createAction(alm + "/removeAll");
8637 var removeListener = createAction(alm + "/remove");
8638 var defaultErrorHandler = function () {
8639 var args = [];
8640 for (var _i = 0; _i < arguments.length; _i++) {
8641 args[_i] = arguments[_i];
8642 }
8643 console.error.apply(console, __spreadArray([alm + "/error"], args));
8644 };
8645 function createListenerMiddleware(middlewareOptions) {
8646 var _this = this;
8647 if (middlewareOptions === void 0) { middlewareOptions = {}; }
8648 var listenerMap = new Map();
8649 var extra = middlewareOptions.extra, _c = middlewareOptions.onError, onError = _c === void 0 ? defaultErrorHandler : _c;
8650 assertFunction(onError, "onError");
8651 var insertEntry = function (entry) {
8652 entry.unsubscribe = function () { return listenerMap.delete(entry.id); };
8653 listenerMap.set(entry.id, entry);
8654 return function (cancelOptions) {
8655 entry.unsubscribe();
8656 if (cancelOptions == null ? void 0 : cancelOptions.cancelActive) {
8657 cancelActiveListeners(entry);
8658 }
8659 };
8660 };
8661 var findListenerEntry = function (comparator) {
8662 for (var _i = 0, _c = Array.from(listenerMap.values()); _i < _c.length; _i++) {
8663 var entry = _c[_i];
8664 if (comparator(entry)) {
8665 return entry;
8666 }
8667 }
8668 return void 0;
8669 };
8670 var startListening = function (options) {
8671 var entry = findListenerEntry(function (existingEntry) { return existingEntry.effect === options.effect; });
8672 if (!entry) {
8673 entry = createListenerEntry(options);
8674 }
8675 return insertEntry(entry);
8676 };
8677 var stopListening = function (options) {
8678 var _c = getListenerEntryPropsFrom(options), type = _c.type, effect = _c.effect, predicate = _c.predicate;
8679 var entry = findListenerEntry(function (entry2) {
8680 var matchPredicateOrType = typeof type === "string" ? entry2.type === type : entry2.predicate === predicate;
8681 return matchPredicateOrType && entry2.effect === effect;
8682 });
8683 if (entry) {
8684 entry.unsubscribe();
8685 if (options.cancelActive) {
8686 cancelActiveListeners(entry);
8687 }
8688 }
8689 return !!entry;
8690 };
8691 var notifyListener = function (entry, action, api, getOriginalState) { return __async(_this, null, function () {
8692 var internalTaskController, take, autoJoinPromises, listenerError_1;
8693 return __generator(this, function (_c) {
8694 switch (_c.label) {
8695 case 0:
8696 internalTaskController = new AbortController();
8697 take = createTakePattern(startListening, internalTaskController.signal);
8698 autoJoinPromises = [];
8699 _c.label = 1;
8700 case 1:
8701 _c.trys.push([1, 3, 4, 6]);
8702 entry.pending.add(internalTaskController);
8703 return [4 /*yield*/, Promise.resolve(entry.effect(action, assign({}, api, {
8704 getOriginalState: getOriginalState,
8705 condition: function (predicate, timeout) { return take(predicate, timeout).then(Boolean); },
8706 take: take,
8707 delay: createDelay(internalTaskController.signal),
8708 pause: createPause(internalTaskController.signal),
8709 extra: extra,
8710 signal: internalTaskController.signal,
8711 fork: createFork(internalTaskController.signal, autoJoinPromises),
8712 unsubscribe: entry.unsubscribe,
8713 subscribe: function () {
8714 listenerMap.set(entry.id, entry);
8715 },
8716 cancelActiveListeners: function () {
8717 entry.pending.forEach(function (controller, _, set) {
8718 if (controller !== internalTaskController) {
8719 abortControllerWithReason(controller, listenerCancelled);
8720 set.delete(controller);
8721 }
8722 });
8723 }
8724 })))];
8725 case 2:
8726 _c.sent();
8727 return [3 /*break*/, 6];
8728 case 3:
8729 listenerError_1 = _c.sent();
8730 if (!(listenerError_1 instanceof TaskAbortError)) {
8731 safelyNotifyError(onError, listenerError_1, {
8732 raisedBy: "effect"
8733 });
8734 }
8735 return [3 /*break*/, 6];
8736 case 4: return [4 /*yield*/, Promise.allSettled(autoJoinPromises)];
8737 case 5:
8738 _c.sent();
8739 abortControllerWithReason(internalTaskController, listenerCompleted);
8740 entry.pending.delete(internalTaskController);
8741 return [7 /*endfinally*/];
8742 case 6: return [2 /*return*/];
8743 }
8744 });
8745 }); };
8746 var clearListenerMiddleware = createClearListenerMiddleware(listenerMap);
8747 var middleware = function (api) { return function (next) { return function (action) {
8748 if (!isAction(action)) {
8749 return next(action);
8750 }
8751 if (addListener.match(action)) {
8752 return startListening(action.payload);
8753 }
8754 if (clearAllListeners.match(action)) {
8755 clearListenerMiddleware();
8756 return;
8757 }
8758 if (removeListener.match(action)) {
8759 return stopListening(action.payload);
8760 }
8761 var originalState = api.getState();
8762 var getOriginalState = function () {
8763 if (originalState === INTERNAL_NIL_TOKEN) {
8764 throw new Error(alm + ": getOriginalState can only be called synchronously");
8765 }
8766 return originalState;
8767 };
8768 var result;
8769 try {
8770 result = next(action);
8771 if (listenerMap.size > 0) {
8772 var currentState = api.getState();
8773 var listenerEntries = Array.from(listenerMap.values());
8774 for (var _i = 0, listenerEntries_1 = listenerEntries; _i < listenerEntries_1.length; _i++) {
8775 var entry = listenerEntries_1[_i];
8776 var runListener = false;
8777 try {
8778 runListener = entry.predicate(action, currentState, originalState);
8779 }
8780 catch (predicateError) {
8781 runListener = false;
8782 safelyNotifyError(onError, predicateError, {
8783 raisedBy: "predicate"
8784 });
8785 }
8786 if (!runListener) {
8787 continue;
8788 }
8789 notifyListener(entry, action, api, getOriginalState);
8790 }
8791 }
8792 }
8793 finally {
8794 originalState = INTERNAL_NIL_TOKEN;
8795 }
8796 return result;
8797 }; }; };
8798 return {
8799 middleware: middleware,
8800 startListening: startListening,
8801 stopListening: stopListening,
8802 clearListeners: clearListenerMiddleware
8803 };
8804 }
8805 // src/autoBatchEnhancer.ts
8806 var SHOULD_AUTOBATCH = "RTK_autoBatch";
8807 var prepareAutoBatched = function () { return function (payload) {
8808 var _c;
8809 return ({
8810 payload: payload,
8811 meta: (_c = {}, _c[SHOULD_AUTOBATCH] = true, _c)
8812 });
8813 }; };
8814 var promise;
8815 var queueMicrotaskShim = typeof queueMicrotask === "function" ? queueMicrotask.bind(typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : globalThis) : function (cb) { return (promise || (promise = Promise.resolve())).then(cb).catch(function (err) { return setTimeout(function () {
8816 throw err;
8817 }, 0); }); };
8818 var createQueueWithTimer = function (timeout) {
8819 return function (notify) {
8820 setTimeout(notify, timeout);
8821 };
8822 };
8823 var rAF = typeof window !== "undefined" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);
8824 var autoBatchEnhancer = function (options) {
8825 if (options === void 0) { options = { type: "raf" }; }
8826 return function (next) { return function () {
8827 var args = [];
8828 for (var _i = 0; _i < arguments.length; _i++) {
8829 args[_i] = arguments[_i];
8830 }
8831 var store = next.apply(void 0, args);
8832 var notifying = true;
8833 var shouldNotifyAtEndOfTick = false;
8834 var notificationQueued = false;
8835 var listeners = new Set();
8836 var queueCallback = options.type === "tick" ? queueMicrotaskShim : options.type === "raf" ? rAF : options.type === "callback" ? options.queueNotification : createQueueWithTimer(options.timeout);
8837 var notifyListeners = function () {
8838 notificationQueued = false;
8839 if (shouldNotifyAtEndOfTick) {
8840 shouldNotifyAtEndOfTick = false;
8841 listeners.forEach(function (l) { return l(); });
8842 }
8843 };
8844 return Object.assign({}, store, {
8845 subscribe: function (listener2) {
8846 var wrappedListener = function () { return notifying && listener2(); };
8847 var unsubscribe = store.subscribe(wrappedListener);
8848 listeners.add(listener2);
8849 return function () {
8850 unsubscribe();
8851 listeners.delete(listener2);
8852 };
8853 },
8854 dispatch: function (action) {
8855 var _a;
8856 try {
8857 notifying = !((_a = action == null ? void 0 : action.meta) == null ? void 0 : _a[SHOULD_AUTOBATCH]);
8858 shouldNotifyAtEndOfTick = !notifying;
8859 if (shouldNotifyAtEndOfTick) {
8860 if (!notificationQueued) {
8861 notificationQueued = true;
8862 queueCallback(notifyListeners);
8863 }
8864 }
8865 return store.dispatch(action);
8866 }
8867 finally {
8868 notifying = true;
8869 }
8870 }
8871 });
8872 }; };
8873 };
8874 // src/index.ts
8875 (0,immer__WEBPACK_IMPORTED_MODULE_0__.enableES5)();
8876
8877 //# sourceMappingURL=redux-toolkit.esm.js.map
8878
8879 /***/ }),
8880
8881 /***/ "../node_modules/immer/dist/immer.esm.mjs":
8882 /*!************************************************!*\
8883 !*** ../node_modules/immer/dist/immer.esm.mjs ***!
8884 \************************************************/
8885 /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
8886
8887 "use strict";
8888 __webpack_require__.r(__webpack_exports__);
8889 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
8890 /* harmony export */ Immer: () => (/* binding */ un),
8891 /* harmony export */ applyPatches: () => (/* binding */ pn),
8892 /* harmony export */ castDraft: () => (/* binding */ K),
8893 /* harmony export */ castImmutable: () => (/* binding */ $),
8894 /* harmony export */ createDraft: () => (/* binding */ ln),
8895 /* harmony export */ current: () => (/* binding */ R),
8896 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__),
8897 /* harmony export */ enableAllPlugins: () => (/* binding */ J),
8898 /* harmony export */ enableES5: () => (/* binding */ F),
8899 /* harmony export */ enableMapSet: () => (/* binding */ C),
8900 /* harmony export */ enablePatches: () => (/* binding */ T),
8901 /* harmony export */ finishDraft: () => (/* binding */ dn),
8902 /* harmony export */ freeze: () => (/* binding */ d),
8903 /* harmony export */ immerable: () => (/* binding */ L),
8904 /* harmony export */ isDraft: () => (/* binding */ r),
8905 /* harmony export */ isDraftable: () => (/* binding */ t),
8906 /* harmony export */ nothing: () => (/* binding */ H),
8907 /* harmony export */ original: () => (/* binding */ e),
8908 /* harmony export */ produce: () => (/* binding */ fn),
8909 /* harmony export */ produceWithPatches: () => (/* binding */ cn),
8910 /* harmony export */ setAutoFreeze: () => (/* binding */ sn),
8911 /* harmony export */ setUseProxies: () => (/* binding */ vn)
8912 /* harmony export */ });
8913 function n(n){for(var r=arguments.length,t=Array(r>1?r-1:0),e=1;e<r;e++)t[e-1]=arguments[e];if(true){var i=Y[n],o=i?"function"==typeof i?i.apply(null,t):i:"unknown error nr: "+n;throw Error("[Immer] "+o)}// removed by dead control flow
8914 }function r(n){return!!n&&!!n[Q]}function t(n){var r;return!!n&&(function(n){if(!n||"object"!=typeof n)return!1;var r=Object.getPrototypeOf(n);if(null===r)return!0;var t=Object.hasOwnProperty.call(r,"constructor")&&r.constructor;return t===Object||"function"==typeof t&&Function.toString.call(t)===Z}(n)||Array.isArray(n)||!!n[L]||!!(null===(r=n.constructor)||void 0===r?void 0:r[L])||s(n)||v(n))}function e(t){return r(t)||n(23,t),t[Q].t}function i(n,r,t){void 0===t&&(t=!1),0===o(n)?(t?Object.keys:nn)(n).forEach((function(e){t&&"symbol"==typeof e||r(e,n[e],n)})):n.forEach((function(t,e){return r(e,t,n)}))}function o(n){var r=n[Q];return r?r.i>3?r.i-4:r.i:Array.isArray(n)?1:s(n)?2:v(n)?3:0}function u(n,r){return 2===o(n)?n.has(r):Object.prototype.hasOwnProperty.call(n,r)}function a(n,r){return 2===o(n)?n.get(r):n[r]}function f(n,r,t){var e=o(n);2===e?n.set(r,t):3===e?n.add(t):n[r]=t}function c(n,r){return n===r?0!==n||1/n==1/r:n!=n&&r!=r}function s(n){return X&&n instanceof Map}function v(n){return q&&n instanceof Set}function p(n){return n.o||n.t}function l(n){if(Array.isArray(n))return Array.prototype.slice.call(n);var r=rn(n);delete r[Q];for(var t=nn(r),e=0;e<t.length;e++){var i=t[e],o=r[i];!1===o.writable&&(o.writable=!0,o.configurable=!0),(o.get||o.set)&&(r[i]={configurable:!0,writable:!0,enumerable:o.enumerable,value:n[i]})}return Object.create(Object.getPrototypeOf(n),r)}function d(n,e){return void 0===e&&(e=!1),y(n)||r(n)||!t(n)||(o(n)>1&&(n.set=n.add=n.clear=n.delete=h),Object.freeze(n),e&&i(n,(function(n,r){return d(r,!0)}),!0)),n}function h(){n(2)}function y(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function b(r){var t=tn[r];return t||n(18,r),t}function m(n,r){tn[n]||(tn[n]=r)}function _(){return false||U||n(0),U}function j(n,r){r&&(b("Patches"),n.u=[],n.s=[],n.v=r)}function g(n){O(n),n.p.forEach(S),n.p=null}function O(n){n===U&&(U=n.l)}function w(n){return U={p:[],l:U,h:n,m:!0,_:0}}function S(n){var r=n[Q];0===r.i||1===r.i?r.j():r.g=!0}function P(r,e){e._=e.p.length;var i=e.p[0],o=void 0!==r&&r!==i;return e.h.O||b("ES5").S(e,r,o),o?(i[Q].P&&(g(e),n(4)),t(r)&&(r=M(e,r),e.l||x(e,r)),e.u&&b("Patches").M(i[Q].t,r,e.u,e.s)):r=M(e,i,[]),g(e),e.u&&e.v(e.u,e.s),r!==H?r:void 0}function M(n,r,t){if(y(r))return r;var e=r[Q];if(!e)return i(r,(function(i,o){return A(n,e,r,i,o,t)}),!0),r;if(e.A!==n)return r;if(!e.P)return x(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=l(e.k):e.o,u=o,a=!1;3===e.i&&(u=new Set(o),o.clear(),a=!0),i(u,(function(r,i){return A(n,e,o,r,i,t,a)})),x(n,o,!1),t&&n.u&&b("Patches").N(e,t,n.u,n.s)}return e.o}function A(e,i,o,a,c,s,v){if( true&&c===o&&n(5),r(c)){var p=M(e,c,s&&i&&3!==i.i&&!u(i.R,a)?s.concat(a):void 0);if(f(o,a,p),!r(p))return;e.m=!1}else v&&o.add(c);if(t(c)&&!y(c)){if(!e.h.D&&e._<1)return;M(e,c),i&&i.A.l||x(e,c)}}function x(n,r,t){void 0===t&&(t=!1),!n.l&&n.h.D&&n.m&&d(r,t)}function z(n,r){var t=n[Q];return(t?p(t):n)[r]}function I(n,r){if(r in n)for(var t=Object.getPrototypeOf(n);t;){var e=Object.getOwnPropertyDescriptor(t,r);if(e)return e;t=Object.getPrototypeOf(t)}}function k(n){n.P||(n.P=!0,n.l&&k(n.l))}function E(n){n.o||(n.o=l(n.t))}function N(n,r,t){var e=s(r)?b("MapSet").F(r,t):v(r)?b("MapSet").T(r,t):n.O?function(n,r){var t=Array.isArray(n),e={i:t?1:0,A:r?r.A:_(),P:!1,I:!1,R:{},l:r,t:n,k:null,o:null,j:null,C:!1},i=e,o=en;t&&(i=[e],o=on);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(r,t):b("ES5").J(r,t);return(t?t.A:_()).p.push(e),e}function R(e){return r(e)||n(22,e),function n(r){if(!t(r))return r;var e,u=r[Q],c=o(r);if(u){if(!u.P&&(u.i<4||!b("ES5").K(u)))return u.t;u.I=!0,e=D(r,c),u.I=!1}else e=D(r,c);return i(e,(function(r,t){u&&a(u.t,r)===t||f(e,r,n(t))})),3===c?new Set(e):e}(e)}function D(n,r){switch(r){case 2:return new Map(n);case 3:return Array.from(n)}return l(n)}function F(){function t(n,r){var t=s[n];return t?t.enumerable=r:s[n]=t={configurable:!0,enumerable:r,get:function(){var r=this[Q];return true&&f(r),en.get(r,n)},set:function(r){var t=this[Q]; true&&f(t),en.set(t,n,r)}},t}function e(n){for(var r=n.length-1;r>=0;r--){var t=n[r][Q];if(!t.P)switch(t.i){case 5:a(t)&&k(t);break;case 4:o(t)&&k(t)}}}function o(n){for(var r=n.t,t=n.k,e=nn(t),i=e.length-1;i>=0;i--){var o=e[i];if(o!==Q){var a=r[o];if(void 0===a&&!u(r,o))return!0;var f=t[o],s=f&&f[Q];if(s?s.t!==a:!c(f,a))return!0}}var v=!!r[Q];return e.length!==nn(r).length+(v?0:1)}function a(n){var r=n.k;if(r.length!==n.t.length)return!0;var t=Object.getOwnPropertyDescriptor(r,r.length-1);if(t&&!t.get)return!0;for(var e=0;e<r.length;e++)if(!r.hasOwnProperty(e))return!0;return!1}function f(r){r.g&&n(3,JSON.stringify(p(r)))}var s={};m("ES5",{J:function(n,r){var e=Array.isArray(n),i=function(n,r){if(n){for(var e=Array(r.length),i=0;i<r.length;i++)Object.defineProperty(e,""+i,t(i,!0));return e}var o=rn(r);delete o[Q];for(var u=nn(o),a=0;a<u.length;a++){var f=u[a];o[f]=t(f,n||!!o[f].enumerable)}return Object.create(Object.getPrototypeOf(r),o)}(e,n),o={i:e?5:4,A:r?r.A:_(),P:!1,I:!1,R:{},l:r,t:n,k:i,o:null,g:!1,C:!1};return Object.defineProperty(i,Q,{value:o,writable:!0}),i},S:function(n,t,o){o?r(t)&&t[Q].A===n&&e(n.p):(n.u&&function n(r){if(r&&"object"==typeof r){var t=r[Q];if(t){var e=t.t,o=t.k,f=t.R,c=t.i;if(4===c)i(o,(function(r){r!==Q&&(void 0!==e[r]||u(e,r)?f[r]||n(o[r]):(f[r]=!0,k(t)))})),i(e,(function(n){void 0!==o[n]||u(o,n)||(f[n]=!1,k(t))}));else if(5===c){if(a(t)&&(k(t),f.length=!0),o.length<e.length)for(var s=o.length;s<e.length;s++)f[s]=!1;else for(var v=e.length;v<o.length;v++)f[v]=!0;for(var p=Math.min(o.length,e.length),l=0;l<p;l++)o.hasOwnProperty(l)||(f[l]=!0),void 0===f[l]&&n(o[l])}}}}(n.p[0]),e(n.p))},K:function(n){return 4===n.i?o(n):a(n)}})}function T(){function e(n){if(!t(n))return n;if(Array.isArray(n))return n.map(e);if(s(n))return new Map(Array.from(n.entries()).map((function(n){return[n[0],e(n[1])]})));if(v(n))return new Set(Array.from(n).map(e));var r=Object.create(Object.getPrototypeOf(n));for(var i in n)r[i]=e(n[i]);return u(n,L)&&(r[L]=n[L]),r}function f(n){return r(n)?e(n):n}var c="add";m("Patches",{$:function(r,t){return t.forEach((function(t){for(var i=t.path,u=t.op,f=r,s=0;s<i.length-1;s++){var v=o(f),p=i[s];"string"!=typeof p&&"number"!=typeof p&&(p=""+p),0!==v&&1!==v||"__proto__"!==p&&"constructor"!==p||n(24),"function"==typeof f&&"prototype"===p&&n(24),"object"!=typeof(f=a(f,p))&&n(15,i.join("/"))}var l=o(f),d=e(t.value),h=i[i.length-1];switch(u){case"replace":switch(l){case 2:return f.set(h,d);case 3:n(16);default:return f[h]=d}case c:switch(l){case 1:return"-"===h?f.push(d):f.splice(h,0,d);case 2:return f.set(h,d);case 3:return f.add(d);default:return f[h]=d}case"remove":switch(l){case 1:return f.splice(h,1);case 2:return f.delete(h);case 3:return f.delete(t.value);default:return delete f[h]}default:n(17,u)}})),r},N:function(n,r,t,e){switch(n.i){case 0:case 4:case 2:return function(n,r,t,e){var o=n.t,s=n.o;i(n.R,(function(n,i){var v=a(o,n),p=a(s,n),l=i?u(o,n)?"replace":c:"remove";if(v!==p||"replace"!==l){var d=r.concat(n);t.push("remove"===l?{op:l,path:d}:{op:l,path:d,value:p}),e.push(l===c?{op:"remove",path:d}:"remove"===l?{op:c,path:d,value:f(v)}:{op:"replace",path:d,value:f(v)})}}))}(n,r,t,e);case 5:case 1:return function(n,r,t,e){var i=n.t,o=n.R,u=n.o;if(u.length<i.length){var a=[u,i];i=a[0],u=a[1];var s=[e,t];t=s[0],e=s[1]}for(var v=0;v<i.length;v++)if(o[v]&&u[v]!==i[v]){var p=r.concat([v]);t.push({op:"replace",path:p,value:f(u[v])}),e.push({op:"replace",path:p,value:f(i[v])})}for(var l=i.length;l<u.length;l++){var d=r.concat([l]);t.push({op:c,path:d,value:f(u[l])})}i.length<u.length&&e.push({op:"replace",path:r.concat(["length"]),value:i.length})}(n,r,t,e);case 3:return function(n,r,t,e){var i=n.t,o=n.o,u=0;i.forEach((function(n){if(!o.has(n)){var i=r.concat([u]);t.push({op:"remove",path:i,value:n}),e.unshift({op:c,path:i,value:n})}u++})),u=0,o.forEach((function(n){if(!i.has(n)){var o=r.concat([u]);t.push({op:c,path:o,value:n}),e.unshift({op:"remove",path:o,value:n})}u++}))}(n,r,t,e)}},M:function(n,r,t,e){t.push({op:"replace",path:[],value:r===H?void 0:r}),e.push({op:"replace",path:[],value:n})}})}function C(){function r(n,r){function t(){this.constructor=n}a(n,r),n.prototype=(t.prototype=r.prototype,new t)}function e(n){n.o||(n.R=new Map,n.o=new Map(n.t))}function o(n){n.o||(n.o=new Set,n.t.forEach((function(r){if(t(r)){var e=N(n.A.h,r,n);n.p.set(r,e),n.o.add(e)}else n.o.add(r)})))}function u(r){r.g&&n(3,JSON.stringify(p(r)))}var a=function(n,r){return(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var t in r)r.hasOwnProperty(t)&&(n[t]=r[t])})(n,r)},f=function(){function n(n,r){return this[Q]={i:2,l:r,A:r?r.A:_(),P:!1,I:!1,o:void 0,R:void 0,t:n,k:this,C:!1,g:!1},this}r(n,Map);var o=n.prototype;return Object.defineProperty(o,"size",{get:function(){return p(this[Q]).size}}),o.has=function(n){return p(this[Q]).has(n)},o.set=function(n,r){var t=this[Q];return u(t),p(t).has(n)&&p(t).get(n)===r||(e(t),k(t),t.R.set(n,!0),t.o.set(n,r),t.R.set(n,!0)),this},o.delete=function(n){if(!this.has(n))return!1;var r=this[Q];return u(r),e(r),k(r),r.t.has(n)?r.R.set(n,!1):r.R.delete(n),r.o.delete(n),!0},o.clear=function(){var n=this[Q];u(n),p(n).size&&(e(n),k(n),n.R=new Map,i(n.t,(function(r){n.R.set(r,!1)})),n.o.clear())},o.forEach=function(n,r){var t=this;p(this[Q]).forEach((function(e,i){n.call(r,t.get(i),i,t)}))},o.get=function(n){var r=this[Q];u(r);var i=p(r).get(n);if(r.I||!t(i))return i;if(i!==r.t.get(n))return i;var o=N(r.A.h,i,r);return e(r),r.o.set(n,o),o},o.keys=function(){return p(this[Q]).keys()},o.values=function(){var n,r=this,t=this.keys();return(n={})[V]=function(){return r.values()},n.next=function(){var n=t.next();return n.done?n:{done:!1,value:r.get(n.value)}},n},o.entries=function(){var n,r=this,t=this.keys();return(n={})[V]=function(){return r.entries()},n.next=function(){var n=t.next();if(n.done)return n;var e=r.get(n.value);return{done:!1,value:[n.value,e]}},n},o[V]=function(){return this.entries()},n}(),c=function(){function n(n,r){return this[Q]={i:3,l:r,A:r?r.A:_(),P:!1,I:!1,o:void 0,t:n,k:this,p:new Map,g:!1,C:!1},this}r(n,Set);var t=n.prototype;return Object.defineProperty(t,"size",{get:function(){return p(this[Q]).size}}),t.has=function(n){var r=this[Q];return u(r),r.o?!!r.o.has(n)||!(!r.p.has(n)||!r.o.has(r.p.get(n))):r.t.has(n)},t.add=function(n){var r=this[Q];return u(r),this.has(n)||(o(r),k(r),r.o.add(n)),this},t.delete=function(n){if(!this.has(n))return!1;var r=this[Q];return u(r),o(r),k(r),r.o.delete(n)||!!r.p.has(n)&&r.o.delete(r.p.get(n))},t.clear=function(){var n=this[Q];u(n),p(n).size&&(o(n),k(n),n.o.clear())},t.values=function(){var n=this[Q];return u(n),o(n),n.o.values()},t.entries=function(){var n=this[Q];return u(n),o(n),n.o.entries()},t.keys=function(){return this.values()},t[V]=function(){return this.values()},t.forEach=function(n,r){for(var t=this.values(),e=t.next();!e.done;)n.call(r,e.value,e.value,this),e=t.next()},n}();m("MapSet",{F:function(n,r){return new f(n,r)},T:function(n,r){return new c(n,r)}})}function J(){F(),C(),T()}function K(n){return n}function $(n){return n}var G,U,W="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),X="undefined"!=typeof Map,q="undefined"!=typeof Set,B="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,H=W?Symbol.for("immer-nothing"):((G={})["immer-nothing"]=!0,G),L=W?Symbol.for("immer-draftable"):"__$immer_draftable",Q=W?Symbol.for("immer-state"):"__$immer_state",V="undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator",Y={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(n){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+n},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(n){return"Cannot apply patch, path doesn't resolve: "+n},16:'Sets cannot have "replace" patches.',17:function(n){return"Unsupported patch operation: "+n},18:function(n){return"The plugin for '"+n+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+n+"()` when initializing your application."},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",21:function(n){return"produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '"+n+"'"},22:function(n){return"'current' expects a draft, got: "+n},23:function(n){return"'original' expects a draft, got: "+n},24:"Patching reserved attributes like __proto__, prototype and constructor is not allowed"},Z=""+Object.prototype.constructor,nn="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:Object.getOwnPropertyNames,rn=Object.getOwnPropertyDescriptors||function(n){var r={};return nn(n).forEach((function(t){r[t]=Object.getOwnPropertyDescriptor(n,t)})),r},tn={},en={get:function(n,r){if(r===Q)return n;var e=p(n);if(!u(e,r))return function(n,r,t){var e,i=I(r,t);return i?"value"in i?i.value:null===(e=i.get)||void 0===e?void 0:e.call(n.k):void 0}(n,e,r);var i=e[r];return n.I||!t(i)?i:i===z(n.t,r)?(E(n),n.o[r]=N(n.A.h,i,n)):i},has:function(n,r){return r in p(n)},ownKeys:function(n){return Reflect.ownKeys(p(n))},set:function(n,r,t){var e=I(p(n),r);if(null==e?void 0:e.set)return e.set.call(n.k,t),!0;if(!n.P){var i=z(p(n),r),o=null==i?void 0:i[Q];if(o&&o.t===t)return n.o[r]=t,n.R[r]=!1,!0;if(c(t,i)&&(void 0!==t||u(n.t,r)))return!0;E(n),k(n)}return n.o[r]===t&&(void 0!==t||r in n.o)||Number.isNaN(t)&&Number.isNaN(n.o[r])||(n.o[r]=t,n.R[r]=!0),!0},deleteProperty:function(n,r){return void 0!==z(n.t,r)||r in n.t?(n.R[r]=!1,E(n),k(n)):delete n.R[r],n.o&&delete n.o[r],!0},getOwnPropertyDescriptor:function(n,r){var t=p(n),e=Reflect.getOwnPropertyDescriptor(t,r);return e?{writable:!0,configurable:1!==n.i||"length"!==r,enumerable:e.enumerable,value:t[r]}:e},defineProperty:function(){n(11)},getPrototypeOf:function(n){return Object.getPrototypeOf(n.t)},setPrototypeOf:function(){n(12)}},on={};i(en,(function(n,r){on[n]=function(){return arguments[0]=arguments[0][0],r.apply(this,arguments)}})),on.deleteProperty=function(r,t){return true&&isNaN(parseInt(t))&&n(13),on.set.call(this,r,t,void 0)},on.set=function(r,t,e){return true&&"length"!==t&&isNaN(parseInt(t))&&n(14),en.set.call(this,r[0],t,e,r[0])};var un=function(){function e(r){var e=this;this.O=B,this.D=!0,this.produce=function(r,i,o){if("function"==typeof r&&"function"!=typeof i){var u=i;i=r;var a=e;return function(n){var r=this;void 0===n&&(n=u);for(var t=arguments.length,e=Array(t>1?t-1:0),o=1;o<t;o++)e[o-1]=arguments[o];return a.produce(n,(function(n){var t;return(t=i).call.apply(t,[r,n].concat(e))}))}}var f;if("function"!=typeof i&&n(6),void 0!==o&&"function"!=typeof o&&n(7),t(r)){var c=w(e),s=N(e,r,void 0),v=!0;try{f=i(s),v=!1}finally{v?g(c):O(c)}return"undefined"!=typeof Promise&&f instanceof Promise?f.then((function(n){return j(c,o),P(n,c)}),(function(n){throw g(c),n})):(j(c,o),P(f,c))}if(!r||"object"!=typeof r){if(void 0===(f=i(r))&&(f=r),f===H&&(f=void 0),e.D&&d(f,!0),o){var p=[],l=[];b("Patches").M(r,f,p,l),o(p,l)}return f}n(21,r)},this.produceWithPatches=function(n,r){if("function"==typeof n)return function(r){for(var t=arguments.length,i=Array(t>1?t-1:0),o=1;o<t;o++)i[o-1]=arguments[o];return e.produceWithPatches(r,(function(r){return n.apply(void 0,[r].concat(i))}))};var t,i,o=e.produce(n,r,(function(n,r){t=n,i=r}));return"undefined"!=typeof Promise&&o instanceof Promise?o.then((function(n){return[n,t,i]})):[o,t,i]},"boolean"==typeof(null==r?void 0:r.useProxies)&&this.setUseProxies(r.useProxies),"boolean"==typeof(null==r?void 0:r.autoFreeze)&&this.setAutoFreeze(r.autoFreeze)}var i=e.prototype;return i.createDraft=function(e){t(e)||n(8),r(e)&&(e=R(e));var i=w(this),o=N(this,e,void 0);return o[Q].C=!0,O(i),o},i.finishDraft=function(r,t){var e=r&&r[Q]; true&&(e&&e.C||n(9),e.I&&n(10));var i=e.A;return j(i,t),P(void 0,i)},i.setAutoFreeze=function(n){this.D=n},i.setUseProxies=function(r){r&&!B&&n(20),this.O=r},i.applyPatches=function(n,t){var e;for(e=t.length-1;e>=0;e--){var i=t[e];if(0===i.path.length&&"replace"===i.op){n=i.value;break}}e>-1&&(t=t.slice(e+1));var o=b("Patches").$;return r(n)?o(n,t):this.produce(n,(function(n){return o(n,t)}))},e}(),an=new un,fn=an.produce,cn=an.produceWithPatches.bind(an),sn=an.setAutoFreeze.bind(an),vn=an.setUseProxies.bind(an),pn=an.applyPatches.bind(an),ln=an.createDraft.bind(an),dn=an.finishDraft.bind(an);/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (fn);
8915 //# sourceMappingURL=immer.esm.js.map
8916
8917
8918 /***/ }),
8919
8920 /***/ "../node_modules/mixpanel-browser/dist/mixpanel.module.js":
8921 /*!****************************************************************!*\
8922 !*** ../node_modules/mixpanel-browser/dist/mixpanel.module.js ***!
8923 \****************************************************************/
8924 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
8925
8926 "use strict";
8927 __webpack_require__.r(__webpack_exports__);
8928 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
8929 /* harmony export */ "default": () => (/* binding */ mixpanel)
8930 /* harmony export */ });
8931 // since es6 imports are static and we run unit tests from the console, window won't be defined when importing this file
8932 var win;
8933 if (typeof(window) === 'undefined') {
8934 var loc = {
8935 hostname: ''
8936 };
8937 win = {
8938 crypto: {randomUUID: function() {throw Error('unsupported');}},
8939 navigator: { userAgent: '', onLine: true },
8940 document: {
8941 createElement: function() { return {}; },
8942 location: loc,
8943 referrer: ''
8944 },
8945 screen: { width: 0, height: 0 },
8946 location: loc,
8947 addEventListener: function() {},
8948 removeEventListener: function() {}
8949 };
8950 } else {
8951 win = window;
8952 }
8953
8954 function _array_like_to_array(arr, len) {
8955 if (len == null || len > arr.length) len = arr.length;
8956 for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
8957 return arr2;
8958 }
8959 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
8960 try {
8961 var info = gen[key](arg);
8962 var value = info.value;
8963 } catch (error) {
8964 reject(error);
8965 return;
8966 }
8967 if (info.done) {
8968 resolve(value);
8969 } else {
8970 Promise.resolve(value).then(_next, _throw);
8971 }
8972 }
8973 function _async_to_generator(fn) {
8974 return function() {
8975 var self = this, args = arguments;
8976 return new Promise(function(resolve, reject) {
8977 var gen = fn.apply(self, args);
8978 function _next(value) {
8979 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
8980 }
8981 function _throw(err) {
8982 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
8983 }
8984 _next(undefined);
8985 });
8986 };
8987 }
8988 function _construct(Parent, args, Class) {
8989 if (_is_native_reflect_construct()) {
8990 _construct = Reflect.construct;
8991 } else {
8992 _construct = function construct(Parent, args, Class) {
8993 var a = [
8994 null
8995 ];
8996 a.push.apply(a, args);
8997 var Constructor = Function.bind.apply(Parent, a);
8998 var instance = new Constructor();
8999 if (Class) _set_prototype_of(instance, Class.prototype);
9000 return instance;
9001 };
9002 }
9003 return _construct.apply(null, arguments);
9004 }
9005 function _defineProperties(target, props) {
9006 for(var i = 0; i < props.length; i++){
9007 var descriptor = props[i];
9008 descriptor.enumerable = descriptor.enumerable || false;
9009 descriptor.configurable = true;
9010 if ("value" in descriptor) descriptor.writable = true;
9011 Object.defineProperty(target, descriptor.key, descriptor);
9012 }
9013 }
9014 function _create_class(Constructor, protoProps, staticProps) {
9015 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
9016 return Constructor;
9017 }
9018 function _extends() {
9019 _extends = Object.assign || function(target) {
9020 for(var i = 1; i < arguments.length; i++){
9021 var source = arguments[i];
9022 for(var key in source){
9023 if (Object.prototype.hasOwnProperty.call(source, key)) {
9024 target[key] = source[key];
9025 }
9026 }
9027 }
9028 return target;
9029 };
9030 return _extends.apply(this, arguments);
9031 }
9032 function _get_prototype_of(o) {
9033 _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
9034 return o.__proto__ || Object.getPrototypeOf(o);
9035 };
9036 return _get_prototype_of(o);
9037 }
9038 function _inherits(subClass, superClass) {
9039 if (typeof superClass !== "function" && superClass !== null) {
9040 throw new TypeError("Super expression must either be null or a function");
9041 }
9042 subClass.prototype = Object.create(superClass && superClass.prototype, {
9043 constructor: {
9044 value: subClass,
9045 writable: true,
9046 configurable: true
9047 }
9048 });
9049 if (superClass) _set_prototype_of(subClass, superClass);
9050 }
9051 function _instanceof(left, right) {
9052 if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
9053 return !!right[Symbol.hasInstance](left);
9054 } else {
9055 return left instanceof right;
9056 }
9057 }
9058 function _is_native_function(fn) {
9059 return Function.toString.call(fn).indexOf("[native code]") !== -1;
9060 }
9061 function _object_without_properties_loose(source, excluded) {
9062 if (source == null) return {};
9063 var target = {};
9064 var sourceKeys = Object.keys(source);
9065 var key, i;
9066 for(i = 0; i < sourceKeys.length; i++){
9067 key = sourceKeys[i];
9068 if (excluded.indexOf(key) >= 0) continue;
9069 target[key] = source[key];
9070 }
9071 return target;
9072 }
9073 function _set_prototype_of(o, p) {
9074 _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
9075 o.__proto__ = p;
9076 return o;
9077 };
9078 return _set_prototype_of(o, p);
9079 }
9080 function _type_of(obj) {
9081 "@swc/helpers - typeof";
9082 return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
9083 }
9084 function _unsupported_iterable_to_array(o, minLen) {
9085 if (!o) return;
9086 if (typeof o === "string") return _array_like_to_array(o, minLen);
9087 var n = Object.prototype.toString.call(o).slice(8, -1);
9088 if (n === "Object" && o.constructor) n = o.constructor.name;
9089 if (n === "Map" || n === "Set") return Array.from(n);
9090 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
9091 }
9092 function _wrap_native_super(Class) {
9093 var _cache = typeof Map === "function" ? new Map() : undefined;
9094 _wrap_native_super = function wrapNativeSuper(Class) {
9095 if (Class === null || !_is_native_function(Class)) return Class;
9096 if (typeof Class !== "function") {
9097 throw new TypeError("Super expression must either be null or a function");
9098 }
9099 if (typeof _cache !== "undefined") {
9100 if (_cache.has(Class)) return _cache.get(Class);
9101 _cache.set(Class, Wrapper);
9102 }
9103 function Wrapper() {
9104 return _construct(Class, arguments, _get_prototype_of(this).constructor);
9105 }
9106 Wrapper.prototype = Object.create(Class.prototype, {
9107 constructor: {
9108 value: Wrapper,
9109 enumerable: false,
9110 writable: true,
9111 configurable: true
9112 }
9113 });
9114 return _set_prototype_of(Wrapper, Class);
9115 };
9116 return _wrap_native_super(Class);
9117 }
9118 function _is_native_reflect_construct() {
9119 try {
9120 var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
9121 } catch (_) {}
9122 return (_is_native_reflect_construct = function() {
9123 return !!result;
9124 })();
9125 }
9126 function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
9127 var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
9128 if (it) return (it = it.call(o)).next.bind(it);
9129 if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike) {
9130 if (it) o = it;
9131 var i = 0;
9132 return function() {
9133 if (i >= o.length) {
9134 return {
9135 done: true
9136 };
9137 }
9138 return {
9139 done: false,
9140 value: o[i++]
9141 };
9142 };
9143 }
9144 throw new TypeError("Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
9145 }
9146 function _ts_generator(thisArg, body) {
9147 var f, y, t, g, _ = {
9148 label: 0,
9149 sent: function() {
9150 if (t[0] & 1) throw t[1];
9151 return t[1];
9152 },
9153 trys: [],
9154 ops: []
9155 };
9156 return g = {
9157 next: verb(0),
9158 "throw": verb(1),
9159 "return": verb(2)
9160 }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
9161 return this;
9162 }), g;
9163 function verb(n) {
9164 return function(v) {
9165 return step([
9166 n,
9167 v
9168 ]);
9169 };
9170 }
9171 function step(op) {
9172 if (f) throw new TypeError("Generator is already executing.");
9173 while(_)try {
9174 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;
9175 if (y = 0, t) op = [
9176 op[0] & 2,
9177 t.value
9178 ];
9179 switch(op[0]){
9180 case 0:
9181 case 1:
9182 t = op;
9183 break;
9184 case 4:
9185 _.label++;
9186 return {
9187 value: op[1],
9188 done: false
9189 };
9190 case 5:
9191 _.label++;
9192 y = op[1];
9193 op = [
9194 0
9195 ];
9196 continue;
9197 case 7:
9198 op = _.ops.pop();
9199 _.trys.pop();
9200 continue;
9201 default:
9202 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
9203 _ = 0;
9204 continue;
9205 }
9206 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
9207 _.label = op[1];
9208 break;
9209 }
9210 if (op[0] === 6 && _.label < t[1]) {
9211 _.label = t[1];
9212 t = op;
9213 break;
9214 }
9215 if (t && _.label < t[2]) {
9216 _.label = t[2];
9217 _.ops.push(op);
9218 break;
9219 }
9220 if (t[2]) _.ops.pop();
9221 _.trys.pop();
9222 continue;
9223 }
9224 op = body.call(thisArg, _);
9225 } catch (e) {
9226 op = [
9227 6,
9228 e
9229 ];
9230 y = 0;
9231 } finally{
9232 f = t = 0;
9233 }
9234 if (op[0] & 5) throw op[1];
9235 return {
9236 value: op[0] ? op[1] : void 0,
9237 done: true
9238 };
9239 }
9240 }
9241 function _ts_values(o) {
9242 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
9243 if (m) return m.call(o);
9244 if (o && typeof o.length === "number") return {
9245 next: function() {
9246 if (o && i >= o.length) o = void 0;
9247 return {
9248 value: o && o[i++],
9249 done: !o
9250 };
9251 }
9252 };
9253 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
9254 }
9255 var __defProp = Object.defineProperty;
9256 var __defNormalProp = function(obj, key, value) {
9257 return key in obj ? __defProp(obj, key, {
9258 enumerable: true,
9259 configurable: true,
9260 writable: true,
9261 value: value
9262 }) : obj[key] = value;
9263 };
9264 var __publicField = function(obj, key, value) {
9265 return __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
9266 };
9267 var _a;
9268 var __defProp$1 = Object.defineProperty;
9269 var __defNormalProp$1 = function(obj, key, value) {
9270 return key in obj ? __defProp$1(obj, key, {
9271 enumerable: true,
9272 configurable: true,
9273 writable: true,
9274 value: value
9275 }) : obj[key] = value;
9276 };
9277 var __publicField$1 = function(obj, key, value) {
9278 return __defNormalProp$1(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
9279 };
9280 var NodeType$3 = /* @__PURE__ */ function(NodeType2) {
9281 NodeType2[NodeType2["Document"] = 0] = "Document";
9282 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
9283 NodeType2[NodeType2["Element"] = 2] = "Element";
9284 NodeType2[NodeType2["Text"] = 3] = "Text";
9285 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
9286 NodeType2[NodeType2["Comment"] = 5] = "Comment";
9287 return NodeType2;
9288 }(NodeType$3 || {});
9289 var testableAccessors$1 = {
9290 Node: [
9291 "childNodes",
9292 "parentNode",
9293 "parentElement",
9294 "textContent"
9295 ],
9296 ShadowRoot: [
9297 "host",
9298 "styleSheets"
9299 ],
9300 Element: [
9301 "shadowRoot",
9302 "querySelector",
9303 "querySelectorAll"
9304 ],
9305 MutationObserver: []
9306 };
9307 var testableMethods$1 = {
9308 Node: [
9309 "contains",
9310 "getRootNode"
9311 ],
9312 ShadowRoot: [
9313 "getSelection"
9314 ],
9315 Element: [],
9316 MutationObserver: [
9317 "constructor"
9318 ]
9319 };
9320 var untaintedBasePrototype$1 = {};
9321 var isAngularZonePresent$1 = function() {
9322 return !!globalThis.Zone;
9323 };
9324 function getUntaintedPrototype$1(key) {
9325 if (untaintedBasePrototype$1[key]) return untaintedBasePrototype$1[key];
9326 var defaultObj = globalThis[key];
9327 var defaultPrototype = defaultObj.prototype;
9328 var accessorNames = key in testableAccessors$1 ? testableAccessors$1[key] : void 0;
9329 var isUntaintedAccessors = Boolean(accessorNames && // @ts-expect-error 2345
9330 accessorNames.every(function(accessor) {
9331 var _a2, _b;
9332 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
9333 }));
9334 var methodNames = key in testableMethods$1 ? testableMethods$1[key] : void 0;
9335 var isUntaintedMethods = Boolean(methodNames && methodNames.every(// @ts-expect-error 2345
9336 function(method) {
9337 var _a2;
9338 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
9339 }));
9340 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent$1()) {
9341 untaintedBasePrototype$1[key] = defaultObj.prototype;
9342 return defaultObj.prototype;
9343 }
9344 try {
9345 var iframeEl = document.createElement("iframe");
9346 document.body.appendChild(iframeEl);
9347 var win = iframeEl.contentWindow;
9348 if (!win) return defaultObj.prototype;
9349 var untaintedObject = win[key].prototype;
9350 document.body.removeChild(iframeEl);
9351 if (!untaintedObject) return defaultPrototype;
9352 return untaintedBasePrototype$1[key] = untaintedObject;
9353 } catch (e) {
9354 return defaultPrototype;
9355 }
9356 }
9357 var untaintedAccessorCache$1 = {};
9358 function getUntaintedAccessor$1(key, instance, accessor) {
9359 var _a2;
9360 var cacheKey = key + "." + String(accessor);
9361 if (untaintedAccessorCache$1[cacheKey]) return untaintedAccessorCache$1[cacheKey].call(instance);
9362 var untaintedPrototype = getUntaintedPrototype$1(key);
9363 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
9364 if (!untaintedAccessor) return instance[accessor];
9365 untaintedAccessorCache$1[cacheKey] = untaintedAccessor;
9366 return untaintedAccessor.call(instance);
9367 }
9368 var untaintedMethodCache$1 = {};
9369 function getUntaintedMethod$1(key, instance, method) {
9370 var cacheKey = key + "." + String(method);
9371 if (untaintedMethodCache$1[cacheKey]) return untaintedMethodCache$1[cacheKey].bind(instance);
9372 var untaintedPrototype = getUntaintedPrototype$1(key);
9373 var untaintedMethod = untaintedPrototype[method];
9374 if (typeof untaintedMethod !== "function") return instance[method];
9375 untaintedMethodCache$1[cacheKey] = untaintedMethod;
9376 return untaintedMethod.bind(instance);
9377 }
9378 function childNodes$1(n2) {
9379 return getUntaintedAccessor$1("Node", n2, "childNodes");
9380 }
9381 function parentNode$1(n2) {
9382 return getUntaintedAccessor$1("Node", n2, "parentNode");
9383 }
9384 function parentElement$1(n2) {
9385 return getUntaintedAccessor$1("Node", n2, "parentElement");
9386 }
9387 function textContent$1(n2) {
9388 return getUntaintedAccessor$1("Node", n2, "textContent");
9389 }
9390 function contains$1(n2, other) {
9391 return getUntaintedMethod$1("Node", n2, "contains")(other);
9392 }
9393 function getRootNode$1(n2) {
9394 return getUntaintedMethod$1("Node", n2, "getRootNode")();
9395 }
9396 function host$1(n2) {
9397 if (!n2 || !("host" in n2)) return null;
9398 return getUntaintedAccessor$1("ShadowRoot", n2, "host");
9399 }
9400 function styleSheets$1(n2) {
9401 return n2.styleSheets;
9402 }
9403 function shadowRoot$1(n2) {
9404 if (!n2 || !("shadowRoot" in n2)) return null;
9405 return getUntaintedAccessor$1("Element", n2, "shadowRoot");
9406 }
9407 function querySelector$1(n2, selectors) {
9408 return getUntaintedAccessor$1("Element", n2, "querySelector")(selectors);
9409 }
9410 function querySelectorAll$1(n2, selectors) {
9411 return getUntaintedAccessor$1("Element", n2, "querySelectorAll")(selectors);
9412 }
9413 function mutationObserverCtor$1() {
9414 return getUntaintedPrototype$1("MutationObserver").constructor;
9415 }
9416 function patch$1(source, name, replacement) {
9417 try {
9418 if (!(name in source)) {
9419 return function() {};
9420 }
9421 var original = source[name];
9422 var wrapped = replacement(original);
9423 if (typeof wrapped === "function") {
9424 wrapped.prototype = wrapped.prototype || {};
9425 Object.defineProperties(wrapped, {
9426 __rrweb_original__: {
9427 enumerable: false,
9428 value: original
9429 }
9430 });
9431 }
9432 source[name] = wrapped;
9433 return function() {
9434 source[name] = original;
9435 };
9436 } catch (e) {
9437 return function() {};
9438 }
9439 }
9440 var index$1 = {
9441 childNodes: childNodes$1,
9442 parentNode: parentNode$1,
9443 parentElement: parentElement$1,
9444 textContent: textContent$1,
9445 contains: contains$1,
9446 getRootNode: getRootNode$1,
9447 host: host$1,
9448 styleSheets: styleSheets$1,
9449 shadowRoot: shadowRoot$1,
9450 querySelector: querySelector$1,
9451 querySelectorAll: querySelectorAll$1,
9452 mutationObserver: mutationObserverCtor$1,
9453 patch: patch$1
9454 };
9455 function isElement(n2) {
9456 return n2.nodeType === n2.ELEMENT_NODE;
9457 }
9458 function isShadowRoot(n2) {
9459 var hostEl = // anchor and textarea elements also have a `host` property
9460 // but only shadow roots have a `mode` property
9461 n2 && "host" in n2 && "mode" in n2 && index$1.host(n2) || null;
9462 return Boolean(hostEl && "shadowRoot" in hostEl && index$1.shadowRoot(hostEl) === n2);
9463 }
9464 function isNativeShadowDom(shadowRoot2) {
9465 return Object.prototype.toString.call(shadowRoot2) === "[object ShadowRoot]";
9466 }
9467 function fixBrowserCompatibilityIssuesInCSS(cssText) {
9468 if (cssText.includes(" background-clip: text;") && !cssText.includes(" -webkit-background-clip: text;")) {
9469 cssText = cssText.replace(/\sbackground-clip:\s*text;/g, " -webkit-background-clip: text; background-clip: text;");
9470 }
9471 return cssText;
9472 }
9473 function escapeImportStatement(rule2) {
9474 var cssText = rule2.cssText;
9475 if (cssText.split('"').length < 3) return cssText;
9476 var statement = [
9477 "@import",
9478 "url(" + JSON.stringify(rule2.href) + ")"
9479 ];
9480 if (rule2.layerName === "") {
9481 statement.push("layer");
9482 } else if (rule2.layerName) {
9483 statement.push("layer(" + rule2.layerName + ")");
9484 }
9485 if (rule2.supportsText) {
9486 statement.push("supports(" + rule2.supportsText + ")");
9487 }
9488 if (rule2.media.length) {
9489 statement.push(rule2.media.mediaText);
9490 }
9491 return statement.join(" ") + ";";
9492 }
9493 function stringifyStylesheet(s2) {
9494 try {
9495 var rules2 = s2.rules || s2.cssRules;
9496 if (!rules2) {
9497 return null;
9498 }
9499 var sheetHref = s2.href;
9500 if (!sheetHref && s2.ownerNode && s2.ownerNode.ownerDocument) {
9501 sheetHref = s2.ownerNode.ownerDocument.location.href;
9502 }
9503 var stringifiedRules = Array.from(rules2, function(rule2) {
9504 return stringifyRule(rule2, sheetHref);
9505 }).join("");
9506 return fixBrowserCompatibilityIssuesInCSS(stringifiedRules);
9507 } catch (error) {
9508 return null;
9509 }
9510 }
9511 function stringifyRule(rule2, sheetHref) {
9512 if (isCSSImportRule(rule2)) {
9513 var importStringified;
9514 try {
9515 importStringified = // we can access the imported stylesheet rules directly
9516 stringifyStylesheet(rule2.styleSheet) || // work around browser issues with the raw string `@import url(...)` statement
9517 escapeImportStatement(rule2);
9518 } catch (error) {
9519 importStringified = rule2.cssText;
9520 }
9521 if (rule2.styleSheet.href) {
9522 return absolutifyURLs(importStringified, rule2.styleSheet.href);
9523 }
9524 return importStringified;
9525 } else {
9526 var ruleStringified = rule2.cssText;
9527 if (isCSSStyleRule(rule2) && rule2.selectorText.includes(":")) {
9528 ruleStringified = fixSafariColons(ruleStringified);
9529 }
9530 if (sheetHref) {
9531 return absolutifyURLs(ruleStringified, sheetHref);
9532 }
9533 return ruleStringified;
9534 }
9535 }
9536 function fixSafariColons(cssStringified) {
9537 var regex = /(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;
9538 return cssStringified.replace(regex, "$1\\$2");
9539 }
9540 function isCSSImportRule(rule2) {
9541 return "styleSheet" in rule2;
9542 }
9543 function isCSSStyleRule(rule2) {
9544 return "selectorText" in rule2;
9545 }
9546 var Mirror = /*#__PURE__*/ function() {
9547 function Mirror() {
9548 __publicField$1(this, "idNodeMap", /* @__PURE__ */ new Map());
9549 __publicField$1(this, "nodeMetaMap", /* @__PURE__ */ new WeakMap());
9550 }
9551 var _proto = Mirror.prototype;
9552 _proto.getId = function getId(n2) {
9553 var _a2;
9554 if (!n2) return -1;
9555 var id = (_a2 = this.getMeta(n2)) == null ? void 0 : _a2.id;
9556 return id != null ? id : -1;
9557 };
9558 _proto.getNode = function getNode(id) {
9559 return this.idNodeMap.get(id) || null;
9560 };
9561 _proto.getIds = function getIds() {
9562 return Array.from(this.idNodeMap.keys());
9563 };
9564 _proto.getMeta = function getMeta(n2) {
9565 return this.nodeMetaMap.get(n2) || null;
9566 };
9567 // removes the node from idNodeMap
9568 // doesn't remove the node from nodeMetaMap
9569 _proto.removeNodeFromMap = function removeNodeFromMap(n2) {
9570 var _this = this;
9571 var id = this.getId(n2);
9572 this.idNodeMap.delete(id);
9573 if (n2.childNodes) {
9574 n2.childNodes.forEach(function(childNode) {
9575 return _this.removeNodeFromMap(childNode);
9576 });
9577 }
9578 };
9579 _proto.has = function has(id) {
9580 return this.idNodeMap.has(id);
9581 };
9582 _proto.hasNode = function hasNode(node2) {
9583 return this.nodeMetaMap.has(node2);
9584 };
9585 _proto.add = function add(n2, meta) {
9586 var id = meta.id;
9587 this.idNodeMap.set(id, n2);
9588 this.nodeMetaMap.set(n2, meta);
9589 };
9590 _proto.replace = function replace(id, n2) {
9591 var oldNode = this.getNode(id);
9592 if (oldNode) {
9593 var meta = this.nodeMetaMap.get(oldNode);
9594 if (meta) this.nodeMetaMap.set(n2, meta);
9595 }
9596 this.idNodeMap.set(id, n2);
9597 };
9598 _proto.reset = function reset() {
9599 this.idNodeMap = /* @__PURE__ */ new Map();
9600 this.nodeMetaMap = /* @__PURE__ */ new WeakMap();
9601 };
9602 return Mirror;
9603 }();
9604 function createMirror$2() {
9605 return new Mirror();
9606 }
9607 function maskInputValue(param) {
9608 var element = param.element, maskInputOptions = param.maskInputOptions, tagName = param.tagName, type = param.type, value = param.value, maskInputFn = param.maskInputFn;
9609 var text = value || "";
9610 var actualType = type && toLowerCase(type);
9611 if (maskInputOptions[tagName.toLowerCase()] || actualType && maskInputOptions[actualType]) {
9612 if (maskInputFn) {
9613 text = maskInputFn(text, element);
9614 } else {
9615 text = "*".repeat(text.length);
9616 }
9617 }
9618 return text;
9619 }
9620 function toLowerCase(str) {
9621 return str.toLowerCase();
9622 }
9623 var ORIGINAL_ATTRIBUTE_NAME = "__rrweb_original__";
9624 function is2DCanvasBlank(canvas) {
9625 var ctx = canvas.getContext("2d");
9626 if (!ctx) return true;
9627 var chunkSize = 50;
9628 for(var x2 = 0; x2 < canvas.width; x2 += chunkSize){
9629 for(var y = 0; y < canvas.height; y += chunkSize){
9630 var getImageData = ctx.getImageData;
9631 var originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData ? getImageData[ORIGINAL_ATTRIBUTE_NAME] : getImageData;
9632 var pixelBuffer = new Uint32Array(// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
9633 originalGetImageData.call(ctx, x2, y, Math.min(chunkSize, canvas.width - x2), Math.min(chunkSize, canvas.height - y)).data.buffer);
9634 if (pixelBuffer.some(function(pixel) {
9635 return pixel !== 0;
9636 })) return false;
9637 }
9638 }
9639 return true;
9640 }
9641 function getInputType(element) {
9642 var type = element.type;
9643 return element.hasAttribute("data-rr-is-password") ? "password" : type ? // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
9644 toLowerCase(type) : null;
9645 }
9646 function extractFileExtension(path, baseURL) {
9647 var url;
9648 try {
9649 url = new URL(path, baseURL != null ? baseURL : window.location.href);
9650 } catch (err) {
9651 return null;
9652 }
9653 var regex = /\.([0-9a-z]+)(?:$)/i;
9654 var match = url.pathname.match(regex);
9655 var _ref;
9656 return (_ref = match == null ? void 0 : match[1]) != null ? _ref : null;
9657 }
9658 function extractOrigin(url) {
9659 var origin = "";
9660 if (url.indexOf("//") > -1) {
9661 origin = url.split("/").slice(0, 3).join("/");
9662 } else {
9663 origin = url.split("/")[0];
9664 }
9665 origin = origin.split("?")[0];
9666 return origin;
9667 }
9668 var URL_IN_CSS_REF = /url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm;
9669 var URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\/\//i;
9670 var URL_WWW_MATCH = /^www\..*/i;
9671 var DATA_URI = /^(data:)([^,]*),(.*)/i;
9672 function absolutifyURLs(cssText, href) {
9673 return (cssText || "").replace(URL_IN_CSS_REF, function(origin, quote1, path1, quote2, path2, path3) {
9674 var filePath = path1 || path2 || path3;
9675 var maybeQuote = quote1 || quote2 || "";
9676 if (!filePath) {
9677 return origin;
9678 }
9679 if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {
9680 return "url(" + maybeQuote + filePath + maybeQuote + ")";
9681 }
9682 if (DATA_URI.test(filePath)) {
9683 return "url(" + maybeQuote + filePath + maybeQuote + ")";
9684 }
9685 if (filePath[0] === "/") {
9686 return "url(" + maybeQuote + (extractOrigin(href) + filePath) + maybeQuote + ")";
9687 }
9688 var stack = href.split("/");
9689 var parts = filePath.split("/");
9690 stack.pop();
9691 for(var _iterator = _create_for_of_iterator_helper_loose(parts), _step; !(_step = _iterator()).done;){
9692 var part = _step.value;
9693 if (part === ".") {
9694 continue;
9695 } else if (part === "..") {
9696 stack.pop();
9697 } else {
9698 stack.push(part);
9699 }
9700 }
9701 return "url(" + maybeQuote + stack.join("/") + maybeQuote + ")";
9702 });
9703 }
9704 function normalizeCssString(cssText, _testNoPxNorm) {
9705 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
9706 if (_testNoPxNorm) {
9707 return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "");
9708 } else {
9709 return cssText.replace(/(\/\*[^*]*\*\/)|[\s;]/g, "").replace(/0px/g, "0");
9710 }
9711 }
9712 function splitCssText(cssText, style, _testNoPxNorm) {
9713 if (_testNoPxNorm === void 0) _testNoPxNorm = false;
9714 var childNodes2 = Array.from(style.childNodes);
9715 var splits = [];
9716 var iterCount = 0;
9717 if (childNodes2.length > 1 && cssText && typeof cssText === "string") {
9718 var cssTextNorm = normalizeCssString(cssText, _testNoPxNorm);
9719 var normFactor = cssTextNorm.length / cssText.length;
9720 for(var i2 = 1; i2 < childNodes2.length; i2++){
9721 if (childNodes2[i2].textContent && typeof childNodes2[i2].textContent === "string") {
9722 var textContentNorm = normalizeCssString(childNodes2[i2].textContent, _testNoPxNorm);
9723 var jLimit = 100;
9724 var j = 3;
9725 for(; j < textContentNorm.length; j++){
9726 if (// keep consuming css identifiers (to get a decent chunk more quickly)
9727 textContentNorm[j].match(/[a-zA-Z0-9]/) || // substring needs to be unique to this section
9728 textContentNorm.indexOf(textContentNorm.substring(0, j), 1) !== -1) {
9729 continue;
9730 }
9731 break;
9732 }
9733 for(; j < textContentNorm.length; j++){
9734 var startSubstring = textContentNorm.substring(0, j);
9735 var cssNormSplits = cssTextNorm.split(startSubstring);
9736 var splitNorm = -1;
9737 if (cssNormSplits.length === 2) {
9738 splitNorm = cssNormSplits[0].length;
9739 } else if (cssNormSplits.length > 2 && cssNormSplits[0] === "" && childNodes2[i2 - 1].textContent !== "") {
9740 splitNorm = cssTextNorm.indexOf(startSubstring, 1);
9741 } else if (cssNormSplits.length === 1) {
9742 startSubstring = startSubstring.substring(0, startSubstring.length - 1);
9743 cssNormSplits = cssTextNorm.split(startSubstring);
9744 if (cssNormSplits.length <= 1) {
9745 splits.push(cssText);
9746 return splits;
9747 }
9748 j = jLimit + 1;
9749 } else if (j === textContentNorm.length - 1) {
9750 splitNorm = cssTextNorm.indexOf(startSubstring);
9751 }
9752 if (cssNormSplits.length >= 2 && j > jLimit) {
9753 var prevTextContent = childNodes2[i2 - 1].textContent;
9754 if (prevTextContent && typeof prevTextContent === "string") {
9755 var prevMinLength = normalizeCssString(prevTextContent).length;
9756 splitNorm = cssTextNorm.indexOf(startSubstring, prevMinLength);
9757 }
9758 if (splitNorm === -1) {
9759 splitNorm = cssNormSplits[0].length;
9760 }
9761 }
9762 if (splitNorm !== -1) {
9763 var k = Math.floor(splitNorm / normFactor);
9764 for(; k > 0 && k < cssText.length;){
9765 iterCount += 1;
9766 if (iterCount > 50 * childNodes2.length) {
9767 splits.push(cssText);
9768 return splits;
9769 }
9770 var normPart = normalizeCssString(cssText.substring(0, k), _testNoPxNorm);
9771 if (normPart.length === splitNorm) {
9772 splits.push(cssText.substring(0, k));
9773 cssText = cssText.substring(k);
9774 cssTextNorm = cssTextNorm.substring(splitNorm);
9775 break;
9776 } else if (normPart.length < splitNorm) {
9777 k += Math.max(1, Math.floor((splitNorm - normPart.length) / normFactor));
9778 } else {
9779 k -= Math.max(1, Math.floor((normPart.length - splitNorm) * normFactor));
9780 }
9781 }
9782 break;
9783 }
9784 }
9785 }
9786 }
9787 }
9788 splits.push(cssText);
9789 return splits;
9790 }
9791 function markCssSplits(cssText, style) {
9792 return splitCssText(cssText, style).join("/* rr_split */");
9793 }
9794 var _id = 1;
9795 var tagNameRegex = new RegExp("[^a-z0-9-_:]");
9796 var IGNORED_NODE = -2;
9797 function genId() {
9798 return _id++;
9799 }
9800 function getValidTagName$1(element) {
9801 if (_instanceof(element, HTMLFormElement)) {
9802 return "form";
9803 }
9804 var processedTagName = toLowerCase(element.tagName);
9805 if (tagNameRegex.test(processedTagName)) {
9806 return "div";
9807 }
9808 return processedTagName;
9809 }
9810 var canvasService;
9811 var canvasCtx;
9812 var SRCSET_NOT_SPACES = /^[^ \t\n\r\u000c]+/;
9813 var SRCSET_COMMAS_OR_SPACES = /^[, \t\n\r\u000c]+/;
9814 function getAbsoluteSrcsetString(doc, attributeValue) {
9815 if (attributeValue.trim() === "") {
9816 return attributeValue;
9817 }
9818 var pos = 0;
9819 function collectCharacters(regEx) {
9820 var chars2;
9821 var match = regEx.exec(attributeValue.substring(pos));
9822 if (match) {
9823 chars2 = match[0];
9824 pos += chars2.length;
9825 return chars2;
9826 }
9827 return "";
9828 }
9829 var output = [];
9830 while(true){
9831 collectCharacters(SRCSET_COMMAS_OR_SPACES);
9832 if (pos >= attributeValue.length) {
9833 break;
9834 }
9835 var url = collectCharacters(SRCSET_NOT_SPACES);
9836 if (url.slice(-1) === ",") {
9837 url = absoluteToDoc(doc, url.substring(0, url.length - 1));
9838 output.push(url);
9839 } else {
9840 var descriptorsStr = "";
9841 url = absoluteToDoc(doc, url);
9842 var inParens = false;
9843 while(true){
9844 var c2 = attributeValue.charAt(pos);
9845 if (c2 === "") {
9846 output.push((url + descriptorsStr).trim());
9847 break;
9848 } else if (!inParens) {
9849 if (c2 === ",") {
9850 pos += 1;
9851 output.push((url + descriptorsStr).trim());
9852 break;
9853 } else if (c2 === "(") {
9854 inParens = true;
9855 }
9856 } else {
9857 if (c2 === ")") {
9858 inParens = false;
9859 }
9860 }
9861 descriptorsStr += c2;
9862 pos += 1;
9863 }
9864 }
9865 }
9866 return output.join(", ");
9867 }
9868 var cachedDocument = /* @__PURE__ */ new WeakMap();
9869 function absoluteToDoc(doc, attributeValue) {
9870 if (!attributeValue || attributeValue.trim() === "") {
9871 return attributeValue;
9872 }
9873 return getHref(doc, attributeValue);
9874 }
9875 function isSVGElement(el) {
9876 return Boolean(el.tagName === "svg" || el.ownerSVGElement);
9877 }
9878 function getHref(doc, customHref) {
9879 var a2 = cachedDocument.get(doc);
9880 if (!a2) {
9881 a2 = doc.createElement("a");
9882 cachedDocument.set(doc, a2);
9883 }
9884 if (!customHref) {
9885 customHref = "";
9886 } else if (customHref.startsWith("blob:") || customHref.startsWith("data:")) {
9887 return customHref;
9888 }
9889 a2.setAttribute("href", customHref);
9890 return a2.href;
9891 }
9892 function transformAttribute(doc, tagName, name, value) {
9893 if (!value) {
9894 return value;
9895 }
9896 if (name === "src" || name === "href" && !(tagName === "use" && value[0] === "#")) {
9897 return absoluteToDoc(doc, value);
9898 } else if (name === "xlink:href" && value[0] !== "#") {
9899 return absoluteToDoc(doc, value);
9900 } else if (name === "background" && (tagName === "table" || tagName === "td" || tagName === "th")) {
9901 return absoluteToDoc(doc, value);
9902 } else if (name === "srcset") {
9903 return getAbsoluteSrcsetString(doc, value);
9904 } else if (name === "style") {
9905 return absolutifyURLs(value, getHref(doc));
9906 } else if (tagName === "object" && name === "data") {
9907 return absoluteToDoc(doc, value);
9908 }
9909 return value;
9910 }
9911 function ignoreAttribute(tagName, name, _value) {
9912 return (tagName === "video" || tagName === "audio") && name === "autoplay";
9913 }
9914 function _isBlockedElement(element, blockClass, blockSelector) {
9915 try {
9916 if (typeof blockClass === "string") {
9917 if (element.classList.contains(blockClass)) {
9918 return true;
9919 }
9920 } else {
9921 for(var eIndex = element.classList.length; eIndex--;){
9922 var className = element.classList[eIndex];
9923 if (blockClass.test(className)) {
9924 return true;
9925 }
9926 }
9927 }
9928 if (blockSelector) {
9929 return element.matches(blockSelector);
9930 }
9931 } catch (e2) {}
9932 return false;
9933 }
9934 function classMatchesRegex(node2, regex, checkAncestors) {
9935 if (!node2) return false;
9936 if (node2.nodeType !== node2.ELEMENT_NODE) {
9937 if (!checkAncestors) return false;
9938 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
9939 }
9940 for(var eIndex = node2.classList.length; eIndex--;){
9941 var className = node2.classList[eIndex];
9942 if (regex.test(className)) {
9943 return true;
9944 }
9945 }
9946 if (!checkAncestors) return false;
9947 return classMatchesRegex(index$1.parentNode(node2), regex, checkAncestors);
9948 }
9949 function needMaskingText(node2, maskTextClass, maskTextSelector, checkAncestors) {
9950 var el;
9951 if (isElement(node2)) {
9952 el = node2;
9953 if (!index$1.childNodes(el).length) {
9954 return false;
9955 }
9956 } else if (index$1.parentElement(node2) === null) {
9957 return false;
9958 } else {
9959 el = index$1.parentElement(node2);
9960 }
9961 try {
9962 if (typeof maskTextClass === "string") {
9963 if (checkAncestors) {
9964 if (el.closest("." + maskTextClass)) return true;
9965 } else {
9966 if (el.classList.contains(maskTextClass)) return true;
9967 }
9968 } else {
9969 if (classMatchesRegex(el, maskTextClass, checkAncestors)) return true;
9970 }
9971 if (maskTextSelector) {
9972 if (checkAncestors) {
9973 if (el.closest(maskTextSelector)) return true;
9974 } else {
9975 if (el.matches(maskTextSelector)) return true;
9976 }
9977 }
9978 } catch (e2) {}
9979 return false;
9980 }
9981 function onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {
9982 var win = iframeEl.contentWindow;
9983 if (!win) {
9984 return;
9985 }
9986 var fired = false;
9987 var readyState;
9988 try {
9989 readyState = win.document.readyState;
9990 } catch (error) {
9991 return;
9992 }
9993 if (readyState !== "complete") {
9994 var timer = setTimeout(function() {
9995 if (!fired) {
9996 listener();
9997 fired = true;
9998 }
9999 }, iframeLoadTimeout);
10000 iframeEl.addEventListener("load", function() {
10001 clearTimeout(timer);
10002 fired = true;
10003 listener();
10004 });
10005 return;
10006 }
10007 var blankUrl = "about:blank";
10008 if (win.location.href !== blankUrl || iframeEl.src === blankUrl || iframeEl.src === "") {
10009 setTimeout(listener, 0);
10010 return iframeEl.addEventListener("load", listener);
10011 }
10012 iframeEl.addEventListener("load", listener);
10013 }
10014 function onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {
10015 var fired = false;
10016 var styleSheetLoaded;
10017 try {
10018 styleSheetLoaded = link.sheet;
10019 } catch (error) {
10020 return;
10021 }
10022 if (styleSheetLoaded) return;
10023 var timer = setTimeout(function() {
10024 if (!fired) {
10025 listener();
10026 fired = true;
10027 }
10028 }, styleSheetLoadTimeout);
10029 link.addEventListener("load", function() {
10030 clearTimeout(timer);
10031 fired = true;
10032 listener();
10033 });
10034 }
10035 function serializeNode(n2, options) {
10036 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;
10037 var rootId = getRootId(doc, mirror2);
10038 switch(n2.nodeType){
10039 case n2.DOCUMENT_NODE:
10040 if (n2.compatMode !== "CSS1Compat") {
10041 return {
10042 type: NodeType$3.Document,
10043 childNodes: [],
10044 compatMode: n2.compatMode
10045 };
10046 } else {
10047 return {
10048 type: NodeType$3.Document,
10049 childNodes: []
10050 };
10051 }
10052 case n2.DOCUMENT_TYPE_NODE:
10053 return {
10054 type: NodeType$3.DocumentType,
10055 name: n2.name,
10056 publicId: n2.publicId,
10057 systemId: n2.systemId,
10058 rootId: rootId
10059 };
10060 case n2.ELEMENT_NODE:
10061 return serializeElementNode(n2, {
10062 doc: doc,
10063 blockClass: blockClass,
10064 blockSelector: blockSelector,
10065 inlineStylesheet: inlineStylesheet,
10066 maskInputOptions: maskInputOptions,
10067 maskInputFn: maskInputFn,
10068 dataURLOptions: dataURLOptions,
10069 inlineImages: inlineImages,
10070 recordCanvas: recordCanvas,
10071 keepIframeSrcFn: keepIframeSrcFn,
10072 newlyAddedElement: newlyAddedElement,
10073 rootId: rootId
10074 });
10075 case n2.TEXT_NODE:
10076 return serializeTextNode(n2, {
10077 doc: doc,
10078 needsMask: needsMask,
10079 maskTextFn: maskTextFn,
10080 rootId: rootId,
10081 cssCaptured: cssCaptured
10082 });
10083 case n2.CDATA_SECTION_NODE:
10084 return {
10085 type: NodeType$3.CDATA,
10086 textContent: "",
10087 rootId: rootId
10088 };
10089 case n2.COMMENT_NODE:
10090 return {
10091 type: NodeType$3.Comment,
10092 textContent: index$1.textContent(n2) || "",
10093 rootId: rootId
10094 };
10095 default:
10096 return false;
10097 }
10098 }
10099 function getRootId(doc, mirror2) {
10100 if (!mirror2.hasNode(doc)) return void 0;
10101 var docId = mirror2.getId(doc);
10102 return docId === 1 ? void 0 : docId;
10103 }
10104 function serializeTextNode(n2, options) {
10105 var needsMask = options.needsMask, maskTextFn = options.maskTextFn, rootId = options.rootId, cssCaptured = options.cssCaptured;
10106 var parent = index$1.parentNode(n2);
10107 var parentTagName = parent && parent.tagName;
10108 var textContent2 = "";
10109 var isStyle = parentTagName === "STYLE" ? true : void 0;
10110 var isScript = parentTagName === "SCRIPT" ? true : void 0;
10111 if (isScript) {
10112 textContent2 = "SCRIPT_PLACEHOLDER";
10113 } else if (!cssCaptured) {
10114 textContent2 = index$1.textContent(n2);
10115 if (isStyle && textContent2) {
10116 textContent2 = absolutifyURLs(textContent2, getHref(options.doc));
10117 }
10118 }
10119 if (!isStyle && !isScript && textContent2 && needsMask) {
10120 textContent2 = maskTextFn ? maskTextFn(textContent2, index$1.parentElement(n2)) : textContent2.replace(/[\S]/g, "*");
10121 }
10122 return {
10123 type: NodeType$3.Text,
10124 textContent: textContent2 || "",
10125 rootId: rootId
10126 };
10127 }
10128 function serializeElementNode(n2, options) {
10129 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;
10130 var needBlock = _isBlockedElement(n2, blockClass, blockSelector);
10131 var tagName = getValidTagName$1(n2);
10132 var attributes = {};
10133 var len = n2.attributes.length;
10134 for(var i2 = 0; i2 < len; i2++){
10135 var attr = n2.attributes[i2];
10136 if (!ignoreAttribute(tagName, attr.name, attr.value)) {
10137 attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value);
10138 }
10139 }
10140 if (tagName === "link" && inlineStylesheet) {
10141 var stylesheet = Array.from(doc.styleSheets).find(function(s2) {
10142 return s2.href === n2.href;
10143 });
10144 var cssText = null;
10145 if (stylesheet) {
10146 cssText = stringifyStylesheet(stylesheet);
10147 }
10148 if (cssText) {
10149 delete attributes.rel;
10150 delete attributes.href;
10151 attributes._cssText = cssText;
10152 }
10153 }
10154 if (tagName === "style" && n2.sheet) {
10155 var cssText1 = stringifyStylesheet(n2.sheet);
10156 if (cssText1) {
10157 if (n2.childNodes.length > 1) {
10158 cssText1 = markCssSplits(cssText1, n2);
10159 }
10160 attributes._cssText = cssText1;
10161 }
10162 }
10163 if (tagName === "input" || tagName === "textarea" || tagName === "select") {
10164 var value = n2.value;
10165 var checked = n2.checked;
10166 if (attributes.type !== "radio" && attributes.type !== "checkbox" && attributes.type !== "submit" && attributes.type !== "button" && value) {
10167 attributes.value = maskInputValue({
10168 element: n2,
10169 type: getInputType(n2),
10170 tagName: tagName,
10171 value: value,
10172 maskInputOptions: maskInputOptions,
10173 maskInputFn: maskInputFn
10174 });
10175 } else if (checked) {
10176 attributes.checked = checked;
10177 }
10178 }
10179 if (tagName === "option") {
10180 if (n2.selected && !maskInputOptions["select"]) {
10181 attributes.selected = true;
10182 } else {
10183 delete attributes.selected;
10184 }
10185 }
10186 if (tagName === "dialog" && n2.open) {
10187 attributes.rr_open_mode = n2.matches("dialog:modal") ? "modal" : "non-modal";
10188 }
10189 if (tagName === "canvas" && recordCanvas) {
10190 if (n2.__context === "2d") {
10191 if (!is2DCanvasBlank(n2)) {
10192 attributes.rr_dataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
10193 }
10194 } else if (!("__context" in n2)) {
10195 var canvasDataURL = n2.toDataURL(dataURLOptions.type, dataURLOptions.quality);
10196 var blankCanvas = doc.createElement("canvas");
10197 blankCanvas.width = n2.width;
10198 blankCanvas.height = n2.height;
10199 var blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);
10200 if (canvasDataURL !== blankCanvasDataURL) {
10201 attributes.rr_dataURL = canvasDataURL;
10202 }
10203 }
10204 }
10205 if (tagName === "img" && inlineImages) {
10206 if (!canvasService) {
10207 canvasService = doc.createElement("canvas");
10208 canvasCtx = canvasService.getContext("2d");
10209 }
10210 var image = n2;
10211 var imageSrc = image.currentSrc || image.getAttribute("src") || "<unknown-src>";
10212 var priorCrossOrigin = image.crossOrigin;
10213 var recordInlineImage = function() {
10214 image.removeEventListener("load", recordInlineImage);
10215 try {
10216 canvasService.width = image.naturalWidth;
10217 canvasService.height = image.naturalHeight;
10218 canvasCtx.drawImage(image, 0, 0);
10219 attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);
10220 } catch (err) {
10221 if (image.crossOrigin !== "anonymous") {
10222 image.crossOrigin = "anonymous";
10223 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
10224 else image.addEventListener("load", recordInlineImage);
10225 return;
10226 } else {
10227 console.warn("Cannot inline img src=" + imageSrc + "! Error: " + err);
10228 }
10229 }
10230 if (image.crossOrigin === "anonymous") {
10231 priorCrossOrigin ? attributes.crossOrigin = priorCrossOrigin : image.removeAttribute("crossorigin");
10232 }
10233 };
10234 if (image.complete && image.naturalWidth !== 0) recordInlineImage();
10235 else image.addEventListener("load", recordInlineImage);
10236 }
10237 if (tagName === "audio" || tagName === "video") {
10238 var mediaAttributes = attributes;
10239 mediaAttributes.rr_mediaState = n2.paused ? "paused" : "played";
10240 mediaAttributes.rr_mediaCurrentTime = n2.currentTime;
10241 mediaAttributes.rr_mediaPlaybackRate = n2.playbackRate;
10242 mediaAttributes.rr_mediaMuted = n2.muted;
10243 mediaAttributes.rr_mediaLoop = n2.loop;
10244 mediaAttributes.rr_mediaVolume = n2.volume;
10245 }
10246 if (!newlyAddedElement) {
10247 if (n2.scrollLeft) {
10248 attributes.rr_scrollLeft = n2.scrollLeft;
10249 }
10250 if (n2.scrollTop) {
10251 attributes.rr_scrollTop = n2.scrollTop;
10252 }
10253 }
10254 if (needBlock) {
10255 var _n2_getBoundingClientRect = n2.getBoundingClientRect(), width = _n2_getBoundingClientRect.width, height = _n2_getBoundingClientRect.height;
10256 attributes = {
10257 class: attributes.class,
10258 rr_width: "" + width + "px",
10259 rr_height: "" + height + "px"
10260 };
10261 }
10262 if (tagName === "iframe" && !keepIframeSrcFn(attributes.src)) {
10263 if (!n2.contentDocument) {
10264 attributes.rr_src = attributes.src;
10265 }
10266 delete attributes.src;
10267 }
10268 var isCustomElement;
10269 try {
10270 if (customElements.get(tagName)) isCustomElement = true;
10271 } catch (e2) {}
10272 return {
10273 type: NodeType$3.Element,
10274 tagName: tagName,
10275 attributes: attributes,
10276 childNodes: [],
10277 isSVG: isSVGElement(n2) || void 0,
10278 needBlock: needBlock,
10279 rootId: rootId,
10280 isCustom: isCustomElement
10281 };
10282 }
10283 function lowerIfExists(maybeAttr) {
10284 if (maybeAttr === void 0 || maybeAttr === null) {
10285 return "";
10286 } else {
10287 return maybeAttr.toLowerCase();
10288 }
10289 }
10290 function slimDOMExcluded(sn, slimDOMOptions) {
10291 if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) {
10292 return true;
10293 } else if (sn.type === NodeType$3.Element) {
10294 if (slimDOMOptions.script && // script tag
10295 (sn.tagName === "script" || // (module)preload link
10296 sn.tagName === "link" && (sn.attributes.rel === "preload" && sn.attributes.as === "script" || sn.attributes.rel === "modulepreload") || // prefetch link
10297 sn.tagName === "link" && sn.attributes.rel === "prefetch" && typeof sn.attributes.href === "string" && extractFileExtension(sn.attributes.href) === "js")) {
10298 return true;
10299 } 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"))) {
10300 return true;
10301 } else if (sn.tagName === "meta") {
10302 if (slimDOMOptions.headMetaDescKeywords && lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {
10303 return true;
10304 } else if (slimDOMOptions.headMetaSocial && (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) || // og = opengraph (facebook)
10305 lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) || lowerIfExists(sn.attributes.name) === "pinterest")) {
10306 return true;
10307 } else if (slimDOMOptions.headMetaRobots && (lowerIfExists(sn.attributes.name) === "robots" || lowerIfExists(sn.attributes.name) === "googlebot" || lowerIfExists(sn.attributes.name) === "bingbot")) {
10308 return true;
10309 } else if (slimDOMOptions.headMetaHttpEquiv && sn.attributes["http-equiv"] !== void 0) {
10310 return true;
10311 } 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:/))) {
10312 return true;
10313 } 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")) {
10314 return true;
10315 }
10316 }
10317 }
10318 return false;
10319 }
10320 function serializeNodeWithId(n2, options) {
10321 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() {
10322 return false;
10323 } : _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;
10324 var needsMask = options.needsMask;
10325 var _options_preserveWhiteSpace = options.preserveWhiteSpace, preserveWhiteSpace = _options_preserveWhiteSpace === void 0 ? true : _options_preserveWhiteSpace;
10326 if (!needsMask) {
10327 var checkAncestors = needsMask === void 0;
10328 needsMask = needMaskingText(n2, maskTextClass, maskTextSelector, checkAncestors);
10329 }
10330 var _serializedNode = serializeNode(n2, {
10331 doc: doc,
10332 mirror: mirror2,
10333 blockClass: blockClass,
10334 blockSelector: blockSelector,
10335 needsMask: needsMask,
10336 inlineStylesheet: inlineStylesheet,
10337 maskInputOptions: maskInputOptions,
10338 maskTextFn: maskTextFn,
10339 maskInputFn: maskInputFn,
10340 dataURLOptions: dataURLOptions,
10341 inlineImages: inlineImages,
10342 recordCanvas: recordCanvas,
10343 keepIframeSrcFn: keepIframeSrcFn,
10344 newlyAddedElement: newlyAddedElement,
10345 cssCaptured: cssCaptured
10346 });
10347 if (!_serializedNode) {
10348 console.warn(n2, "not serialized");
10349 return null;
10350 }
10351 var id;
10352 if (mirror2.hasNode(n2)) {
10353 id = mirror2.getId(n2);
10354 } else if (slimDOMExcluded(_serializedNode, slimDOMOptions) || !preserveWhiteSpace && _serializedNode.type === NodeType$3.Text && !_serializedNode.textContent.replace(/^\s+|\s+$/gm, "").length) {
10355 id = IGNORED_NODE;
10356 } else {
10357 id = genId();
10358 }
10359 var serializedNode = Object.assign(_serializedNode, {
10360 id: id
10361 });
10362 mirror2.add(n2, serializedNode);
10363 if (id === IGNORED_NODE) {
10364 return null;
10365 }
10366 if (onSerialize) {
10367 onSerialize(n2);
10368 }
10369 var recordChild = !skipChild;
10370 if (serializedNode.type === NodeType$3.Element) {
10371 recordChild = recordChild && !serializedNode.needBlock;
10372 delete serializedNode.needBlock;
10373 var shadowRootEl = index$1.shadowRoot(n2);
10374 if (shadowRootEl && isNativeShadowDom(shadowRootEl)) serializedNode.isShadowHost = true;
10375 }
10376 if ((serializedNode.type === NodeType$3.Document || serializedNode.type === NodeType$3.Element) && recordChild) {
10377 if (slimDOMOptions.headWhitespace && serializedNode.type === NodeType$3.Element && serializedNode.tagName === "head") {
10378 preserveWhiteSpace = false;
10379 }
10380 var bypassOptions = {
10381 doc: doc,
10382 mirror: mirror2,
10383 blockClass: blockClass,
10384 blockSelector: blockSelector,
10385 needsMask: needsMask,
10386 maskTextClass: maskTextClass,
10387 maskTextSelector: maskTextSelector,
10388 skipChild: skipChild,
10389 inlineStylesheet: inlineStylesheet,
10390 maskInputOptions: maskInputOptions,
10391 maskTextFn: maskTextFn,
10392 maskInputFn: maskInputFn,
10393 slimDOMOptions: slimDOMOptions,
10394 dataURLOptions: dataURLOptions,
10395 inlineImages: inlineImages,
10396 recordCanvas: recordCanvas,
10397 preserveWhiteSpace: preserveWhiteSpace,
10398 onSerialize: onSerialize,
10399 onIframeLoad: onIframeLoad,
10400 iframeLoadTimeout: iframeLoadTimeout,
10401 onStylesheetLoad: onStylesheetLoad,
10402 stylesheetLoadTimeout: stylesheetLoadTimeout,
10403 keepIframeSrcFn: keepIframeSrcFn,
10404 cssCaptured: false
10405 };
10406 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "textarea" && serializedNode.attributes.value !== void 0) ;
10407 else {
10408 if (serializedNode.type === NodeType$3.Element && serializedNode.attributes._cssText !== void 0 && typeof serializedNode.attributes._cssText === "string") {
10409 bypassOptions.cssCaptured = true;
10410 }
10411 for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(n2))), _step; !(_step = _iterator()).done;){
10412 var childN = _step.value;
10413 var serializedChildNode = serializeNodeWithId(childN, bypassOptions);
10414 if (serializedChildNode) {
10415 serializedNode.childNodes.push(serializedChildNode);
10416 }
10417 }
10418 }
10419 var shadowRootEl1 = null;
10420 if (isElement(n2) && (shadowRootEl1 = index$1.shadowRoot(n2))) {
10421 for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(index$1.childNodes(shadowRootEl1))), _step1; !(_step1 = _iterator1()).done;){
10422 var childN1 = _step1.value;
10423 var serializedChildNode1 = serializeNodeWithId(childN1, bypassOptions);
10424 if (serializedChildNode1) {
10425 isNativeShadowDom(shadowRootEl1) && (serializedChildNode1.isShadow = true);
10426 serializedNode.childNodes.push(serializedChildNode1);
10427 }
10428 }
10429 }
10430 }
10431 var parent = index$1.parentNode(n2);
10432 if (parent && isShadowRoot(parent) && isNativeShadowDom(parent)) {
10433 serializedNode.isShadow = true;
10434 }
10435 if (serializedNode.type === NodeType$3.Element && serializedNode.tagName === "iframe") {
10436 onceIframeLoaded(n2, function() {
10437 var iframeDoc = n2.contentDocument;
10438 if (iframeDoc && onIframeLoad) {
10439 var serializedIframeNode = serializeNodeWithId(iframeDoc, {
10440 doc: iframeDoc,
10441 mirror: mirror2,
10442 blockClass: blockClass,
10443 blockSelector: blockSelector,
10444 needsMask: needsMask,
10445 maskTextClass: maskTextClass,
10446 maskTextSelector: maskTextSelector,
10447 skipChild: false,
10448 inlineStylesheet: inlineStylesheet,
10449 maskInputOptions: maskInputOptions,
10450 maskTextFn: maskTextFn,
10451 maskInputFn: maskInputFn,
10452 slimDOMOptions: slimDOMOptions,
10453 dataURLOptions: dataURLOptions,
10454 inlineImages: inlineImages,
10455 recordCanvas: recordCanvas,
10456 preserveWhiteSpace: preserveWhiteSpace,
10457 onSerialize: onSerialize,
10458 onIframeLoad: onIframeLoad,
10459 iframeLoadTimeout: iframeLoadTimeout,
10460 onStylesheetLoad: onStylesheetLoad,
10461 stylesheetLoadTimeout: stylesheetLoadTimeout,
10462 keepIframeSrcFn: keepIframeSrcFn
10463 });
10464 if (serializedIframeNode) {
10465 onIframeLoad(n2, serializedIframeNode);
10466 }
10467 }
10468 }, iframeLoadTimeout);
10469 }
10470 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")) {
10471 onceStylesheetLoaded(n2, function() {
10472 if (onStylesheetLoad) {
10473 var serializedLinkNode = serializeNodeWithId(n2, {
10474 doc: doc,
10475 mirror: mirror2,
10476 blockClass: blockClass,
10477 blockSelector: blockSelector,
10478 needsMask: needsMask,
10479 maskTextClass: maskTextClass,
10480 maskTextSelector: maskTextSelector,
10481 skipChild: false,
10482 inlineStylesheet: inlineStylesheet,
10483 maskInputOptions: maskInputOptions,
10484 maskTextFn: maskTextFn,
10485 maskInputFn: maskInputFn,
10486 slimDOMOptions: slimDOMOptions,
10487 dataURLOptions: dataURLOptions,
10488 inlineImages: inlineImages,
10489 recordCanvas: recordCanvas,
10490 preserveWhiteSpace: preserveWhiteSpace,
10491 onSerialize: onSerialize,
10492 onIframeLoad: onIframeLoad,
10493 iframeLoadTimeout: iframeLoadTimeout,
10494 onStylesheetLoad: onStylesheetLoad,
10495 stylesheetLoadTimeout: stylesheetLoadTimeout,
10496 keepIframeSrcFn: keepIframeSrcFn
10497 });
10498 if (serializedLinkNode) {
10499 onStylesheetLoad(n2, serializedLinkNode);
10500 }
10501 }
10502 }, stylesheetLoadTimeout);
10503 }
10504 return serializedNode;
10505 }
10506 function snapshot(n2, options) {
10507 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() {
10508 return false;
10509 } : _ref_keepIframeSrcFn;
10510 var maskInputOptions = maskAllInputs === true ? {
10511 color: true,
10512 date: true,
10513 "datetime-local": true,
10514 email: true,
10515 month: true,
10516 number: true,
10517 range: true,
10518 search: true,
10519 tel: true,
10520 text: true,
10521 time: true,
10522 url: true,
10523 week: true,
10524 textarea: true,
10525 select: true,
10526 password: true,
10527 hidden: true
10528 } : maskAllInputs === false ? {
10529 password: true
10530 } : maskAllInputs;
10531 var slimDOMOptions = slimDOM === true || slimDOM === "all" ? // if true: set of sensible options that should not throw away any information
10532 {
10533 script: true,
10534 comment: true,
10535 headFavicon: true,
10536 headWhitespace: true,
10537 headMetaDescKeywords: slimDOM === "all",
10538 // destructive
10539 headMetaSocial: true,
10540 headMetaRobots: true,
10541 headMetaHttpEquiv: true,
10542 headMetaAuthorship: true,
10543 headMetaVerification: true
10544 } : slimDOM === false ? {} : slimDOM;
10545 return serializeNodeWithId(n2, {
10546 doc: n2,
10547 mirror: mirror2,
10548 blockClass: blockClass,
10549 blockSelector: blockSelector,
10550 maskTextClass: maskTextClass,
10551 maskTextSelector: maskTextSelector,
10552 skipChild: false,
10553 inlineStylesheet: inlineStylesheet,
10554 maskInputOptions: maskInputOptions,
10555 maskTextFn: maskTextFn,
10556 maskInputFn: maskInputFn,
10557 slimDOMOptions: slimDOMOptions,
10558 dataURLOptions: dataURLOptions,
10559 inlineImages: inlineImages,
10560 recordCanvas: recordCanvas,
10561 preserveWhiteSpace: preserveWhiteSpace,
10562 onSerialize: onSerialize,
10563 onIframeLoad: onIframeLoad,
10564 iframeLoadTimeout: iframeLoadTimeout,
10565 onStylesheetLoad: onStylesheetLoad,
10566 stylesheetLoadTimeout: stylesheetLoadTimeout,
10567 keepIframeSrcFn: keepIframeSrcFn,
10568 newlyAddedElement: false
10569 });
10570 }
10571 function getDefaultExportFromCjs$1(x2) {
10572 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
10573 }
10574 function getAugmentedNamespace$1(n2) {
10575 if (n2.__esModule) return n2;
10576 var f2 = n2.default;
10577 if (typeof f2 == "function") {
10578 var a2 = function a22() {
10579 if (_instanceof(this, a22)) {
10580 return Reflect.construct(f2, arguments, this.constructor);
10581 }
10582 return f2.apply(this, arguments);
10583 };
10584 a2.prototype = f2.prototype;
10585 } else a2 = {};
10586 Object.defineProperty(a2, "__esModule", {
10587 value: true
10588 });
10589 Object.keys(n2).forEach(function(k) {
10590 var d = Object.getOwnPropertyDescriptor(n2, k);
10591 Object.defineProperty(a2, k, d.get ? d : {
10592 enumerable: true,
10593 get: function get() {
10594 return n2[k];
10595 }
10596 });
10597 });
10598 return a2;
10599 }
10600 var picocolors_browser$1 = {
10601 exports: {}
10602 };
10603 var x$1 = String;
10604 var create$1 = function create$1() {
10605 return {
10606 isColorSupported: false,
10607 reset: x$1,
10608 bold: x$1,
10609 dim: x$1,
10610 italic: x$1,
10611 underline: x$1,
10612 inverse: x$1,
10613 hidden: x$1,
10614 strikethrough: x$1,
10615 black: x$1,
10616 red: x$1,
10617 green: x$1,
10618 yellow: x$1,
10619 blue: x$1,
10620 magenta: x$1,
10621 cyan: x$1,
10622 white: x$1,
10623 gray: x$1,
10624 bgBlack: x$1,
10625 bgRed: x$1,
10626 bgGreen: x$1,
10627 bgYellow: x$1,
10628 bgBlue: x$1,
10629 bgMagenta: x$1,
10630 bgCyan: x$1,
10631 bgWhite: x$1
10632 };
10633 };
10634 picocolors_browser$1.exports = create$1();
10635 picocolors_browser$1.exports.createColors = create$1;
10636 var picocolors_browserExports$1 = picocolors_browser$1.exports;
10637 var __viteBrowserExternal$2 = {};
10638 var __viteBrowserExternal$1$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
10639 __proto__: null,
10640 default: __viteBrowserExternal$2
10641 }, Symbol.toStringTag, {
10642 value: "Module"
10643 }));
10644 var require$$2$1 = /* @__PURE__ */ getAugmentedNamespace$1(__viteBrowserExternal$1$1);
10645 var pico$1 = picocolors_browserExports$1;
10646 var terminalHighlight$1$1 = require$$2$1;
10647 var CssSyntaxError$3$1 = /*#__PURE__*/ function(Error1) {
10648 _inherits(CssSyntaxError, Error1);
10649 function CssSyntaxError(message, line, column, source, file, plugin22) {
10650 var _this;
10651 _this = Error1.call(this, message) || this;
10652 _this.name = "CssSyntaxError";
10653 _this.reason = message;
10654 if (file) {
10655 _this.file = file;
10656 }
10657 if (source) {
10658 _this.source = source;
10659 }
10660 if (plugin22) {
10661 _this.plugin = plugin22;
10662 }
10663 if (typeof line !== "undefined" && typeof column !== "undefined") {
10664 if (typeof line === "number") {
10665 _this.line = line;
10666 _this.column = column;
10667 } else {
10668 _this.line = line.line;
10669 _this.column = line.column;
10670 _this.endLine = column.line;
10671 _this.endColumn = column.column;
10672 }
10673 }
10674 _this.setMessage();
10675 if (Error.captureStackTrace) {
10676 Error.captureStackTrace(_this, CssSyntaxError);
10677 }
10678 return _this;
10679 }
10680 var _proto = CssSyntaxError.prototype;
10681 _proto.setMessage = function setMessage() {
10682 this.message = this.plugin ? this.plugin + ": " : "";
10683 this.message += this.file ? this.file : "<css input>";
10684 if (typeof this.line !== "undefined") {
10685 this.message += ":" + this.line + ":" + this.column;
10686 }
10687 this.message += ": " + this.reason;
10688 };
10689 _proto.showSourceCode = function showSourceCode(color) {
10690 var _this = this;
10691 if (!this.source) return "";
10692 var css = this.source;
10693 if (color == null) color = pico$1.isColorSupported;
10694 if (terminalHighlight$1$1) {
10695 if (color) css = terminalHighlight$1$1(css);
10696 }
10697 var lines = css.split(/\r?\n/);
10698 var start = Math.max(this.line - 3, 0);
10699 var end = Math.min(this.line + 2, lines.length);
10700 var maxWidth = String(end).length;
10701 var mark, aside;
10702 if (color) {
10703 var _pico$1_createColors = pico$1.createColors(true), bold = _pico$1_createColors.bold, gray = _pico$1_createColors.gray, red = _pico$1_createColors.red;
10704 mark = function(text) {
10705 return bold(red(text));
10706 };
10707 aside = function(text) {
10708 return gray(text);
10709 };
10710 } else {
10711 mark = aside = function(str) {
10712 return str;
10713 };
10714 }
10715 return lines.slice(start, end).map(function(line, index2) {
10716 var number = start + 1 + index2;
10717 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
10718 if (number === _this.line) {
10719 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
10720 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
10721 }
10722 return " " + aside(gutter) + line;
10723 }).join("\n");
10724 };
10725 _proto.toString = function toString() {
10726 var code = this.showSourceCode();
10727 if (code) {
10728 code = "\n\n" + code + "\n";
10729 }
10730 return this.name + ": " + this.message + code;
10731 };
10732 return CssSyntaxError;
10733 }(_wrap_native_super(Error));
10734 var cssSyntaxError$1 = CssSyntaxError$3$1;
10735 CssSyntaxError$3$1.default = CssSyntaxError$3$1;
10736 var symbols$1 = {};
10737 symbols$1.isClean = Symbol("isClean");
10738 symbols$1.my = Symbol("my");
10739 var DEFAULT_RAW$1 = {
10740 after: "\n",
10741 beforeClose: "\n",
10742 beforeComment: "\n",
10743 beforeDecl: "\n",
10744 beforeOpen: " ",
10745 beforeRule: "\n",
10746 colon: ": ",
10747 commentLeft: " ",
10748 commentRight: " ",
10749 emptyBody: "",
10750 indent: " ",
10751 semicolon: false
10752 };
10753 function capitalize$1(str) {
10754 return str[0].toUpperCase() + str.slice(1);
10755 }
10756 var Stringifier$2$1 = /*#__PURE__*/ function() {
10757 function Stringifier(builder) {
10758 this.builder = builder;
10759 }
10760 var _proto = Stringifier.prototype;
10761 _proto.atrule = function atrule(node2, semicolon) {
10762 var name = "@" + node2.name;
10763 var params = node2.params ? this.rawValue(node2, "params") : "";
10764 if (typeof node2.raws.afterName !== "undefined") {
10765 name += node2.raws.afterName;
10766 } else if (params) {
10767 name += " ";
10768 }
10769 if (node2.nodes) {
10770 this.block(node2, name + params);
10771 } else {
10772 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
10773 this.builder(name + params + end, node2);
10774 }
10775 };
10776 _proto.beforeAfter = function beforeAfter(node2, detect) {
10777 var value;
10778 if (node2.type === "decl") {
10779 value = this.raw(node2, null, "beforeDecl");
10780 } else if (node2.type === "comment") {
10781 value = this.raw(node2, null, "beforeComment");
10782 } else if (detect === "before") {
10783 value = this.raw(node2, null, "beforeRule");
10784 } else {
10785 value = this.raw(node2, null, "beforeClose");
10786 }
10787 var buf = node2.parent;
10788 var depth = 0;
10789 while(buf && buf.type !== "root"){
10790 depth += 1;
10791 buf = buf.parent;
10792 }
10793 if (value.includes("\n")) {
10794 var indent = this.raw(node2, null, "indent");
10795 if (indent.length) {
10796 for(var step = 0; step < depth; step++)value += indent;
10797 }
10798 }
10799 return value;
10800 };
10801 _proto.block = function block(node2, start) {
10802 var between = this.raw(node2, "between", "beforeOpen");
10803 this.builder(start + between + "{", node2, "start");
10804 var after;
10805 if (node2.nodes && node2.nodes.length) {
10806 this.body(node2);
10807 after = this.raw(node2, "after");
10808 } else {
10809 after = this.raw(node2, "after", "emptyBody");
10810 }
10811 if (after) this.builder(after);
10812 this.builder("}", node2, "end");
10813 };
10814 _proto.body = function body(node2) {
10815 var last = node2.nodes.length - 1;
10816 while(last > 0){
10817 if (node2.nodes[last].type !== "comment") break;
10818 last -= 1;
10819 }
10820 var semicolon = this.raw(node2, "semicolon");
10821 for(var i2 = 0; i2 < node2.nodes.length; i2++){
10822 var child = node2.nodes[i2];
10823 var before = this.raw(child, "before");
10824 if (before) this.builder(before);
10825 this.stringify(child, last !== i2 || semicolon);
10826 }
10827 };
10828 _proto.comment = function comment(node2) {
10829 var left = this.raw(node2, "left", "commentLeft");
10830 var right = this.raw(node2, "right", "commentRight");
10831 this.builder("/*" + left + node2.text + right + "*/", node2);
10832 };
10833 _proto.decl = function decl(node2, semicolon) {
10834 var between = this.raw(node2, "between", "colon");
10835 var string = node2.prop + between + this.rawValue(node2, "value");
10836 if (node2.important) {
10837 string += node2.raws.important || " !important";
10838 }
10839 if (semicolon) string += ";";
10840 this.builder(string, node2);
10841 };
10842 _proto.document = function document1(node2) {
10843 this.body(node2);
10844 };
10845 _proto.raw = function raw(node2, own, detect) {
10846 var value;
10847 if (!detect) detect = own;
10848 if (own) {
10849 value = node2.raws[own];
10850 if (typeof value !== "undefined") return value;
10851 }
10852 var parent = node2.parent;
10853 if (detect === "before") {
10854 if (!parent || parent.type === "root" && parent.first === node2) {
10855 return "";
10856 }
10857 if (parent && parent.type === "document") {
10858 return "";
10859 }
10860 }
10861 if (!parent) return DEFAULT_RAW$1[detect];
10862 var root2 = node2.root();
10863 if (!root2.rawCache) root2.rawCache = {};
10864 if (typeof root2.rawCache[detect] !== "undefined") {
10865 return root2.rawCache[detect];
10866 }
10867 if (detect === "before" || detect === "after") {
10868 return this.beforeAfter(node2, detect);
10869 } else {
10870 var method = "raw" + capitalize$1(detect);
10871 if (this[method]) {
10872 value = this[method](root2, node2);
10873 } else {
10874 root2.walk(function(i2) {
10875 value = i2.raws[own];
10876 if (typeof value !== "undefined") return false;
10877 });
10878 }
10879 }
10880 if (typeof value === "undefined") value = DEFAULT_RAW$1[detect];
10881 root2.rawCache[detect] = value;
10882 return value;
10883 };
10884 _proto.rawBeforeClose = function rawBeforeClose(root2) {
10885 var value;
10886 root2.walk(function(i2) {
10887 if (i2.nodes && i2.nodes.length > 0) {
10888 if (typeof i2.raws.after !== "undefined") {
10889 value = i2.raws.after;
10890 if (value.includes("\n")) {
10891 value = value.replace(/[^\n]+$/, "");
10892 }
10893 return false;
10894 }
10895 }
10896 });
10897 if (value) value = value.replace(/\S/g, "");
10898 return value;
10899 };
10900 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
10901 var value;
10902 root2.walkComments(function(i2) {
10903 if (typeof i2.raws.before !== "undefined") {
10904 value = i2.raws.before;
10905 if (value.includes("\n")) {
10906 value = value.replace(/[^\n]+$/, "");
10907 }
10908 return false;
10909 }
10910 });
10911 if (typeof value === "undefined") {
10912 value = this.raw(node2, null, "beforeDecl");
10913 } else if (value) {
10914 value = value.replace(/\S/g, "");
10915 }
10916 return value;
10917 };
10918 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
10919 var value;
10920 root2.walkDecls(function(i2) {
10921 if (typeof i2.raws.before !== "undefined") {
10922 value = i2.raws.before;
10923 if (value.includes("\n")) {
10924 value = value.replace(/[^\n]+$/, "");
10925 }
10926 return false;
10927 }
10928 });
10929 if (typeof value === "undefined") {
10930 value = this.raw(node2, null, "beforeRule");
10931 } else if (value) {
10932 value = value.replace(/\S/g, "");
10933 }
10934 return value;
10935 };
10936 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
10937 var value;
10938 root2.walk(function(i2) {
10939 if (i2.type !== "decl") {
10940 value = i2.raws.between;
10941 if (typeof value !== "undefined") return false;
10942 }
10943 });
10944 return value;
10945 };
10946 _proto.rawBeforeRule = function rawBeforeRule(root2) {
10947 var value;
10948 root2.walk(function(i2) {
10949 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
10950 if (typeof i2.raws.before !== "undefined") {
10951 value = i2.raws.before;
10952 if (value.includes("\n")) {
10953 value = value.replace(/[^\n]+$/, "");
10954 }
10955 return false;
10956 }
10957 }
10958 });
10959 if (value) value = value.replace(/\S/g, "");
10960 return value;
10961 };
10962 _proto.rawColon = function rawColon(root2) {
10963 var value;
10964 root2.walkDecls(function(i2) {
10965 if (typeof i2.raws.between !== "undefined") {
10966 value = i2.raws.between.replace(/[^\s:]/g, "");
10967 return false;
10968 }
10969 });
10970 return value;
10971 };
10972 _proto.rawEmptyBody = function rawEmptyBody(root2) {
10973 var value;
10974 root2.walk(function(i2) {
10975 if (i2.nodes && i2.nodes.length === 0) {
10976 value = i2.raws.after;
10977 if (typeof value !== "undefined") return false;
10978 }
10979 });
10980 return value;
10981 };
10982 _proto.rawIndent = function rawIndent(root2) {
10983 if (root2.raws.indent) return root2.raws.indent;
10984 var value;
10985 root2.walk(function(i2) {
10986 var p = i2.parent;
10987 if (p && p !== root2 && p.parent && p.parent === root2) {
10988 if (typeof i2.raws.before !== "undefined") {
10989 var parts = i2.raws.before.split("\n");
10990 value = parts[parts.length - 1];
10991 value = value.replace(/\S/g, "");
10992 return false;
10993 }
10994 }
10995 });
10996 return value;
10997 };
10998 _proto.rawSemicolon = function rawSemicolon(root2) {
10999 var value;
11000 root2.walk(function(i2) {
11001 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
11002 value = i2.raws.semicolon;
11003 if (typeof value !== "undefined") return false;
11004 }
11005 });
11006 return value;
11007 };
11008 _proto.rawValue = function rawValue(node2, prop) {
11009 var value = node2[prop];
11010 var raw = node2.raws[prop];
11011 if (raw && raw.value === value) {
11012 return raw.raw;
11013 }
11014 return value;
11015 };
11016 _proto.root = function root(node2) {
11017 this.body(node2);
11018 if (node2.raws.after) this.builder(node2.raws.after);
11019 };
11020 _proto.rule = function rule(node2) {
11021 this.block(node2, this.rawValue(node2, "selector"));
11022 if (node2.raws.ownSemicolon) {
11023 this.builder(node2.raws.ownSemicolon, node2, "end");
11024 }
11025 };
11026 _proto.stringify = function stringify(node2, semicolon) {
11027 if (!this[node2.type]) {
11028 throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
11029 }
11030 this[node2.type](node2, semicolon);
11031 };
11032 return Stringifier;
11033 }();
11034 var stringifier$1 = Stringifier$2$1;
11035 Stringifier$2$1.default = Stringifier$2$1;
11036 var Stringifier$1$1 = stringifier$1;
11037 function stringify$4$1(node2, builder) {
11038 var str = new Stringifier$1$1(builder);
11039 str.stringify(node2);
11040 }
11041 var stringify_1$1 = stringify$4$1;
11042 stringify$4$1.default = stringify$4$1;
11043 var isClean$2$1 = symbols$1.isClean, my$2$1 = symbols$1.my;
11044 var CssSyntaxError$2$1 = cssSyntaxError$1;
11045 var Stringifier2$1 = stringifier$1;
11046 var stringify$3$1 = stringify_1$1;
11047 function cloneNode$1(obj, parent) {
11048 var cloned = new obj.constructor();
11049 for(var i2 in obj){
11050 if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
11051 continue;
11052 }
11053 if (i2 === "proxyCache") continue;
11054 var value = obj[i2];
11055 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
11056 if (i2 === "parent" && type === "object") {
11057 if (parent) cloned[i2] = parent;
11058 } else if (i2 === "source") {
11059 cloned[i2] = value;
11060 } else if (Array.isArray(value)) {
11061 cloned[i2] = value.map(function(j) {
11062 return cloneNode$1(j, cloned);
11063 });
11064 } else {
11065 if (type === "object" && value !== null) value = cloneNode$1(value);
11066 cloned[i2] = value;
11067 }
11068 }
11069 return cloned;
11070 }
11071 var Node$4$1 = /*#__PURE__*/ function() {
11072 function Node2(defaults) {
11073 if (defaults === void 0) defaults = {};
11074 this.raws = {};
11075 this[isClean$2$1] = false;
11076 this[my$2$1] = true;
11077 for(var name in defaults){
11078 if (name === "nodes") {
11079 this.nodes = [];
11080 for(var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;){
11081 var node2 = _step.value;
11082 if (typeof node2.clone === "function") {
11083 this.append(node2.clone());
11084 } else {
11085 this.append(node2);
11086 }
11087 }
11088 } else {
11089 this[name] = defaults[name];
11090 }
11091 }
11092 }
11093 var _proto = Node2.prototype;
11094 _proto.addToError = function addToError(error) {
11095 error.postcssNode = this;
11096 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
11097 var s2 = this.source;
11098 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
11099 }
11100 return error;
11101 };
11102 _proto.after = function after(add) {
11103 this.parent.insertAfter(this, add);
11104 return this;
11105 };
11106 _proto.assign = function assign(overrides) {
11107 if (overrides === void 0) overrides = {};
11108 for(var name in overrides){
11109 this[name] = overrides[name];
11110 }
11111 return this;
11112 };
11113 _proto.before = function before(add) {
11114 this.parent.insertBefore(this, add);
11115 return this;
11116 };
11117 _proto.cleanRaws = function cleanRaws(keepBetween) {
11118 delete this.raws.before;
11119 delete this.raws.after;
11120 if (!keepBetween) delete this.raws.between;
11121 };
11122 _proto.clone = function clone(overrides) {
11123 if (overrides === void 0) overrides = {};
11124 var cloned = cloneNode$1(this);
11125 for(var name in overrides){
11126 cloned[name] = overrides[name];
11127 }
11128 return cloned;
11129 };
11130 _proto.cloneAfter = function cloneAfter(overrides) {
11131 if (overrides === void 0) overrides = {};
11132 var cloned = this.clone(overrides);
11133 this.parent.insertAfter(this, cloned);
11134 return cloned;
11135 };
11136 _proto.cloneBefore = function cloneBefore(overrides) {
11137 if (overrides === void 0) overrides = {};
11138 var cloned = this.clone(overrides);
11139 this.parent.insertBefore(this, cloned);
11140 return cloned;
11141 };
11142 _proto.error = function error(message, opts) {
11143 if (opts === void 0) opts = {};
11144 if (this.source) {
11145 var _this_rangeBy = this.rangeBy(opts), end = _this_rangeBy.end, start = _this_rangeBy.start;
11146 return this.source.input.error(message, {
11147 column: start.column,
11148 line: start.line
11149 }, {
11150 column: end.column,
11151 line: end.line
11152 }, opts);
11153 }
11154 return new CssSyntaxError$2$1(message);
11155 };
11156 _proto.getProxyProcessor = function getProxyProcessor() {
11157 return {
11158 get: function get(node2, prop) {
11159 if (prop === "proxyOf") {
11160 return node2;
11161 } else if (prop === "root") {
11162 return function() {
11163 return node2.root().toProxy();
11164 };
11165 } else {
11166 return node2[prop];
11167 }
11168 },
11169 set: function set(node2, prop, value) {
11170 if (node2[prop] === value) return true;
11171 node2[prop] = value;
11172 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */ prop === "text") {
11173 node2.markDirty();
11174 }
11175 return true;
11176 }
11177 };
11178 };
11179 _proto.markDirty = function markDirty() {
11180 if (this[isClean$2$1]) {
11181 this[isClean$2$1] = false;
11182 var next = this;
11183 while(next = next.parent){
11184 next[isClean$2$1] = false;
11185 }
11186 }
11187 };
11188 _proto.next = function next() {
11189 if (!this.parent) return void 0;
11190 var index2 = this.parent.index(this);
11191 return this.parent.nodes[index2 + 1];
11192 };
11193 _proto.positionBy = function positionBy(opts, stringRepresentation) {
11194 var pos = this.source.start;
11195 if (opts.index) {
11196 pos = this.positionInside(opts.index, stringRepresentation);
11197 } else if (opts.word) {
11198 stringRepresentation = this.toString();
11199 var index2 = stringRepresentation.indexOf(opts.word);
11200 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
11201 }
11202 return pos;
11203 };
11204 _proto.positionInside = function positionInside(index2, stringRepresentation) {
11205 var string = stringRepresentation || this.toString();
11206 var column = this.source.start.column;
11207 var line = this.source.start.line;
11208 for(var i2 = 0; i2 < index2; i2++){
11209 if (string[i2] === "\n") {
11210 column = 1;
11211 line += 1;
11212 } else {
11213 column += 1;
11214 }
11215 }
11216 return {
11217 column: column,
11218 line: line
11219 };
11220 };
11221 _proto.prev = function prev() {
11222 if (!this.parent) return void 0;
11223 var index2 = this.parent.index(this);
11224 return this.parent.nodes[index2 - 1];
11225 };
11226 _proto.rangeBy = function rangeBy(opts) {
11227 var start = {
11228 column: this.source.start.column,
11229 line: this.source.start.line
11230 };
11231 var end = this.source.end ? {
11232 column: this.source.end.column + 1,
11233 line: this.source.end.line
11234 } : {
11235 column: start.column + 1,
11236 line: start.line
11237 };
11238 if (opts.word) {
11239 var stringRepresentation = this.toString();
11240 var index2 = stringRepresentation.indexOf(opts.word);
11241 if (index2 !== -1) {
11242 start = this.positionInside(index2, stringRepresentation);
11243 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
11244 }
11245 } else {
11246 if (opts.start) {
11247 start = {
11248 column: opts.start.column,
11249 line: opts.start.line
11250 };
11251 } else if (opts.index) {
11252 start = this.positionInside(opts.index);
11253 }
11254 if (opts.end) {
11255 end = {
11256 column: opts.end.column,
11257 line: opts.end.line
11258 };
11259 } else if (typeof opts.endIndex === "number") {
11260 end = this.positionInside(opts.endIndex);
11261 } else if (opts.index) {
11262 end = this.positionInside(opts.index + 1);
11263 }
11264 }
11265 if (end.line < start.line || end.line === start.line && end.column <= start.column) {
11266 end = {
11267 column: start.column + 1,
11268 line: start.line
11269 };
11270 }
11271 return {
11272 end: end,
11273 start: start
11274 };
11275 };
11276 _proto.raw = function raw(prop, defaultType) {
11277 var str = new Stringifier2$1();
11278 return str.raw(this, prop, defaultType);
11279 };
11280 _proto.remove = function remove() {
11281 if (this.parent) {
11282 this.parent.removeChild(this);
11283 }
11284 this.parent = void 0;
11285 return this;
11286 };
11287 _proto.replaceWith = function replaceWith() {
11288 for(var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++){
11289 nodes[_key] = arguments[_key];
11290 }
11291 if (this.parent) {
11292 var bookmark = this;
11293 var foundSelf = false;
11294 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
11295 var node2 = _step.value;
11296 if (node2 === this) {
11297 foundSelf = true;
11298 } else if (foundSelf) {
11299 this.parent.insertAfter(bookmark, node2);
11300 bookmark = node2;
11301 } else {
11302 this.parent.insertBefore(bookmark, node2);
11303 }
11304 }
11305 if (!foundSelf) {
11306 this.remove();
11307 }
11308 }
11309 return this;
11310 };
11311 _proto.root = function root() {
11312 var result2 = this;
11313 while(result2.parent && result2.parent.type !== "document"){
11314 result2 = result2.parent;
11315 }
11316 return result2;
11317 };
11318 _proto.toJSON = function toJSON(_, inputs) {
11319 var fixed = {};
11320 var emitInputs = inputs == null;
11321 inputs = inputs || /* @__PURE__ */ new Map();
11322 var inputsNextIndex = 0;
11323 for(var name in this){
11324 if (!Object.prototype.hasOwnProperty.call(this, name)) {
11325 continue;
11326 }
11327 if (name === "parent" || name === "proxyCache") continue;
11328 var value = this[name];
11329 if (Array.isArray(value)) {
11330 fixed[name] = value.map(function(i2) {
11331 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) {
11332 return i2.toJSON(null, inputs);
11333 } else {
11334 return i2;
11335 }
11336 });
11337 } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) {
11338 fixed[name] = value.toJSON(null, inputs);
11339 } else if (name === "source") {
11340 var inputId = inputs.get(value.input);
11341 if (inputId == null) {
11342 inputId = inputsNextIndex;
11343 inputs.set(value.input, inputsNextIndex);
11344 inputsNextIndex++;
11345 }
11346 fixed[name] = {
11347 end: value.end,
11348 inputId: inputId,
11349 start: value.start
11350 };
11351 } else {
11352 fixed[name] = value;
11353 }
11354 }
11355 if (emitInputs) {
11356 fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
11357 return input2.toJSON();
11358 });
11359 }
11360 return fixed;
11361 };
11362 _proto.toProxy = function toProxy() {
11363 if (!this.proxyCache) {
11364 this.proxyCache = new Proxy(this, this.getProxyProcessor());
11365 }
11366 return this.proxyCache;
11367 };
11368 _proto.toString = function toString(stringifier2) {
11369 if (stringifier2 === void 0) stringifier2 = stringify$3$1;
11370 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
11371 var result2 = "";
11372 stringifier2(this, function(i2) {
11373 result2 += i2;
11374 });
11375 return result2;
11376 };
11377 _proto.warn = function warn(result2, text, opts) {
11378 var data = {
11379 node: this
11380 };
11381 for(var i2 in opts)data[i2] = opts[i2];
11382 return result2.warn(text, data);
11383 };
11384 _create_class(Node2, [
11385 {
11386 key: "proxyOf",
11387 get: function get() {
11388 return this;
11389 }
11390 }
11391 ]);
11392 return Node2;
11393 }();
11394 var node$1 = Node$4$1;
11395 Node$4$1.default = Node$4$1;
11396 var Node$3$1 = node$1;
11397 var Declaration$4$1 = /*#__PURE__*/ function(Node$3$1) {
11398 _inherits(Declaration, Node$3$1);
11399 function Declaration(defaults) {
11400 var _this;
11401 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
11402 defaults = _extends({}, defaults, {
11403 value: String(defaults.value)
11404 });
11405 }
11406 _this = Node$3$1.call(this, defaults) || this;
11407 _this.type = "decl";
11408 return _this;
11409 }
11410 _create_class(Declaration, [
11411 {
11412 key: "variable",
11413 get: function get() {
11414 return this.prop.startsWith("--") || this.prop[0] === "$";
11415 }
11416 }
11417 ]);
11418 return Declaration;
11419 }(Node$3$1);
11420 var declaration$1 = Declaration$4$1;
11421 Declaration$4$1.default = Declaration$4$1;
11422 var urlAlphabet$1 = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
11423 var nanoid$1$1 = function(size) {
11424 if (size === void 0) size = 21;
11425 var id = "";
11426 var i2 = size;
11427 while(i2--){
11428 id += urlAlphabet$1[Math.random() * 64 | 0];
11429 }
11430 return id;
11431 };
11432 var nonSecure$1 = {
11433 nanoid: nanoid$1$1};
11434 var SourceMapConsumer$2$1 = require$$2$1.SourceMapConsumer, SourceMapGenerator$2$1 = require$$2$1.SourceMapGenerator;
11435 var existsSync$1 = require$$2$1.existsSync, readFileSync$1 = require$$2$1.readFileSync;
11436 var dirname$1$1 = require$$2$1.dirname, join$1 = require$$2$1.join;
11437 function fromBase64$1(str) {
11438 if (Buffer) {
11439 return Buffer.from(str, "base64").toString();
11440 } else {
11441 return window.atob(str);
11442 }
11443 }
11444 var PreviousMap$2$1 = /*#__PURE__*/ function() {
11445 function PreviousMap(css, opts) {
11446 if (opts.map === false) return;
11447 this.loadAnnotation(css);
11448 this.inline = this.startWith(this.annotation, "data:");
11449 var prev = opts.map ? opts.map.prev : void 0;
11450 var text = this.loadMap(opts.from, prev);
11451 if (!this.mapFile && opts.from) {
11452 this.mapFile = opts.from;
11453 }
11454 if (this.mapFile) this.root = dirname$1$1(this.mapFile);
11455 if (text) this.text = text;
11456 }
11457 var _proto = PreviousMap.prototype;
11458 _proto.consumer = function consumer() {
11459 if (!this.consumerCache) {
11460 this.consumerCache = new SourceMapConsumer$2$1(this.text);
11461 }
11462 return this.consumerCache;
11463 };
11464 _proto.decodeInline = function decodeInline(text) {
11465 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
11466 var baseUri = /^data:application\/json;base64,/;
11467 var charsetUri = /^data:application\/json;charset=utf-?8,/;
11468 var uri = /^data:application\/json,/;
11469 if (charsetUri.test(text) || uri.test(text)) {
11470 return decodeURIComponent(text.substr(RegExp.lastMatch.length));
11471 }
11472 if (baseCharsetUri.test(text) || baseUri.test(text)) {
11473 return fromBase64$1(text.substr(RegExp.lastMatch.length));
11474 }
11475 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
11476 throw new Error("Unsupported source map encoding " + encoding);
11477 };
11478 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
11479 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
11480 };
11481 _proto.isMap = function isMap(map) {
11482 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
11483 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
11484 };
11485 _proto.loadAnnotation = function loadAnnotation(css) {
11486 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
11487 if (!comments) return;
11488 var start = css.lastIndexOf(comments.pop());
11489 var end = css.indexOf("*/", start);
11490 if (start > -1 && end > -1) {
11491 this.annotation = this.getAnnotationURL(css.substring(start, end));
11492 }
11493 };
11494 _proto.loadFile = function loadFile(path) {
11495 this.root = dirname$1$1(path);
11496 if (existsSync$1(path)) {
11497 this.mapFile = path;
11498 return readFileSync$1(path, "utf-8").toString().trim();
11499 }
11500 };
11501 _proto.loadMap = function loadMap(file, prev) {
11502 if (prev === false) return false;
11503 if (prev) {
11504 if (typeof prev === "string") {
11505 return prev;
11506 } else if (typeof prev === "function") {
11507 var prevPath = prev(file);
11508 if (prevPath) {
11509 var map = this.loadFile(prevPath);
11510 if (!map) {
11511 throw new Error("Unable to load previous source map: " + prevPath.toString());
11512 }
11513 return map;
11514 }
11515 } else if (_instanceof(prev, SourceMapConsumer$2$1)) {
11516 return SourceMapGenerator$2$1.fromSourceMap(prev).toString();
11517 } else if (_instanceof(prev, SourceMapGenerator$2$1)) {
11518 return prev.toString();
11519 } else if (this.isMap(prev)) {
11520 return JSON.stringify(prev);
11521 } else {
11522 throw new Error("Unsupported previous source map format: " + prev.toString());
11523 }
11524 } else if (this.inline) {
11525 return this.decodeInline(this.annotation);
11526 } else if (this.annotation) {
11527 var map1 = this.annotation;
11528 if (file) map1 = join$1(dirname$1$1(file), map1);
11529 return this.loadFile(map1);
11530 }
11531 };
11532 _proto.startWith = function startWith(string, start) {
11533 if (!string) return false;
11534 return string.substr(0, start.length) === start;
11535 };
11536 _proto.withContent = function withContent() {
11537 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
11538 };
11539 return PreviousMap;
11540 }();
11541 var previousMap$1 = PreviousMap$2$1;
11542 PreviousMap$2$1.default = PreviousMap$2$1;
11543 var SourceMapConsumer$1$1 = require$$2$1.SourceMapConsumer, SourceMapGenerator$1$1 = require$$2$1.SourceMapGenerator;
11544 var fileURLToPath$1 = require$$2$1.fileURLToPath, pathToFileURL$1$1 = require$$2$1.pathToFileURL;
11545 var isAbsolute$1 = require$$2$1.isAbsolute, resolve$1$1 = require$$2$1.resolve;
11546 var nanoid$2 = nonSecure$1.nanoid;
11547 var terminalHighlight$2 = require$$2$1;
11548 var CssSyntaxError$1$1 = cssSyntaxError$1;
11549 var PreviousMap$1$1 = previousMap$1;
11550 var fromOffsetCache$1 = Symbol("fromOffsetCache");
11551 var sourceMapAvailable$1$1 = Boolean(SourceMapConsumer$1$1 && SourceMapGenerator$1$1);
11552 var pathAvailable$1$1 = Boolean(resolve$1$1 && isAbsolute$1);
11553 var Input$4$1 = /*#__PURE__*/ function() {
11554 function Input(css, opts) {
11555 if (opts === void 0) opts = {};
11556 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) {
11557 throw new Error("PostCSS received " + css + " instead of CSS string");
11558 }
11559 this.css = css.toString();
11560 if (this.css[0] === "\uFEFF" || this.css[0] === "￾") {
11561 this.hasBOM = true;
11562 this.css = this.css.slice(1);
11563 } else {
11564 this.hasBOM = false;
11565 }
11566 if (opts.from) {
11567 if (!pathAvailable$1$1 || /^\w+:\/\//.test(opts.from) || isAbsolute$1(opts.from)) {
11568 this.file = opts.from;
11569 } else {
11570 this.file = resolve$1$1(opts.from);
11571 }
11572 }
11573 if (pathAvailable$1$1 && sourceMapAvailable$1$1) {
11574 var map = new PreviousMap$1$1(this.css, opts);
11575 if (map.text) {
11576 this.map = map;
11577 var file = map.consumer().file;
11578 if (!this.file && file) this.file = this.mapResolve(file);
11579 }
11580 }
11581 if (!this.file) {
11582 this.id = "<input css " + nanoid$2(6) + ">";
11583 }
11584 if (this.map) this.map.file = this.from;
11585 }
11586 var _proto = Input.prototype;
11587 _proto.error = function error(message, line, column, opts) {
11588 if (opts === void 0) opts = {};
11589 var result2, endLine, endColumn;
11590 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
11591 var start = line;
11592 var end = column;
11593 if (typeof start.offset === "number") {
11594 var pos = this.fromOffset(start.offset);
11595 line = pos.line;
11596 column = pos.col;
11597 } else {
11598 line = start.line;
11599 column = start.column;
11600 }
11601 if (typeof end.offset === "number") {
11602 var pos1 = this.fromOffset(end.offset);
11603 endLine = pos1.line;
11604 endColumn = pos1.col;
11605 } else {
11606 endLine = end.line;
11607 endColumn = end.column;
11608 }
11609 } else if (!column) {
11610 var pos2 = this.fromOffset(line);
11611 line = pos2.line;
11612 column = pos2.col;
11613 }
11614 var origin = this.origin(line, column, endLine, endColumn);
11615 if (origin) {
11616 result2 = new CssSyntaxError$1$1(message, origin.endLine === void 0 ? origin.line : {
11617 column: origin.column,
11618 line: origin.line
11619 }, origin.endLine === void 0 ? origin.column : {
11620 column: origin.endColumn,
11621 line: origin.endLine
11622 }, origin.source, origin.file, opts.plugin);
11623 } else {
11624 result2 = new CssSyntaxError$1$1(message, endLine === void 0 ? line : {
11625 column: column,
11626 line: line
11627 }, endLine === void 0 ? column : {
11628 column: endColumn,
11629 line: endLine
11630 }, this.css, this.file, opts.plugin);
11631 }
11632 result2.input = {
11633 column: column,
11634 endColumn: endColumn,
11635 endLine: endLine,
11636 line: line,
11637 source: this.css
11638 };
11639 if (this.file) {
11640 if (pathToFileURL$1$1) {
11641 result2.input.url = pathToFileURL$1$1(this.file).toString();
11642 }
11643 result2.input.file = this.file;
11644 }
11645 return result2;
11646 };
11647 _proto.fromOffset = function fromOffset(offset) {
11648 var lastLine, lineToIndex;
11649 if (!this[fromOffsetCache$1]) {
11650 var lines = this.css.split("\n");
11651 lineToIndex = new Array(lines.length);
11652 var prevIndex = 0;
11653 for(var i2 = 0, l2 = lines.length; i2 < l2; i2++){
11654 lineToIndex[i2] = prevIndex;
11655 prevIndex += lines[i2].length + 1;
11656 }
11657 this[fromOffsetCache$1] = lineToIndex;
11658 } else {
11659 lineToIndex = this[fromOffsetCache$1];
11660 }
11661 lastLine = lineToIndex[lineToIndex.length - 1];
11662 var min = 0;
11663 if (offset >= lastLine) {
11664 min = lineToIndex.length - 1;
11665 } else {
11666 var max = lineToIndex.length - 2;
11667 var mid;
11668 while(min < max){
11669 mid = min + (max - min >> 1);
11670 if (offset < lineToIndex[mid]) {
11671 max = mid - 1;
11672 } else if (offset >= lineToIndex[mid + 1]) {
11673 min = mid + 1;
11674 } else {
11675 min = mid;
11676 break;
11677 }
11678 }
11679 }
11680 return {
11681 col: offset - lineToIndex[min] + 1,
11682 line: min + 1
11683 };
11684 };
11685 _proto.mapResolve = function mapResolve(file) {
11686 if (/^\w+:\/\//.test(file)) {
11687 return file;
11688 }
11689 return resolve$1$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
11690 };
11691 _proto.origin = function origin(line, column, endLine, endColumn) {
11692 if (!this.map) return false;
11693 var consumer = this.map.consumer();
11694 var from = consumer.originalPositionFor({
11695 column: column,
11696 line: line
11697 });
11698 if (!from.source) return false;
11699 var to;
11700 if (typeof endLine === "number") {
11701 to = consumer.originalPositionFor({
11702 column: endColumn,
11703 line: endLine
11704 });
11705 }
11706 var fromUrl;
11707 if (isAbsolute$1(from.source)) {
11708 fromUrl = pathToFileURL$1$1(from.source);
11709 } else {
11710 fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1$1(this.map.mapFile));
11711 }
11712 var result2 = {
11713 column: from.column,
11714 endColumn: to && to.column,
11715 endLine: to && to.line,
11716 line: from.line,
11717 url: fromUrl.toString()
11718 };
11719 if (fromUrl.protocol === "file:") {
11720 if (fileURLToPath$1) {
11721 result2.file = fileURLToPath$1(fromUrl);
11722 } else {
11723 throw new Error("file: protocol is not available in this PostCSS build");
11724 }
11725 }
11726 var source = consumer.sourceContentFor(from.source);
11727 if (source) result2.source = source;
11728 return result2;
11729 };
11730 _proto.toJSON = function toJSON() {
11731 var json = {};
11732 for(var _i = 0, _iter = [
11733 "hasBOM",
11734 "css",
11735 "file",
11736 "id"
11737 ]; _i < _iter.length; _i++){
11738 var name = _iter[_i];
11739 if (this[name] != null) {
11740 json[name] = this[name];
11741 }
11742 }
11743 if (this.map) {
11744 json.map = _extends({}, this.map);
11745 if (json.map.consumerCache) {
11746 json.map.consumerCache = void 0;
11747 }
11748 }
11749 return json;
11750 };
11751 _create_class(Input, [
11752 {
11753 key: "from",
11754 get: function get() {
11755 return this.file || this.id;
11756 }
11757 }
11758 ]);
11759 return Input;
11760 }();
11761 var input$1 = Input$4$1;
11762 Input$4$1.default = Input$4$1;
11763 if (terminalHighlight$2 && terminalHighlight$2.registerInput) {
11764 terminalHighlight$2.registerInput(Input$4$1);
11765 }
11766 var SourceMapConsumer$3 = require$$2$1.SourceMapConsumer, SourceMapGenerator$3 = require$$2$1.SourceMapGenerator;
11767 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;
11768 var pathToFileURL$2 = require$$2$1.pathToFileURL;
11769 var Input$3$1 = input$1;
11770 var sourceMapAvailable$2 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$3);
11771 var pathAvailable$2 = Boolean(dirname$2 && resolve$2 && relative$1 && sep$1);
11772 var MapGenerator$2$1 = /*#__PURE__*/ function() {
11773 function MapGenerator(stringify2, root2, opts, cssString) {
11774 this.stringify = stringify2;
11775 this.mapOpts = opts.map || {};
11776 this.root = root2;
11777 this.opts = opts;
11778 this.css = cssString;
11779 this.originalCSS = cssString;
11780 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
11781 this.memoizedFileURLs = /* @__PURE__ */ new Map();
11782 this.memoizedPaths = /* @__PURE__ */ new Map();
11783 this.memoizedURLs = /* @__PURE__ */ new Map();
11784 }
11785 var _proto = MapGenerator.prototype;
11786 _proto.addAnnotation = function addAnnotation() {
11787 var content;
11788 if (this.isInline()) {
11789 content = "data:application/json;base64," + this.toBase64(this.map.toString());
11790 } else if (typeof this.mapOpts.annotation === "string") {
11791 content = this.mapOpts.annotation;
11792 } else if (typeof this.mapOpts.annotation === "function") {
11793 content = this.mapOpts.annotation(this.opts.to, this.root);
11794 } else {
11795 content = this.outputFile() + ".map";
11796 }
11797 var eol = "\n";
11798 if (this.css.includes("\r\n")) eol = "\r\n";
11799 this.css += eol + "/*# sourceMappingURL=" + content + " */";
11800 };
11801 _proto.applyPrevMaps = function applyPrevMaps() {
11802 for(var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;){
11803 var prev = _step.value;
11804 var from = this.toUrl(this.path(prev.file));
11805 var root2 = prev.root || dirname$2(prev.file);
11806 var map = void 0;
11807 if (this.mapOpts.sourcesContent === false) {
11808 map = new SourceMapConsumer$3(prev.text);
11809 if (map.sourcesContent) {
11810 map.sourcesContent = null;
11811 }
11812 } else {
11813 map = prev.consumer();
11814 }
11815 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
11816 }
11817 };
11818 _proto.clearAnnotation = function clearAnnotation() {
11819 if (this.mapOpts.annotation === false) return;
11820 if (this.root) {
11821 var node2;
11822 for(var i2 = this.root.nodes.length - 1; i2 >= 0; i2--){
11823 node2 = this.root.nodes[i2];
11824 if (node2.type !== "comment") continue;
11825 if (node2.text.indexOf("# sourceMappingURL=") === 0) {
11826 this.root.removeChild(i2);
11827 }
11828 }
11829 } else if (this.css) {
11830 this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
11831 }
11832 };
11833 _proto.generate = function generate() {
11834 this.clearAnnotation();
11835 if (pathAvailable$2 && sourceMapAvailable$2 && this.isMap()) {
11836 return this.generateMap();
11837 } else {
11838 var result2 = "";
11839 this.stringify(this.root, function(i2) {
11840 result2 += i2;
11841 });
11842 return [
11843 result2
11844 ];
11845 }
11846 };
11847 _proto.generateMap = function generateMap() {
11848 if (this.root) {
11849 this.generateString();
11850 } else if (this.previous().length === 1) {
11851 var prev = this.previous()[0].consumer();
11852 prev.file = this.outputFile();
11853 this.map = SourceMapGenerator$3.fromSourceMap(prev, {
11854 ignoreInvalidMapping: true
11855 });
11856 } else {
11857 this.map = new SourceMapGenerator$3({
11858 file: this.outputFile(),
11859 ignoreInvalidMapping: true
11860 });
11861 this.map.addMapping({
11862 generated: {
11863 column: 0,
11864 line: 1
11865 },
11866 original: {
11867 column: 0,
11868 line: 1
11869 },
11870 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
11871 });
11872 }
11873 if (this.isSourcesContent()) this.setSourcesContent();
11874 if (this.root && this.previous().length > 0) this.applyPrevMaps();
11875 if (this.isAnnotation()) this.addAnnotation();
11876 if (this.isInline()) {
11877 return [
11878 this.css
11879 ];
11880 } else {
11881 return [
11882 this.css,
11883 this.map
11884 ];
11885 }
11886 };
11887 _proto.generateString = function generateString() {
11888 var _this = this;
11889 this.css = "";
11890 this.map = new SourceMapGenerator$3({
11891 file: this.outputFile(),
11892 ignoreInvalidMapping: true
11893 });
11894 var line = 1;
11895 var column = 1;
11896 var noSource = "<no source>";
11897 var mapping = {
11898 generated: {
11899 column: 0,
11900 line: 0
11901 },
11902 original: {
11903 column: 0,
11904 line: 0
11905 },
11906 source: ""
11907 };
11908 var lines, last;
11909 this.stringify(this.root, function(str, node2, type) {
11910 _this.css += str;
11911 if (node2 && type !== "end") {
11912 mapping.generated.line = line;
11913 mapping.generated.column = column - 1;
11914 if (node2.source && node2.source.start) {
11915 mapping.source = _this.sourcePath(node2);
11916 mapping.original.line = node2.source.start.line;
11917 mapping.original.column = node2.source.start.column - 1;
11918 _this.map.addMapping(mapping);
11919 } else {
11920 mapping.source = noSource;
11921 mapping.original.line = 1;
11922 mapping.original.column = 0;
11923 _this.map.addMapping(mapping);
11924 }
11925 }
11926 lines = str.match(/\n/g);
11927 if (lines) {
11928 line += lines.length;
11929 last = str.lastIndexOf("\n");
11930 column = str.length - last;
11931 } else {
11932 column += str.length;
11933 }
11934 if (node2 && type !== "start") {
11935 var p = node2.parent || {
11936 raws: {}
11937 };
11938 var childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
11939 if (!childless || node2 !== p.last || p.raws.semicolon) {
11940 if (node2.source && node2.source.end) {
11941 mapping.source = _this.sourcePath(node2);
11942 mapping.original.line = node2.source.end.line;
11943 mapping.original.column = node2.source.end.column - 1;
11944 mapping.generated.line = line;
11945 mapping.generated.column = column - 2;
11946 _this.map.addMapping(mapping);
11947 } else {
11948 mapping.source = noSource;
11949 mapping.original.line = 1;
11950 mapping.original.column = 0;
11951 mapping.generated.line = line;
11952 mapping.generated.column = column - 1;
11953 _this.map.addMapping(mapping);
11954 }
11955 }
11956 }
11957 });
11958 };
11959 _proto.isAnnotation = function isAnnotation() {
11960 if (this.isInline()) {
11961 return true;
11962 }
11963 if (typeof this.mapOpts.annotation !== "undefined") {
11964 return this.mapOpts.annotation;
11965 }
11966 if (this.previous().length) {
11967 return this.previous().some(function(i2) {
11968 return i2.annotation;
11969 });
11970 }
11971 return true;
11972 };
11973 _proto.isInline = function isInline() {
11974 if (typeof this.mapOpts.inline !== "undefined") {
11975 return this.mapOpts.inline;
11976 }
11977 var annotation = this.mapOpts.annotation;
11978 if (typeof annotation !== "undefined" && annotation !== true) {
11979 return false;
11980 }
11981 if (this.previous().length) {
11982 return this.previous().some(function(i2) {
11983 return i2.inline;
11984 });
11985 }
11986 return true;
11987 };
11988 _proto.isMap = function isMap() {
11989 if (typeof this.opts.map !== "undefined") {
11990 return !!this.opts.map;
11991 }
11992 return this.previous().length > 0;
11993 };
11994 _proto.isSourcesContent = function isSourcesContent() {
11995 if (typeof this.mapOpts.sourcesContent !== "undefined") {
11996 return this.mapOpts.sourcesContent;
11997 }
11998 if (this.previous().length) {
11999 return this.previous().some(function(i2) {
12000 return i2.withContent();
12001 });
12002 }
12003 return true;
12004 };
12005 _proto.outputFile = function outputFile() {
12006 if (this.opts.to) {
12007 return this.path(this.opts.to);
12008 } else if (this.opts.from) {
12009 return this.path(this.opts.from);
12010 } else {
12011 return "to.css";
12012 }
12013 };
12014 _proto.path = function path(file) {
12015 if (this.mapOpts.absolute) return file;
12016 if (file.charCodeAt(0) === 60) return file;
12017 if (/^\w+:\/\//.test(file)) return file;
12018 var cached = this.memoizedPaths.get(file);
12019 if (cached) return cached;
12020 var from = this.opts.to ? dirname$2(this.opts.to) : ".";
12021 if (typeof this.mapOpts.annotation === "string") {
12022 from = dirname$2(resolve$2(from, this.mapOpts.annotation));
12023 }
12024 var path = relative$1(from, file);
12025 this.memoizedPaths.set(file, path);
12026 return path;
12027 };
12028 _proto.previous = function previous() {
12029 var _this = this;
12030 if (!this.previousMaps) {
12031 this.previousMaps = [];
12032 if (this.root) {
12033 this.root.walk(function(node2) {
12034 if (node2.source && node2.source.input.map) {
12035 var map = node2.source.input.map;
12036 if (!_this.previousMaps.includes(map)) {
12037 _this.previousMaps.push(map);
12038 }
12039 }
12040 });
12041 } else {
12042 var input2 = new Input$3$1(this.originalCSS, this.opts);
12043 if (input2.map) this.previousMaps.push(input2.map);
12044 }
12045 }
12046 return this.previousMaps;
12047 };
12048 _proto.setSourcesContent = function setSourcesContent() {
12049 var _this = this;
12050 var already = {};
12051 if (this.root) {
12052 this.root.walk(function(node2) {
12053 if (node2.source) {
12054 var from = node2.source.input.from;
12055 if (from && !already[from]) {
12056 already[from] = true;
12057 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
12058 _this.map.setSourceContent(fromUrl, node2.source.input.css);
12059 }
12060 }
12061 });
12062 } else if (this.css) {
12063 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
12064 this.map.setSourceContent(from, this.css);
12065 }
12066 };
12067 _proto.sourcePath = function sourcePath(node2) {
12068 if (this.mapOpts.from) {
12069 return this.toUrl(this.mapOpts.from);
12070 } else if (this.usesFileUrls) {
12071 return this.toFileUrl(node2.source.input.from);
12072 } else {
12073 return this.toUrl(this.path(node2.source.input.from));
12074 }
12075 };
12076 _proto.toBase64 = function toBase64(str) {
12077 if (Buffer) {
12078 return Buffer.from(str).toString("base64");
12079 } else {
12080 return window.btoa(unescape(encodeURIComponent(str)));
12081 }
12082 };
12083 _proto.toFileUrl = function toFileUrl(path) {
12084 var cached = this.memoizedFileURLs.get(path);
12085 if (cached) return cached;
12086 if (pathToFileURL$2) {
12087 var fileURL = pathToFileURL$2(path).toString();
12088 this.memoizedFileURLs.set(path, fileURL);
12089 return fileURL;
12090 } else {
12091 throw new Error("`map.absolute` option is not available in this PostCSS build");
12092 }
12093 };
12094 _proto.toUrl = function toUrl(path) {
12095 var cached = this.memoizedURLs.get(path);
12096 if (cached) return cached;
12097 if (sep$1 === "\\") {
12098 path = path.replace(/\\/g, "/");
12099 }
12100 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
12101 this.memoizedURLs.set(path, url);
12102 return url;
12103 };
12104 return MapGenerator;
12105 }();
12106 var mapGenerator$1 = MapGenerator$2$1;
12107 var Node$2$1 = node$1;
12108 var Comment$4$1 = /*#__PURE__*/ function(Node$2$1) {
12109 _inherits(Comment, Node$2$1);
12110 function Comment(defaults) {
12111 var _this;
12112 _this = Node$2$1.call(this, defaults) || this;
12113 _this.type = "comment";
12114 return _this;
12115 }
12116 return Comment;
12117 }(Node$2$1);
12118 var comment$1 = Comment$4$1;
12119 Comment$4$1.default = Comment$4$1;
12120 var isClean$1$1 = symbols$1.isClean, my$1$1 = symbols$1.my;
12121 var Declaration$3$1 = declaration$1;
12122 var Comment$3$1 = comment$1;
12123 var Node$1$1 = node$1;
12124 var parse$4$1, Rule$4$1, AtRule$4$1, Root$6$1;
12125 function cleanSource$1(nodes) {
12126 return nodes.map(function(i2) {
12127 if (i2.nodes) i2.nodes = cleanSource$1(i2.nodes);
12128 delete i2.source;
12129 return i2;
12130 });
12131 }
12132 function markDirtyUp$1(node2) {
12133 node2[isClean$1$1] = false;
12134 if (node2.proxyOf.nodes) {
12135 for(var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;){
12136 var i2 = _step.value;
12137 markDirtyUp$1(i2);
12138 }
12139 }
12140 }
12141 var Container$7$1 = /*#__PURE__*/ function(Node$1$1) {
12142 _inherits(Container, Node$1$1);
12143 function Container() {
12144 return Node$1$1.apply(this, arguments) || this;
12145 }
12146 var _proto = Container.prototype;
12147 _proto.append = function append() {
12148 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
12149 children[_key] = arguments[_key];
12150 }
12151 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
12152 var child = _step.value;
12153 var nodes = this.normalize(child, this.last);
12154 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
12155 var node2 = _step1.value;
12156 this.proxyOf.nodes.push(node2);
12157 }
12158 }
12159 this.markDirty();
12160 return this;
12161 };
12162 _proto.cleanRaws = function cleanRaws(keepBetween) {
12163 Node$1$1.prototype.cleanRaws.call(this, keepBetween);
12164 if (this.nodes) {
12165 for(var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;){
12166 var node2 = _step.value;
12167 node2.cleanRaws(keepBetween);
12168 }
12169 }
12170 };
12171 _proto.each = function each(callback) {
12172 if (!this.proxyOf.nodes) return void 0;
12173 var iterator = this.getIterator();
12174 var index2, result2;
12175 while(this.indexes[iterator] < this.proxyOf.nodes.length){
12176 index2 = this.indexes[iterator];
12177 result2 = callback(this.proxyOf.nodes[index2], index2);
12178 if (result2 === false) break;
12179 this.indexes[iterator] += 1;
12180 }
12181 delete this.indexes[iterator];
12182 return result2;
12183 };
12184 _proto.every = function every(condition) {
12185 return this.nodes.every(condition);
12186 };
12187 _proto.getIterator = function getIterator() {
12188 if (!this.lastEach) this.lastEach = 0;
12189 if (!this.indexes) this.indexes = {};
12190 this.lastEach += 1;
12191 var iterator = this.lastEach;
12192 this.indexes[iterator] = 0;
12193 return iterator;
12194 };
12195 _proto.getProxyProcessor = function getProxyProcessor() {
12196 return {
12197 get: function get(node2, prop) {
12198 if (prop === "proxyOf") {
12199 return node2;
12200 } else if (!node2[prop]) {
12201 return node2[prop];
12202 } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
12203 return function() {
12204 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
12205 args[_key] = arguments[_key];
12206 }
12207 var _node2;
12208 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
12209 if (typeof i2 === "function") {
12210 return function(child, index2) {
12211 return i2(child.toProxy(), index2);
12212 };
12213 } else {
12214 return i2;
12215 }
12216 })));
12217 };
12218 } else if (prop === "every" || prop === "some") {
12219 return function(cb) {
12220 return node2[prop](function(child) {
12221 for(var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
12222 other[_key - 1] = arguments[_key];
12223 }
12224 return cb.apply(void 0, [].concat([
12225 child.toProxy()
12226 ], other));
12227 });
12228 };
12229 } else if (prop === "root") {
12230 return function() {
12231 return node2.root().toProxy();
12232 };
12233 } else if (prop === "nodes") {
12234 return node2.nodes.map(function(i2) {
12235 return i2.toProxy();
12236 });
12237 } else if (prop === "first" || prop === "last") {
12238 return node2[prop].toProxy();
12239 } else {
12240 return node2[prop];
12241 }
12242 },
12243 set: function set(node2, prop, value) {
12244 if (node2[prop] === value) return true;
12245 node2[prop] = value;
12246 if (prop === "name" || prop === "params" || prop === "selector") {
12247 node2.markDirty();
12248 }
12249 return true;
12250 }
12251 };
12252 };
12253 _proto.index = function index(child) {
12254 if (typeof child === "number") return child;
12255 if (child.proxyOf) child = child.proxyOf;
12256 return this.proxyOf.nodes.indexOf(child);
12257 };
12258 _proto.insertAfter = function insertAfter(exist, add) {
12259 var existIndex = this.index(exist);
12260 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
12261 existIndex = this.index(exist);
12262 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
12263 var node2 = _step.value;
12264 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
12265 }
12266 var index2;
12267 for(var id in this.indexes){
12268 index2 = this.indexes[id];
12269 if (existIndex < index2) {
12270 this.indexes[id] = index2 + nodes.length;
12271 }
12272 }
12273 this.markDirty();
12274 return this;
12275 };
12276 _proto.insertBefore = function insertBefore(exist, add) {
12277 var existIndex = this.index(exist);
12278 var type = existIndex === 0 ? "prepend" : false;
12279 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
12280 existIndex = this.index(exist);
12281 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
12282 var node2 = _step.value;
12283 this.proxyOf.nodes.splice(existIndex, 0, node2);
12284 }
12285 var index2;
12286 for(var id in this.indexes){
12287 index2 = this.indexes[id];
12288 if (existIndex <= index2) {
12289 this.indexes[id] = index2 + nodes.length;
12290 }
12291 }
12292 this.markDirty();
12293 return this;
12294 };
12295 _proto.normalize = function normalize(nodes, sample) {
12296 var _this = this;
12297 if (typeof nodes === "string") {
12298 nodes = cleanSource$1(parse$4$1(nodes).nodes);
12299 } else if (typeof nodes === "undefined") {
12300 nodes = [];
12301 } else if (Array.isArray(nodes)) {
12302 nodes = nodes.slice(0);
12303 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
12304 var i2 = _step.value;
12305 if (i2.parent) i2.parent.removeChild(i2, "ignore");
12306 }
12307 } else if (nodes.type === "root" && this.type !== "document") {
12308 nodes = nodes.nodes.slice(0);
12309 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
12310 var i21 = _step1.value;
12311 if (i21.parent) i21.parent.removeChild(i21, "ignore");
12312 }
12313 } else if (nodes.type) {
12314 nodes = [
12315 nodes
12316 ];
12317 } else if (nodes.prop) {
12318 if (typeof nodes.value === "undefined") {
12319 throw new Error("Value field is missed in node creation");
12320 } else if (typeof nodes.value !== "string") {
12321 nodes.value = String(nodes.value);
12322 }
12323 nodes = [
12324 new Declaration$3$1(nodes)
12325 ];
12326 } else if (nodes.selector) {
12327 nodes = [
12328 new Rule$4$1(nodes)
12329 ];
12330 } else if (nodes.name) {
12331 nodes = [
12332 new AtRule$4$1(nodes)
12333 ];
12334 } else if (nodes.text) {
12335 nodes = [
12336 new Comment$3$1(nodes)
12337 ];
12338 } else {
12339 throw new Error("Unknown node type in node creation");
12340 }
12341 var processed = nodes.map(function(i2) {
12342 if (!i2[my$1$1]) Container.rebuild(i2);
12343 i2 = i2.proxyOf;
12344 if (i2.parent) i2.parent.removeChild(i2);
12345 if (i2[isClean$1$1]) markDirtyUp$1(i2);
12346 if (typeof i2.raws.before === "undefined") {
12347 if (sample && typeof sample.raws.before !== "undefined") {
12348 i2.raws.before = sample.raws.before.replace(/\S/g, "");
12349 }
12350 }
12351 i2.parent = _this.proxyOf;
12352 return i2;
12353 });
12354 return processed;
12355 };
12356 _proto.prepend = function prepend() {
12357 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
12358 children[_key] = arguments[_key];
12359 }
12360 children = children.reverse();
12361 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
12362 var child = _step.value;
12363 var nodes = this.normalize(child, this.first, "prepend").reverse();
12364 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
12365 var node2 = _step1.value;
12366 this.proxyOf.nodes.unshift(node2);
12367 }
12368 for(var id in this.indexes){
12369 this.indexes[id] = this.indexes[id] + nodes.length;
12370 }
12371 }
12372 this.markDirty();
12373 return this;
12374 };
12375 _proto.push = function push(child) {
12376 child.parent = this;
12377 this.proxyOf.nodes.push(child);
12378 return this;
12379 };
12380 _proto.removeAll = function removeAll() {
12381 for(var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;){
12382 var node2 = _step.value;
12383 node2.parent = void 0;
12384 }
12385 this.proxyOf.nodes = [];
12386 this.markDirty();
12387 return this;
12388 };
12389 _proto.removeChild = function removeChild(child) {
12390 child = this.index(child);
12391 this.proxyOf.nodes[child].parent = void 0;
12392 this.proxyOf.nodes.splice(child, 1);
12393 var index2;
12394 for(var id in this.indexes){
12395 index2 = this.indexes[id];
12396 if (index2 >= child) {
12397 this.indexes[id] = index2 - 1;
12398 }
12399 }
12400 this.markDirty();
12401 return this;
12402 };
12403 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
12404 if (!callback) {
12405 callback = opts;
12406 opts = {};
12407 }
12408 this.walkDecls(function(decl) {
12409 if (opts.props && !opts.props.includes(decl.prop)) return;
12410 if (opts.fast && !decl.value.includes(opts.fast)) return;
12411 decl.value = decl.value.replace(pattern, callback);
12412 });
12413 this.markDirty();
12414 return this;
12415 };
12416 _proto.some = function some(condition) {
12417 return this.nodes.some(condition);
12418 };
12419 _proto.walk = function walk(callback) {
12420 return this.each(function(child, i2) {
12421 var result2;
12422 try {
12423 result2 = callback(child, i2);
12424 } catch (e2) {
12425 throw child.addToError(e2);
12426 }
12427 if (result2 !== false && child.walk) {
12428 result2 = child.walk(callback);
12429 }
12430 return result2;
12431 });
12432 };
12433 _proto.walkAtRules = function walkAtRules(name, callback) {
12434 if (!callback) {
12435 callback = name;
12436 return this.walk(function(child, i2) {
12437 if (child.type === "atrule") {
12438 return callback(child, i2);
12439 }
12440 });
12441 }
12442 if (_instanceof(name, RegExp)) {
12443 return this.walk(function(child, i2) {
12444 if (child.type === "atrule" && name.test(child.name)) {
12445 return callback(child, i2);
12446 }
12447 });
12448 }
12449 return this.walk(function(child, i2) {
12450 if (child.type === "atrule" && child.name === name) {
12451 return callback(child, i2);
12452 }
12453 });
12454 };
12455 _proto.walkComments = function walkComments(callback) {
12456 return this.walk(function(child, i2) {
12457 if (child.type === "comment") {
12458 return callback(child, i2);
12459 }
12460 });
12461 };
12462 _proto.walkDecls = function walkDecls(prop, callback) {
12463 if (!callback) {
12464 callback = prop;
12465 return this.walk(function(child, i2) {
12466 if (child.type === "decl") {
12467 return callback(child, i2);
12468 }
12469 });
12470 }
12471 if (_instanceof(prop, RegExp)) {
12472 return this.walk(function(child, i2) {
12473 if (child.type === "decl" && prop.test(child.prop)) {
12474 return callback(child, i2);
12475 }
12476 });
12477 }
12478 return this.walk(function(child, i2) {
12479 if (child.type === "decl" && child.prop === prop) {
12480 return callback(child, i2);
12481 }
12482 });
12483 };
12484 _proto.walkRules = function walkRules(selector, callback) {
12485 if (!callback) {
12486 callback = selector;
12487 return this.walk(function(child, i2) {
12488 if (child.type === "rule") {
12489 return callback(child, i2);
12490 }
12491 });
12492 }
12493 if (_instanceof(selector, RegExp)) {
12494 return this.walk(function(child, i2) {
12495 if (child.type === "rule" && selector.test(child.selector)) {
12496 return callback(child, i2);
12497 }
12498 });
12499 }
12500 return this.walk(function(child, i2) {
12501 if (child.type === "rule" && child.selector === selector) {
12502 return callback(child, i2);
12503 }
12504 });
12505 };
12506 _create_class(Container, [
12507 {
12508 key: "first",
12509 get: function get() {
12510 if (!this.proxyOf.nodes) return void 0;
12511 return this.proxyOf.nodes[0];
12512 }
12513 },
12514 {
12515 key: "last",
12516 get: function get() {
12517 if (!this.proxyOf.nodes) return void 0;
12518 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
12519 }
12520 }
12521 ]);
12522 return Container;
12523 }(Node$1$1);
12524 Container$7$1.registerParse = function(dependant) {
12525 parse$4$1 = dependant;
12526 };
12527 Container$7$1.registerRule = function(dependant) {
12528 Rule$4$1 = dependant;
12529 };
12530 Container$7$1.registerAtRule = function(dependant) {
12531 AtRule$4$1 = dependant;
12532 };
12533 Container$7$1.registerRoot = function(dependant) {
12534 Root$6$1 = dependant;
12535 };
12536 var container$1 = Container$7$1;
12537 Container$7$1.default = Container$7$1;
12538 Container$7$1.rebuild = function(node2) {
12539 if (node2.type === "atrule") {
12540 Object.setPrototypeOf(node2, AtRule$4$1.prototype);
12541 } else if (node2.type === "rule") {
12542 Object.setPrototypeOf(node2, Rule$4$1.prototype);
12543 } else if (node2.type === "decl") {
12544 Object.setPrototypeOf(node2, Declaration$3$1.prototype);
12545 } else if (node2.type === "comment") {
12546 Object.setPrototypeOf(node2, Comment$3$1.prototype);
12547 } else if (node2.type === "root") {
12548 Object.setPrototypeOf(node2, Root$6$1.prototype);
12549 }
12550 node2[my$1$1] = true;
12551 if (node2.nodes) {
12552 node2.nodes.forEach(function(child) {
12553 Container$7$1.rebuild(child);
12554 });
12555 }
12556 };
12557 var Container$6$1 = container$1;
12558 var LazyResult$4$1, Processor$3$1;
12559 var Document$3$1 = /*#__PURE__*/ function(Container$6$1) {
12560 _inherits(Document2, Container$6$1);
12561 function Document2(defaults) {
12562 var _this;
12563 _this = Container$6$1.call(this, _extends({
12564 type: "document"
12565 }, defaults)) || this;
12566 if (!_this.nodes) {
12567 _this.nodes = [];
12568 }
12569 return _this;
12570 }
12571 var _proto = Document2.prototype;
12572 _proto.toResult = function toResult(opts) {
12573 if (opts === void 0) opts = {};
12574 var lazy = new LazyResult$4$1(new Processor$3$1(), this, opts);
12575 return lazy.stringify();
12576 };
12577 return Document2;
12578 }(Container$6$1);
12579 Document$3$1.registerLazyResult = function(dependant) {
12580 LazyResult$4$1 = dependant;
12581 };
12582 Document$3$1.registerProcessor = function(dependant) {
12583 Processor$3$1 = dependant;
12584 };
12585 var document$1$1 = Document$3$1;
12586 Document$3$1.default = Document$3$1;
12587 var printed$1 = {};
12588 var warnOnce$2$1 = function warnOnce(message) {
12589 if (printed$1[message]) return;
12590 printed$1[message] = true;
12591 if (typeof console !== "undefined" && console.warn) {
12592 console.warn(message);
12593 }
12594 };
12595 var Warning$2$1 = /*#__PURE__*/ function() {
12596 function Warning(text, opts) {
12597 if (opts === void 0) opts = {};
12598 this.type = "warning";
12599 this.text = text;
12600 if (opts.node && opts.node.source) {
12601 var range = opts.node.rangeBy(opts);
12602 this.line = range.start.line;
12603 this.column = range.start.column;
12604 this.endLine = range.end.line;
12605 this.endColumn = range.end.column;
12606 }
12607 for(var opt in opts)this[opt] = opts[opt];
12608 }
12609 var _proto = Warning.prototype;
12610 _proto.toString = function toString() {
12611 if (this.node) {
12612 return this.node.error(this.text, {
12613 index: this.index,
12614 plugin: this.plugin,
12615 word: this.word
12616 }).message;
12617 }
12618 if (this.plugin) {
12619 return this.plugin + ": " + this.text;
12620 }
12621 return this.text;
12622 };
12623 return Warning;
12624 }();
12625 var warning$1 = Warning$2$1;
12626 Warning$2$1.default = Warning$2$1;
12627 var Warning$1$1 = warning$1;
12628 var Result$3$1 = /*#__PURE__*/ function() {
12629 function Result(processor2, root2, opts) {
12630 this.processor = processor2;
12631 this.messages = [];
12632 this.root = root2;
12633 this.opts = opts;
12634 this.css = void 0;
12635 this.map = void 0;
12636 }
12637 var _proto = Result.prototype;
12638 _proto.toString = function toString() {
12639 return this.css;
12640 };
12641 _proto.warn = function warn(text, opts) {
12642 if (opts === void 0) opts = {};
12643 if (!opts.plugin) {
12644 if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
12645 opts.plugin = this.lastPlugin.postcssPlugin;
12646 }
12647 }
12648 var warning2 = new Warning$1$1(text, opts);
12649 this.messages.push(warning2);
12650 return warning2;
12651 };
12652 _proto.warnings = function warnings() {
12653 return this.messages.filter(function(i2) {
12654 return i2.type === "warning";
12655 });
12656 };
12657 _create_class(Result, [
12658 {
12659 key: "content",
12660 get: function get() {
12661 return this.css;
12662 }
12663 }
12664 ]);
12665 return Result;
12666 }();
12667 var result$1 = Result$3$1;
12668 Result$3$1.default = Result$3$1;
12669 var SINGLE_QUOTE$1 = "'".charCodeAt(0);
12670 var DOUBLE_QUOTE$1 = '"'.charCodeAt(0);
12671 var BACKSLASH$1 = "\\".charCodeAt(0);
12672 var SLASH$1 = "/".charCodeAt(0);
12673 var NEWLINE$1 = "\n".charCodeAt(0);
12674 var SPACE$1 = " ".charCodeAt(0);
12675 var FEED$1 = "\f".charCodeAt(0);
12676 var TAB$1 = " ".charCodeAt(0);
12677 var CR$1 = "\r".charCodeAt(0);
12678 var OPEN_SQUARE$1 = "[".charCodeAt(0);
12679 var CLOSE_SQUARE$1 = "]".charCodeAt(0);
12680 var OPEN_PARENTHESES$1 = "(".charCodeAt(0);
12681 var CLOSE_PARENTHESES$1 = ")".charCodeAt(0);
12682 var OPEN_CURLY$1 = "{".charCodeAt(0);
12683 var CLOSE_CURLY$1 = "}".charCodeAt(0);
12684 var SEMICOLON$1 = ";".charCodeAt(0);
12685 var ASTERISK$1 = "*".charCodeAt(0);
12686 var COLON$1 = ":".charCodeAt(0);
12687 var AT$1 = "@".charCodeAt(0);
12688 var RE_AT_END$1 = /[\t\n\f\r "#'()/;[\\\]{}]/g;
12689 var RE_WORD_END$1 = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
12690 var RE_BAD_BRACKET$1 = /.[\r\n"'(/\\]/;
12691 var RE_HEX_ESCAPE$1 = /[\da-f]/i;
12692 var tokenize$1 = function tokenizer(input2, options) {
12693 if (options === void 0) options = {};
12694 var css = input2.css.valueOf();
12695 var ignore = options.ignoreErrors;
12696 var code, next, quote, content, escape;
12697 var escaped, escapePos, prev, n2, currentToken;
12698 var length = css.length;
12699 var pos = 0;
12700 var buffer = [];
12701 var returned = [];
12702 function position() {
12703 return pos;
12704 }
12705 function unclosed(what) {
12706 throw input2.error("Unclosed " + what, pos);
12707 }
12708 function endOfFile() {
12709 return returned.length === 0 && pos >= length;
12710 }
12711 function nextToken(opts) {
12712 if (returned.length) return returned.pop();
12713 if (pos >= length) return;
12714 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
12715 code = css.charCodeAt(pos);
12716 switch(code){
12717 case NEWLINE$1:
12718 case SPACE$1:
12719 case TAB$1:
12720 case CR$1:
12721 case FEED$1:
12722 {
12723 next = pos;
12724 do {
12725 next += 1;
12726 code = css.charCodeAt(next);
12727 }while (code === SPACE$1 || code === NEWLINE$1 || code === TAB$1 || code === CR$1 || code === FEED$1);
12728 currentToken = [
12729 "space",
12730 css.slice(pos, next)
12731 ];
12732 pos = next - 1;
12733 break;
12734 }
12735 case OPEN_SQUARE$1:
12736 case CLOSE_SQUARE$1:
12737 case OPEN_CURLY$1:
12738 case CLOSE_CURLY$1:
12739 case COLON$1:
12740 case SEMICOLON$1:
12741 case CLOSE_PARENTHESES$1:
12742 {
12743 var controlChar = String.fromCharCode(code);
12744 currentToken = [
12745 controlChar,
12746 controlChar,
12747 pos
12748 ];
12749 break;
12750 }
12751 case OPEN_PARENTHESES$1:
12752 {
12753 prev = buffer.length ? buffer.pop()[1] : "";
12754 n2 = css.charCodeAt(pos + 1);
12755 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) {
12756 next = pos;
12757 do {
12758 escaped = false;
12759 next = css.indexOf(")", next + 1);
12760 if (next === -1) {
12761 if (ignore || ignoreUnclosed) {
12762 next = pos;
12763 break;
12764 } else {
12765 unclosed("bracket");
12766 }
12767 }
12768 escapePos = next;
12769 while(css.charCodeAt(escapePos - 1) === BACKSLASH$1){
12770 escapePos -= 1;
12771 escaped = !escaped;
12772 }
12773 }while (escaped);
12774 currentToken = [
12775 "brackets",
12776 css.slice(pos, next + 1),
12777 pos,
12778 next
12779 ];
12780 pos = next;
12781 } else {
12782 next = css.indexOf(")", pos + 1);
12783 content = css.slice(pos, next + 1);
12784 if (next === -1 || RE_BAD_BRACKET$1.test(content)) {
12785 currentToken = [
12786 "(",
12787 "(",
12788 pos
12789 ];
12790 } else {
12791 currentToken = [
12792 "brackets",
12793 content,
12794 pos,
12795 next
12796 ];
12797 pos = next;
12798 }
12799 }
12800 break;
12801 }
12802 case SINGLE_QUOTE$1:
12803 case DOUBLE_QUOTE$1:
12804 {
12805 quote = code === SINGLE_QUOTE$1 ? "'" : '"';
12806 next = pos;
12807 do {
12808 escaped = false;
12809 next = css.indexOf(quote, next + 1);
12810 if (next === -1) {
12811 if (ignore || ignoreUnclosed) {
12812 next = pos + 1;
12813 break;
12814 } else {
12815 unclosed("string");
12816 }
12817 }
12818 escapePos = next;
12819 while(css.charCodeAt(escapePos - 1) === BACKSLASH$1){
12820 escapePos -= 1;
12821 escaped = !escaped;
12822 }
12823 }while (escaped);
12824 currentToken = [
12825 "string",
12826 css.slice(pos, next + 1),
12827 pos,
12828 next
12829 ];
12830 pos = next;
12831 break;
12832 }
12833 case AT$1:
12834 {
12835 RE_AT_END$1.lastIndex = pos + 1;
12836 RE_AT_END$1.test(css);
12837 if (RE_AT_END$1.lastIndex === 0) {
12838 next = css.length - 1;
12839 } else {
12840 next = RE_AT_END$1.lastIndex - 2;
12841 }
12842 currentToken = [
12843 "at-word",
12844 css.slice(pos, next + 1),
12845 pos,
12846 next
12847 ];
12848 pos = next;
12849 break;
12850 }
12851 case BACKSLASH$1:
12852 {
12853 next = pos;
12854 escape = true;
12855 while(css.charCodeAt(next + 1) === BACKSLASH$1){
12856 next += 1;
12857 escape = !escape;
12858 }
12859 code = css.charCodeAt(next + 1);
12860 if (escape && code !== SLASH$1 && code !== SPACE$1 && code !== NEWLINE$1 && code !== TAB$1 && code !== CR$1 && code !== FEED$1) {
12861 next += 1;
12862 if (RE_HEX_ESCAPE$1.test(css.charAt(next))) {
12863 while(RE_HEX_ESCAPE$1.test(css.charAt(next + 1))){
12864 next += 1;
12865 }
12866 if (css.charCodeAt(next + 1) === SPACE$1) {
12867 next += 1;
12868 }
12869 }
12870 }
12871 currentToken = [
12872 "word",
12873 css.slice(pos, next + 1),
12874 pos,
12875 next
12876 ];
12877 pos = next;
12878 break;
12879 }
12880 default:
12881 {
12882 if (code === SLASH$1 && css.charCodeAt(pos + 1) === ASTERISK$1) {
12883 next = css.indexOf("*/", pos + 2) + 1;
12884 if (next === 0) {
12885 if (ignore || ignoreUnclosed) {
12886 next = css.length;
12887 } else {
12888 unclosed("comment");
12889 }
12890 }
12891 currentToken = [
12892 "comment",
12893 css.slice(pos, next + 1),
12894 pos,
12895 next
12896 ];
12897 pos = next;
12898 } else {
12899 RE_WORD_END$1.lastIndex = pos + 1;
12900 RE_WORD_END$1.test(css);
12901 if (RE_WORD_END$1.lastIndex === 0) {
12902 next = css.length - 1;
12903 } else {
12904 next = RE_WORD_END$1.lastIndex - 2;
12905 }
12906 currentToken = [
12907 "word",
12908 css.slice(pos, next + 1),
12909 pos,
12910 next
12911 ];
12912 buffer.push(currentToken);
12913 pos = next;
12914 }
12915 break;
12916 }
12917 }
12918 pos++;
12919 return currentToken;
12920 }
12921 function back(token) {
12922 returned.push(token);
12923 }
12924 return {
12925 back: back,
12926 endOfFile: endOfFile,
12927 nextToken: nextToken,
12928 position: position
12929 };
12930 };
12931 var Container$5$1 = container$1;
12932 var AtRule$3$1 = /*#__PURE__*/ function(Container$5$1) {
12933 _inherits(AtRule, Container$5$1);
12934 function AtRule(defaults) {
12935 var _this;
12936 _this = Container$5$1.call(this, defaults) || this;
12937 _this.type = "atrule";
12938 return _this;
12939 }
12940 var _proto = AtRule.prototype;
12941 _proto.append = function append() {
12942 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
12943 children[_key] = arguments[_key];
12944 }
12945 var _Container$5$1_prototype_append;
12946 if (!this.proxyOf.nodes) this.nodes = [];
12947 return (_Container$5$1_prototype_append = Container$5$1.prototype.append).call.apply(_Container$5$1_prototype_append, [].concat([
12948 this
12949 ], children));
12950 };
12951 _proto.prepend = function prepend() {
12952 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
12953 children[_key] = arguments[_key];
12954 }
12955 var _Container$5$1_prototype_prepend;
12956 if (!this.proxyOf.nodes) this.nodes = [];
12957 return (_Container$5$1_prototype_prepend = Container$5$1.prototype.prepend).call.apply(_Container$5$1_prototype_prepend, [].concat([
12958 this
12959 ], children));
12960 };
12961 return AtRule;
12962 }(Container$5$1);
12963 var atRule$1 = AtRule$3$1;
12964 AtRule$3$1.default = AtRule$3$1;
12965 Container$5$1.registerAtRule(AtRule$3$1);
12966 var Container$4$1 = container$1;
12967 var LazyResult$3$1, Processor$2$1;
12968 var Root$5$1 = /*#__PURE__*/ function(Container$4$1) {
12969 _inherits(Root, Container$4$1);
12970 function Root(defaults) {
12971 var _this;
12972 _this = Container$4$1.call(this, defaults) || this;
12973 _this.type = "root";
12974 if (!_this.nodes) _this.nodes = [];
12975 return _this;
12976 }
12977 var _proto = Root.prototype;
12978 _proto.normalize = function normalize(child, sample, type) {
12979 var nodes = Container$4$1.prototype.normalize.call(this, child);
12980 if (sample) {
12981 if (type === "prepend") {
12982 if (this.nodes.length > 1) {
12983 sample.raws.before = this.nodes[1].raws.before;
12984 } else {
12985 delete sample.raws.before;
12986 }
12987 } else if (this.first !== sample) {
12988 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
12989 var node2 = _step.value;
12990 node2.raws.before = sample.raws.before;
12991 }
12992 }
12993 }
12994 return nodes;
12995 };
12996 _proto.removeChild = function removeChild(child, ignore) {
12997 var index2 = this.index(child);
12998 if (!ignore && index2 === 0 && this.nodes.length > 1) {
12999 this.nodes[1].raws.before = this.nodes[index2].raws.before;
13000 }
13001 return Container$4$1.prototype.removeChild.call(this, child);
13002 };
13003 _proto.toResult = function toResult(opts) {
13004 if (opts === void 0) opts = {};
13005 var lazy = new LazyResult$3$1(new Processor$2$1(), this, opts);
13006 return lazy.stringify();
13007 };
13008 return Root;
13009 }(Container$4$1);
13010 Root$5$1.registerLazyResult = function(dependant) {
13011 LazyResult$3$1 = dependant;
13012 };
13013 Root$5$1.registerProcessor = function(dependant) {
13014 Processor$2$1 = dependant;
13015 };
13016 var root$1 = Root$5$1;
13017 Root$5$1.default = Root$5$1;
13018 Container$4$1.registerRoot(Root$5$1);
13019 var list$2$1 = {
13020 comma: function comma(string) {
13021 return list$2$1.split(string, [
13022 ","
13023 ], true);
13024 },
13025 space: function space(string) {
13026 var spaces = [
13027 " ",
13028 "\n",
13029 " "
13030 ];
13031 return list$2$1.split(string, spaces);
13032 },
13033 split: function split(string, separators, last) {
13034 var array = [];
13035 var current = "";
13036 var split = false;
13037 var func = 0;
13038 var inQuote = false;
13039 var prevQuote = "";
13040 var escape = false;
13041 for(var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;){
13042 var letter = _step.value;
13043 if (escape) {
13044 escape = false;
13045 } else if (letter === "\\") {
13046 escape = true;
13047 } else if (inQuote) {
13048 if (letter === prevQuote) {
13049 inQuote = false;
13050 }
13051 } else if (letter === '"' || letter === "'") {
13052 inQuote = true;
13053 prevQuote = letter;
13054 } else if (letter === "(") {
13055 func += 1;
13056 } else if (letter === ")") {
13057 if (func > 0) func -= 1;
13058 } else if (func === 0) {
13059 if (separators.includes(letter)) split = true;
13060 }
13061 if (split) {
13062 if (current !== "") array.push(current.trim());
13063 current = "";
13064 split = false;
13065 } else {
13066 current += letter;
13067 }
13068 }
13069 if (last || current !== "") array.push(current.trim());
13070 return array;
13071 }
13072 };
13073 var list_1$1 = list$2$1;
13074 list$2$1.default = list$2$1;
13075 var Container$3$1 = container$1;
13076 var list$1$1 = list_1$1;
13077 var Rule$3$1 = /*#__PURE__*/ function(Container$3$1) {
13078 _inherits(Rule, Container$3$1);
13079 function Rule(defaults) {
13080 var _this;
13081 _this = Container$3$1.call(this, defaults) || this;
13082 _this.type = "rule";
13083 if (!_this.nodes) _this.nodes = [];
13084 return _this;
13085 }
13086 _create_class(Rule, [
13087 {
13088 key: "selectors",
13089 get: function get() {
13090 return list$1$1.comma(this.selector);
13091 },
13092 set: function set(values) {
13093 var match = this.selector ? this.selector.match(/,\s*/) : null;
13094 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
13095 this.selector = values.join(sep2);
13096 }
13097 }
13098 ]);
13099 return Rule;
13100 }(Container$3$1);
13101 var rule$1 = Rule$3$1;
13102 Rule$3$1.default = Rule$3$1;
13103 Container$3$1.registerRule(Rule$3$1);
13104 var Declaration$2$1 = declaration$1;
13105 var tokenizer2$1 = tokenize$1;
13106 var Comment$2$1 = comment$1;
13107 var AtRule$2$1 = atRule$1;
13108 var Root$4$1 = root$1;
13109 var Rule$2$1 = rule$1;
13110 var SAFE_COMMENT_NEIGHBOR$1 = {
13111 empty: true,
13112 space: true
13113 };
13114 function findLastWithPosition$1(tokens) {
13115 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
13116 var token = tokens[i2];
13117 var pos = token[3] || token[2];
13118 if (pos) return pos;
13119 }
13120 }
13121 var Parser$1$1 = /*#__PURE__*/ function() {
13122 function Parser(input2) {
13123 this.input = input2;
13124 this.root = new Root$4$1();
13125 this.current = this.root;
13126 this.spaces = "";
13127 this.semicolon = false;
13128 this.createTokenizer();
13129 this.root.source = {
13130 input: input2,
13131 start: {
13132 column: 1,
13133 line: 1,
13134 offset: 0
13135 }
13136 };
13137 }
13138 var _proto = Parser.prototype;
13139 _proto.atrule = function atrule(token) {
13140 var node2 = new AtRule$2$1();
13141 node2.name = token[1].slice(1);
13142 if (node2.name === "") {
13143 this.unnamedAtrule(node2, token);
13144 }
13145 this.init(node2, token[2]);
13146 var type;
13147 var prev;
13148 var shift;
13149 var last = false;
13150 var open = false;
13151 var params = [];
13152 var brackets = [];
13153 while(!this.tokenizer.endOfFile()){
13154 token = this.tokenizer.nextToken();
13155 type = token[0];
13156 if (type === "(" || type === "[") {
13157 brackets.push(type === "(" ? ")" : "]");
13158 } else if (type === "{" && brackets.length > 0) {
13159 brackets.push("}");
13160 } else if (type === brackets[brackets.length - 1]) {
13161 brackets.pop();
13162 }
13163 if (brackets.length === 0) {
13164 if (type === ";") {
13165 node2.source.end = this.getPosition(token[2]);
13166 node2.source.end.offset++;
13167 this.semicolon = true;
13168 break;
13169 } else if (type === "{") {
13170 open = true;
13171 break;
13172 } else if (type === "}") {
13173 if (params.length > 0) {
13174 shift = params.length - 1;
13175 prev = params[shift];
13176 while(prev && prev[0] === "space"){
13177 prev = params[--shift];
13178 }
13179 if (prev) {
13180 node2.source.end = this.getPosition(prev[3] || prev[2]);
13181 node2.source.end.offset++;
13182 }
13183 }
13184 this.end(token);
13185 break;
13186 } else {
13187 params.push(token);
13188 }
13189 } else {
13190 params.push(token);
13191 }
13192 if (this.tokenizer.endOfFile()) {
13193 last = true;
13194 break;
13195 }
13196 }
13197 node2.raws.between = this.spacesAndCommentsFromEnd(params);
13198 if (params.length) {
13199 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
13200 this.raw(node2, "params", params);
13201 if (last) {
13202 token = params[params.length - 1];
13203 node2.source.end = this.getPosition(token[3] || token[2]);
13204 node2.source.end.offset++;
13205 this.spaces = node2.raws.between;
13206 node2.raws.between = "";
13207 }
13208 } else {
13209 node2.raws.afterName = "";
13210 node2.params = "";
13211 }
13212 if (open) {
13213 node2.nodes = [];
13214 this.current = node2;
13215 }
13216 };
13217 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
13218 var colon = this.colon(tokens);
13219 if (colon === false) return;
13220 var founded = 0;
13221 var token;
13222 for(var j = colon - 1; j >= 0; j--){
13223 token = tokens[j];
13224 if (token[0] !== "space") {
13225 founded += 1;
13226 if (founded === 2) break;
13227 }
13228 }
13229 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
13230 };
13231 _proto.colon = function colon(tokens) {
13232 var brackets = 0;
13233 var token, type, prev;
13234 for(var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;){
13235 var _step_value = _step.value, i2 = _step_value[0], element = _step_value[1];
13236 token = element;
13237 type = token[0];
13238 if (type === "(") {
13239 brackets += 1;
13240 }
13241 if (type === ")") {
13242 brackets -= 1;
13243 }
13244 if (brackets === 0 && type === ":") {
13245 if (!prev) {
13246 this.doubleColon(token);
13247 } else if (prev[0] === "word" && prev[1] === "progid") {
13248 continue;
13249 } else {
13250 return i2;
13251 }
13252 }
13253 prev = token;
13254 }
13255 return false;
13256 };
13257 _proto.comment = function comment(token) {
13258 var node2 = new Comment$2$1();
13259 this.init(node2, token[2]);
13260 node2.source.end = this.getPosition(token[3] || token[2]);
13261 node2.source.end.offset++;
13262 var text = token[1].slice(2, -2);
13263 if (/^\s*$/.test(text)) {
13264 node2.text = "";
13265 node2.raws.left = text;
13266 node2.raws.right = "";
13267 } else {
13268 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
13269 node2.text = match[2];
13270 node2.raws.left = match[1];
13271 node2.raws.right = match[3];
13272 }
13273 };
13274 _proto.createTokenizer = function createTokenizer() {
13275 this.tokenizer = tokenizer2$1(this.input);
13276 };
13277 _proto.decl = function decl(tokens, customProperty) {
13278 var node2 = new Declaration$2$1();
13279 this.init(node2, tokens[0][2]);
13280 var last = tokens[tokens.length - 1];
13281 if (last[0] === ";") {
13282 this.semicolon = true;
13283 tokens.pop();
13284 }
13285 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition$1(tokens));
13286 node2.source.end.offset++;
13287 while(tokens[0][0] !== "word"){
13288 if (tokens.length === 1) this.unknownWord(tokens);
13289 node2.raws.before += tokens.shift()[1];
13290 }
13291 node2.source.start = this.getPosition(tokens[0][2]);
13292 node2.prop = "";
13293 while(tokens.length){
13294 var type = tokens[0][0];
13295 if (type === ":" || type === "space" || type === "comment") {
13296 break;
13297 }
13298 node2.prop += tokens.shift()[1];
13299 }
13300 node2.raws.between = "";
13301 var token;
13302 while(tokens.length){
13303 token = tokens.shift();
13304 if (token[0] === ":") {
13305 node2.raws.between += token[1];
13306 break;
13307 } else {
13308 if (token[0] === "word" && /\w/.test(token[1])) {
13309 this.unknownWord([
13310 token
13311 ]);
13312 }
13313 node2.raws.between += token[1];
13314 }
13315 }
13316 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
13317 node2.raws.before += node2.prop[0];
13318 node2.prop = node2.prop.slice(1);
13319 }
13320 var firstSpaces = [];
13321 var next;
13322 while(tokens.length){
13323 next = tokens[0][0];
13324 if (next !== "space" && next !== "comment") break;
13325 firstSpaces.push(tokens.shift());
13326 }
13327 this.precheckMissedSemicolon(tokens);
13328 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
13329 token = tokens[i2];
13330 if (token[1].toLowerCase() === "!important") {
13331 node2.important = true;
13332 var string = this.stringFrom(tokens, i2);
13333 string = this.spacesFromEnd(tokens) + string;
13334 if (string !== " !important") node2.raws.important = string;
13335 break;
13336 } else if (token[1].toLowerCase() === "important") {
13337 var cache = tokens.slice(0);
13338 var str = "";
13339 for(var j = i2; j > 0; j--){
13340 var type1 = cache[j][0];
13341 if (str.trim().indexOf("!") === 0 && type1 !== "space") {
13342 break;
13343 }
13344 str = cache.pop()[1] + str;
13345 }
13346 if (str.trim().indexOf("!") === 0) {
13347 node2.important = true;
13348 node2.raws.important = str;
13349 tokens = cache;
13350 }
13351 }
13352 if (token[0] !== "space" && token[0] !== "comment") {
13353 break;
13354 }
13355 }
13356 var hasWord = tokens.some(function(i2) {
13357 return i2[0] !== "space" && i2[0] !== "comment";
13358 });
13359 if (hasWord) {
13360 node2.raws.between += firstSpaces.map(function(i2) {
13361 return i2[1];
13362 }).join("");
13363 firstSpaces = [];
13364 }
13365 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
13366 if (node2.value.includes(":") && !customProperty) {
13367 this.checkMissedSemicolon(tokens);
13368 }
13369 };
13370 _proto.doubleColon = function doubleColon(token) {
13371 throw this.input.error("Double colon", {
13372 offset: token[2]
13373 }, {
13374 offset: token[2] + token[1].length
13375 });
13376 };
13377 _proto.emptyRule = function emptyRule(token) {
13378 var node2 = new Rule$2$1();
13379 this.init(node2, token[2]);
13380 node2.selector = "";
13381 node2.raws.between = "";
13382 this.current = node2;
13383 };
13384 _proto.end = function end(token) {
13385 if (this.current.nodes && this.current.nodes.length) {
13386 this.current.raws.semicolon = this.semicolon;
13387 }
13388 this.semicolon = false;
13389 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
13390 this.spaces = "";
13391 if (this.current.parent) {
13392 this.current.source.end = this.getPosition(token[2]);
13393 this.current.source.end.offset++;
13394 this.current = this.current.parent;
13395 } else {
13396 this.unexpectedClose(token);
13397 }
13398 };
13399 _proto.endFile = function endFile() {
13400 if (this.current.parent) this.unclosedBlock();
13401 if (this.current.nodes && this.current.nodes.length) {
13402 this.current.raws.semicolon = this.semicolon;
13403 }
13404 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
13405 this.root.source.end = this.getPosition(this.tokenizer.position());
13406 };
13407 _proto.freeSemicolon = function freeSemicolon(token) {
13408 this.spaces += token[1];
13409 if (this.current.nodes) {
13410 var prev = this.current.nodes[this.current.nodes.length - 1];
13411 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
13412 prev.raws.ownSemicolon = this.spaces;
13413 this.spaces = "";
13414 }
13415 }
13416 };
13417 // Helpers
13418 _proto.getPosition = function getPosition(offset) {
13419 var pos = this.input.fromOffset(offset);
13420 return {
13421 column: pos.col,
13422 line: pos.line,
13423 offset: offset
13424 };
13425 };
13426 _proto.init = function init(node2, offset) {
13427 this.current.push(node2);
13428 node2.source = {
13429 input: this.input,
13430 start: this.getPosition(offset)
13431 };
13432 node2.raws.before = this.spaces;
13433 this.spaces = "";
13434 if (node2.type !== "comment") this.semicolon = false;
13435 };
13436 _proto.other = function other(start) {
13437 var end = false;
13438 var type = null;
13439 var colon = false;
13440 var bracket = null;
13441 var brackets = [];
13442 var customProperty = start[1].startsWith("--");
13443 var tokens = [];
13444 var token = start;
13445 while(token){
13446 type = token[0];
13447 tokens.push(token);
13448 if (type === "(" || type === "[") {
13449 if (!bracket) bracket = token;
13450 brackets.push(type === "(" ? ")" : "]");
13451 } else if (customProperty && colon && type === "{") {
13452 if (!bracket) bracket = token;
13453 brackets.push("}");
13454 } else if (brackets.length === 0) {
13455 if (type === ";") {
13456 if (colon) {
13457 this.decl(tokens, customProperty);
13458 return;
13459 } else {
13460 break;
13461 }
13462 } else if (type === "{") {
13463 this.rule(tokens);
13464 return;
13465 } else if (type === "}") {
13466 this.tokenizer.back(tokens.pop());
13467 end = true;
13468 break;
13469 } else if (type === ":") {
13470 colon = true;
13471 }
13472 } else if (type === brackets[brackets.length - 1]) {
13473 brackets.pop();
13474 if (brackets.length === 0) bracket = null;
13475 }
13476 token = this.tokenizer.nextToken();
13477 }
13478 if (this.tokenizer.endOfFile()) end = true;
13479 if (brackets.length > 0) this.unclosedBracket(bracket);
13480 if (end && colon) {
13481 if (!customProperty) {
13482 while(tokens.length){
13483 token = tokens[tokens.length - 1][0];
13484 if (token !== "space" && token !== "comment") break;
13485 this.tokenizer.back(tokens.pop());
13486 }
13487 }
13488 this.decl(tokens, customProperty);
13489 } else {
13490 this.unknownWord(tokens);
13491 }
13492 };
13493 _proto.parse = function parse() {
13494 var token;
13495 while(!this.tokenizer.endOfFile()){
13496 token = this.tokenizer.nextToken();
13497 switch(token[0]){
13498 case "space":
13499 this.spaces += token[1];
13500 break;
13501 case ";":
13502 this.freeSemicolon(token);
13503 break;
13504 case "}":
13505 this.end(token);
13506 break;
13507 case "comment":
13508 this.comment(token);
13509 break;
13510 case "at-word":
13511 this.atrule(token);
13512 break;
13513 case "{":
13514 this.emptyRule(token);
13515 break;
13516 default:
13517 this.other(token);
13518 break;
13519 }
13520 }
13521 this.endFile();
13522 };
13523 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
13524 _proto.raw = function raw(node2, prop, tokens, customProperty) {
13525 var token, type;
13526 var length = tokens.length;
13527 var value = "";
13528 var clean = true;
13529 var next, prev;
13530 for(var i2 = 0; i2 < length; i2 += 1){
13531 token = tokens[i2];
13532 type = token[0];
13533 if (type === "space" && i2 === length - 1 && !customProperty) {
13534 clean = false;
13535 } else if (type === "comment") {
13536 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
13537 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
13538 if (!SAFE_COMMENT_NEIGHBOR$1[prev] && !SAFE_COMMENT_NEIGHBOR$1[next]) {
13539 if (value.slice(-1) === ",") {
13540 clean = false;
13541 } else {
13542 value += token[1];
13543 }
13544 } else {
13545 clean = false;
13546 }
13547 } else {
13548 value += token[1];
13549 }
13550 }
13551 if (!clean) {
13552 var raw = tokens.reduce(function(all, i2) {
13553 return all + i2[1];
13554 }, "");
13555 node2.raws[prop] = {
13556 raw: raw,
13557 value: value
13558 };
13559 }
13560 node2[prop] = value;
13561 };
13562 _proto.rule = function rule(tokens) {
13563 tokens.pop();
13564 var node2 = new Rule$2$1();
13565 this.init(node2, tokens[0][2]);
13566 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
13567 this.raw(node2, "selector", tokens);
13568 this.current = node2;
13569 };
13570 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
13571 var lastTokenType;
13572 var spaces = "";
13573 while(tokens.length){
13574 lastTokenType = tokens[tokens.length - 1][0];
13575 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
13576 spaces = tokens.pop()[1] + spaces;
13577 }
13578 return spaces;
13579 };
13580 // Errors
13581 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
13582 var next;
13583 var spaces = "";
13584 while(tokens.length){
13585 next = tokens[0][0];
13586 if (next !== "space" && next !== "comment") break;
13587 spaces += tokens.shift()[1];
13588 }
13589 return spaces;
13590 };
13591 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
13592 var lastTokenType;
13593 var spaces = "";
13594 while(tokens.length){
13595 lastTokenType = tokens[tokens.length - 1][0];
13596 if (lastTokenType !== "space") break;
13597 spaces = tokens.pop()[1] + spaces;
13598 }
13599 return spaces;
13600 };
13601 _proto.stringFrom = function stringFrom(tokens, from) {
13602 var result2 = "";
13603 for(var i2 = from; i2 < tokens.length; i2++){
13604 result2 += tokens[i2][1];
13605 }
13606 tokens.splice(from, tokens.length - from);
13607 return result2;
13608 };
13609 _proto.unclosedBlock = function unclosedBlock() {
13610 var pos = this.current.source.start;
13611 throw this.input.error("Unclosed block", pos.line, pos.column);
13612 };
13613 _proto.unclosedBracket = function unclosedBracket(bracket) {
13614 throw this.input.error("Unclosed bracket", {
13615 offset: bracket[2]
13616 }, {
13617 offset: bracket[2] + 1
13618 });
13619 };
13620 _proto.unexpectedClose = function unexpectedClose(token) {
13621 throw this.input.error("Unexpected }", {
13622 offset: token[2]
13623 }, {
13624 offset: token[2] + 1
13625 });
13626 };
13627 _proto.unknownWord = function unknownWord(tokens) {
13628 throw this.input.error("Unknown word", {
13629 offset: tokens[0][2]
13630 }, {
13631 offset: tokens[0][2] + tokens[0][1].length
13632 });
13633 };
13634 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
13635 throw this.input.error("At-rule without name", {
13636 offset: token[2]
13637 }, {
13638 offset: token[2] + token[1].length
13639 });
13640 };
13641 return Parser;
13642 }();
13643 var parser$1 = Parser$1$1;
13644 var Container$2$1 = container$1;
13645 var Parser2$1 = parser$1;
13646 var Input$2$1 = input$1;
13647 function parse$3$1(css, opts) {
13648 var input2 = new Input$2$1(css, opts);
13649 var parser2 = new Parser2$1(input2);
13650 try {
13651 parser2.parse();
13652 } catch (e2) {
13653 if (true) {
13654 if (e2.name === "CssSyntaxError" && opts && opts.from) {
13655 if (/\.scss$/i.test(opts.from)) {
13656 e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
13657 } else if (/\.sass/i.test(opts.from)) {
13658 e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
13659 } else if (/\.less$/i.test(opts.from)) {
13660 e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
13661 }
13662 }
13663 }
13664 throw e2;
13665 }
13666 return parser2.root;
13667 }
13668 var parse_1$1 = parse$3$1;
13669 parse$3$1.default = parse$3$1;
13670 Container$2$1.registerParse(parse$3$1);
13671 var isClean$3 = symbols$1.isClean, my$3 = symbols$1.my;
13672 var MapGenerator$1$1 = mapGenerator$1;
13673 var stringify$2$1 = stringify_1$1;
13674 var Container$1$1 = container$1;
13675 var Document$2$1 = document$1$1;
13676 var warnOnce$1$1 = warnOnce$2$1;
13677 var Result$2$1 = result$1;
13678 var parse$2$1 = parse_1$1;
13679 var Root$3$1 = root$1;
13680 var TYPE_TO_CLASS_NAME$1 = {
13681 atrule: "AtRule",
13682 comment: "Comment",
13683 decl: "Declaration",
13684 document: "Document",
13685 root: "Root",
13686 rule: "Rule"
13687 };
13688 var PLUGIN_PROPS$1 = {
13689 AtRule: true,
13690 AtRuleExit: true,
13691 Comment: true,
13692 CommentExit: true,
13693 Declaration: true,
13694 DeclarationExit: true,
13695 Document: true,
13696 DocumentExit: true,
13697 Once: true,
13698 OnceExit: true,
13699 postcssPlugin: true,
13700 prepare: true,
13701 Root: true,
13702 RootExit: true,
13703 Rule: true,
13704 RuleExit: true
13705 };
13706 var NOT_VISITORS$1 = {
13707 Once: true,
13708 postcssPlugin: true,
13709 prepare: true
13710 };
13711 var CHILDREN$1 = 0;
13712 function isPromise$1(obj) {
13713 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
13714 }
13715 function getEvents$1(node2) {
13716 var key = false;
13717 var type = TYPE_TO_CLASS_NAME$1[node2.type];
13718 if (node2.type === "decl") {
13719 key = node2.prop.toLowerCase();
13720 } else if (node2.type === "atrule") {
13721 key = node2.name.toLowerCase();
13722 }
13723 if (key && node2.append) {
13724 return [
13725 type,
13726 type + "-" + key,
13727 CHILDREN$1,
13728 type + "Exit",
13729 type + "Exit-" + key
13730 ];
13731 } else if (key) {
13732 return [
13733 type,
13734 type + "-" + key,
13735 type + "Exit",
13736 type + "Exit-" + key
13737 ];
13738 } else if (node2.append) {
13739 return [
13740 type,
13741 CHILDREN$1,
13742 type + "Exit"
13743 ];
13744 } else {
13745 return [
13746 type,
13747 type + "Exit"
13748 ];
13749 }
13750 }
13751 function toStack$1(node2) {
13752 var events;
13753 if (node2.type === "document") {
13754 events = [
13755 "Document",
13756 CHILDREN$1,
13757 "DocumentExit"
13758 ];
13759 } else if (node2.type === "root") {
13760 events = [
13761 "Root",
13762 CHILDREN$1,
13763 "RootExit"
13764 ];
13765 } else {
13766 events = getEvents$1(node2);
13767 }
13768 return {
13769 eventIndex: 0,
13770 events: events,
13771 iterator: 0,
13772 node: node2,
13773 visitorIndex: 0,
13774 visitors: []
13775 };
13776 }
13777 function cleanMarks$1(node2) {
13778 node2[isClean$3] = false;
13779 if (node2.nodes) node2.nodes.forEach(function(i2) {
13780 return cleanMarks$1(i2);
13781 });
13782 return node2;
13783 }
13784 var postcss$2$1 = {};
13785 var LazyResult$2$1 = /*#__PURE__*/ function() {
13786 function LazyResult(processor2, css, opts) {
13787 var _this = this;
13788 this.stringified = false;
13789 this.processed = false;
13790 var root2;
13791 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) {
13792 root2 = cleanMarks$1(css);
13793 } else if (_instanceof(css, LazyResult) || _instanceof(css, Result$2$1)) {
13794 root2 = cleanMarks$1(css.root);
13795 if (css.map) {
13796 if (typeof opts.map === "undefined") opts.map = {};
13797 if (!opts.map.inline) opts.map.inline = false;
13798 opts.map.prev = css.map;
13799 }
13800 } else {
13801 var parser2 = parse$2$1;
13802 if (opts.syntax) parser2 = opts.syntax.parse;
13803 if (opts.parser) parser2 = opts.parser;
13804 if (parser2.parse) parser2 = parser2.parse;
13805 try {
13806 root2 = parser2(css, opts);
13807 } catch (error) {
13808 this.processed = true;
13809 this.error = error;
13810 }
13811 if (root2 && !root2[my$3]) {
13812 Container$1$1.rebuild(root2);
13813 }
13814 }
13815 this.result = new Result$2$1(processor2, root2, opts);
13816 this.helpers = _extends({}, postcss$2$1, {
13817 postcss: postcss$2$1,
13818 result: this.result
13819 });
13820 this.plugins = this.processor.plugins.map(function(plugin22) {
13821 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) {
13822 return _extends({}, plugin22, plugin22.prepare(_this.result));
13823 } else {
13824 return plugin22;
13825 }
13826 });
13827 }
13828 var _proto = LazyResult.prototype;
13829 _proto.async = function async() {
13830 if (this.error) return Promise.reject(this.error);
13831 if (this.processed) return Promise.resolve(this.result);
13832 if (!this.processing) {
13833 this.processing = this.runAsync();
13834 }
13835 return this.processing;
13836 };
13837 _proto.catch = function _catch(onRejected) {
13838 return this.async().catch(onRejected);
13839 };
13840 _proto.finally = function _finally(onFinally) {
13841 return this.async().then(onFinally, onFinally);
13842 };
13843 _proto.getAsyncError = function getAsyncError() {
13844 throw new Error("Use process(css).then(cb) to work with async plugins");
13845 };
13846 _proto.handleError = function handleError(error, node2) {
13847 var plugin22 = this.result.lastPlugin;
13848 try {
13849 if (node2) node2.addToError(error);
13850 this.error = error;
13851 if (error.name === "CssSyntaxError" && !error.plugin) {
13852 error.plugin = plugin22.postcssPlugin;
13853 error.setMessage();
13854 } else if (plugin22.postcssVersion) {
13855 if (true) {
13856 var pluginName = plugin22.postcssPlugin;
13857 var pluginVer = plugin22.postcssVersion;
13858 var runtimeVer = this.result.processor.version;
13859 var a2 = pluginVer.split(".");
13860 var b = runtimeVer.split(".");
13861 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) {
13862 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.");
13863 }
13864 }
13865 }
13866 } catch (err) {
13867 if (console && console.error) console.error(err);
13868 }
13869 return error;
13870 };
13871 _proto.prepareVisitors = function prepareVisitors() {
13872 var _this = this;
13873 this.listeners = {};
13874 var add = function(plugin22, type, cb) {
13875 if (!_this.listeners[type]) _this.listeners[type] = [];
13876 _this.listeners[type].push([
13877 plugin22,
13878 cb
13879 ]);
13880 };
13881 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
13882 var plugin22 = _step.value;
13883 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") {
13884 for(var event in plugin22){
13885 if (!PLUGIN_PROPS$1[event] && /^[A-Z]/.test(event)) {
13886 throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
13887 }
13888 if (!NOT_VISITORS$1[event]) {
13889 if (_type_of(plugin22[event]) === "object") {
13890 for(var filter in plugin22[event]){
13891 if (filter === "*") {
13892 add(plugin22, event, plugin22[event][filter]);
13893 } else {
13894 add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
13895 }
13896 }
13897 } else if (typeof plugin22[event] === "function") {
13898 add(plugin22, event, plugin22[event]);
13899 }
13900 }
13901 }
13902 }
13903 }
13904 this.hasListener = Object.keys(this.listeners).length > 0;
13905 };
13906 _proto.runAsync = function runAsync() {
13907 var _this = this;
13908 return _async_to_generator(function() {
13909 var i2, plugin22, promise, error, root2, stack, promise1, e2, node2, _loop, _iterator, _step;
13910 return _ts_generator(this, function(_state) {
13911 switch(_state.label){
13912 case 0:
13913 _this.plugin = 0;
13914 i2 = 0;
13915 _state.label = 1;
13916 case 1:
13917 if (!(i2 < _this.plugins.length)) return [
13918 3,
13919 6
13920 ];
13921 plugin22 = _this.plugins[i2];
13922 promise = _this.runOnRoot(plugin22);
13923 if (!isPromise$1(promise)) return [
13924 3,
13925 5
13926 ];
13927 _state.label = 2;
13928 case 2:
13929 _state.trys.push([
13930 2,
13931 4,
13932 ,
13933 5
13934 ]);
13935 return [
13936 4,
13937 promise
13938 ];
13939 case 3:
13940 _state.sent();
13941 return [
13942 3,
13943 5
13944 ];
13945 case 4:
13946 error = _state.sent();
13947 throw _this.handleError(error);
13948 case 5:
13949 i2++;
13950 return [
13951 3,
13952 1
13953 ];
13954 case 6:
13955 _this.prepareVisitors();
13956 if (!_this.hasListener) return [
13957 3,
13958 18
13959 ];
13960 root2 = _this.result.root;
13961 _state.label = 7;
13962 case 7:
13963 if (!!root2[isClean$3]) return [
13964 3,
13965 14
13966 ];
13967 root2[isClean$3] = true;
13968 stack = [
13969 toStack$1(root2)
13970 ];
13971 _state.label = 8;
13972 case 8:
13973 if (!(stack.length > 0)) return [
13974 3,
13975 13
13976 ];
13977 promise1 = _this.visitTick(stack);
13978 if (!isPromise$1(promise1)) return [
13979 3,
13980 12
13981 ];
13982 _state.label = 9;
13983 case 9:
13984 _state.trys.push([
13985 9,
13986 11,
13987 ,
13988 12
13989 ]);
13990 return [
13991 4,
13992 promise1
13993 ];
13994 case 10:
13995 _state.sent();
13996 return [
13997 3,
13998 12
13999 ];
14000 case 11:
14001 e2 = _state.sent();
14002 node2 = stack[stack.length - 1].node;
14003 throw _this.handleError(e2, node2);
14004 case 12:
14005 return [
14006 3,
14007 8
14008 ];
14009 case 13:
14010 return [
14011 3,
14012 7
14013 ];
14014 case 14:
14015 if (!_this.listeners.OnceExit) return [
14016 3,
14017 18
14018 ];
14019 _loop = function() {
14020 var _step_value, plugin22, visitor, roots, e2;
14021 return _ts_generator(this, function(_state) {
14022 switch(_state.label){
14023 case 0:
14024 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
14025 _this.result.lastPlugin = plugin22;
14026 _state.label = 1;
14027 case 1:
14028 _state.trys.push([
14029 1,
14030 6,
14031 ,
14032 7
14033 ]);
14034 if (!(root2.type === "document")) return [
14035 3,
14036 3
14037 ];
14038 roots = root2.nodes.map(function(subRoot) {
14039 return visitor(subRoot, _this.helpers);
14040 });
14041 return [
14042 4,
14043 Promise.all(roots)
14044 ];
14045 case 2:
14046 _state.sent();
14047 return [
14048 3,
14049 5
14050 ];
14051 case 3:
14052 return [
14053 4,
14054 visitor(root2, _this.helpers)
14055 ];
14056 case 4:
14057 _state.sent();
14058 _state.label = 5;
14059 case 5:
14060 return [
14061 3,
14062 7
14063 ];
14064 case 6:
14065 e2 = _state.sent();
14066 throw _this.handleError(e2);
14067 case 7:
14068 return [
14069 2
14070 ];
14071 }
14072 });
14073 };
14074 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
14075 _state.label = 15;
14076 case 15:
14077 if (!!(_step = _iterator()).done) return [
14078 3,
14079 18
14080 ];
14081 return [
14082 5,
14083 _ts_values(_loop())
14084 ];
14085 case 16:
14086 _state.sent();
14087 _state.label = 17;
14088 case 17:
14089 return [
14090 3,
14091 15
14092 ];
14093 case 18:
14094 _this.processed = true;
14095 return [
14096 2,
14097 _this.stringify()
14098 ];
14099 }
14100 });
14101 })();
14102 };
14103 _proto.runOnRoot = function runOnRoot(plugin22) {
14104 var _this = this;
14105 this.result.lastPlugin = plugin22;
14106 try {
14107 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
14108 if (this.result.root.type === "document") {
14109 var roots = this.result.root.nodes.map(function(root2) {
14110 return plugin22.Once(root2, _this.helpers);
14111 });
14112 if (isPromise$1(roots[0])) {
14113 return Promise.all(roots);
14114 }
14115 return roots;
14116 }
14117 return plugin22.Once(this.result.root, this.helpers);
14118 } else if (typeof plugin22 === "function") {
14119 return plugin22(this.result.root, this.result);
14120 }
14121 } catch (error) {
14122 throw this.handleError(error);
14123 }
14124 };
14125 _proto.stringify = function stringify() {
14126 if (this.error) throw this.error;
14127 if (this.stringified) return this.result;
14128 this.stringified = true;
14129 this.sync();
14130 var opts = this.result.opts;
14131 var str = stringify$2$1;
14132 if (opts.syntax) str = opts.syntax.stringify;
14133 if (opts.stringifier) str = opts.stringifier;
14134 if (str.stringify) str = str.stringify;
14135 var map = new MapGenerator$1$1(str, this.result.root, this.result.opts);
14136 var data = map.generate();
14137 this.result.css = data[0];
14138 this.result.map = data[1];
14139 return this.result;
14140 };
14141 _proto.sync = function sync() {
14142 if (this.error) throw this.error;
14143 if (this.processed) return this.result;
14144 this.processed = true;
14145 if (this.processing) {
14146 throw this.getAsyncError();
14147 }
14148 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
14149 var plugin22 = _step.value;
14150 var promise = this.runOnRoot(plugin22);
14151 if (isPromise$1(promise)) {
14152 throw this.getAsyncError();
14153 }
14154 }
14155 this.prepareVisitors();
14156 if (this.hasListener) {
14157 var root2 = this.result.root;
14158 while(!root2[isClean$3]){
14159 root2[isClean$3] = true;
14160 this.walkSync(root2);
14161 }
14162 if (this.listeners.OnceExit) {
14163 if (root2.type === "document") {
14164 for(var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;){
14165 var subRoot = _step1.value;
14166 this.visitSync(this.listeners.OnceExit, subRoot);
14167 }
14168 } else {
14169 this.visitSync(this.listeners.OnceExit, root2);
14170 }
14171 }
14172 }
14173 return this.result;
14174 };
14175 _proto.then = function then(onFulfilled, onRejected) {
14176 if (true) {
14177 if (!("from" in this.opts)) {
14178 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.");
14179 }
14180 }
14181 return this.async().then(onFulfilled, onRejected);
14182 };
14183 _proto.toString = function toString() {
14184 return this.css;
14185 };
14186 _proto.visitSync = function visitSync(visitors, node2) {
14187 for(var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;){
14188 var _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
14189 this.result.lastPlugin = plugin22;
14190 var promise = void 0;
14191 try {
14192 promise = visitor(node2, this.helpers);
14193 } catch (e2) {
14194 throw this.handleError(e2, node2.proxyOf);
14195 }
14196 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
14197 return true;
14198 }
14199 if (isPromise$1(promise)) {
14200 throw this.getAsyncError();
14201 }
14202 }
14203 };
14204 _proto.visitTick = function visitTick(stack) {
14205 var visit2 = stack[stack.length - 1];
14206 var node2 = visit2.node, visitors = visit2.visitors;
14207 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
14208 stack.pop();
14209 return;
14210 }
14211 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
14212 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex], plugin22 = _visitors_visit2_visitorIndex[0], visitor = _visitors_visit2_visitorIndex[1];
14213 visit2.visitorIndex += 1;
14214 if (visit2.visitorIndex === visitors.length) {
14215 visit2.visitors = [];
14216 visit2.visitorIndex = 0;
14217 }
14218 this.result.lastPlugin = plugin22;
14219 try {
14220 return visitor(node2.toProxy(), this.helpers);
14221 } catch (e2) {
14222 throw this.handleError(e2, node2);
14223 }
14224 }
14225 if (visit2.iterator !== 0) {
14226 var iterator = visit2.iterator;
14227 var child;
14228 while(child = node2.nodes[node2.indexes[iterator]]){
14229 node2.indexes[iterator] += 1;
14230 if (!child[isClean$3]) {
14231 child[isClean$3] = true;
14232 stack.push(toStack$1(child));
14233 return;
14234 }
14235 }
14236 visit2.iterator = 0;
14237 delete node2.indexes[iterator];
14238 }
14239 var events = visit2.events;
14240 while(visit2.eventIndex < events.length){
14241 var event = events[visit2.eventIndex];
14242 visit2.eventIndex += 1;
14243 if (event === CHILDREN$1) {
14244 if (node2.nodes && node2.nodes.length) {
14245 node2[isClean$3] = true;
14246 visit2.iterator = node2.getIterator();
14247 }
14248 return;
14249 } else if (this.listeners[event]) {
14250 visit2.visitors = this.listeners[event];
14251 return;
14252 }
14253 }
14254 stack.pop();
14255 };
14256 _proto.walkSync = function walkSync(node2) {
14257 var _this = this;
14258 node2[isClean$3] = true;
14259 var events = getEvents$1(node2);
14260 for(var _iterator = _create_for_of_iterator_helper_loose(events), _step; !(_step = _iterator()).done;){
14261 var event = _step.value;
14262 if (event === CHILDREN$1) {
14263 if (node2.nodes) {
14264 node2.each(function(child) {
14265 if (!child[isClean$3]) _this.walkSync(child);
14266 });
14267 }
14268 } else {
14269 var visitors = this.listeners[event];
14270 if (visitors) {
14271 if (this.visitSync(visitors, node2.toProxy())) return;
14272 }
14273 }
14274 }
14275 };
14276 _proto.warnings = function warnings() {
14277 return this.sync().warnings();
14278 };
14279 _create_class(LazyResult, [
14280 {
14281 key: "content",
14282 get: function get() {
14283 return this.stringify().content;
14284 }
14285 },
14286 {
14287 key: "css",
14288 get: function get() {
14289 return this.stringify().css;
14290 }
14291 },
14292 {
14293 key: "map",
14294 get: function get() {
14295 return this.stringify().map;
14296 }
14297 },
14298 {
14299 key: "messages",
14300 get: function get() {
14301 return this.sync().messages;
14302 }
14303 },
14304 {
14305 key: "opts",
14306 get: function get() {
14307 return this.result.opts;
14308 }
14309 },
14310 {
14311 key: "processor",
14312 get: function get() {
14313 return this.result.processor;
14314 }
14315 },
14316 {
14317 key: "root",
14318 get: function get() {
14319 return this.sync().root;
14320 }
14321 },
14322 {
14323 key: Symbol.toStringTag,
14324 get: function get() {
14325 return "LazyResult";
14326 }
14327 }
14328 ]);
14329 return LazyResult;
14330 }();
14331 LazyResult$2$1.registerPostcss = function(dependant) {
14332 postcss$2$1 = dependant;
14333 };
14334 var lazyResult$1 = LazyResult$2$1;
14335 LazyResult$2$1.default = LazyResult$2$1;
14336 Root$3$1.registerLazyResult(LazyResult$2$1);
14337 Document$2$1.registerLazyResult(LazyResult$2$1);
14338 var MapGenerator2$1 = mapGenerator$1;
14339 var stringify$1$1 = stringify_1$1;
14340 var warnOnce2$1 = warnOnce$2$1;
14341 var parse$1$1 = parse_1$1;
14342 var Result$1$1 = result$1;
14343 var NoWorkResult$1$1 = /*#__PURE__*/ function() {
14344 function NoWorkResult(processor2, css, opts) {
14345 css = css.toString();
14346 this.stringified = false;
14347 this._processor = processor2;
14348 this._css = css;
14349 this._opts = opts;
14350 this._map = void 0;
14351 var root2;
14352 var str = stringify$1$1;
14353 this.result = new Result$1$1(this._processor, root2, this._opts);
14354 this.result.css = css;
14355 var self = this;
14356 Object.defineProperty(this.result, "root", {
14357 get: function get() {
14358 return self.root;
14359 }
14360 });
14361 var map = new MapGenerator2$1(str, root2, this._opts, css);
14362 if (map.isMap()) {
14363 var _map_generate = map.generate(), generatedCSS = _map_generate[0], generatedMap = _map_generate[1];
14364 if (generatedCSS) {
14365 this.result.css = generatedCSS;
14366 }
14367 if (generatedMap) {
14368 this.result.map = generatedMap;
14369 }
14370 } else {
14371 map.clearAnnotation();
14372 this.result.css = map.css;
14373 }
14374 }
14375 var _proto = NoWorkResult.prototype;
14376 _proto.async = function async() {
14377 if (this.error) return Promise.reject(this.error);
14378 return Promise.resolve(this.result);
14379 };
14380 _proto.catch = function _catch(onRejected) {
14381 return this.async().catch(onRejected);
14382 };
14383 _proto.finally = function _finally(onFinally) {
14384 return this.async().then(onFinally, onFinally);
14385 };
14386 _proto.sync = function sync() {
14387 if (this.error) throw this.error;
14388 return this.result;
14389 };
14390 _proto.then = function then(onFulfilled, onRejected) {
14391 if (true) {
14392 if (!("from" in this._opts)) {
14393 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.");
14394 }
14395 }
14396 return this.async().then(onFulfilled, onRejected);
14397 };
14398 _proto.toString = function toString() {
14399 return this._css;
14400 };
14401 _proto.warnings = function warnings() {
14402 return [];
14403 };
14404 _create_class(NoWorkResult, [
14405 {
14406 key: "content",
14407 get: function get() {
14408 return this.result.css;
14409 }
14410 },
14411 {
14412 key: "css",
14413 get: function get() {
14414 return this.result.css;
14415 }
14416 },
14417 {
14418 key: "map",
14419 get: function get() {
14420 return this.result.map;
14421 }
14422 },
14423 {
14424 key: "messages",
14425 get: function get() {
14426 return [];
14427 }
14428 },
14429 {
14430 key: "opts",
14431 get: function get() {
14432 return this.result.opts;
14433 }
14434 },
14435 {
14436 key: "processor",
14437 get: function get() {
14438 return this.result.processor;
14439 }
14440 },
14441 {
14442 key: "root",
14443 get: function get() {
14444 if (this._root) {
14445 return this._root;
14446 }
14447 var root2;
14448 var parser2 = parse$1$1;
14449 try {
14450 root2 = parser2(this._css, this._opts);
14451 } catch (error) {
14452 this.error = error;
14453 }
14454 if (this.error) {
14455 throw this.error;
14456 } else {
14457 this._root = root2;
14458 return root2;
14459 }
14460 }
14461 },
14462 {
14463 key: Symbol.toStringTag,
14464 get: function get() {
14465 return "NoWorkResult";
14466 }
14467 }
14468 ]);
14469 return NoWorkResult;
14470 }();
14471 var noWorkResult$1 = NoWorkResult$1$1;
14472 NoWorkResult$1$1.default = NoWorkResult$1$1;
14473 var NoWorkResult2$1 = noWorkResult$1;
14474 var LazyResult$1$1 = lazyResult$1;
14475 var Document$1$1 = document$1$1;
14476 var Root$2$1 = root$1;
14477 var Processor$1$1 = /*#__PURE__*/ function() {
14478 function Processor(plugins) {
14479 if (plugins === void 0) plugins = [];
14480 this.version = "8.4.38";
14481 this.plugins = this.normalize(plugins);
14482 }
14483 var _proto = Processor.prototype;
14484 _proto.normalize = function normalize(plugins) {
14485 var normalized = [];
14486 for(var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;){
14487 var i2 = _step.value;
14488 if (i2.postcss === true) {
14489 i2 = i2();
14490 } else if (i2.postcss) {
14491 i2 = i2.postcss;
14492 }
14493 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) {
14494 normalized = normalized.concat(i2.plugins);
14495 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) {
14496 normalized.push(i2);
14497 } else if (typeof i2 === "function") {
14498 normalized.push(i2);
14499 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) {
14500 if (true) {
14501 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.");
14502 }
14503 } else {
14504 throw new Error(i2 + " is not a PostCSS plugin");
14505 }
14506 }
14507 return normalized;
14508 };
14509 _proto.process = function process1(css, opts) {
14510 if (opts === void 0) opts = {};
14511 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
14512 return new NoWorkResult2$1(this, css, opts);
14513 } else {
14514 return new LazyResult$1$1(this, css, opts);
14515 }
14516 };
14517 _proto.use = function use(plugin22) {
14518 this.plugins = this.plugins.concat(this.normalize([
14519 plugin22
14520 ]));
14521 return this;
14522 };
14523 return Processor;
14524 }();
14525 var processor$1 = Processor$1$1;
14526 Processor$1$1.default = Processor$1$1;
14527 Root$2$1.registerProcessor(Processor$1$1);
14528 Document$1$1.registerProcessor(Processor$1$1);
14529 var Declaration$1$1 = declaration$1;
14530 var PreviousMap2$1 = previousMap$1;
14531 var Comment$1$1 = comment$1;
14532 var AtRule$1$1 = atRule$1;
14533 var Input$1$1 = input$1;
14534 var Root$1$1 = root$1;
14535 var Rule$1$1 = rule$1;
14536 function fromJSON$1$1(json, inputs) {
14537 if (Array.isArray(json)) return json.map(function(n2) {
14538 return fromJSON$1$1(n2);
14539 });
14540 var ownInputs = json.inputs, defaults = _object_without_properties_loose(json, [
14541 "inputs"
14542 ]);
14543 if (ownInputs) {
14544 inputs = [];
14545 for(var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;){
14546 var input2 = _step.value;
14547 var inputHydrated = _extends({}, input2, {
14548 __proto__: Input$1$1.prototype
14549 });
14550 if (inputHydrated.map) {
14551 inputHydrated.map = _extends({}, inputHydrated.map, {
14552 __proto__: PreviousMap2$1.prototype
14553 });
14554 }
14555 inputs.push(inputHydrated);
14556 }
14557 }
14558 if (defaults.nodes) {
14559 defaults.nodes = json.nodes.map(function(n2) {
14560 return fromJSON$1$1(n2, inputs);
14561 });
14562 }
14563 if (defaults.source) {
14564 var _defaults_source = defaults.source, inputId = _defaults_source.inputId, source = _object_without_properties_loose(_defaults_source, [
14565 "inputId"
14566 ]);
14567 defaults.source = source;
14568 if (inputId != null) {
14569 defaults.source.input = inputs[inputId];
14570 }
14571 }
14572 if (defaults.type === "root") {
14573 return new Root$1$1(defaults);
14574 } else if (defaults.type === "decl") {
14575 return new Declaration$1$1(defaults);
14576 } else if (defaults.type === "rule") {
14577 return new Rule$1$1(defaults);
14578 } else if (defaults.type === "comment") {
14579 return new Comment$1$1(defaults);
14580 } else if (defaults.type === "atrule") {
14581 return new AtRule$1$1(defaults);
14582 } else {
14583 throw new Error("Unknown node type: " + json.type);
14584 }
14585 }
14586 var fromJSON_1$1 = fromJSON$1$1;
14587 fromJSON$1$1.default = fromJSON$1$1;
14588 var CssSyntaxError2$1 = cssSyntaxError$1;
14589 var Declaration2$1 = declaration$1;
14590 var LazyResult2$1 = lazyResult$1;
14591 var Container2$1 = container$1;
14592 var Processor2$1 = processor$1;
14593 var stringify$5 = stringify_1$1;
14594 var fromJSON$2 = fromJSON_1$1;
14595 var Document22 = document$1$1;
14596 var Warning2$1 = warning$1;
14597 var Comment2$1 = comment$1;
14598 var AtRule2$1 = atRule$1;
14599 var Result2$1 = result$1;
14600 var Input2$1 = input$1;
14601 var parse$5 = parse_1$1;
14602 var list$3 = list_1$1;
14603 var Rule2$1 = rule$1;
14604 var Root2$1 = root$1;
14605 var Node2$1 = node$1;
14606 function postcss$3() {
14607 for(var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++){
14608 plugins[_key] = arguments[_key];
14609 }
14610 if (plugins.length === 1 && Array.isArray(plugins[0])) {
14611 plugins = plugins[0];
14612 }
14613 return new Processor2$1(plugins);
14614 }
14615 postcss$3.plugin = function plugin(name, initializer) {
14616 var warningPrinted = false;
14617 function creator() {
14618 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
14619 args[_key] = arguments[_key];
14620 }
14621 if (console && console.warn && !warningPrinted) {
14622 warningPrinted = true;
14623 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
14624 if (process.env.LANG && process.env.LANG.startsWith("cn")) {
14625 console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
14626 }
14627 }
14628 var transformer = initializer.apply(void 0, [].concat(args));
14629 transformer.postcssPlugin = name;
14630 transformer.postcssVersion = new Processor2$1().version;
14631 return transformer;
14632 }
14633 var cache;
14634 Object.defineProperty(creator, "postcss", {
14635 get: function get() {
14636 if (!cache) cache = creator();
14637 return cache;
14638 }
14639 });
14640 creator.process = function(css, processOpts, pluginOpts) {
14641 return postcss$3([
14642 creator(pluginOpts)
14643 ]).process(css, processOpts);
14644 };
14645 return creator;
14646 };
14647 postcss$3.stringify = stringify$5;
14648 postcss$3.parse = parse$5;
14649 postcss$3.fromJSON = fromJSON$2;
14650 postcss$3.list = list$3;
14651 postcss$3.comment = function(defaults) {
14652 return new Comment2$1(defaults);
14653 };
14654 postcss$3.atRule = function(defaults) {
14655 return new AtRule2$1(defaults);
14656 };
14657 postcss$3.decl = function(defaults) {
14658 return new Declaration2$1(defaults);
14659 };
14660 postcss$3.rule = function(defaults) {
14661 return new Rule2$1(defaults);
14662 };
14663 postcss$3.root = function(defaults) {
14664 return new Root2$1(defaults);
14665 };
14666 postcss$3.document = function(defaults) {
14667 return new Document22(defaults);
14668 };
14669 postcss$3.CssSyntaxError = CssSyntaxError2$1;
14670 postcss$3.Declaration = Declaration2$1;
14671 postcss$3.Container = Container2$1;
14672 postcss$3.Processor = Processor2$1;
14673 postcss$3.Document = Document22;
14674 postcss$3.Comment = Comment2$1;
14675 postcss$3.Warning = Warning2$1;
14676 postcss$3.AtRule = AtRule2$1;
14677 postcss$3.Result = Result2$1;
14678 postcss$3.Input = Input2$1;
14679 postcss$3.Rule = Rule2$1;
14680 postcss$3.Root = Root2$1;
14681 postcss$3.Node = Node2$1;
14682 LazyResult2$1.registerPostcss(postcss$3);
14683 var postcss_1$1 = postcss$3;
14684 postcss$3.default = postcss$3;
14685 var postcss$1$1 = /* @__PURE__ */ getDefaultExportFromCjs$1(postcss_1$1);
14686 postcss$1$1.stringify;
14687 postcss$1$1.fromJSON;
14688 postcss$1$1.plugin;
14689 postcss$1$1.parse;
14690 postcss$1$1.list;
14691 postcss$1$1.document;
14692 postcss$1$1.comment;
14693 postcss$1$1.atRule;
14694 postcss$1$1.rule;
14695 postcss$1$1.decl;
14696 postcss$1$1.root;
14697 postcss$1$1.CssSyntaxError;
14698 postcss$1$1.Declaration;
14699 postcss$1$1.Container;
14700 postcss$1$1.Processor;
14701 postcss$1$1.Document;
14702 postcss$1$1.Comment;
14703 postcss$1$1.Warning;
14704 postcss$1$1.AtRule;
14705 postcss$1$1.Result;
14706 postcss$1$1.Input;
14707 postcss$1$1.Rule;
14708 postcss$1$1.Root;
14709 postcss$1$1.Node;
14710 var __defProp2 = Object.defineProperty;
14711 var __defNormalProp2 = function(obj, key, value) {
14712 return key in obj ? __defProp2(obj, key, {
14713 enumerable: true,
14714 configurable: true,
14715 writable: true,
14716 value: value
14717 }) : obj[key] = value;
14718 };
14719 var __publicField2 = function(obj, key, value) {
14720 return __defNormalProp2(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
14721 };
14722 function getDefaultExportFromCjs(x2) {
14723 return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
14724 }
14725 function getAugmentedNamespace(n2) {
14726 if (n2.__esModule) return n2;
14727 var f2 = n2.default;
14728 if (typeof f2 == "function") {
14729 var a2 = function a22() {
14730 if (_instanceof(this, a22)) {
14731 return Reflect.construct(f2, arguments, this.constructor);
14732 }
14733 return f2.apply(this, arguments);
14734 };
14735 a2.prototype = f2.prototype;
14736 } else a2 = {};
14737 Object.defineProperty(a2, "__esModule", {
14738 value: true
14739 });
14740 Object.keys(n2).forEach(function(k) {
14741 var d = Object.getOwnPropertyDescriptor(n2, k);
14742 Object.defineProperty(a2, k, d.get ? d : {
14743 enumerable: true,
14744 get: function get() {
14745 return n2[k];
14746 }
14747 });
14748 });
14749 return a2;
14750 }
14751 var picocolors_browser = {
14752 exports: {}
14753 };
14754 var x = String;
14755 var create = function create() {
14756 return {
14757 isColorSupported: false,
14758 reset: x,
14759 bold: x,
14760 dim: x,
14761 italic: x,
14762 underline: x,
14763 inverse: x,
14764 hidden: x,
14765 strikethrough: x,
14766 black: x,
14767 red: x,
14768 green: x,
14769 yellow: x,
14770 blue: x,
14771 magenta: x,
14772 cyan: x,
14773 white: x,
14774 gray: x,
14775 bgBlack: x,
14776 bgRed: x,
14777 bgGreen: x,
14778 bgYellow: x,
14779 bgBlue: x,
14780 bgMagenta: x,
14781 bgCyan: x,
14782 bgWhite: x
14783 };
14784 };
14785 picocolors_browser.exports = create();
14786 picocolors_browser.exports.createColors = create;
14787 var picocolors_browserExports = picocolors_browser.exports;
14788 var __viteBrowserExternal = {};
14789 var __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
14790 __proto__: null,
14791 default: __viteBrowserExternal
14792 }, Symbol.toStringTag, {
14793 value: "Module"
14794 }));
14795 var require$$2 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
14796 var pico = picocolors_browserExports;
14797 var terminalHighlight$1 = require$$2;
14798 var CssSyntaxError$3 = /*#__PURE__*/ function(Error1) {
14799 _inherits(CssSyntaxError2, Error1);
14800 function CssSyntaxError2(message, line, column, source, file, plugin22) {
14801 var _this;
14802 _this = Error1.call(this, message) || this;
14803 _this.name = "CssSyntaxError";
14804 _this.reason = message;
14805 if (file) {
14806 _this.file = file;
14807 }
14808 if (source) {
14809 _this.source = source;
14810 }
14811 if (plugin22) {
14812 _this.plugin = plugin22;
14813 }
14814 if (typeof line !== "undefined" && typeof column !== "undefined") {
14815 if (typeof line === "number") {
14816 _this.line = line;
14817 _this.column = column;
14818 } else {
14819 _this.line = line.line;
14820 _this.column = line.column;
14821 _this.endLine = column.line;
14822 _this.endColumn = column.column;
14823 }
14824 }
14825 _this.setMessage();
14826 if (Error.captureStackTrace) {
14827 Error.captureStackTrace(_this, CssSyntaxError2);
14828 }
14829 return _this;
14830 }
14831 var _proto = CssSyntaxError2.prototype;
14832 _proto.setMessage = function setMessage() {
14833 this.message = this.plugin ? this.plugin + ": " : "";
14834 this.message += this.file ? this.file : "<css input>";
14835 if (typeof this.line !== "undefined") {
14836 this.message += ":" + this.line + ":" + this.column;
14837 }
14838 this.message += ": " + this.reason;
14839 };
14840 _proto.showSourceCode = function showSourceCode(color) {
14841 var _this = this;
14842 if (!this.source) return "";
14843 var css = this.source;
14844 if (color == null) color = pico.isColorSupported;
14845 if (terminalHighlight$1) {
14846 if (color) css = terminalHighlight$1(css);
14847 }
14848 var lines = css.split(/\r?\n/);
14849 var start = Math.max(this.line - 3, 0);
14850 var end = Math.min(this.line + 2, lines.length);
14851 var maxWidth = String(end).length;
14852 var mark, aside;
14853 if (color) {
14854 var _pico_createColors = pico.createColors(true), bold = _pico_createColors.bold, gray = _pico_createColors.gray, red = _pico_createColors.red;
14855 mark = function(text) {
14856 return bold(red(text));
14857 };
14858 aside = function(text) {
14859 return gray(text);
14860 };
14861 } else {
14862 mark = aside = function(str) {
14863 return str;
14864 };
14865 }
14866 return lines.slice(start, end).map(function(line, index2) {
14867 var number = start + 1 + index2;
14868 var gutter = " " + (" " + number).slice(-maxWidth) + " | ";
14869 if (number === _this.line) {
14870 var spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, _this.column - 1).replace(/[^\t]/g, " ");
14871 return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
14872 }
14873 return " " + aside(gutter) + line;
14874 }).join("\n");
14875 };
14876 _proto.toString = function toString() {
14877 var code = this.showSourceCode();
14878 if (code) {
14879 code = "\n\n" + code + "\n";
14880 }
14881 return this.name + ": " + this.message + code;
14882 };
14883 return CssSyntaxError2;
14884 }(_wrap_native_super(Error));
14885 var cssSyntaxError = CssSyntaxError$3;
14886 CssSyntaxError$3.default = CssSyntaxError$3;
14887 var symbols = {};
14888 symbols.isClean = Symbol("isClean");
14889 symbols.my = Symbol("my");
14890 var DEFAULT_RAW = {
14891 after: "\n",
14892 beforeClose: "\n",
14893 beforeComment: "\n",
14894 beforeDecl: "\n",
14895 beforeOpen: " ",
14896 beforeRule: "\n",
14897 colon: ": ",
14898 commentLeft: " ",
14899 commentRight: " ",
14900 emptyBody: "",
14901 indent: " ",
14902 semicolon: false
14903 };
14904 function capitalize(str) {
14905 return str[0].toUpperCase() + str.slice(1);
14906 }
14907 var Stringifier$2 = /*#__PURE__*/ function() {
14908 function Stringifier2(builder) {
14909 this.builder = builder;
14910 }
14911 var _proto = Stringifier2.prototype;
14912 _proto.atrule = function atrule(node2, semicolon) {
14913 var name = "@" + node2.name;
14914 var params = node2.params ? this.rawValue(node2, "params") : "";
14915 if (typeof node2.raws.afterName !== "undefined") {
14916 name += node2.raws.afterName;
14917 } else if (params) {
14918 name += " ";
14919 }
14920 if (node2.nodes) {
14921 this.block(node2, name + params);
14922 } else {
14923 var end = (node2.raws.between || "") + (semicolon ? ";" : "");
14924 this.builder(name + params + end, node2);
14925 }
14926 };
14927 _proto.beforeAfter = function beforeAfter(node2, detect) {
14928 var value;
14929 if (node2.type === "decl") {
14930 value = this.raw(node2, null, "beforeDecl");
14931 } else if (node2.type === "comment") {
14932 value = this.raw(node2, null, "beforeComment");
14933 } else if (detect === "before") {
14934 value = this.raw(node2, null, "beforeRule");
14935 } else {
14936 value = this.raw(node2, null, "beforeClose");
14937 }
14938 var buf = node2.parent;
14939 var depth = 0;
14940 while(buf && buf.type !== "root"){
14941 depth += 1;
14942 buf = buf.parent;
14943 }
14944 if (value.includes("\n")) {
14945 var indent = this.raw(node2, null, "indent");
14946 if (indent.length) {
14947 for(var step = 0; step < depth; step++)value += indent;
14948 }
14949 }
14950 return value;
14951 };
14952 _proto.block = function block(node2, start) {
14953 var between = this.raw(node2, "between", "beforeOpen");
14954 this.builder(start + between + "{", node2, "start");
14955 var after;
14956 if (node2.nodes && node2.nodes.length) {
14957 this.body(node2);
14958 after = this.raw(node2, "after");
14959 } else {
14960 after = this.raw(node2, "after", "emptyBody");
14961 }
14962 if (after) this.builder(after);
14963 this.builder("}", node2, "end");
14964 };
14965 _proto.body = function body(node2) {
14966 var last = node2.nodes.length - 1;
14967 while(last > 0){
14968 if (node2.nodes[last].type !== "comment") break;
14969 last -= 1;
14970 }
14971 var semicolon = this.raw(node2, "semicolon");
14972 for(var i2 = 0; i2 < node2.nodes.length; i2++){
14973 var child = node2.nodes[i2];
14974 var before = this.raw(child, "before");
14975 if (before) this.builder(before);
14976 this.stringify(child, last !== i2 || semicolon);
14977 }
14978 };
14979 _proto.comment = function comment(node2) {
14980 var left = this.raw(node2, "left", "commentLeft");
14981 var right = this.raw(node2, "right", "commentRight");
14982 this.builder("/*" + left + node2.text + right + "*/", node2);
14983 };
14984 _proto.decl = function decl(node2, semicolon) {
14985 var between = this.raw(node2, "between", "colon");
14986 var string = node2.prop + between + this.rawValue(node2, "value");
14987 if (node2.important) {
14988 string += node2.raws.important || " !important";
14989 }
14990 if (semicolon) string += ";";
14991 this.builder(string, node2);
14992 };
14993 _proto.document = function document1(node2) {
14994 this.body(node2);
14995 };
14996 _proto.raw = function raw(node2, own, detect) {
14997 var value;
14998 if (!detect) detect = own;
14999 if (own) {
15000 value = node2.raws[own];
15001 if (typeof value !== "undefined") return value;
15002 }
15003 var parent = node2.parent;
15004 if (detect === "before") {
15005 if (!parent || parent.type === "root" && parent.first === node2) {
15006 return "";
15007 }
15008 if (parent && parent.type === "document") {
15009 return "";
15010 }
15011 }
15012 if (!parent) return DEFAULT_RAW[detect];
15013 var root2 = node2.root();
15014 if (!root2.rawCache) root2.rawCache = {};
15015 if (typeof root2.rawCache[detect] !== "undefined") {
15016 return root2.rawCache[detect];
15017 }
15018 if (detect === "before" || detect === "after") {
15019 return this.beforeAfter(node2, detect);
15020 } else {
15021 var method = "raw" + capitalize(detect);
15022 if (this[method]) {
15023 value = this[method](root2, node2);
15024 } else {
15025 root2.walk(function(i2) {
15026 value = i2.raws[own];
15027 if (typeof value !== "undefined") return false;
15028 });
15029 }
15030 }
15031 if (typeof value === "undefined") value = DEFAULT_RAW[detect];
15032 root2.rawCache[detect] = value;
15033 return value;
15034 };
15035 _proto.rawBeforeClose = function rawBeforeClose(root2) {
15036 var value;
15037 root2.walk(function(i2) {
15038 if (i2.nodes && i2.nodes.length > 0) {
15039 if (typeof i2.raws.after !== "undefined") {
15040 value = i2.raws.after;
15041 if (value.includes("\n")) {
15042 value = value.replace(/[^\n]+$/, "");
15043 }
15044 return false;
15045 }
15046 }
15047 });
15048 if (value) value = value.replace(/\S/g, "");
15049 return value;
15050 };
15051 _proto.rawBeforeComment = function rawBeforeComment(root2, node2) {
15052 var value;
15053 root2.walkComments(function(i2) {
15054 if (typeof i2.raws.before !== "undefined") {
15055 value = i2.raws.before;
15056 if (value.includes("\n")) {
15057 value = value.replace(/[^\n]+$/, "");
15058 }
15059 return false;
15060 }
15061 });
15062 if (typeof value === "undefined") {
15063 value = this.raw(node2, null, "beforeDecl");
15064 } else if (value) {
15065 value = value.replace(/\S/g, "");
15066 }
15067 return value;
15068 };
15069 _proto.rawBeforeDecl = function rawBeforeDecl(root2, node2) {
15070 var value;
15071 root2.walkDecls(function(i2) {
15072 if (typeof i2.raws.before !== "undefined") {
15073 value = i2.raws.before;
15074 if (value.includes("\n")) {
15075 value = value.replace(/[^\n]+$/, "");
15076 }
15077 return false;
15078 }
15079 });
15080 if (typeof value === "undefined") {
15081 value = this.raw(node2, null, "beforeRule");
15082 } else if (value) {
15083 value = value.replace(/\S/g, "");
15084 }
15085 return value;
15086 };
15087 _proto.rawBeforeOpen = function rawBeforeOpen(root2) {
15088 var value;
15089 root2.walk(function(i2) {
15090 if (i2.type !== "decl") {
15091 value = i2.raws.between;
15092 if (typeof value !== "undefined") return false;
15093 }
15094 });
15095 return value;
15096 };
15097 _proto.rawBeforeRule = function rawBeforeRule(root2) {
15098 var value;
15099 root2.walk(function(i2) {
15100 if (i2.nodes && (i2.parent !== root2 || root2.first !== i2)) {
15101 if (typeof i2.raws.before !== "undefined") {
15102 value = i2.raws.before;
15103 if (value.includes("\n")) {
15104 value = value.replace(/[^\n]+$/, "");
15105 }
15106 return false;
15107 }
15108 }
15109 });
15110 if (value) value = value.replace(/\S/g, "");
15111 return value;
15112 };
15113 _proto.rawColon = function rawColon(root2) {
15114 var value;
15115 root2.walkDecls(function(i2) {
15116 if (typeof i2.raws.between !== "undefined") {
15117 value = i2.raws.between.replace(/[^\s:]/g, "");
15118 return false;
15119 }
15120 });
15121 return value;
15122 };
15123 _proto.rawEmptyBody = function rawEmptyBody(root2) {
15124 var value;
15125 root2.walk(function(i2) {
15126 if (i2.nodes && i2.nodes.length === 0) {
15127 value = i2.raws.after;
15128 if (typeof value !== "undefined") return false;
15129 }
15130 });
15131 return value;
15132 };
15133 _proto.rawIndent = function rawIndent(root2) {
15134 if (root2.raws.indent) return root2.raws.indent;
15135 var value;
15136 root2.walk(function(i2) {
15137 var p = i2.parent;
15138 if (p && p !== root2 && p.parent && p.parent === root2) {
15139 if (typeof i2.raws.before !== "undefined") {
15140 var parts = i2.raws.before.split("\n");
15141 value = parts[parts.length - 1];
15142 value = value.replace(/\S/g, "");
15143 return false;
15144 }
15145 }
15146 });
15147 return value;
15148 };
15149 _proto.rawSemicolon = function rawSemicolon(root2) {
15150 var value;
15151 root2.walk(function(i2) {
15152 if (i2.nodes && i2.nodes.length && i2.last.type === "decl") {
15153 value = i2.raws.semicolon;
15154 if (typeof value !== "undefined") return false;
15155 }
15156 });
15157 return value;
15158 };
15159 _proto.rawValue = function rawValue(node2, prop) {
15160 var value = node2[prop];
15161 var raw = node2.raws[prop];
15162 if (raw && raw.value === value) {
15163 return raw.raw;
15164 }
15165 return value;
15166 };
15167 _proto.root = function root(node2) {
15168 this.body(node2);
15169 if (node2.raws.after) this.builder(node2.raws.after);
15170 };
15171 _proto.rule = function rule(node2) {
15172 this.block(node2, this.rawValue(node2, "selector"));
15173 if (node2.raws.ownSemicolon) {
15174 this.builder(node2.raws.ownSemicolon, node2, "end");
15175 }
15176 };
15177 _proto.stringify = function stringify(node2, semicolon) {
15178 if (!this[node2.type]) {
15179 throw new Error("Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier.");
15180 }
15181 this[node2.type](node2, semicolon);
15182 };
15183 return Stringifier2;
15184 }();
15185 var stringifier = Stringifier$2;
15186 Stringifier$2.default = Stringifier$2;
15187 var Stringifier$1 = stringifier;
15188 function stringify$4(node2, builder) {
15189 var str = new Stringifier$1(builder);
15190 str.stringify(node2);
15191 }
15192 var stringify_1 = stringify$4;
15193 stringify$4.default = stringify$4;
15194 var isClean$2 = symbols.isClean, my$2 = symbols.my;
15195 var CssSyntaxError$2 = cssSyntaxError;
15196 var Stringifier22 = stringifier;
15197 var stringify$3 = stringify_1;
15198 function cloneNode(obj, parent) {
15199 var cloned = new obj.constructor();
15200 for(var i2 in obj){
15201 if (!Object.prototype.hasOwnProperty.call(obj, i2)) {
15202 continue;
15203 }
15204 if (i2 === "proxyCache") continue;
15205 var value = obj[i2];
15206 var type = typeof value === "undefined" ? "undefined" : _type_of(value);
15207 if (i2 === "parent" && type === "object") {
15208 if (parent) cloned[i2] = parent;
15209 } else if (i2 === "source") {
15210 cloned[i2] = value;
15211 } else if (Array.isArray(value)) {
15212 cloned[i2] = value.map(function(j) {
15213 return cloneNode(j, cloned);
15214 });
15215 } else {
15216 if (type === "object" && value !== null) value = cloneNode(value);
15217 cloned[i2] = value;
15218 }
15219 }
15220 return cloned;
15221 }
15222 var Node$4 = /*#__PURE__*/ function() {
15223 function Node3(defaults) {
15224 if (defaults === void 0) defaults = {};
15225 this.raws = {};
15226 this[isClean$2] = false;
15227 this[my$2] = true;
15228 for(var name in defaults){
15229 if (name === "nodes") {
15230 this.nodes = [];
15231 for(var _iterator = _create_for_of_iterator_helper_loose(defaults[name]), _step; !(_step = _iterator()).done;){
15232 var node2 = _step.value;
15233 if (typeof node2.clone === "function") {
15234 this.append(node2.clone());
15235 } else {
15236 this.append(node2);
15237 }
15238 }
15239 } else {
15240 this[name] = defaults[name];
15241 }
15242 }
15243 }
15244 var _proto = Node3.prototype;
15245 _proto.addToError = function addToError(error) {
15246 error.postcssNode = this;
15247 if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) {
15248 var s2 = this.source;
15249 error.stack = error.stack.replace(/\n\s{4}at /, "$&" + s2.input.from + ":" + s2.start.line + ":" + s2.start.column + "$&");
15250 }
15251 return error;
15252 };
15253 _proto.after = function after(add) {
15254 this.parent.insertAfter(this, add);
15255 return this;
15256 };
15257 _proto.assign = function assign(overrides) {
15258 if (overrides === void 0) overrides = {};
15259 for(var name in overrides){
15260 this[name] = overrides[name];
15261 }
15262 return this;
15263 };
15264 _proto.before = function before(add) {
15265 this.parent.insertBefore(this, add);
15266 return this;
15267 };
15268 _proto.cleanRaws = function cleanRaws(keepBetween) {
15269 delete this.raws.before;
15270 delete this.raws.after;
15271 if (!keepBetween) delete this.raws.between;
15272 };
15273 _proto.clone = function clone(overrides) {
15274 if (overrides === void 0) overrides = {};
15275 var cloned = cloneNode(this);
15276 for(var name in overrides){
15277 cloned[name] = overrides[name];
15278 }
15279 return cloned;
15280 };
15281 _proto.cloneAfter = function cloneAfter(overrides) {
15282 if (overrides === void 0) overrides = {};
15283 var cloned = this.clone(overrides);
15284 this.parent.insertAfter(this, cloned);
15285 return cloned;
15286 };
15287 _proto.cloneBefore = function cloneBefore(overrides) {
15288 if (overrides === void 0) overrides = {};
15289 var cloned = this.clone(overrides);
15290 this.parent.insertBefore(this, cloned);
15291 return cloned;
15292 };
15293 _proto.error = function error(message, opts) {
15294 if (opts === void 0) opts = {};
15295 if (this.source) {
15296 var _this_rangeBy = this.rangeBy(opts), end = _this_rangeBy.end, start = _this_rangeBy.start;
15297 return this.source.input.error(message, {
15298 column: start.column,
15299 line: start.line
15300 }, {
15301 column: end.column,
15302 line: end.line
15303 }, opts);
15304 }
15305 return new CssSyntaxError$2(message);
15306 };
15307 _proto.getProxyProcessor = function getProxyProcessor() {
15308 return {
15309 get: function get(node2, prop) {
15310 if (prop === "proxyOf") {
15311 return node2;
15312 } else if (prop === "root") {
15313 return function() {
15314 return node2.root().toProxy();
15315 };
15316 } else {
15317 return node2[prop];
15318 }
15319 },
15320 set: function set(node2, prop, value) {
15321 if (node2[prop] === value) return true;
15322 node2[prop] = value;
15323 if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */ prop === "text") {
15324 node2.markDirty();
15325 }
15326 return true;
15327 }
15328 };
15329 };
15330 _proto.markDirty = function markDirty() {
15331 if (this[isClean$2]) {
15332 this[isClean$2] = false;
15333 var next = this;
15334 while(next = next.parent){
15335 next[isClean$2] = false;
15336 }
15337 }
15338 };
15339 _proto.next = function next() {
15340 if (!this.parent) return void 0;
15341 var index2 = this.parent.index(this);
15342 return this.parent.nodes[index2 + 1];
15343 };
15344 _proto.positionBy = function positionBy(opts, stringRepresentation) {
15345 var pos = this.source.start;
15346 if (opts.index) {
15347 pos = this.positionInside(opts.index, stringRepresentation);
15348 } else if (opts.word) {
15349 stringRepresentation = this.toString();
15350 var index2 = stringRepresentation.indexOf(opts.word);
15351 if (index2 !== -1) pos = this.positionInside(index2, stringRepresentation);
15352 }
15353 return pos;
15354 };
15355 _proto.positionInside = function positionInside(index2, stringRepresentation) {
15356 var string = stringRepresentation || this.toString();
15357 var column = this.source.start.column;
15358 var line = this.source.start.line;
15359 for(var i2 = 0; i2 < index2; i2++){
15360 if (string[i2] === "\n") {
15361 column = 1;
15362 line += 1;
15363 } else {
15364 column += 1;
15365 }
15366 }
15367 return {
15368 column: column,
15369 line: line
15370 };
15371 };
15372 _proto.prev = function prev() {
15373 if (!this.parent) return void 0;
15374 var index2 = this.parent.index(this);
15375 return this.parent.nodes[index2 - 1];
15376 };
15377 _proto.rangeBy = function rangeBy(opts) {
15378 var start = {
15379 column: this.source.start.column,
15380 line: this.source.start.line
15381 };
15382 var end = this.source.end ? {
15383 column: this.source.end.column + 1,
15384 line: this.source.end.line
15385 } : {
15386 column: start.column + 1,
15387 line: start.line
15388 };
15389 if (opts.word) {
15390 var stringRepresentation = this.toString();
15391 var index2 = stringRepresentation.indexOf(opts.word);
15392 if (index2 !== -1) {
15393 start = this.positionInside(index2, stringRepresentation);
15394 end = this.positionInside(index2 + opts.word.length, stringRepresentation);
15395 }
15396 } else {
15397 if (opts.start) {
15398 start = {
15399 column: opts.start.column,
15400 line: opts.start.line
15401 };
15402 } else if (opts.index) {
15403 start = this.positionInside(opts.index);
15404 }
15405 if (opts.end) {
15406 end = {
15407 column: opts.end.column,
15408 line: opts.end.line
15409 };
15410 } else if (typeof opts.endIndex === "number") {
15411 end = this.positionInside(opts.endIndex);
15412 } else if (opts.index) {
15413 end = this.positionInside(opts.index + 1);
15414 }
15415 }
15416 if (end.line < start.line || end.line === start.line && end.column <= start.column) {
15417 end = {
15418 column: start.column + 1,
15419 line: start.line
15420 };
15421 }
15422 return {
15423 end: end,
15424 start: start
15425 };
15426 };
15427 _proto.raw = function raw(prop, defaultType) {
15428 var str = new Stringifier22();
15429 return str.raw(this, prop, defaultType);
15430 };
15431 _proto.remove = function remove() {
15432 if (this.parent) {
15433 this.parent.removeChild(this);
15434 }
15435 this.parent = void 0;
15436 return this;
15437 };
15438 _proto.replaceWith = function replaceWith() {
15439 for(var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++){
15440 nodes[_key] = arguments[_key];
15441 }
15442 if (this.parent) {
15443 var bookmark = this;
15444 var foundSelf = false;
15445 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
15446 var node2 = _step.value;
15447 if (node2 === this) {
15448 foundSelf = true;
15449 } else if (foundSelf) {
15450 this.parent.insertAfter(bookmark, node2);
15451 bookmark = node2;
15452 } else {
15453 this.parent.insertBefore(bookmark, node2);
15454 }
15455 }
15456 if (!foundSelf) {
15457 this.remove();
15458 }
15459 }
15460 return this;
15461 };
15462 _proto.root = function root() {
15463 var result2 = this;
15464 while(result2.parent && result2.parent.type !== "document"){
15465 result2 = result2.parent;
15466 }
15467 return result2;
15468 };
15469 _proto.toJSON = function toJSON(_, inputs) {
15470 var fixed = {};
15471 var emitInputs = inputs == null;
15472 inputs = inputs || /* @__PURE__ */ new Map();
15473 var inputsNextIndex = 0;
15474 for(var name in this){
15475 if (!Object.prototype.hasOwnProperty.call(this, name)) {
15476 continue;
15477 }
15478 if (name === "parent" || name === "proxyCache") continue;
15479 var value = this[name];
15480 if (Array.isArray(value)) {
15481 fixed[name] = value.map(function(i2) {
15482 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.toJSON) {
15483 return i2.toJSON(null, inputs);
15484 } else {
15485 return i2;
15486 }
15487 });
15488 } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value.toJSON) {
15489 fixed[name] = value.toJSON(null, inputs);
15490 } else if (name === "source") {
15491 var inputId = inputs.get(value.input);
15492 if (inputId == null) {
15493 inputId = inputsNextIndex;
15494 inputs.set(value.input, inputsNextIndex);
15495 inputsNextIndex++;
15496 }
15497 fixed[name] = {
15498 end: value.end,
15499 inputId: inputId,
15500 start: value.start
15501 };
15502 } else {
15503 fixed[name] = value;
15504 }
15505 }
15506 if (emitInputs) {
15507 fixed.inputs = [].concat(inputs.keys()).map(function(input2) {
15508 return input2.toJSON();
15509 });
15510 }
15511 return fixed;
15512 };
15513 _proto.toProxy = function toProxy() {
15514 if (!this.proxyCache) {
15515 this.proxyCache = new Proxy(this, this.getProxyProcessor());
15516 }
15517 return this.proxyCache;
15518 };
15519 _proto.toString = function toString(stringifier2) {
15520 if (stringifier2 === void 0) stringifier2 = stringify$3;
15521 if (stringifier2.stringify) stringifier2 = stringifier2.stringify;
15522 var result2 = "";
15523 stringifier2(this, function(i2) {
15524 result2 += i2;
15525 });
15526 return result2;
15527 };
15528 _proto.warn = function warn(result2, text, opts) {
15529 var data = {
15530 node: this
15531 };
15532 for(var i2 in opts)data[i2] = opts[i2];
15533 return result2.warn(text, data);
15534 };
15535 _create_class(Node3, [
15536 {
15537 key: "proxyOf",
15538 get: function get() {
15539 return this;
15540 }
15541 }
15542 ]);
15543 return Node3;
15544 }();
15545 var node = Node$4;
15546 Node$4.default = Node$4;
15547 var Node$3 = node;
15548 var Declaration$4 = /*#__PURE__*/ function(Node$3) {
15549 _inherits(Declaration2, Node$3);
15550 function Declaration2(defaults) {
15551 var _this;
15552 if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
15553 defaults = _extends({}, defaults, {
15554 value: String(defaults.value)
15555 });
15556 }
15557 _this = Node$3.call(this, defaults) || this;
15558 _this.type = "decl";
15559 return _this;
15560 }
15561 _create_class(Declaration2, [
15562 {
15563 key: "variable",
15564 get: function get() {
15565 return this.prop.startsWith("--") || this.prop[0] === "$";
15566 }
15567 }
15568 ]);
15569 return Declaration2;
15570 }(Node$3);
15571 var declaration = Declaration$4;
15572 Declaration$4.default = Declaration$4;
15573 var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
15574 var nanoid$1 = function(size) {
15575 if (size === void 0) size = 21;
15576 var id = "";
15577 var i2 = size;
15578 while(i2--){
15579 id += urlAlphabet[Math.random() * 64 | 0];
15580 }
15581 return id;
15582 };
15583 var nonSecure = {
15584 nanoid: nanoid$1};
15585 var SourceMapConsumer$2 = require$$2.SourceMapConsumer, SourceMapGenerator$2 = require$$2.SourceMapGenerator;
15586 var existsSync = require$$2.existsSync, readFileSync = require$$2.readFileSync;
15587 var dirname$1 = require$$2.dirname, join = require$$2.join;
15588 function fromBase64(str) {
15589 if (Buffer) {
15590 return Buffer.from(str, "base64").toString();
15591 } else {
15592 return window.atob(str);
15593 }
15594 }
15595 var PreviousMap$2 = /*#__PURE__*/ function() {
15596 function PreviousMap2(css, opts) {
15597 if (opts.map === false) return;
15598 this.loadAnnotation(css);
15599 this.inline = this.startWith(this.annotation, "data:");
15600 var prev = opts.map ? opts.map.prev : void 0;
15601 var text = this.loadMap(opts.from, prev);
15602 if (!this.mapFile && opts.from) {
15603 this.mapFile = opts.from;
15604 }
15605 if (this.mapFile) this.root = dirname$1(this.mapFile);
15606 if (text) this.text = text;
15607 }
15608 var _proto = PreviousMap2.prototype;
15609 _proto.consumer = function consumer() {
15610 if (!this.consumerCache) {
15611 this.consumerCache = new SourceMapConsumer$2(this.text);
15612 }
15613 return this.consumerCache;
15614 };
15615 _proto.decodeInline = function decodeInline(text) {
15616 var baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
15617 var baseUri = /^data:application\/json;base64,/;
15618 var charsetUri = /^data:application\/json;charset=utf-?8,/;
15619 var uri = /^data:application\/json,/;
15620 if (charsetUri.test(text) || uri.test(text)) {
15621 return decodeURIComponent(text.substr(RegExp.lastMatch.length));
15622 }
15623 if (baseCharsetUri.test(text) || baseUri.test(text)) {
15624 return fromBase64(text.substr(RegExp.lastMatch.length));
15625 }
15626 var encoding = text.match(/data:application\/json;([^,]+),/)[1];
15627 throw new Error("Unsupported source map encoding " + encoding);
15628 };
15629 _proto.getAnnotationURL = function getAnnotationURL(sourceMapString) {
15630 return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
15631 };
15632 _proto.isMap = function isMap(map) {
15633 if ((typeof map === "undefined" ? "undefined" : _type_of(map)) !== "object") return false;
15634 return typeof map.mappings === "string" || typeof map._mappings === "string" || Array.isArray(map.sections);
15635 };
15636 _proto.loadAnnotation = function loadAnnotation(css) {
15637 var comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
15638 if (!comments) return;
15639 var start = css.lastIndexOf(comments.pop());
15640 var end = css.indexOf("*/", start);
15641 if (start > -1 && end > -1) {
15642 this.annotation = this.getAnnotationURL(css.substring(start, end));
15643 }
15644 };
15645 _proto.loadFile = function loadFile(path) {
15646 this.root = dirname$1(path);
15647 if (existsSync(path)) {
15648 this.mapFile = path;
15649 return readFileSync(path, "utf-8").toString().trim();
15650 }
15651 };
15652 _proto.loadMap = function loadMap(file, prev) {
15653 if (prev === false) return false;
15654 if (prev) {
15655 if (typeof prev === "string") {
15656 return prev;
15657 } else if (typeof prev === "function") {
15658 var prevPath = prev(file);
15659 if (prevPath) {
15660 var map = this.loadFile(prevPath);
15661 if (!map) {
15662 throw new Error("Unable to load previous source map: " + prevPath.toString());
15663 }
15664 return map;
15665 }
15666 } else if (_instanceof(prev, SourceMapConsumer$2)) {
15667 return SourceMapGenerator$2.fromSourceMap(prev).toString();
15668 } else if (_instanceof(prev, SourceMapGenerator$2)) {
15669 return prev.toString();
15670 } else if (this.isMap(prev)) {
15671 return JSON.stringify(prev);
15672 } else {
15673 throw new Error("Unsupported previous source map format: " + prev.toString());
15674 }
15675 } else if (this.inline) {
15676 return this.decodeInline(this.annotation);
15677 } else if (this.annotation) {
15678 var map1 = this.annotation;
15679 if (file) map1 = join(dirname$1(file), map1);
15680 return this.loadFile(map1);
15681 }
15682 };
15683 _proto.startWith = function startWith(string, start) {
15684 if (!string) return false;
15685 return string.substr(0, start.length) === start;
15686 };
15687 _proto.withContent = function withContent() {
15688 return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
15689 };
15690 return PreviousMap2;
15691 }();
15692 var previousMap = PreviousMap$2;
15693 PreviousMap$2.default = PreviousMap$2;
15694 var SourceMapConsumer$1 = require$$2.SourceMapConsumer, SourceMapGenerator$1 = require$$2.SourceMapGenerator;
15695 var fileURLToPath = require$$2.fileURLToPath, pathToFileURL$1 = require$$2.pathToFileURL;
15696 var isAbsolute = require$$2.isAbsolute, resolve$1 = require$$2.resolve;
15697 var nanoid = nonSecure.nanoid;
15698 var terminalHighlight = require$$2;
15699 var CssSyntaxError$1 = cssSyntaxError;
15700 var PreviousMap$1 = previousMap;
15701 var fromOffsetCache = Symbol("fromOffsetCache");
15702 var sourceMapAvailable$1 = Boolean(SourceMapConsumer$1 && SourceMapGenerator$1);
15703 var pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
15704 var Input$4 = /*#__PURE__*/ function() {
15705 function Input2(css, opts) {
15706 if (opts === void 0) opts = {};
15707 if (css === null || typeof css === "undefined" || (typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && !css.toString) {
15708 throw new Error("PostCSS received " + css + " instead of CSS string");
15709 }
15710 this.css = css.toString();
15711 if (this.css[0] === "\uFEFF" || this.css[0] === "￾") {
15712 this.hasBOM = true;
15713 this.css = this.css.slice(1);
15714 } else {
15715 this.hasBOM = false;
15716 }
15717 if (opts.from) {
15718 if (!pathAvailable$1 || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from)) {
15719 this.file = opts.from;
15720 } else {
15721 this.file = resolve$1(opts.from);
15722 }
15723 }
15724 if (pathAvailable$1 && sourceMapAvailable$1) {
15725 var map = new PreviousMap$1(this.css, opts);
15726 if (map.text) {
15727 this.map = map;
15728 var file = map.consumer().file;
15729 if (!this.file && file) this.file = this.mapResolve(file);
15730 }
15731 }
15732 if (!this.file) {
15733 this.id = "<input css " + nanoid(6) + ">";
15734 }
15735 if (this.map) this.map.file = this.from;
15736 }
15737 var _proto = Input2.prototype;
15738 _proto.error = function error(message, line, column, opts) {
15739 if (opts === void 0) opts = {};
15740 var result2, endLine, endColumn;
15741 if (line && (typeof line === "undefined" ? "undefined" : _type_of(line)) === "object") {
15742 var start = line;
15743 var end = column;
15744 if (typeof start.offset === "number") {
15745 var pos = this.fromOffset(start.offset);
15746 line = pos.line;
15747 column = pos.col;
15748 } else {
15749 line = start.line;
15750 column = start.column;
15751 }
15752 if (typeof end.offset === "number") {
15753 var pos1 = this.fromOffset(end.offset);
15754 endLine = pos1.line;
15755 endColumn = pos1.col;
15756 } else {
15757 endLine = end.line;
15758 endColumn = end.column;
15759 }
15760 } else if (!column) {
15761 var pos2 = this.fromOffset(line);
15762 line = pos2.line;
15763 column = pos2.col;
15764 }
15765 var origin = this.origin(line, column, endLine, endColumn);
15766 if (origin) {
15767 result2 = new CssSyntaxError$1(message, origin.endLine === void 0 ? origin.line : {
15768 column: origin.column,
15769 line: origin.line
15770 }, origin.endLine === void 0 ? origin.column : {
15771 column: origin.endColumn,
15772 line: origin.endLine
15773 }, origin.source, origin.file, opts.plugin);
15774 } else {
15775 result2 = new CssSyntaxError$1(message, endLine === void 0 ? line : {
15776 column: column,
15777 line: line
15778 }, endLine === void 0 ? column : {
15779 column: endColumn,
15780 line: endLine
15781 }, this.css, this.file, opts.plugin);
15782 }
15783 result2.input = {
15784 column: column,
15785 endColumn: endColumn,
15786 endLine: endLine,
15787 line: line,
15788 source: this.css
15789 };
15790 if (this.file) {
15791 if (pathToFileURL$1) {
15792 result2.input.url = pathToFileURL$1(this.file).toString();
15793 }
15794 result2.input.file = this.file;
15795 }
15796 return result2;
15797 };
15798 _proto.fromOffset = function fromOffset(offset) {
15799 var lastLine, lineToIndex;
15800 if (!this[fromOffsetCache]) {
15801 var lines = this.css.split("\n");
15802 lineToIndex = new Array(lines.length);
15803 var prevIndex = 0;
15804 for(var i2 = 0, l2 = lines.length; i2 < l2; i2++){
15805 lineToIndex[i2] = prevIndex;
15806 prevIndex += lines[i2].length + 1;
15807 }
15808 this[fromOffsetCache] = lineToIndex;
15809 } else {
15810 lineToIndex = this[fromOffsetCache];
15811 }
15812 lastLine = lineToIndex[lineToIndex.length - 1];
15813 var min = 0;
15814 if (offset >= lastLine) {
15815 min = lineToIndex.length - 1;
15816 } else {
15817 var max = lineToIndex.length - 2;
15818 var mid;
15819 while(min < max){
15820 mid = min + (max - min >> 1);
15821 if (offset < lineToIndex[mid]) {
15822 max = mid - 1;
15823 } else if (offset >= lineToIndex[mid + 1]) {
15824 min = mid + 1;
15825 } else {
15826 min = mid;
15827 break;
15828 }
15829 }
15830 }
15831 return {
15832 col: offset - lineToIndex[min] + 1,
15833 line: min + 1
15834 };
15835 };
15836 _proto.mapResolve = function mapResolve(file) {
15837 if (/^\w+:\/\//.test(file)) {
15838 return file;
15839 }
15840 return resolve$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
15841 };
15842 _proto.origin = function origin(line, column, endLine, endColumn) {
15843 if (!this.map) return false;
15844 var consumer = this.map.consumer();
15845 var from = consumer.originalPositionFor({
15846 column: column,
15847 line: line
15848 });
15849 if (!from.source) return false;
15850 var to;
15851 if (typeof endLine === "number") {
15852 to = consumer.originalPositionFor({
15853 column: endColumn,
15854 line: endLine
15855 });
15856 }
15857 var fromUrl;
15858 if (isAbsolute(from.source)) {
15859 fromUrl = pathToFileURL$1(from.source);
15860 } else {
15861 fromUrl = new URL(from.source, this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile));
15862 }
15863 var result2 = {
15864 column: from.column,
15865 endColumn: to && to.column,
15866 endLine: to && to.line,
15867 line: from.line,
15868 url: fromUrl.toString()
15869 };
15870 if (fromUrl.protocol === "file:") {
15871 if (fileURLToPath) {
15872 result2.file = fileURLToPath(fromUrl);
15873 } else {
15874 throw new Error("file: protocol is not available in this PostCSS build");
15875 }
15876 }
15877 var source = consumer.sourceContentFor(from.source);
15878 if (source) result2.source = source;
15879 return result2;
15880 };
15881 _proto.toJSON = function toJSON() {
15882 var json = {};
15883 for(var _i = 0, _iter = [
15884 "hasBOM",
15885 "css",
15886 "file",
15887 "id"
15888 ]; _i < _iter.length; _i++){
15889 var name = _iter[_i];
15890 if (this[name] != null) {
15891 json[name] = this[name];
15892 }
15893 }
15894 if (this.map) {
15895 json.map = _extends({}, this.map);
15896 if (json.map.consumerCache) {
15897 json.map.consumerCache = void 0;
15898 }
15899 }
15900 return json;
15901 };
15902 _create_class(Input2, [
15903 {
15904 key: "from",
15905 get: function get() {
15906 return this.file || this.id;
15907 }
15908 }
15909 ]);
15910 return Input2;
15911 }();
15912 var input = Input$4;
15913 Input$4.default = Input$4;
15914 if (terminalHighlight && terminalHighlight.registerInput) {
15915 terminalHighlight.registerInput(Input$4);
15916 }
15917 var SourceMapConsumer = require$$2.SourceMapConsumer, SourceMapGenerator = require$$2.SourceMapGenerator;
15918 var dirname = require$$2.dirname, relative = require$$2.relative, resolve$3 = require$$2.resolve, sep = require$$2.sep;
15919 var pathToFileURL = require$$2.pathToFileURL;
15920 var Input$3 = input;
15921 var sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator);
15922 var pathAvailable = Boolean(dirname && resolve$3 && relative && sep);
15923 var MapGenerator$2 = /*#__PURE__*/ function() {
15924 function MapGenerator2(stringify2, root2, opts, cssString) {
15925 this.stringify = stringify2;
15926 this.mapOpts = opts.map || {};
15927 this.root = root2;
15928 this.opts = opts;
15929 this.css = cssString;
15930 this.originalCSS = cssString;
15931 this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
15932 this.memoizedFileURLs = /* @__PURE__ */ new Map();
15933 this.memoizedPaths = /* @__PURE__ */ new Map();
15934 this.memoizedURLs = /* @__PURE__ */ new Map();
15935 }
15936 var _proto = MapGenerator2.prototype;
15937 _proto.addAnnotation = function addAnnotation() {
15938 var content;
15939 if (this.isInline()) {
15940 content = "data:application/json;base64," + this.toBase64(this.map.toString());
15941 } else if (typeof this.mapOpts.annotation === "string") {
15942 content = this.mapOpts.annotation;
15943 } else if (typeof this.mapOpts.annotation === "function") {
15944 content = this.mapOpts.annotation(this.opts.to, this.root);
15945 } else {
15946 content = this.outputFile() + ".map";
15947 }
15948 var eol = "\n";
15949 if (this.css.includes("\r\n")) eol = "\r\n";
15950 this.css += eol + "/*# sourceMappingURL=" + content + " */";
15951 };
15952 _proto.applyPrevMaps = function applyPrevMaps() {
15953 for(var _iterator = _create_for_of_iterator_helper_loose(this.previous()), _step; !(_step = _iterator()).done;){
15954 var prev = _step.value;
15955 var from = this.toUrl(this.path(prev.file));
15956 var root2 = prev.root || dirname(prev.file);
15957 var map = void 0;
15958 if (this.mapOpts.sourcesContent === false) {
15959 map = new SourceMapConsumer(prev.text);
15960 if (map.sourcesContent) {
15961 map.sourcesContent = null;
15962 }
15963 } else {
15964 map = prev.consumer();
15965 }
15966 this.map.applySourceMap(map, from, this.toUrl(this.path(root2)));
15967 }
15968 };
15969 _proto.clearAnnotation = function clearAnnotation() {
15970 if (this.mapOpts.annotation === false) return;
15971 if (this.root) {
15972 var node2;
15973 for(var i2 = this.root.nodes.length - 1; i2 >= 0; i2--){
15974 node2 = this.root.nodes[i2];
15975 if (node2.type !== "comment") continue;
15976 if (node2.text.indexOf("# sourceMappingURL=") === 0) {
15977 this.root.removeChild(i2);
15978 }
15979 }
15980 } else if (this.css) {
15981 this.css = this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm, "");
15982 }
15983 };
15984 _proto.generate = function generate() {
15985 this.clearAnnotation();
15986 if (pathAvailable && sourceMapAvailable && this.isMap()) {
15987 return this.generateMap();
15988 } else {
15989 var result2 = "";
15990 this.stringify(this.root, function(i2) {
15991 result2 += i2;
15992 });
15993 return [
15994 result2
15995 ];
15996 }
15997 };
15998 _proto.generateMap = function generateMap() {
15999 if (this.root) {
16000 this.generateString();
16001 } else if (this.previous().length === 1) {
16002 var prev = this.previous()[0].consumer();
16003 prev.file = this.outputFile();
16004 this.map = SourceMapGenerator.fromSourceMap(prev, {
16005 ignoreInvalidMapping: true
16006 });
16007 } else {
16008 this.map = new SourceMapGenerator({
16009 file: this.outputFile(),
16010 ignoreInvalidMapping: true
16011 });
16012 this.map.addMapping({
16013 generated: {
16014 column: 0,
16015 line: 1
16016 },
16017 original: {
16018 column: 0,
16019 line: 1
16020 },
16021 source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>"
16022 });
16023 }
16024 if (this.isSourcesContent()) this.setSourcesContent();
16025 if (this.root && this.previous().length > 0) this.applyPrevMaps();
16026 if (this.isAnnotation()) this.addAnnotation();
16027 if (this.isInline()) {
16028 return [
16029 this.css
16030 ];
16031 } else {
16032 return [
16033 this.css,
16034 this.map
16035 ];
16036 }
16037 };
16038 _proto.generateString = function generateString() {
16039 var _this = this;
16040 this.css = "";
16041 this.map = new SourceMapGenerator({
16042 file: this.outputFile(),
16043 ignoreInvalidMapping: true
16044 });
16045 var line = 1;
16046 var column = 1;
16047 var noSource = "<no source>";
16048 var mapping = {
16049 generated: {
16050 column: 0,
16051 line: 0
16052 },
16053 original: {
16054 column: 0,
16055 line: 0
16056 },
16057 source: ""
16058 };
16059 var lines, last;
16060 this.stringify(this.root, function(str, node2, type) {
16061 _this.css += str;
16062 if (node2 && type !== "end") {
16063 mapping.generated.line = line;
16064 mapping.generated.column = column - 1;
16065 if (node2.source && node2.source.start) {
16066 mapping.source = _this.sourcePath(node2);
16067 mapping.original.line = node2.source.start.line;
16068 mapping.original.column = node2.source.start.column - 1;
16069 _this.map.addMapping(mapping);
16070 } else {
16071 mapping.source = noSource;
16072 mapping.original.line = 1;
16073 mapping.original.column = 0;
16074 _this.map.addMapping(mapping);
16075 }
16076 }
16077 lines = str.match(/\n/g);
16078 if (lines) {
16079 line += lines.length;
16080 last = str.lastIndexOf("\n");
16081 column = str.length - last;
16082 } else {
16083 column += str.length;
16084 }
16085 if (node2 && type !== "start") {
16086 var p = node2.parent || {
16087 raws: {}
16088 };
16089 var childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
16090 if (!childless || node2 !== p.last || p.raws.semicolon) {
16091 if (node2.source && node2.source.end) {
16092 mapping.source = _this.sourcePath(node2);
16093 mapping.original.line = node2.source.end.line;
16094 mapping.original.column = node2.source.end.column - 1;
16095 mapping.generated.line = line;
16096 mapping.generated.column = column - 2;
16097 _this.map.addMapping(mapping);
16098 } else {
16099 mapping.source = noSource;
16100 mapping.original.line = 1;
16101 mapping.original.column = 0;
16102 mapping.generated.line = line;
16103 mapping.generated.column = column - 1;
16104 _this.map.addMapping(mapping);
16105 }
16106 }
16107 }
16108 });
16109 };
16110 _proto.isAnnotation = function isAnnotation() {
16111 if (this.isInline()) {
16112 return true;
16113 }
16114 if (typeof this.mapOpts.annotation !== "undefined") {
16115 return this.mapOpts.annotation;
16116 }
16117 if (this.previous().length) {
16118 return this.previous().some(function(i2) {
16119 return i2.annotation;
16120 });
16121 }
16122 return true;
16123 };
16124 _proto.isInline = function isInline() {
16125 if (typeof this.mapOpts.inline !== "undefined") {
16126 return this.mapOpts.inline;
16127 }
16128 var annotation = this.mapOpts.annotation;
16129 if (typeof annotation !== "undefined" && annotation !== true) {
16130 return false;
16131 }
16132 if (this.previous().length) {
16133 return this.previous().some(function(i2) {
16134 return i2.inline;
16135 });
16136 }
16137 return true;
16138 };
16139 _proto.isMap = function isMap() {
16140 if (typeof this.opts.map !== "undefined") {
16141 return !!this.opts.map;
16142 }
16143 return this.previous().length > 0;
16144 };
16145 _proto.isSourcesContent = function isSourcesContent() {
16146 if (typeof this.mapOpts.sourcesContent !== "undefined") {
16147 return this.mapOpts.sourcesContent;
16148 }
16149 if (this.previous().length) {
16150 return this.previous().some(function(i2) {
16151 return i2.withContent();
16152 });
16153 }
16154 return true;
16155 };
16156 _proto.outputFile = function outputFile() {
16157 if (this.opts.to) {
16158 return this.path(this.opts.to);
16159 } else if (this.opts.from) {
16160 return this.path(this.opts.from);
16161 } else {
16162 return "to.css";
16163 }
16164 };
16165 _proto.path = function path(file) {
16166 if (this.mapOpts.absolute) return file;
16167 if (file.charCodeAt(0) === 60) return file;
16168 if (/^\w+:\/\//.test(file)) return file;
16169 var cached = this.memoizedPaths.get(file);
16170 if (cached) return cached;
16171 var from = this.opts.to ? dirname(this.opts.to) : ".";
16172 if (typeof this.mapOpts.annotation === "string") {
16173 from = dirname(resolve$3(from, this.mapOpts.annotation));
16174 }
16175 var path = relative(from, file);
16176 this.memoizedPaths.set(file, path);
16177 return path;
16178 };
16179 _proto.previous = function previous() {
16180 var _this = this;
16181 if (!this.previousMaps) {
16182 this.previousMaps = [];
16183 if (this.root) {
16184 this.root.walk(function(node2) {
16185 if (node2.source && node2.source.input.map) {
16186 var map = node2.source.input.map;
16187 if (!_this.previousMaps.includes(map)) {
16188 _this.previousMaps.push(map);
16189 }
16190 }
16191 });
16192 } else {
16193 var input2 = new Input$3(this.originalCSS, this.opts);
16194 if (input2.map) this.previousMaps.push(input2.map);
16195 }
16196 }
16197 return this.previousMaps;
16198 };
16199 _proto.setSourcesContent = function setSourcesContent() {
16200 var _this = this;
16201 var already = {};
16202 if (this.root) {
16203 this.root.walk(function(node2) {
16204 if (node2.source) {
16205 var from = node2.source.input.from;
16206 if (from && !already[from]) {
16207 already[from] = true;
16208 var fromUrl = _this.usesFileUrls ? _this.toFileUrl(from) : _this.toUrl(_this.path(from));
16209 _this.map.setSourceContent(fromUrl, node2.source.input.css);
16210 }
16211 }
16212 });
16213 } else if (this.css) {
16214 var from = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
16215 this.map.setSourceContent(from, this.css);
16216 }
16217 };
16218 _proto.sourcePath = function sourcePath(node2) {
16219 if (this.mapOpts.from) {
16220 return this.toUrl(this.mapOpts.from);
16221 } else if (this.usesFileUrls) {
16222 return this.toFileUrl(node2.source.input.from);
16223 } else {
16224 return this.toUrl(this.path(node2.source.input.from));
16225 }
16226 };
16227 _proto.toBase64 = function toBase64(str) {
16228 if (Buffer) {
16229 return Buffer.from(str).toString("base64");
16230 } else {
16231 return window.btoa(unescape(encodeURIComponent(str)));
16232 }
16233 };
16234 _proto.toFileUrl = function toFileUrl(path) {
16235 var cached = this.memoizedFileURLs.get(path);
16236 if (cached) return cached;
16237 if (pathToFileURL) {
16238 var fileURL = pathToFileURL(path).toString();
16239 this.memoizedFileURLs.set(path, fileURL);
16240 return fileURL;
16241 } else {
16242 throw new Error("`map.absolute` option is not available in this PostCSS build");
16243 }
16244 };
16245 _proto.toUrl = function toUrl(path) {
16246 var cached = this.memoizedURLs.get(path);
16247 if (cached) return cached;
16248 if (sep === "\\") {
16249 path = path.replace(/\\/g, "/");
16250 }
16251 var url = encodeURI(path).replace(/[#?]/g, encodeURIComponent);
16252 this.memoizedURLs.set(path, url);
16253 return url;
16254 };
16255 return MapGenerator2;
16256 }();
16257 var mapGenerator = MapGenerator$2;
16258 var Node$2 = node;
16259 var Comment$4 = /*#__PURE__*/ function(Node$2) {
16260 _inherits(Comment2, Node$2);
16261 function Comment2(defaults) {
16262 var _this;
16263 _this = Node$2.call(this, defaults) || this;
16264 _this.type = "comment";
16265 return _this;
16266 }
16267 return Comment2;
16268 }(Node$2);
16269 var comment = Comment$4;
16270 Comment$4.default = Comment$4;
16271 var isClean$1 = symbols.isClean, my$1 = symbols.my;
16272 var Declaration$3 = declaration;
16273 var Comment$3 = comment;
16274 var Node$1 = node;
16275 var parse$4, Rule$4, AtRule$4, Root$6;
16276 function cleanSource(nodes) {
16277 return nodes.map(function(i2) {
16278 if (i2.nodes) i2.nodes = cleanSource(i2.nodes);
16279 delete i2.source;
16280 return i2;
16281 });
16282 }
16283 function markDirtyUp(node2) {
16284 node2[isClean$1] = false;
16285 if (node2.proxyOf.nodes) {
16286 for(var _iterator = _create_for_of_iterator_helper_loose(node2.proxyOf.nodes), _step; !(_step = _iterator()).done;){
16287 var i2 = _step.value;
16288 markDirtyUp(i2);
16289 }
16290 }
16291 }
16292 var Container$7 = /*#__PURE__*/ function(Node$1) {
16293 _inherits(Container2, Node$1);
16294 function Container2() {
16295 return Node$1.apply(this, arguments) || this;
16296 }
16297 var _proto = Container2.prototype;
16298 _proto.append = function append() {
16299 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
16300 children[_key] = arguments[_key];
16301 }
16302 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
16303 var child = _step.value;
16304 var nodes = this.normalize(child, this.last);
16305 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
16306 var node2 = _step1.value;
16307 this.proxyOf.nodes.push(node2);
16308 }
16309 }
16310 this.markDirty();
16311 return this;
16312 };
16313 _proto.cleanRaws = function cleanRaws(keepBetween) {
16314 Node$1.prototype.cleanRaws.call(this, keepBetween);
16315 if (this.nodes) {
16316 for(var _iterator = _create_for_of_iterator_helper_loose(this.nodes), _step; !(_step = _iterator()).done;){
16317 var node2 = _step.value;
16318 node2.cleanRaws(keepBetween);
16319 }
16320 }
16321 };
16322 _proto.each = function each(callback) {
16323 if (!this.proxyOf.nodes) return void 0;
16324 var iterator = this.getIterator();
16325 var index2, result2;
16326 while(this.indexes[iterator] < this.proxyOf.nodes.length){
16327 index2 = this.indexes[iterator];
16328 result2 = callback(this.proxyOf.nodes[index2], index2);
16329 if (result2 === false) break;
16330 this.indexes[iterator] += 1;
16331 }
16332 delete this.indexes[iterator];
16333 return result2;
16334 };
16335 _proto.every = function every(condition) {
16336 return this.nodes.every(condition);
16337 };
16338 _proto.getIterator = function getIterator() {
16339 if (!this.lastEach) this.lastEach = 0;
16340 if (!this.indexes) this.indexes = {};
16341 this.lastEach += 1;
16342 var iterator = this.lastEach;
16343 this.indexes[iterator] = 0;
16344 return iterator;
16345 };
16346 _proto.getProxyProcessor = function getProxyProcessor() {
16347 return {
16348 get: function get(node2, prop) {
16349 if (prop === "proxyOf") {
16350 return node2;
16351 } else if (!node2[prop]) {
16352 return node2[prop];
16353 } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
16354 return function() {
16355 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
16356 args[_key] = arguments[_key];
16357 }
16358 var _node2;
16359 return (_node2 = node2)[prop].apply(_node2, [].concat(args.map(function(i2) {
16360 if (typeof i2 === "function") {
16361 return function(child, index2) {
16362 return i2(child.toProxy(), index2);
16363 };
16364 } else {
16365 return i2;
16366 }
16367 })));
16368 };
16369 } else if (prop === "every" || prop === "some") {
16370 return function(cb) {
16371 return node2[prop](function(child) {
16372 for(var _len = arguments.length, other = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
16373 other[_key - 1] = arguments[_key];
16374 }
16375 return cb.apply(void 0, [].concat([
16376 child.toProxy()
16377 ], other));
16378 });
16379 };
16380 } else if (prop === "root") {
16381 return function() {
16382 return node2.root().toProxy();
16383 };
16384 } else if (prop === "nodes") {
16385 return node2.nodes.map(function(i2) {
16386 return i2.toProxy();
16387 });
16388 } else if (prop === "first" || prop === "last") {
16389 return node2[prop].toProxy();
16390 } else {
16391 return node2[prop];
16392 }
16393 },
16394 set: function set(node2, prop, value) {
16395 if (node2[prop] === value) return true;
16396 node2[prop] = value;
16397 if (prop === "name" || prop === "params" || prop === "selector") {
16398 node2.markDirty();
16399 }
16400 return true;
16401 }
16402 };
16403 };
16404 _proto.index = function index(child) {
16405 if (typeof child === "number") return child;
16406 if (child.proxyOf) child = child.proxyOf;
16407 return this.proxyOf.nodes.indexOf(child);
16408 };
16409 _proto.insertAfter = function insertAfter(exist, add) {
16410 var existIndex = this.index(exist);
16411 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse();
16412 existIndex = this.index(exist);
16413 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
16414 var node2 = _step.value;
16415 this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
16416 }
16417 var index2;
16418 for(var id in this.indexes){
16419 index2 = this.indexes[id];
16420 if (existIndex < index2) {
16421 this.indexes[id] = index2 + nodes.length;
16422 }
16423 }
16424 this.markDirty();
16425 return this;
16426 };
16427 _proto.insertBefore = function insertBefore(exist, add) {
16428 var existIndex = this.index(exist);
16429 var type = existIndex === 0 ? "prepend" : false;
16430 var nodes = this.normalize(add, this.proxyOf.nodes[existIndex], type).reverse();
16431 existIndex = this.index(exist);
16432 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
16433 var node2 = _step.value;
16434 this.proxyOf.nodes.splice(existIndex, 0, node2);
16435 }
16436 var index2;
16437 for(var id in this.indexes){
16438 index2 = this.indexes[id];
16439 if (existIndex <= index2) {
16440 this.indexes[id] = index2 + nodes.length;
16441 }
16442 }
16443 this.markDirty();
16444 return this;
16445 };
16446 _proto.normalize = function normalize(nodes, sample) {
16447 var _this = this;
16448 if (typeof nodes === "string") {
16449 nodes = cleanSource(parse$4(nodes).nodes);
16450 } else if (typeof nodes === "undefined") {
16451 nodes = [];
16452 } else if (Array.isArray(nodes)) {
16453 nodes = nodes.slice(0);
16454 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
16455 var i2 = _step.value;
16456 if (i2.parent) i2.parent.removeChild(i2, "ignore");
16457 }
16458 } else if (nodes.type === "root" && this.type !== "document") {
16459 nodes = nodes.nodes.slice(0);
16460 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
16461 var i21 = _step1.value;
16462 if (i21.parent) i21.parent.removeChild(i21, "ignore");
16463 }
16464 } else if (nodes.type) {
16465 nodes = [
16466 nodes
16467 ];
16468 } else if (nodes.prop) {
16469 if (typeof nodes.value === "undefined") {
16470 throw new Error("Value field is missed in node creation");
16471 } else if (typeof nodes.value !== "string") {
16472 nodes.value = String(nodes.value);
16473 }
16474 nodes = [
16475 new Declaration$3(nodes)
16476 ];
16477 } else if (nodes.selector) {
16478 nodes = [
16479 new Rule$4(nodes)
16480 ];
16481 } else if (nodes.name) {
16482 nodes = [
16483 new AtRule$4(nodes)
16484 ];
16485 } else if (nodes.text) {
16486 nodes = [
16487 new Comment$3(nodes)
16488 ];
16489 } else {
16490 throw new Error("Unknown node type in node creation");
16491 }
16492 var processed = nodes.map(function(i2) {
16493 if (!i2[my$1]) Container2.rebuild(i2);
16494 i2 = i2.proxyOf;
16495 if (i2.parent) i2.parent.removeChild(i2);
16496 if (i2[isClean$1]) markDirtyUp(i2);
16497 if (typeof i2.raws.before === "undefined") {
16498 if (sample && typeof sample.raws.before !== "undefined") {
16499 i2.raws.before = sample.raws.before.replace(/\S/g, "");
16500 }
16501 }
16502 i2.parent = _this.proxyOf;
16503 return i2;
16504 });
16505 return processed;
16506 };
16507 _proto.prepend = function prepend() {
16508 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
16509 children[_key] = arguments[_key];
16510 }
16511 children = children.reverse();
16512 for(var _iterator = _create_for_of_iterator_helper_loose(children), _step; !(_step = _iterator()).done;){
16513 var child = _step.value;
16514 var nodes = this.normalize(child, this.first, "prepend").reverse();
16515 for(var _iterator1 = _create_for_of_iterator_helper_loose(nodes), _step1; !(_step1 = _iterator1()).done;){
16516 var node2 = _step1.value;
16517 this.proxyOf.nodes.unshift(node2);
16518 }
16519 for(var id in this.indexes){
16520 this.indexes[id] = this.indexes[id] + nodes.length;
16521 }
16522 }
16523 this.markDirty();
16524 return this;
16525 };
16526 _proto.push = function push(child) {
16527 child.parent = this;
16528 this.proxyOf.nodes.push(child);
16529 return this;
16530 };
16531 _proto.removeAll = function removeAll() {
16532 for(var _iterator = _create_for_of_iterator_helper_loose(this.proxyOf.nodes), _step; !(_step = _iterator()).done;){
16533 var node2 = _step.value;
16534 node2.parent = void 0;
16535 }
16536 this.proxyOf.nodes = [];
16537 this.markDirty();
16538 return this;
16539 };
16540 _proto.removeChild = function removeChild(child) {
16541 child = this.index(child);
16542 this.proxyOf.nodes[child].parent = void 0;
16543 this.proxyOf.nodes.splice(child, 1);
16544 var index2;
16545 for(var id in this.indexes){
16546 index2 = this.indexes[id];
16547 if (index2 >= child) {
16548 this.indexes[id] = index2 - 1;
16549 }
16550 }
16551 this.markDirty();
16552 return this;
16553 };
16554 _proto.replaceValues = function replaceValues(pattern, opts, callback) {
16555 if (!callback) {
16556 callback = opts;
16557 opts = {};
16558 }
16559 this.walkDecls(function(decl) {
16560 if (opts.props && !opts.props.includes(decl.prop)) return;
16561 if (opts.fast && !decl.value.includes(opts.fast)) return;
16562 decl.value = decl.value.replace(pattern, callback);
16563 });
16564 this.markDirty();
16565 return this;
16566 };
16567 _proto.some = function some(condition) {
16568 return this.nodes.some(condition);
16569 };
16570 _proto.walk = function walk(callback) {
16571 return this.each(function(child, i2) {
16572 var result2;
16573 try {
16574 result2 = callback(child, i2);
16575 } catch (e2) {
16576 throw child.addToError(e2);
16577 }
16578 if (result2 !== false && child.walk) {
16579 result2 = child.walk(callback);
16580 }
16581 return result2;
16582 });
16583 };
16584 _proto.walkAtRules = function walkAtRules(name, callback) {
16585 if (!callback) {
16586 callback = name;
16587 return this.walk(function(child, i2) {
16588 if (child.type === "atrule") {
16589 return callback(child, i2);
16590 }
16591 });
16592 }
16593 if (_instanceof(name, RegExp)) {
16594 return this.walk(function(child, i2) {
16595 if (child.type === "atrule" && name.test(child.name)) {
16596 return callback(child, i2);
16597 }
16598 });
16599 }
16600 return this.walk(function(child, i2) {
16601 if (child.type === "atrule" && child.name === name) {
16602 return callback(child, i2);
16603 }
16604 });
16605 };
16606 _proto.walkComments = function walkComments(callback) {
16607 return this.walk(function(child, i2) {
16608 if (child.type === "comment") {
16609 return callback(child, i2);
16610 }
16611 });
16612 };
16613 _proto.walkDecls = function walkDecls(prop, callback) {
16614 if (!callback) {
16615 callback = prop;
16616 return this.walk(function(child, i2) {
16617 if (child.type === "decl") {
16618 return callback(child, i2);
16619 }
16620 });
16621 }
16622 if (_instanceof(prop, RegExp)) {
16623 return this.walk(function(child, i2) {
16624 if (child.type === "decl" && prop.test(child.prop)) {
16625 return callback(child, i2);
16626 }
16627 });
16628 }
16629 return this.walk(function(child, i2) {
16630 if (child.type === "decl" && child.prop === prop) {
16631 return callback(child, i2);
16632 }
16633 });
16634 };
16635 _proto.walkRules = function walkRules(selector, callback) {
16636 if (!callback) {
16637 callback = selector;
16638 return this.walk(function(child, i2) {
16639 if (child.type === "rule") {
16640 return callback(child, i2);
16641 }
16642 });
16643 }
16644 if (_instanceof(selector, RegExp)) {
16645 return this.walk(function(child, i2) {
16646 if (child.type === "rule" && selector.test(child.selector)) {
16647 return callback(child, i2);
16648 }
16649 });
16650 }
16651 return this.walk(function(child, i2) {
16652 if (child.type === "rule" && child.selector === selector) {
16653 return callback(child, i2);
16654 }
16655 });
16656 };
16657 _create_class(Container2, [
16658 {
16659 key: "first",
16660 get: function get() {
16661 if (!this.proxyOf.nodes) return void 0;
16662 return this.proxyOf.nodes[0];
16663 }
16664 },
16665 {
16666 key: "last",
16667 get: function get() {
16668 if (!this.proxyOf.nodes) return void 0;
16669 return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
16670 }
16671 }
16672 ]);
16673 return Container2;
16674 }(Node$1);
16675 Container$7.registerParse = function(dependant) {
16676 parse$4 = dependant;
16677 };
16678 Container$7.registerRule = function(dependant) {
16679 Rule$4 = dependant;
16680 };
16681 Container$7.registerAtRule = function(dependant) {
16682 AtRule$4 = dependant;
16683 };
16684 Container$7.registerRoot = function(dependant) {
16685 Root$6 = dependant;
16686 };
16687 var container = Container$7;
16688 Container$7.default = Container$7;
16689 Container$7.rebuild = function(node2) {
16690 if (node2.type === "atrule") {
16691 Object.setPrototypeOf(node2, AtRule$4.prototype);
16692 } else if (node2.type === "rule") {
16693 Object.setPrototypeOf(node2, Rule$4.prototype);
16694 } else if (node2.type === "decl") {
16695 Object.setPrototypeOf(node2, Declaration$3.prototype);
16696 } else if (node2.type === "comment") {
16697 Object.setPrototypeOf(node2, Comment$3.prototype);
16698 } else if (node2.type === "root") {
16699 Object.setPrototypeOf(node2, Root$6.prototype);
16700 }
16701 node2[my$1] = true;
16702 if (node2.nodes) {
16703 node2.nodes.forEach(function(child) {
16704 Container$7.rebuild(child);
16705 });
16706 }
16707 };
16708 var Container$6 = container;
16709 var LazyResult$4, Processor$3;
16710 var Document$3 = /*#__PURE__*/ function(Container$6) {
16711 _inherits(Document23, Container$6);
16712 function Document23(defaults) {
16713 var _this;
16714 _this = Container$6.call(this, _extends({
16715 type: "document"
16716 }, defaults)) || this;
16717 if (!_this.nodes) {
16718 _this.nodes = [];
16719 }
16720 return _this;
16721 }
16722 var _proto = Document23.prototype;
16723 _proto.toResult = function toResult(opts) {
16724 if (opts === void 0) opts = {};
16725 var lazy = new LazyResult$4(new Processor$3(), this, opts);
16726 return lazy.stringify();
16727 };
16728 return Document23;
16729 }(Container$6);
16730 Document$3.registerLazyResult = function(dependant) {
16731 LazyResult$4 = dependant;
16732 };
16733 Document$3.registerProcessor = function(dependant) {
16734 Processor$3 = dependant;
16735 };
16736 var document$1$2 = Document$3;
16737 Document$3.default = Document$3;
16738 var printed = {};
16739 var warnOnce$2 = function warnOnce2(message) {
16740 if (printed[message]) return;
16741 printed[message] = true;
16742 if (typeof console !== "undefined" && console.warn) {
16743 console.warn(message);
16744 }
16745 };
16746 var Warning$2 = /*#__PURE__*/ function() {
16747 function Warning2(text, opts) {
16748 if (opts === void 0) opts = {};
16749 this.type = "warning";
16750 this.text = text;
16751 if (opts.node && opts.node.source) {
16752 var range = opts.node.rangeBy(opts);
16753 this.line = range.start.line;
16754 this.column = range.start.column;
16755 this.endLine = range.end.line;
16756 this.endColumn = range.end.column;
16757 }
16758 for(var opt in opts)this[opt] = opts[opt];
16759 }
16760 var _proto = Warning2.prototype;
16761 _proto.toString = function toString() {
16762 if (this.node) {
16763 return this.node.error(this.text, {
16764 index: this.index,
16765 plugin: this.plugin,
16766 word: this.word
16767 }).message;
16768 }
16769 if (this.plugin) {
16770 return this.plugin + ": " + this.text;
16771 }
16772 return this.text;
16773 };
16774 return Warning2;
16775 }();
16776 var warning = Warning$2;
16777 Warning$2.default = Warning$2;
16778 var Warning$1 = warning;
16779 var Result$3 = /*#__PURE__*/ function() {
16780 function Result2(processor2, root2, opts) {
16781 this.processor = processor2;
16782 this.messages = [];
16783 this.root = root2;
16784 this.opts = opts;
16785 this.css = void 0;
16786 this.map = void 0;
16787 }
16788 var _proto = Result2.prototype;
16789 _proto.toString = function toString() {
16790 return this.css;
16791 };
16792 _proto.warn = function warn(text, opts) {
16793 if (opts === void 0) opts = {};
16794 if (!opts.plugin) {
16795 if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
16796 opts.plugin = this.lastPlugin.postcssPlugin;
16797 }
16798 }
16799 var warning2 = new Warning$1(text, opts);
16800 this.messages.push(warning2);
16801 return warning2;
16802 };
16803 _proto.warnings = function warnings() {
16804 return this.messages.filter(function(i2) {
16805 return i2.type === "warning";
16806 });
16807 };
16808 _create_class(Result2, [
16809 {
16810 key: "content",
16811 get: function get() {
16812 return this.css;
16813 }
16814 }
16815 ]);
16816 return Result2;
16817 }();
16818 var result = Result$3;
16819 Result$3.default = Result$3;
16820 var SINGLE_QUOTE = "'".charCodeAt(0);
16821 var DOUBLE_QUOTE = '"'.charCodeAt(0);
16822 var BACKSLASH = "\\".charCodeAt(0);
16823 var SLASH = "/".charCodeAt(0);
16824 var NEWLINE = "\n".charCodeAt(0);
16825 var SPACE = " ".charCodeAt(0);
16826 var FEED = "\f".charCodeAt(0);
16827 var TAB = " ".charCodeAt(0);
16828 var CR = "\r".charCodeAt(0);
16829 var OPEN_SQUARE = "[".charCodeAt(0);
16830 var CLOSE_SQUARE = "]".charCodeAt(0);
16831 var OPEN_PARENTHESES = "(".charCodeAt(0);
16832 var CLOSE_PARENTHESES = ")".charCodeAt(0);
16833 var OPEN_CURLY = "{".charCodeAt(0);
16834 var CLOSE_CURLY = "}".charCodeAt(0);
16835 var SEMICOLON = ";".charCodeAt(0);
16836 var ASTERISK = "*".charCodeAt(0);
16837 var COLON = ":".charCodeAt(0);
16838 var AT = "@".charCodeAt(0);
16839 var RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
16840 var RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
16841 var RE_BAD_BRACKET = /.[\r\n"'(/\\]/;
16842 var RE_HEX_ESCAPE = /[\da-f]/i;
16843 var tokenize = function tokenizer2(input2, options) {
16844 if (options === void 0) options = {};
16845 var css = input2.css.valueOf();
16846 var ignore = options.ignoreErrors;
16847 var code, next, quote, content, escape;
16848 var escaped, escapePos, prev, n2, currentToken;
16849 var length = css.length;
16850 var pos = 0;
16851 var buffer = [];
16852 var returned = [];
16853 function position() {
16854 return pos;
16855 }
16856 function unclosed(what) {
16857 throw input2.error("Unclosed " + what, pos);
16858 }
16859 function endOfFile() {
16860 return returned.length === 0 && pos >= length;
16861 }
16862 function nextToken(opts) {
16863 if (returned.length) return returned.pop();
16864 if (pos >= length) return;
16865 var ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
16866 code = css.charCodeAt(pos);
16867 switch(code){
16868 case NEWLINE:
16869 case SPACE:
16870 case TAB:
16871 case CR:
16872 case FEED:
16873 {
16874 next = pos;
16875 do {
16876 next += 1;
16877 code = css.charCodeAt(next);
16878 }while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
16879 currentToken = [
16880 "space",
16881 css.slice(pos, next)
16882 ];
16883 pos = next - 1;
16884 break;
16885 }
16886 case OPEN_SQUARE:
16887 case CLOSE_SQUARE:
16888 case OPEN_CURLY:
16889 case CLOSE_CURLY:
16890 case COLON:
16891 case SEMICOLON:
16892 case CLOSE_PARENTHESES:
16893 {
16894 var controlChar = String.fromCharCode(code);
16895 currentToken = [
16896 controlChar,
16897 controlChar,
16898 pos
16899 ];
16900 break;
16901 }
16902 case OPEN_PARENTHESES:
16903 {
16904 prev = buffer.length ? buffer.pop()[1] : "";
16905 n2 = css.charCodeAt(pos + 1);
16906 if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE && n2 !== NEWLINE && n2 !== TAB && n2 !== FEED && n2 !== CR) {
16907 next = pos;
16908 do {
16909 escaped = false;
16910 next = css.indexOf(")", next + 1);
16911 if (next === -1) {
16912 if (ignore || ignoreUnclosed) {
16913 next = pos;
16914 break;
16915 } else {
16916 unclosed("bracket");
16917 }
16918 }
16919 escapePos = next;
16920 while(css.charCodeAt(escapePos - 1) === BACKSLASH){
16921 escapePos -= 1;
16922 escaped = !escaped;
16923 }
16924 }while (escaped);
16925 currentToken = [
16926 "brackets",
16927 css.slice(pos, next + 1),
16928 pos,
16929 next
16930 ];
16931 pos = next;
16932 } else {
16933 next = css.indexOf(")", pos + 1);
16934 content = css.slice(pos, next + 1);
16935 if (next === -1 || RE_BAD_BRACKET.test(content)) {
16936 currentToken = [
16937 "(",
16938 "(",
16939 pos
16940 ];
16941 } else {
16942 currentToken = [
16943 "brackets",
16944 content,
16945 pos,
16946 next
16947 ];
16948 pos = next;
16949 }
16950 }
16951 break;
16952 }
16953 case SINGLE_QUOTE:
16954 case DOUBLE_QUOTE:
16955 {
16956 quote = code === SINGLE_QUOTE ? "'" : '"';
16957 next = pos;
16958 do {
16959 escaped = false;
16960 next = css.indexOf(quote, next + 1);
16961 if (next === -1) {
16962 if (ignore || ignoreUnclosed) {
16963 next = pos + 1;
16964 break;
16965 } else {
16966 unclosed("string");
16967 }
16968 }
16969 escapePos = next;
16970 while(css.charCodeAt(escapePos - 1) === BACKSLASH){
16971 escapePos -= 1;
16972 escaped = !escaped;
16973 }
16974 }while (escaped);
16975 currentToken = [
16976 "string",
16977 css.slice(pos, next + 1),
16978 pos,
16979 next
16980 ];
16981 pos = next;
16982 break;
16983 }
16984 case AT:
16985 {
16986 RE_AT_END.lastIndex = pos + 1;
16987 RE_AT_END.test(css);
16988 if (RE_AT_END.lastIndex === 0) {
16989 next = css.length - 1;
16990 } else {
16991 next = RE_AT_END.lastIndex - 2;
16992 }
16993 currentToken = [
16994 "at-word",
16995 css.slice(pos, next + 1),
16996 pos,
16997 next
16998 ];
16999 pos = next;
17000 break;
17001 }
17002 case BACKSLASH:
17003 {
17004 next = pos;
17005 escape = true;
17006 while(css.charCodeAt(next + 1) === BACKSLASH){
17007 next += 1;
17008 escape = !escape;
17009 }
17010 code = css.charCodeAt(next + 1);
17011 if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
17012 next += 1;
17013 if (RE_HEX_ESCAPE.test(css.charAt(next))) {
17014 while(RE_HEX_ESCAPE.test(css.charAt(next + 1))){
17015 next += 1;
17016 }
17017 if (css.charCodeAt(next + 1) === SPACE) {
17018 next += 1;
17019 }
17020 }
17021 }
17022 currentToken = [
17023 "word",
17024 css.slice(pos, next + 1),
17025 pos,
17026 next
17027 ];
17028 pos = next;
17029 break;
17030 }
17031 default:
17032 {
17033 if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
17034 next = css.indexOf("*/", pos + 2) + 1;
17035 if (next === 0) {
17036 if (ignore || ignoreUnclosed) {
17037 next = css.length;
17038 } else {
17039 unclosed("comment");
17040 }
17041 }
17042 currentToken = [
17043 "comment",
17044 css.slice(pos, next + 1),
17045 pos,
17046 next
17047 ];
17048 pos = next;
17049 } else {
17050 RE_WORD_END.lastIndex = pos + 1;
17051 RE_WORD_END.test(css);
17052 if (RE_WORD_END.lastIndex === 0) {
17053 next = css.length - 1;
17054 } else {
17055 next = RE_WORD_END.lastIndex - 2;
17056 }
17057 currentToken = [
17058 "word",
17059 css.slice(pos, next + 1),
17060 pos,
17061 next
17062 ];
17063 buffer.push(currentToken);
17064 pos = next;
17065 }
17066 break;
17067 }
17068 }
17069 pos++;
17070 return currentToken;
17071 }
17072 function back(token) {
17073 returned.push(token);
17074 }
17075 return {
17076 back: back,
17077 endOfFile: endOfFile,
17078 nextToken: nextToken,
17079 position: position
17080 };
17081 };
17082 var Container$5 = container;
17083 var AtRule$3 = /*#__PURE__*/ function(Container$5) {
17084 _inherits(AtRule2, Container$5);
17085 function AtRule2(defaults) {
17086 var _this;
17087 _this = Container$5.call(this, defaults) || this;
17088 _this.type = "atrule";
17089 return _this;
17090 }
17091 var _proto = AtRule2.prototype;
17092 _proto.append = function append() {
17093 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
17094 children[_key] = arguments[_key];
17095 }
17096 var _Container$5_prototype_append;
17097 if (!this.proxyOf.nodes) this.nodes = [];
17098 return (_Container$5_prototype_append = Container$5.prototype.append).call.apply(_Container$5_prototype_append, [].concat([
17099 this
17100 ], children));
17101 };
17102 _proto.prepend = function prepend() {
17103 for(var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++){
17104 children[_key] = arguments[_key];
17105 }
17106 var _Container$5_prototype_prepend;
17107 if (!this.proxyOf.nodes) this.nodes = [];
17108 return (_Container$5_prototype_prepend = Container$5.prototype.prepend).call.apply(_Container$5_prototype_prepend, [].concat([
17109 this
17110 ], children));
17111 };
17112 return AtRule2;
17113 }(Container$5);
17114 var atRule = AtRule$3;
17115 AtRule$3.default = AtRule$3;
17116 Container$5.registerAtRule(AtRule$3);
17117 var Container$4 = container;
17118 var LazyResult$3, Processor$2;
17119 var Root$5 = /*#__PURE__*/ function(Container$4) {
17120 _inherits(Root2, Container$4);
17121 function Root2(defaults) {
17122 var _this;
17123 _this = Container$4.call(this, defaults) || this;
17124 _this.type = "root";
17125 if (!_this.nodes) _this.nodes = [];
17126 return _this;
17127 }
17128 var _proto = Root2.prototype;
17129 _proto.normalize = function normalize(child, sample, type) {
17130 var nodes = Container$4.prototype.normalize.call(this, child);
17131 if (sample) {
17132 if (type === "prepend") {
17133 if (this.nodes.length > 1) {
17134 sample.raws.before = this.nodes[1].raws.before;
17135 } else {
17136 delete sample.raws.before;
17137 }
17138 } else if (this.first !== sample) {
17139 for(var _iterator = _create_for_of_iterator_helper_loose(nodes), _step; !(_step = _iterator()).done;){
17140 var node2 = _step.value;
17141 node2.raws.before = sample.raws.before;
17142 }
17143 }
17144 }
17145 return nodes;
17146 };
17147 _proto.removeChild = function removeChild(child, ignore) {
17148 var index2 = this.index(child);
17149 if (!ignore && index2 === 0 && this.nodes.length > 1) {
17150 this.nodes[1].raws.before = this.nodes[index2].raws.before;
17151 }
17152 return Container$4.prototype.removeChild.call(this, child);
17153 };
17154 _proto.toResult = function toResult(opts) {
17155 if (opts === void 0) opts = {};
17156 var lazy = new LazyResult$3(new Processor$2(), this, opts);
17157 return lazy.stringify();
17158 };
17159 return Root2;
17160 }(Container$4);
17161 Root$5.registerLazyResult = function(dependant) {
17162 LazyResult$3 = dependant;
17163 };
17164 Root$5.registerProcessor = function(dependant) {
17165 Processor$2 = dependant;
17166 };
17167 var root = Root$5;
17168 Root$5.default = Root$5;
17169 Container$4.registerRoot(Root$5);
17170 var list$2 = {
17171 comma: function comma(string) {
17172 return list$2.split(string, [
17173 ","
17174 ], true);
17175 },
17176 space: function space(string) {
17177 var spaces = [
17178 " ",
17179 "\n",
17180 " "
17181 ];
17182 return list$2.split(string, spaces);
17183 },
17184 split: function split(string, separators, last) {
17185 var array = [];
17186 var current = "";
17187 var split = false;
17188 var func = 0;
17189 var inQuote = false;
17190 var prevQuote = "";
17191 var escape = false;
17192 for(var _iterator = _create_for_of_iterator_helper_loose(string), _step; !(_step = _iterator()).done;){
17193 var letter = _step.value;
17194 if (escape) {
17195 escape = false;
17196 } else if (letter === "\\") {
17197 escape = true;
17198 } else if (inQuote) {
17199 if (letter === prevQuote) {
17200 inQuote = false;
17201 }
17202 } else if (letter === '"' || letter === "'") {
17203 inQuote = true;
17204 prevQuote = letter;
17205 } else if (letter === "(") {
17206 func += 1;
17207 } else if (letter === ")") {
17208 if (func > 0) func -= 1;
17209 } else if (func === 0) {
17210 if (separators.includes(letter)) split = true;
17211 }
17212 if (split) {
17213 if (current !== "") array.push(current.trim());
17214 current = "";
17215 split = false;
17216 } else {
17217 current += letter;
17218 }
17219 }
17220 if (last || current !== "") array.push(current.trim());
17221 return array;
17222 }
17223 };
17224 var list_1 = list$2;
17225 list$2.default = list$2;
17226 var Container$3 = container;
17227 var list$1 = list_1;
17228 var Rule$3 = /*#__PURE__*/ function(Container$3) {
17229 _inherits(Rule2, Container$3);
17230 function Rule2(defaults) {
17231 var _this;
17232 _this = Container$3.call(this, defaults) || this;
17233 _this.type = "rule";
17234 if (!_this.nodes) _this.nodes = [];
17235 return _this;
17236 }
17237 _create_class(Rule2, [
17238 {
17239 key: "selectors",
17240 get: function get() {
17241 return list$1.comma(this.selector);
17242 },
17243 set: function set(values) {
17244 var match = this.selector ? this.selector.match(/,\s*/) : null;
17245 var sep2 = match ? match[0] : "," + this.raw("between", "beforeOpen");
17246 this.selector = values.join(sep2);
17247 }
17248 }
17249 ]);
17250 return Rule2;
17251 }(Container$3);
17252 var rule = Rule$3;
17253 Rule$3.default = Rule$3;
17254 Container$3.registerRule(Rule$3);
17255 var Declaration$2 = declaration;
17256 var tokenizer22 = tokenize;
17257 var Comment$2 = comment;
17258 var AtRule$2 = atRule;
17259 var Root$4 = root;
17260 var Rule$2 = rule;
17261 var SAFE_COMMENT_NEIGHBOR = {
17262 empty: true,
17263 space: true
17264 };
17265 function findLastWithPosition(tokens) {
17266 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
17267 var token = tokens[i2];
17268 var pos = token[3] || token[2];
17269 if (pos) return pos;
17270 }
17271 }
17272 var Parser$1 = /*#__PURE__*/ function() {
17273 function Parser2(input2) {
17274 this.input = input2;
17275 this.root = new Root$4();
17276 this.current = this.root;
17277 this.spaces = "";
17278 this.semicolon = false;
17279 this.createTokenizer();
17280 this.root.source = {
17281 input: input2,
17282 start: {
17283 column: 1,
17284 line: 1,
17285 offset: 0
17286 }
17287 };
17288 }
17289 var _proto = Parser2.prototype;
17290 _proto.atrule = function atrule(token) {
17291 var node2 = new AtRule$2();
17292 node2.name = token[1].slice(1);
17293 if (node2.name === "") {
17294 this.unnamedAtrule(node2, token);
17295 }
17296 this.init(node2, token[2]);
17297 var type;
17298 var prev;
17299 var shift;
17300 var last = false;
17301 var open = false;
17302 var params = [];
17303 var brackets = [];
17304 while(!this.tokenizer.endOfFile()){
17305 token = this.tokenizer.nextToken();
17306 type = token[0];
17307 if (type === "(" || type === "[") {
17308 brackets.push(type === "(" ? ")" : "]");
17309 } else if (type === "{" && brackets.length > 0) {
17310 brackets.push("}");
17311 } else if (type === brackets[brackets.length - 1]) {
17312 brackets.pop();
17313 }
17314 if (brackets.length === 0) {
17315 if (type === ";") {
17316 node2.source.end = this.getPosition(token[2]);
17317 node2.source.end.offset++;
17318 this.semicolon = true;
17319 break;
17320 } else if (type === "{") {
17321 open = true;
17322 break;
17323 } else if (type === "}") {
17324 if (params.length > 0) {
17325 shift = params.length - 1;
17326 prev = params[shift];
17327 while(prev && prev[0] === "space"){
17328 prev = params[--shift];
17329 }
17330 if (prev) {
17331 node2.source.end = this.getPosition(prev[3] || prev[2]);
17332 node2.source.end.offset++;
17333 }
17334 }
17335 this.end(token);
17336 break;
17337 } else {
17338 params.push(token);
17339 }
17340 } else {
17341 params.push(token);
17342 }
17343 if (this.tokenizer.endOfFile()) {
17344 last = true;
17345 break;
17346 }
17347 }
17348 node2.raws.between = this.spacesAndCommentsFromEnd(params);
17349 if (params.length) {
17350 node2.raws.afterName = this.spacesAndCommentsFromStart(params);
17351 this.raw(node2, "params", params);
17352 if (last) {
17353 token = params[params.length - 1];
17354 node2.source.end = this.getPosition(token[3] || token[2]);
17355 node2.source.end.offset++;
17356 this.spaces = node2.raws.between;
17357 node2.raws.between = "";
17358 }
17359 } else {
17360 node2.raws.afterName = "";
17361 node2.params = "";
17362 }
17363 if (open) {
17364 node2.nodes = [];
17365 this.current = node2;
17366 }
17367 };
17368 _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
17369 var colon = this.colon(tokens);
17370 if (colon === false) return;
17371 var founded = 0;
17372 var token;
17373 for(var j = colon - 1; j >= 0; j--){
17374 token = tokens[j];
17375 if (token[0] !== "space") {
17376 founded += 1;
17377 if (founded === 2) break;
17378 }
17379 }
17380 throw this.input.error("Missed semicolon", token[0] === "word" ? token[3] + 1 : token[2]);
17381 };
17382 _proto.colon = function colon(tokens) {
17383 var brackets = 0;
17384 var token, type, prev;
17385 for(var _iterator = _create_for_of_iterator_helper_loose(tokens.entries()), _step; !(_step = _iterator()).done;){
17386 var _step_value = _step.value, i2 = _step_value[0], element = _step_value[1];
17387 token = element;
17388 type = token[0];
17389 if (type === "(") {
17390 brackets += 1;
17391 }
17392 if (type === ")") {
17393 brackets -= 1;
17394 }
17395 if (brackets === 0 && type === ":") {
17396 if (!prev) {
17397 this.doubleColon(token);
17398 } else if (prev[0] === "word" && prev[1] === "progid") {
17399 continue;
17400 } else {
17401 return i2;
17402 }
17403 }
17404 prev = token;
17405 }
17406 return false;
17407 };
17408 _proto.comment = function comment(token) {
17409 var node2 = new Comment$2();
17410 this.init(node2, token[2]);
17411 node2.source.end = this.getPosition(token[3] || token[2]);
17412 node2.source.end.offset++;
17413 var text = token[1].slice(2, -2);
17414 if (/^\s*$/.test(text)) {
17415 node2.text = "";
17416 node2.raws.left = text;
17417 node2.raws.right = "";
17418 } else {
17419 var match = text.match(/^(\s*)([^]*\S)(\s*)$/);
17420 node2.text = match[2];
17421 node2.raws.left = match[1];
17422 node2.raws.right = match[3];
17423 }
17424 };
17425 _proto.createTokenizer = function createTokenizer() {
17426 this.tokenizer = tokenizer22(this.input);
17427 };
17428 _proto.decl = function decl(tokens, customProperty) {
17429 var node2 = new Declaration$2();
17430 this.init(node2, tokens[0][2]);
17431 var last = tokens[tokens.length - 1];
17432 if (last[0] === ";") {
17433 this.semicolon = true;
17434 tokens.pop();
17435 }
17436 node2.source.end = this.getPosition(last[3] || last[2] || findLastWithPosition(tokens));
17437 node2.source.end.offset++;
17438 while(tokens[0][0] !== "word"){
17439 if (tokens.length === 1) this.unknownWord(tokens);
17440 node2.raws.before += tokens.shift()[1];
17441 }
17442 node2.source.start = this.getPosition(tokens[0][2]);
17443 node2.prop = "";
17444 while(tokens.length){
17445 var type = tokens[0][0];
17446 if (type === ":" || type === "space" || type === "comment") {
17447 break;
17448 }
17449 node2.prop += tokens.shift()[1];
17450 }
17451 node2.raws.between = "";
17452 var token;
17453 while(tokens.length){
17454 token = tokens.shift();
17455 if (token[0] === ":") {
17456 node2.raws.between += token[1];
17457 break;
17458 } else {
17459 if (token[0] === "word" && /\w/.test(token[1])) {
17460 this.unknownWord([
17461 token
17462 ]);
17463 }
17464 node2.raws.between += token[1];
17465 }
17466 }
17467 if (node2.prop[0] === "_" || node2.prop[0] === "*") {
17468 node2.raws.before += node2.prop[0];
17469 node2.prop = node2.prop.slice(1);
17470 }
17471 var firstSpaces = [];
17472 var next;
17473 while(tokens.length){
17474 next = tokens[0][0];
17475 if (next !== "space" && next !== "comment") break;
17476 firstSpaces.push(tokens.shift());
17477 }
17478 this.precheckMissedSemicolon(tokens);
17479 for(var i2 = tokens.length - 1; i2 >= 0; i2--){
17480 token = tokens[i2];
17481 if (token[1].toLowerCase() === "!important") {
17482 node2.important = true;
17483 var string = this.stringFrom(tokens, i2);
17484 string = this.spacesFromEnd(tokens) + string;
17485 if (string !== " !important") node2.raws.important = string;
17486 break;
17487 } else if (token[1].toLowerCase() === "important") {
17488 var cache = tokens.slice(0);
17489 var str = "";
17490 for(var j = i2; j > 0; j--){
17491 var type1 = cache[j][0];
17492 if (str.trim().indexOf("!") === 0 && type1 !== "space") {
17493 break;
17494 }
17495 str = cache.pop()[1] + str;
17496 }
17497 if (str.trim().indexOf("!") === 0) {
17498 node2.important = true;
17499 node2.raws.important = str;
17500 tokens = cache;
17501 }
17502 }
17503 if (token[0] !== "space" && token[0] !== "comment") {
17504 break;
17505 }
17506 }
17507 var hasWord = tokens.some(function(i2) {
17508 return i2[0] !== "space" && i2[0] !== "comment";
17509 });
17510 if (hasWord) {
17511 node2.raws.between += firstSpaces.map(function(i2) {
17512 return i2[1];
17513 }).join("");
17514 firstSpaces = [];
17515 }
17516 this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
17517 if (node2.value.includes(":") && !customProperty) {
17518 this.checkMissedSemicolon(tokens);
17519 }
17520 };
17521 _proto.doubleColon = function doubleColon(token) {
17522 throw this.input.error("Double colon", {
17523 offset: token[2]
17524 }, {
17525 offset: token[2] + token[1].length
17526 });
17527 };
17528 _proto.emptyRule = function emptyRule(token) {
17529 var node2 = new Rule$2();
17530 this.init(node2, token[2]);
17531 node2.selector = "";
17532 node2.raws.between = "";
17533 this.current = node2;
17534 };
17535 _proto.end = function end(token) {
17536 if (this.current.nodes && this.current.nodes.length) {
17537 this.current.raws.semicolon = this.semicolon;
17538 }
17539 this.semicolon = false;
17540 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
17541 this.spaces = "";
17542 if (this.current.parent) {
17543 this.current.source.end = this.getPosition(token[2]);
17544 this.current.source.end.offset++;
17545 this.current = this.current.parent;
17546 } else {
17547 this.unexpectedClose(token);
17548 }
17549 };
17550 _proto.endFile = function endFile() {
17551 if (this.current.parent) this.unclosedBlock();
17552 if (this.current.nodes && this.current.nodes.length) {
17553 this.current.raws.semicolon = this.semicolon;
17554 }
17555 this.current.raws.after = (this.current.raws.after || "") + this.spaces;
17556 this.root.source.end = this.getPosition(this.tokenizer.position());
17557 };
17558 _proto.freeSemicolon = function freeSemicolon(token) {
17559 this.spaces += token[1];
17560 if (this.current.nodes) {
17561 var prev = this.current.nodes[this.current.nodes.length - 1];
17562 if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
17563 prev.raws.ownSemicolon = this.spaces;
17564 this.spaces = "";
17565 }
17566 }
17567 };
17568 // Helpers
17569 _proto.getPosition = function getPosition(offset) {
17570 var pos = this.input.fromOffset(offset);
17571 return {
17572 column: pos.col,
17573 line: pos.line,
17574 offset: offset
17575 };
17576 };
17577 _proto.init = function init(node2, offset) {
17578 this.current.push(node2);
17579 node2.source = {
17580 input: this.input,
17581 start: this.getPosition(offset)
17582 };
17583 node2.raws.before = this.spaces;
17584 this.spaces = "";
17585 if (node2.type !== "comment") this.semicolon = false;
17586 };
17587 _proto.other = function other(start) {
17588 var end = false;
17589 var type = null;
17590 var colon = false;
17591 var bracket = null;
17592 var brackets = [];
17593 var customProperty = start[1].startsWith("--");
17594 var tokens = [];
17595 var token = start;
17596 while(token){
17597 type = token[0];
17598 tokens.push(token);
17599 if (type === "(" || type === "[") {
17600 if (!bracket) bracket = token;
17601 brackets.push(type === "(" ? ")" : "]");
17602 } else if (customProperty && colon && type === "{") {
17603 if (!bracket) bracket = token;
17604 brackets.push("}");
17605 } else if (brackets.length === 0) {
17606 if (type === ";") {
17607 if (colon) {
17608 this.decl(tokens, customProperty);
17609 return;
17610 } else {
17611 break;
17612 }
17613 } else if (type === "{") {
17614 this.rule(tokens);
17615 return;
17616 } else if (type === "}") {
17617 this.tokenizer.back(tokens.pop());
17618 end = true;
17619 break;
17620 } else if (type === ":") {
17621 colon = true;
17622 }
17623 } else if (type === brackets[brackets.length - 1]) {
17624 brackets.pop();
17625 if (brackets.length === 0) bracket = null;
17626 }
17627 token = this.tokenizer.nextToken();
17628 }
17629 if (this.tokenizer.endOfFile()) end = true;
17630 if (brackets.length > 0) this.unclosedBracket(bracket);
17631 if (end && colon) {
17632 if (!customProperty) {
17633 while(tokens.length){
17634 token = tokens[tokens.length - 1][0];
17635 if (token !== "space" && token !== "comment") break;
17636 this.tokenizer.back(tokens.pop());
17637 }
17638 }
17639 this.decl(tokens, customProperty);
17640 } else {
17641 this.unknownWord(tokens);
17642 }
17643 };
17644 _proto.parse = function parse() {
17645 var token;
17646 while(!this.tokenizer.endOfFile()){
17647 token = this.tokenizer.nextToken();
17648 switch(token[0]){
17649 case "space":
17650 this.spaces += token[1];
17651 break;
17652 case ";":
17653 this.freeSemicolon(token);
17654 break;
17655 case "}":
17656 this.end(token);
17657 break;
17658 case "comment":
17659 this.comment(token);
17660 break;
17661 case "at-word":
17662 this.atrule(token);
17663 break;
17664 case "{":
17665 this.emptyRule(token);
17666 break;
17667 default:
17668 this.other(token);
17669 break;
17670 }
17671 }
17672 this.endFile();
17673 };
17674 _proto.precheckMissedSemicolon = function precheckMissedSemicolon() {};
17675 _proto.raw = function raw(node2, prop, tokens, customProperty) {
17676 var token, type;
17677 var length = tokens.length;
17678 var value = "";
17679 var clean = true;
17680 var next, prev;
17681 for(var i2 = 0; i2 < length; i2 += 1){
17682 token = tokens[i2];
17683 type = token[0];
17684 if (type === "space" && i2 === length - 1 && !customProperty) {
17685 clean = false;
17686 } else if (type === "comment") {
17687 prev = tokens[i2 - 1] ? tokens[i2 - 1][0] : "empty";
17688 next = tokens[i2 + 1] ? tokens[i2 + 1][0] : "empty";
17689 if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
17690 if (value.slice(-1) === ",") {
17691 clean = false;
17692 } else {
17693 value += token[1];
17694 }
17695 } else {
17696 clean = false;
17697 }
17698 } else {
17699 value += token[1];
17700 }
17701 }
17702 if (!clean) {
17703 var raw = tokens.reduce(function(all, i2) {
17704 return all + i2[1];
17705 }, "");
17706 node2.raws[prop] = {
17707 raw: raw,
17708 value: value
17709 };
17710 }
17711 node2[prop] = value;
17712 };
17713 _proto.rule = function rule(tokens) {
17714 tokens.pop();
17715 var node2 = new Rule$2();
17716 this.init(node2, tokens[0][2]);
17717 node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
17718 this.raw(node2, "selector", tokens);
17719 this.current = node2;
17720 };
17721 _proto.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
17722 var lastTokenType;
17723 var spaces = "";
17724 while(tokens.length){
17725 lastTokenType = tokens[tokens.length - 1][0];
17726 if (lastTokenType !== "space" && lastTokenType !== "comment") break;
17727 spaces = tokens.pop()[1] + spaces;
17728 }
17729 return spaces;
17730 };
17731 // Errors
17732 _proto.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
17733 var next;
17734 var spaces = "";
17735 while(tokens.length){
17736 next = tokens[0][0];
17737 if (next !== "space" && next !== "comment") break;
17738 spaces += tokens.shift()[1];
17739 }
17740 return spaces;
17741 };
17742 _proto.spacesFromEnd = function spacesFromEnd(tokens) {
17743 var lastTokenType;
17744 var spaces = "";
17745 while(tokens.length){
17746 lastTokenType = tokens[tokens.length - 1][0];
17747 if (lastTokenType !== "space") break;
17748 spaces = tokens.pop()[1] + spaces;
17749 }
17750 return spaces;
17751 };
17752 _proto.stringFrom = function stringFrom(tokens, from) {
17753 var result2 = "";
17754 for(var i2 = from; i2 < tokens.length; i2++){
17755 result2 += tokens[i2][1];
17756 }
17757 tokens.splice(from, tokens.length - from);
17758 return result2;
17759 };
17760 _proto.unclosedBlock = function unclosedBlock() {
17761 var pos = this.current.source.start;
17762 throw this.input.error("Unclosed block", pos.line, pos.column);
17763 };
17764 _proto.unclosedBracket = function unclosedBracket(bracket) {
17765 throw this.input.error("Unclosed bracket", {
17766 offset: bracket[2]
17767 }, {
17768 offset: bracket[2] + 1
17769 });
17770 };
17771 _proto.unexpectedClose = function unexpectedClose(token) {
17772 throw this.input.error("Unexpected }", {
17773 offset: token[2]
17774 }, {
17775 offset: token[2] + 1
17776 });
17777 };
17778 _proto.unknownWord = function unknownWord(tokens) {
17779 throw this.input.error("Unknown word", {
17780 offset: tokens[0][2]
17781 }, {
17782 offset: tokens[0][2] + tokens[0][1].length
17783 });
17784 };
17785 _proto.unnamedAtrule = function unnamedAtrule(node2, token) {
17786 throw this.input.error("At-rule without name", {
17787 offset: token[2]
17788 }, {
17789 offset: token[2] + token[1].length
17790 });
17791 };
17792 return Parser2;
17793 }();
17794 var parser = Parser$1;
17795 var Container$2 = container;
17796 var Parser22 = parser;
17797 var Input$2 = input;
17798 function parse$3(css, opts) {
17799 var input2 = new Input$2(css, opts);
17800 var parser2 = new Parser22(input2);
17801 try {
17802 parser2.parse();
17803 } catch (e2) {
17804 if (true) {
17805 if (e2.name === "CssSyntaxError" && opts && opts.from) {
17806 if (/\.scss$/i.test(opts.from)) {
17807 e2.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
17808 } else if (/\.sass/i.test(opts.from)) {
17809 e2.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
17810 } else if (/\.less$/i.test(opts.from)) {
17811 e2.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
17812 }
17813 }
17814 }
17815 throw e2;
17816 }
17817 return parser2.root;
17818 }
17819 var parse_1 = parse$3;
17820 parse$3.default = parse$3;
17821 Container$2.registerParse(parse$3);
17822 var isClean = symbols.isClean, my = symbols.my;
17823 var MapGenerator$1 = mapGenerator;
17824 var stringify$2 = stringify_1;
17825 var Container$1 = container;
17826 var Document$2 = document$1$2;
17827 var warnOnce$1 = warnOnce$2;
17828 var Result$2 = result;
17829 var parse$2 = parse_1;
17830 var Root$3 = root;
17831 var TYPE_TO_CLASS_NAME = {
17832 atrule: "AtRule",
17833 comment: "Comment",
17834 decl: "Declaration",
17835 document: "Document",
17836 root: "Root",
17837 rule: "Rule"
17838 };
17839 var PLUGIN_PROPS = {
17840 AtRule: true,
17841 AtRuleExit: true,
17842 Comment: true,
17843 CommentExit: true,
17844 Declaration: true,
17845 DeclarationExit: true,
17846 Document: true,
17847 DocumentExit: true,
17848 Once: true,
17849 OnceExit: true,
17850 postcssPlugin: true,
17851 prepare: true,
17852 Root: true,
17853 RootExit: true,
17854 Rule: true,
17855 RuleExit: true
17856 };
17857 var NOT_VISITORS = {
17858 Once: true,
17859 postcssPlugin: true,
17860 prepare: true
17861 };
17862 var CHILDREN = 0;
17863 function isPromise(obj) {
17864 return (typeof obj === "undefined" ? "undefined" : _type_of(obj)) === "object" && typeof obj.then === "function";
17865 }
17866 function getEvents(node2) {
17867 var key = false;
17868 var type = TYPE_TO_CLASS_NAME[node2.type];
17869 if (node2.type === "decl") {
17870 key = node2.prop.toLowerCase();
17871 } else if (node2.type === "atrule") {
17872 key = node2.name.toLowerCase();
17873 }
17874 if (key && node2.append) {
17875 return [
17876 type,
17877 type + "-" + key,
17878 CHILDREN,
17879 type + "Exit",
17880 type + "Exit-" + key
17881 ];
17882 } else if (key) {
17883 return [
17884 type,
17885 type + "-" + key,
17886 type + "Exit",
17887 type + "Exit-" + key
17888 ];
17889 } else if (node2.append) {
17890 return [
17891 type,
17892 CHILDREN,
17893 type + "Exit"
17894 ];
17895 } else {
17896 return [
17897 type,
17898 type + "Exit"
17899 ];
17900 }
17901 }
17902 function toStack(node2) {
17903 var events;
17904 if (node2.type === "document") {
17905 events = [
17906 "Document",
17907 CHILDREN,
17908 "DocumentExit"
17909 ];
17910 } else if (node2.type === "root") {
17911 events = [
17912 "Root",
17913 CHILDREN,
17914 "RootExit"
17915 ];
17916 } else {
17917 events = getEvents(node2);
17918 }
17919 return {
17920 eventIndex: 0,
17921 events: events,
17922 iterator: 0,
17923 node: node2,
17924 visitorIndex: 0,
17925 visitors: []
17926 };
17927 }
17928 function cleanMarks(node2) {
17929 node2[isClean] = false;
17930 if (node2.nodes) node2.nodes.forEach(function(i2) {
17931 return cleanMarks(i2);
17932 });
17933 return node2;
17934 }
17935 var postcss$2 = {};
17936 var LazyResult$2 = /*#__PURE__*/ function() {
17937 function LazyResult2(processor2, css, opts) {
17938 var _this = this;
17939 this.stringified = false;
17940 this.processed = false;
17941 var root2;
17942 if ((typeof css === "undefined" ? "undefined" : _type_of(css)) === "object" && css !== null && (css.type === "root" || css.type === "document")) {
17943 root2 = cleanMarks(css);
17944 } else if (_instanceof(css, LazyResult2) || _instanceof(css, Result$2)) {
17945 root2 = cleanMarks(css.root);
17946 if (css.map) {
17947 if (typeof opts.map === "undefined") opts.map = {};
17948 if (!opts.map.inline) opts.map.inline = false;
17949 opts.map.prev = css.map;
17950 }
17951 } else {
17952 var parser2 = parse$2;
17953 if (opts.syntax) parser2 = opts.syntax.parse;
17954 if (opts.parser) parser2 = opts.parser;
17955 if (parser2.parse) parser2 = parser2.parse;
17956 try {
17957 root2 = parser2(css, opts);
17958 } catch (error) {
17959 this.processed = true;
17960 this.error = error;
17961 }
17962 if (root2 && !root2[my]) {
17963 Container$1.rebuild(root2);
17964 }
17965 }
17966 this.result = new Result$2(processor2, root2, opts);
17967 this.helpers = _extends({}, postcss$2, {
17968 postcss: postcss$2,
17969 result: this.result
17970 });
17971 this.plugins = this.processor.plugins.map(function(plugin22) {
17972 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.prepare) {
17973 return _extends({}, plugin22, plugin22.prepare(_this.result));
17974 } else {
17975 return plugin22;
17976 }
17977 });
17978 }
17979 var _proto = LazyResult2.prototype;
17980 _proto.async = function async() {
17981 if (this.error) return Promise.reject(this.error);
17982 if (this.processed) return Promise.resolve(this.result);
17983 if (!this.processing) {
17984 this.processing = this.runAsync();
17985 }
17986 return this.processing;
17987 };
17988 _proto.catch = function _catch(onRejected) {
17989 return this.async().catch(onRejected);
17990 };
17991 _proto.finally = function _finally(onFinally) {
17992 return this.async().then(onFinally, onFinally);
17993 };
17994 _proto.getAsyncError = function getAsyncError() {
17995 throw new Error("Use process(css).then(cb) to work with async plugins");
17996 };
17997 _proto.handleError = function handleError(error, node2) {
17998 var plugin22 = this.result.lastPlugin;
17999 try {
18000 if (node2) node2.addToError(error);
18001 this.error = error;
18002 if (error.name === "CssSyntaxError" && !error.plugin) {
18003 error.plugin = plugin22.postcssPlugin;
18004 error.setMessage();
18005 } else if (plugin22.postcssVersion) {
18006 if (true) {
18007 var pluginName = plugin22.postcssPlugin;
18008 var pluginVer = plugin22.postcssVersion;
18009 var runtimeVer = this.result.processor.version;
18010 var a2 = pluginVer.split(".");
18011 var b = runtimeVer.split(".");
18012 if (a2[0] !== b[0] || parseInt(a2[1]) > parseInt(b[1])) {
18013 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.");
18014 }
18015 }
18016 }
18017 } catch (err) {
18018 if (console && console.error) console.error(err);
18019 }
18020 return error;
18021 };
18022 _proto.prepareVisitors = function prepareVisitors() {
18023 var _this = this;
18024 this.listeners = {};
18025 var add = function(plugin22, type, cb) {
18026 if (!_this.listeners[type]) _this.listeners[type] = [];
18027 _this.listeners[type].push([
18028 plugin22,
18029 cb
18030 ]);
18031 };
18032 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
18033 var plugin22 = _step.value;
18034 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object") {
18035 for(var event in plugin22){
18036 if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
18037 throw new Error("Unknown event " + event + " in " + plugin22.postcssPlugin + ". Try to update PostCSS (" + this.processor.version + " now).");
18038 }
18039 if (!NOT_VISITORS[event]) {
18040 if (_type_of(plugin22[event]) === "object") {
18041 for(var filter in plugin22[event]){
18042 if (filter === "*") {
18043 add(plugin22, event, plugin22[event][filter]);
18044 } else {
18045 add(plugin22, event + "-" + filter.toLowerCase(), plugin22[event][filter]);
18046 }
18047 }
18048 } else if (typeof plugin22[event] === "function") {
18049 add(plugin22, event, plugin22[event]);
18050 }
18051 }
18052 }
18053 }
18054 }
18055 this.hasListener = Object.keys(this.listeners).length > 0;
18056 };
18057 _proto.runAsync = function runAsync() {
18058 var _this = this;
18059 return _async_to_generator(function() {
18060 var i2, plugin22, promise, error, root2, stack, promise1, e2, node2, _loop, _iterator, _step;
18061 return _ts_generator(this, function(_state) {
18062 switch(_state.label){
18063 case 0:
18064 _this.plugin = 0;
18065 i2 = 0;
18066 _state.label = 1;
18067 case 1:
18068 if (!(i2 < _this.plugins.length)) return [
18069 3,
18070 6
18071 ];
18072 plugin22 = _this.plugins[i2];
18073 promise = _this.runOnRoot(plugin22);
18074 if (!isPromise(promise)) return [
18075 3,
18076 5
18077 ];
18078 _state.label = 2;
18079 case 2:
18080 _state.trys.push([
18081 2,
18082 4,
18083 ,
18084 5
18085 ]);
18086 return [
18087 4,
18088 promise
18089 ];
18090 case 3:
18091 _state.sent();
18092 return [
18093 3,
18094 5
18095 ];
18096 case 4:
18097 error = _state.sent();
18098 throw _this.handleError(error);
18099 case 5:
18100 i2++;
18101 return [
18102 3,
18103 1
18104 ];
18105 case 6:
18106 _this.prepareVisitors();
18107 if (!_this.hasListener) return [
18108 3,
18109 18
18110 ];
18111 root2 = _this.result.root;
18112 _state.label = 7;
18113 case 7:
18114 if (!!root2[isClean]) return [
18115 3,
18116 14
18117 ];
18118 root2[isClean] = true;
18119 stack = [
18120 toStack(root2)
18121 ];
18122 _state.label = 8;
18123 case 8:
18124 if (!(stack.length > 0)) return [
18125 3,
18126 13
18127 ];
18128 promise1 = _this.visitTick(stack);
18129 if (!isPromise(promise1)) return [
18130 3,
18131 12
18132 ];
18133 _state.label = 9;
18134 case 9:
18135 _state.trys.push([
18136 9,
18137 11,
18138 ,
18139 12
18140 ]);
18141 return [
18142 4,
18143 promise1
18144 ];
18145 case 10:
18146 _state.sent();
18147 return [
18148 3,
18149 12
18150 ];
18151 case 11:
18152 e2 = _state.sent();
18153 node2 = stack[stack.length - 1].node;
18154 throw _this.handleError(e2, node2);
18155 case 12:
18156 return [
18157 3,
18158 8
18159 ];
18160 case 13:
18161 return [
18162 3,
18163 7
18164 ];
18165 case 14:
18166 if (!_this.listeners.OnceExit) return [
18167 3,
18168 18
18169 ];
18170 _loop = function() {
18171 var _step_value, plugin22, visitor, roots, e2;
18172 return _ts_generator(this, function(_state) {
18173 switch(_state.label){
18174 case 0:
18175 _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
18176 _this.result.lastPlugin = plugin22;
18177 _state.label = 1;
18178 case 1:
18179 _state.trys.push([
18180 1,
18181 6,
18182 ,
18183 7
18184 ]);
18185 if (!(root2.type === "document")) return [
18186 3,
18187 3
18188 ];
18189 roots = root2.nodes.map(function(subRoot) {
18190 return visitor(subRoot, _this.helpers);
18191 });
18192 return [
18193 4,
18194 Promise.all(roots)
18195 ];
18196 case 2:
18197 _state.sent();
18198 return [
18199 3,
18200 5
18201 ];
18202 case 3:
18203 return [
18204 4,
18205 visitor(root2, _this.helpers)
18206 ];
18207 case 4:
18208 _state.sent();
18209 _state.label = 5;
18210 case 5:
18211 return [
18212 3,
18213 7
18214 ];
18215 case 6:
18216 e2 = _state.sent();
18217 throw _this.handleError(e2);
18218 case 7:
18219 return [
18220 2
18221 ];
18222 }
18223 });
18224 };
18225 _iterator = _create_for_of_iterator_helper_loose(_this.listeners.OnceExit);
18226 _state.label = 15;
18227 case 15:
18228 if (!!(_step = _iterator()).done) return [
18229 3,
18230 18
18231 ];
18232 return [
18233 5,
18234 _ts_values(_loop())
18235 ];
18236 case 16:
18237 _state.sent();
18238 _state.label = 17;
18239 case 17:
18240 return [
18241 3,
18242 15
18243 ];
18244 case 18:
18245 _this.processed = true;
18246 return [
18247 2,
18248 _this.stringify()
18249 ];
18250 }
18251 });
18252 })();
18253 };
18254 _proto.runOnRoot = function runOnRoot(plugin22) {
18255 var _this = this;
18256 this.result.lastPlugin = plugin22;
18257 try {
18258 if ((typeof plugin22 === "undefined" ? "undefined" : _type_of(plugin22)) === "object" && plugin22.Once) {
18259 if (this.result.root.type === "document") {
18260 var roots = this.result.root.nodes.map(function(root2) {
18261 return plugin22.Once(root2, _this.helpers);
18262 });
18263 if (isPromise(roots[0])) {
18264 return Promise.all(roots);
18265 }
18266 return roots;
18267 }
18268 return plugin22.Once(this.result.root, this.helpers);
18269 } else if (typeof plugin22 === "function") {
18270 return plugin22(this.result.root, this.result);
18271 }
18272 } catch (error) {
18273 throw this.handleError(error);
18274 }
18275 };
18276 _proto.stringify = function stringify() {
18277 if (this.error) throw this.error;
18278 if (this.stringified) return this.result;
18279 this.stringified = true;
18280 this.sync();
18281 var opts = this.result.opts;
18282 var str = stringify$2;
18283 if (opts.syntax) str = opts.syntax.stringify;
18284 if (opts.stringifier) str = opts.stringifier;
18285 if (str.stringify) str = str.stringify;
18286 var map = new MapGenerator$1(str, this.result.root, this.result.opts);
18287 var data = map.generate();
18288 this.result.css = data[0];
18289 this.result.map = data[1];
18290 return this.result;
18291 };
18292 _proto.sync = function sync() {
18293 if (this.error) throw this.error;
18294 if (this.processed) return this.result;
18295 this.processed = true;
18296 if (this.processing) {
18297 throw this.getAsyncError();
18298 }
18299 for(var _iterator = _create_for_of_iterator_helper_loose(this.plugins), _step; !(_step = _iterator()).done;){
18300 var plugin22 = _step.value;
18301 var promise = this.runOnRoot(plugin22);
18302 if (isPromise(promise)) {
18303 throw this.getAsyncError();
18304 }
18305 }
18306 this.prepareVisitors();
18307 if (this.hasListener) {
18308 var root2 = this.result.root;
18309 while(!root2[isClean]){
18310 root2[isClean] = true;
18311 this.walkSync(root2);
18312 }
18313 if (this.listeners.OnceExit) {
18314 if (root2.type === "document") {
18315 for(var _iterator1 = _create_for_of_iterator_helper_loose(root2.nodes), _step1; !(_step1 = _iterator1()).done;){
18316 var subRoot = _step1.value;
18317 this.visitSync(this.listeners.OnceExit, subRoot);
18318 }
18319 } else {
18320 this.visitSync(this.listeners.OnceExit, root2);
18321 }
18322 }
18323 }
18324 return this.result;
18325 };
18326 _proto.then = function then(onFulfilled, onRejected) {
18327 if (true) {
18328 if (!("from" in this.opts)) {
18329 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.");
18330 }
18331 }
18332 return this.async().then(onFulfilled, onRejected);
18333 };
18334 _proto.toString = function toString() {
18335 return this.css;
18336 };
18337 _proto.visitSync = function visitSync(visitors, node2) {
18338 for(var _iterator = _create_for_of_iterator_helper_loose(visitors), _step; !(_step = _iterator()).done;){
18339 var _step_value = _step.value, plugin22 = _step_value[0], visitor = _step_value[1];
18340 this.result.lastPlugin = plugin22;
18341 var promise = void 0;
18342 try {
18343 promise = visitor(node2, this.helpers);
18344 } catch (e2) {
18345 throw this.handleError(e2, node2.proxyOf);
18346 }
18347 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
18348 return true;
18349 }
18350 if (isPromise(promise)) {
18351 throw this.getAsyncError();
18352 }
18353 }
18354 };
18355 _proto.visitTick = function visitTick(stack) {
18356 var visit2 = stack[stack.length - 1];
18357 var node2 = visit2.node, visitors = visit2.visitors;
18358 if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
18359 stack.pop();
18360 return;
18361 }
18362 if (visitors.length > 0 && visit2.visitorIndex < visitors.length) {
18363 var _visitors_visit2_visitorIndex = visitors[visit2.visitorIndex], plugin22 = _visitors_visit2_visitorIndex[0], visitor = _visitors_visit2_visitorIndex[1];
18364 visit2.visitorIndex += 1;
18365 if (visit2.visitorIndex === visitors.length) {
18366 visit2.visitors = [];
18367 visit2.visitorIndex = 0;
18368 }
18369 this.result.lastPlugin = plugin22;
18370 try {
18371 return visitor(node2.toProxy(), this.helpers);
18372 } catch (e2) {
18373 throw this.handleError(e2, node2);
18374 }
18375 }
18376 if (visit2.iterator !== 0) {
18377 var iterator = visit2.iterator;
18378 var child;
18379 while(child = node2.nodes[node2.indexes[iterator]]){
18380 node2.indexes[iterator] += 1;
18381 if (!child[isClean]) {
18382 child[isClean] = true;
18383 stack.push(toStack(child));
18384 return;
18385 }
18386 }
18387 visit2.iterator = 0;
18388 delete node2.indexes[iterator];
18389 }
18390 var events = visit2.events;
18391 while(visit2.eventIndex < events.length){
18392 var event = events[visit2.eventIndex];
18393 visit2.eventIndex += 1;
18394 if (event === CHILDREN) {
18395 if (node2.nodes && node2.nodes.length) {
18396 node2[isClean] = true;
18397 visit2.iterator = node2.getIterator();
18398 }
18399 return;
18400 } else if (this.listeners[event]) {
18401 visit2.visitors = this.listeners[event];
18402 return;
18403 }
18404 }
18405 stack.pop();
18406 };
18407 _proto.walkSync = function walkSync(node2) {
18408 var _this = this;
18409 node2[isClean] = true;
18410 var events = getEvents(node2);
18411 for(var _iterator = _create_for_of_iterator_helper_loose(events), _step; !(_step = _iterator()).done;){
18412 var event = _step.value;
18413 if (event === CHILDREN) {
18414 if (node2.nodes) {
18415 node2.each(function(child) {
18416 if (!child[isClean]) _this.walkSync(child);
18417 });
18418 }
18419 } else {
18420 var visitors = this.listeners[event];
18421 if (visitors) {
18422 if (this.visitSync(visitors, node2.toProxy())) return;
18423 }
18424 }
18425 }
18426 };
18427 _proto.warnings = function warnings() {
18428 return this.sync().warnings();
18429 };
18430 _create_class(LazyResult2, [
18431 {
18432 key: "content",
18433 get: function get() {
18434 return this.stringify().content;
18435 }
18436 },
18437 {
18438 key: "css",
18439 get: function get() {
18440 return this.stringify().css;
18441 }
18442 },
18443 {
18444 key: "map",
18445 get: function get() {
18446 return this.stringify().map;
18447 }
18448 },
18449 {
18450 key: "messages",
18451 get: function get() {
18452 return this.sync().messages;
18453 }
18454 },
18455 {
18456 key: "opts",
18457 get: function get() {
18458 return this.result.opts;
18459 }
18460 },
18461 {
18462 key: "processor",
18463 get: function get() {
18464 return this.result.processor;
18465 }
18466 },
18467 {
18468 key: "root",
18469 get: function get() {
18470 return this.sync().root;
18471 }
18472 },
18473 {
18474 key: Symbol.toStringTag,
18475 get: function get() {
18476 return "LazyResult";
18477 }
18478 }
18479 ]);
18480 return LazyResult2;
18481 }();
18482 LazyResult$2.registerPostcss = function(dependant) {
18483 postcss$2 = dependant;
18484 };
18485 var lazyResult = LazyResult$2;
18486 LazyResult$2.default = LazyResult$2;
18487 Root$3.registerLazyResult(LazyResult$2);
18488 Document$2.registerLazyResult(LazyResult$2);
18489 var MapGenerator22 = mapGenerator;
18490 var stringify$1 = stringify_1;
18491 var warnOnce22 = warnOnce$2;
18492 var parse$1 = parse_1;
18493 var Result$1 = result;
18494 var NoWorkResult$1 = /*#__PURE__*/ function() {
18495 function NoWorkResult2(processor2, css, opts) {
18496 css = css.toString();
18497 this.stringified = false;
18498 this._processor = processor2;
18499 this._css = css;
18500 this._opts = opts;
18501 this._map = void 0;
18502 var root2;
18503 var str = stringify$1;
18504 this.result = new Result$1(this._processor, root2, this._opts);
18505 this.result.css = css;
18506 var self = this;
18507 Object.defineProperty(this.result, "root", {
18508 get: function get() {
18509 return self.root;
18510 }
18511 });
18512 var map = new MapGenerator22(str, root2, this._opts, css);
18513 if (map.isMap()) {
18514 var _map_generate = map.generate(), generatedCSS = _map_generate[0], generatedMap = _map_generate[1];
18515 if (generatedCSS) {
18516 this.result.css = generatedCSS;
18517 }
18518 if (generatedMap) {
18519 this.result.map = generatedMap;
18520 }
18521 } else {
18522 map.clearAnnotation();
18523 this.result.css = map.css;
18524 }
18525 }
18526 var _proto = NoWorkResult2.prototype;
18527 _proto.async = function async() {
18528 if (this.error) return Promise.reject(this.error);
18529 return Promise.resolve(this.result);
18530 };
18531 _proto.catch = function _catch(onRejected) {
18532 return this.async().catch(onRejected);
18533 };
18534 _proto.finally = function _finally(onFinally) {
18535 return this.async().then(onFinally, onFinally);
18536 };
18537 _proto.sync = function sync() {
18538 if (this.error) throw this.error;
18539 return this.result;
18540 };
18541 _proto.then = function then(onFulfilled, onRejected) {
18542 if (true) {
18543 if (!("from" in this._opts)) {
18544 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.");
18545 }
18546 }
18547 return this.async().then(onFulfilled, onRejected);
18548 };
18549 _proto.toString = function toString() {
18550 return this._css;
18551 };
18552 _proto.warnings = function warnings() {
18553 return [];
18554 };
18555 _create_class(NoWorkResult2, [
18556 {
18557 key: "content",
18558 get: function get() {
18559 return this.result.css;
18560 }
18561 },
18562 {
18563 key: "css",
18564 get: function get() {
18565 return this.result.css;
18566 }
18567 },
18568 {
18569 key: "map",
18570 get: function get() {
18571 return this.result.map;
18572 }
18573 },
18574 {
18575 key: "messages",
18576 get: function get() {
18577 return [];
18578 }
18579 },
18580 {
18581 key: "opts",
18582 get: function get() {
18583 return this.result.opts;
18584 }
18585 },
18586 {
18587 key: "processor",
18588 get: function get() {
18589 return this.result.processor;
18590 }
18591 },
18592 {
18593 key: "root",
18594 get: function get() {
18595 if (this._root) {
18596 return this._root;
18597 }
18598 var root2;
18599 var parser2 = parse$1;
18600 try {
18601 root2 = parser2(this._css, this._opts);
18602 } catch (error) {
18603 this.error = error;
18604 }
18605 if (this.error) {
18606 throw this.error;
18607 } else {
18608 this._root = root2;
18609 return root2;
18610 }
18611 }
18612 },
18613 {
18614 key: Symbol.toStringTag,
18615 get: function get() {
18616 return "NoWorkResult";
18617 }
18618 }
18619 ]);
18620 return NoWorkResult2;
18621 }();
18622 var noWorkResult = NoWorkResult$1;
18623 NoWorkResult$1.default = NoWorkResult$1;
18624 var NoWorkResult22 = noWorkResult;
18625 var LazyResult$1 = lazyResult;
18626 var Document$1 = document$1$2;
18627 var Root$2 = root;
18628 var Processor$1 = /*#__PURE__*/ function() {
18629 function Processor2(plugins) {
18630 if (plugins === void 0) plugins = [];
18631 this.version = "8.4.38";
18632 this.plugins = this.normalize(plugins);
18633 }
18634 var _proto = Processor2.prototype;
18635 _proto.normalize = function normalize(plugins) {
18636 var normalized = [];
18637 for(var _iterator = _create_for_of_iterator_helper_loose(plugins), _step; !(_step = _iterator()).done;){
18638 var i2 = _step.value;
18639 if (i2.postcss === true) {
18640 i2 = i2();
18641 } else if (i2.postcss) {
18642 i2 = i2.postcss;
18643 }
18644 if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && Array.isArray(i2.plugins)) {
18645 normalized = normalized.concat(i2.plugins);
18646 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && i2.postcssPlugin) {
18647 normalized.push(i2);
18648 } else if (typeof i2 === "function") {
18649 normalized.push(i2);
18650 } else if ((typeof i2 === "undefined" ? "undefined" : _type_of(i2)) === "object" && (i2.parse || i2.stringify)) {
18651 if (true) {
18652 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.");
18653 }
18654 } else {
18655 throw new Error(i2 + " is not a PostCSS plugin");
18656 }
18657 }
18658 return normalized;
18659 };
18660 _proto.process = function process1(css, opts) {
18661 if (opts === void 0) opts = {};
18662 if (!this.plugins.length && !opts.parser && !opts.stringifier && !opts.syntax) {
18663 return new NoWorkResult22(this, css, opts);
18664 } else {
18665 return new LazyResult$1(this, css, opts);
18666 }
18667 };
18668 _proto.use = function use(plugin22) {
18669 this.plugins = this.plugins.concat(this.normalize([
18670 plugin22
18671 ]));
18672 return this;
18673 };
18674 return Processor2;
18675 }();
18676 var processor = Processor$1;
18677 Processor$1.default = Processor$1;
18678 Root$2.registerProcessor(Processor$1);
18679 Document$1.registerProcessor(Processor$1);
18680 var Declaration$1 = declaration;
18681 var PreviousMap22 = previousMap;
18682 var Comment$1 = comment;
18683 var AtRule$1 = atRule;
18684 var Input$1 = input;
18685 var Root$1 = root;
18686 var Rule$1 = rule;
18687 function fromJSON$1(json, inputs) {
18688 if (Array.isArray(json)) return json.map(function(n2) {
18689 return fromJSON$1(n2);
18690 });
18691 var ownInputs = json.inputs, defaults = _object_without_properties_loose(json, [
18692 "inputs"
18693 ]);
18694 if (ownInputs) {
18695 inputs = [];
18696 for(var _iterator = _create_for_of_iterator_helper_loose(ownInputs), _step; !(_step = _iterator()).done;){
18697 var input2 = _step.value;
18698 var inputHydrated = _extends({}, input2, {
18699 __proto__: Input$1.prototype
18700 });
18701 if (inputHydrated.map) {
18702 inputHydrated.map = _extends({}, inputHydrated.map, {
18703 __proto__: PreviousMap22.prototype
18704 });
18705 }
18706 inputs.push(inputHydrated);
18707 }
18708 }
18709 if (defaults.nodes) {
18710 defaults.nodes = json.nodes.map(function(n2) {
18711 return fromJSON$1(n2, inputs);
18712 });
18713 }
18714 if (defaults.source) {
18715 var _defaults_source = defaults.source, inputId = _defaults_source.inputId, source = _object_without_properties_loose(_defaults_source, [
18716 "inputId"
18717 ]);
18718 defaults.source = source;
18719 if (inputId != null) {
18720 defaults.source.input = inputs[inputId];
18721 }
18722 }
18723 if (defaults.type === "root") {
18724 return new Root$1(defaults);
18725 } else if (defaults.type === "decl") {
18726 return new Declaration$1(defaults);
18727 } else if (defaults.type === "rule") {
18728 return new Rule$1(defaults);
18729 } else if (defaults.type === "comment") {
18730 return new Comment$1(defaults);
18731 } else if (defaults.type === "atrule") {
18732 return new AtRule$1(defaults);
18733 } else {
18734 throw new Error("Unknown node type: " + json.type);
18735 }
18736 }
18737 var fromJSON_1 = fromJSON$1;
18738 fromJSON$1.default = fromJSON$1;
18739 var CssSyntaxError22 = cssSyntaxError;
18740 var Declaration22 = declaration;
18741 var LazyResult22 = lazyResult;
18742 var Container22 = container;
18743 var Processor22 = processor;
18744 var stringify = stringify_1;
18745 var fromJSON = fromJSON_1;
18746 var Document222 = document$1$2;
18747 var Warning22 = warning;
18748 var Comment22 = comment;
18749 var AtRule22 = atRule;
18750 var Result22 = result;
18751 var Input22 = input;
18752 var parse = parse_1;
18753 var list = list_1;
18754 var Rule22 = rule;
18755 var Root22 = root;
18756 var Node22 = node;
18757 function postcss() {
18758 for(var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++){
18759 plugins[_key] = arguments[_key];
18760 }
18761 if (plugins.length === 1 && Array.isArray(plugins[0])) {
18762 plugins = plugins[0];
18763 }
18764 return new Processor22(plugins);
18765 }
18766 postcss.plugin = function plugin2(name, initializer) {
18767 var warningPrinted = false;
18768 function creator() {
18769 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
18770 args[_key] = arguments[_key];
18771 }
18772 if (console && console.warn && !warningPrinted) {
18773 warningPrinted = true;
18774 console.warn(name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration");
18775 if (process.env.LANG && process.env.LANG.startsWith("cn")) {
18776 console.warn(name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226");
18777 }
18778 }
18779 var transformer = initializer.apply(void 0, [].concat(args));
18780 transformer.postcssPlugin = name;
18781 transformer.postcssVersion = new Processor22().version;
18782 return transformer;
18783 }
18784 var cache;
18785 Object.defineProperty(creator, "postcss", {
18786 get: function get() {
18787 if (!cache) cache = creator();
18788 return cache;
18789 }
18790 });
18791 creator.process = function(css, processOpts, pluginOpts) {
18792 return postcss([
18793 creator(pluginOpts)
18794 ]).process(css, processOpts);
18795 };
18796 return creator;
18797 };
18798 postcss.stringify = stringify;
18799 postcss.parse = parse;
18800 postcss.fromJSON = fromJSON;
18801 postcss.list = list;
18802 postcss.comment = function(defaults) {
18803 return new Comment22(defaults);
18804 };
18805 postcss.atRule = function(defaults) {
18806 return new AtRule22(defaults);
18807 };
18808 postcss.decl = function(defaults) {
18809 return new Declaration22(defaults);
18810 };
18811 postcss.rule = function(defaults) {
18812 return new Rule22(defaults);
18813 };
18814 postcss.root = function(defaults) {
18815 return new Root22(defaults);
18816 };
18817 postcss.document = function(defaults) {
18818 return new Document222(defaults);
18819 };
18820 postcss.CssSyntaxError = CssSyntaxError22;
18821 postcss.Declaration = Declaration22;
18822 postcss.Container = Container22;
18823 postcss.Processor = Processor22;
18824 postcss.Document = Document222;
18825 postcss.Comment = Comment22;
18826 postcss.Warning = Warning22;
18827 postcss.AtRule = AtRule22;
18828 postcss.Result = Result22;
18829 postcss.Input = Input22;
18830 postcss.Rule = Rule22;
18831 postcss.Root = Root22;
18832 postcss.Node = Node22;
18833 LazyResult22.registerPostcss(postcss);
18834 var postcss_1 = postcss;
18835 postcss.default = postcss;
18836 var postcss$1 = /* @__PURE__ */ getDefaultExportFromCjs(postcss_1);
18837 postcss$1.stringify;
18838 postcss$1.fromJSON;
18839 postcss$1.plugin;
18840 postcss$1.parse;
18841 postcss$1.list;
18842 postcss$1.document;
18843 postcss$1.comment;
18844 postcss$1.atRule;
18845 postcss$1.rule;
18846 postcss$1.decl;
18847 postcss$1.root;
18848 postcss$1.CssSyntaxError;
18849 postcss$1.Declaration;
18850 postcss$1.Container;
18851 postcss$1.Processor;
18852 postcss$1.Document;
18853 postcss$1.Comment;
18854 postcss$1.Warning;
18855 postcss$1.AtRule;
18856 postcss$1.Result;
18857 postcss$1.Input;
18858 postcss$1.Rule;
18859 postcss$1.Root;
18860 postcss$1.Node;
18861 var BaseRRNode = /*#__PURE__*/ function() {
18862 function BaseRRNode() {
18863 for(var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++){
18864 _args[_key] = arguments[_key];
18865 }
18866 __publicField2(this, "parentElement", null);
18867 __publicField2(this, "parentNode", null);
18868 __publicField2(this, "ownerDocument");
18869 __publicField2(this, "firstChild", null);
18870 __publicField2(this, "lastChild", null);
18871 __publicField2(this, "previousSibling", null);
18872 __publicField2(this, "nextSibling", null);
18873 __publicField2(this, "ELEMENT_NODE", 1);
18874 __publicField2(this, "TEXT_NODE", 3);
18875 __publicField2(this, "nodeType");
18876 __publicField2(this, "nodeName");
18877 __publicField2(this, "RRNodeType");
18878 }
18879 var _proto = BaseRRNode.prototype;
18880 _proto.contains = function contains(node2) {
18881 if (!_instanceof(node2, BaseRRNode)) return false;
18882 else if (node2.ownerDocument !== this.ownerDocument) return false;
18883 else if (node2 === this) return true;
18884 while(node2.parentNode){
18885 if (node2.parentNode === this) return true;
18886 node2 = node2.parentNode;
18887 }
18888 return false;
18889 };
18890 // eslint-disable-next-line @typescript-eslint/no-unused-vars
18891 _proto.appendChild = function appendChild(_newChild) {
18892 throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.");
18893 };
18894 // eslint-disable-next-line @typescript-eslint/no-unused-vars
18895 _proto.insertBefore = function insertBefore(_newChild, _refChild) {
18896 throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.");
18897 };
18898 // eslint-disable-next-line @typescript-eslint/no-unused-vars
18899 _proto.removeChild = function removeChild(_node) {
18900 throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.");
18901 };
18902 _proto.toString = function toString() {
18903 return "RRNode";
18904 };
18905 _create_class(BaseRRNode, [
18906 {
18907 key: "childNodes",
18908 get: function get() {
18909 var childNodes2 = [];
18910 var childIterator = this.firstChild;
18911 while(childIterator){
18912 childNodes2.push(childIterator);
18913 childIterator = childIterator.nextSibling;
18914 }
18915 return childNodes2;
18916 }
18917 }
18918 ]);
18919 return BaseRRNode;
18920 }();
18921 var testableAccessors = {
18922 Node: [
18923 "childNodes",
18924 "parentNode",
18925 "parentElement",
18926 "textContent"
18927 ],
18928 ShadowRoot: [
18929 "host",
18930 "styleSheets"
18931 ],
18932 Element: [
18933 "shadowRoot",
18934 "querySelector",
18935 "querySelectorAll"
18936 ],
18937 MutationObserver: []
18938 };
18939 var testableMethods = {
18940 Node: [
18941 "contains",
18942 "getRootNode"
18943 ],
18944 ShadowRoot: [
18945 "getSelection"
18946 ],
18947 Element: [],
18948 MutationObserver: [
18949 "constructor"
18950 ]
18951 };
18952 var untaintedBasePrototype = {};
18953 var isAngularZonePresent = function() {
18954 return !!globalThis.Zone;
18955 };
18956 function getUntaintedPrototype(key) {
18957 if (untaintedBasePrototype[key]) return untaintedBasePrototype[key];
18958 var defaultObj = globalThis[key];
18959 var defaultPrototype = defaultObj.prototype;
18960 var accessorNames = key in testableAccessors ? testableAccessors[key] : void 0;
18961 var isUntaintedAccessors = Boolean(accessorNames && // @ts-expect-error 2345
18962 accessorNames.every(function(accessor) {
18963 var _a2, _b;
18964 return Boolean((_b = (_a2 = Object.getOwnPropertyDescriptor(defaultPrototype, accessor)) == null ? void 0 : _a2.get) == null ? void 0 : _b.toString().includes("[native code]"));
18965 }));
18966 var methodNames = key in testableMethods ? testableMethods[key] : void 0;
18967 var isUntaintedMethods = Boolean(methodNames && methodNames.every(// @ts-expect-error 2345
18968 function(method) {
18969 var _a2;
18970 return typeof defaultPrototype[method] === "function" && ((_a2 = defaultPrototype[method]) == null ? void 0 : _a2.toString().includes("[native code]"));
18971 }));
18972 if (isUntaintedAccessors && isUntaintedMethods && !isAngularZonePresent()) {
18973 untaintedBasePrototype[key] = defaultObj.prototype;
18974 return defaultObj.prototype;
18975 }
18976 try {
18977 var iframeEl = document.createElement("iframe");
18978 document.body.appendChild(iframeEl);
18979 var win = iframeEl.contentWindow;
18980 if (!win) return defaultObj.prototype;
18981 var untaintedObject = win[key].prototype;
18982 document.body.removeChild(iframeEl);
18983 if (!untaintedObject) return defaultPrototype;
18984 return untaintedBasePrototype[key] = untaintedObject;
18985 } catch (e) {
18986 return defaultPrototype;
18987 }
18988 }
18989 var untaintedAccessorCache = {};
18990 function getUntaintedAccessor(key, instance, accessor) {
18991 var _a2;
18992 var cacheKey = key + "." + String(accessor);
18993 if (untaintedAccessorCache[cacheKey]) return untaintedAccessorCache[cacheKey].call(instance);
18994 var untaintedPrototype = getUntaintedPrototype(key);
18995 var untaintedAccessor = (_a2 = Object.getOwnPropertyDescriptor(untaintedPrototype, accessor)) == null ? void 0 : _a2.get;
18996 if (!untaintedAccessor) return instance[accessor];
18997 untaintedAccessorCache[cacheKey] = untaintedAccessor;
18998 return untaintedAccessor.call(instance);
18999 }
19000 var untaintedMethodCache = {};
19001 function getUntaintedMethod(key, instance, method) {
19002 var cacheKey = key + "." + String(method);
19003 if (untaintedMethodCache[cacheKey]) return untaintedMethodCache[cacheKey].bind(instance);
19004 var untaintedPrototype = getUntaintedPrototype(key);
19005 var untaintedMethod = untaintedPrototype[method];
19006 if (typeof untaintedMethod !== "function") return instance[method];
19007 untaintedMethodCache[cacheKey] = untaintedMethod;
19008 return untaintedMethod.bind(instance);
19009 }
19010 function childNodes(n2) {
19011 return getUntaintedAccessor("Node", n2, "childNodes");
19012 }
19013 function parentNode(n2) {
19014 return getUntaintedAccessor("Node", n2, "parentNode");
19015 }
19016 function parentElement(n2) {
19017 return getUntaintedAccessor("Node", n2, "parentElement");
19018 }
19019 function textContent(n2) {
19020 return getUntaintedAccessor("Node", n2, "textContent");
19021 }
19022 function contains(n2, other) {
19023 return getUntaintedMethod("Node", n2, "contains")(other);
19024 }
19025 function getRootNode(n2) {
19026 return getUntaintedMethod("Node", n2, "getRootNode")();
19027 }
19028 function host(n2) {
19029 if (!n2 || !("host" in n2)) return null;
19030 return getUntaintedAccessor("ShadowRoot", n2, "host");
19031 }
19032 function styleSheets(n2) {
19033 return n2.styleSheets;
19034 }
19035 function shadowRoot(n2) {
19036 if (!n2 || !("shadowRoot" in n2)) return null;
19037 return getUntaintedAccessor("Element", n2, "shadowRoot");
19038 }
19039 function querySelector(n2, selectors) {
19040 return getUntaintedAccessor("Element", n2, "querySelector")(selectors);
19041 }
19042 function querySelectorAll(n2, selectors) {
19043 return getUntaintedAccessor("Element", n2, "querySelectorAll")(selectors);
19044 }
19045 function mutationObserverCtor() {
19046 return getUntaintedPrototype("MutationObserver").constructor;
19047 }
19048 function patch(source, name, replacement) {
19049 try {
19050 if (!(name in source)) {
19051 return function() {};
19052 }
19053 var original = source[name];
19054 var wrapped = replacement(original);
19055 if (typeof wrapped === "function") {
19056 wrapped.prototype = wrapped.prototype || {};
19057 Object.defineProperties(wrapped, {
19058 __rrweb_original__: {
19059 enumerable: false,
19060 value: original
19061 }
19062 });
19063 }
19064 source[name] = wrapped;
19065 return function() {
19066 source[name] = original;
19067 };
19068 } catch (e) {
19069 return function() {};
19070 }
19071 }
19072 var index = {
19073 childNodes: childNodes,
19074 parentNode: parentNode,
19075 parentElement: parentElement,
19076 textContent: textContent,
19077 contains: contains,
19078 getRootNode: getRootNode,
19079 host: host,
19080 styleSheets: styleSheets,
19081 shadowRoot: shadowRoot,
19082 querySelector: querySelector,
19083 querySelectorAll: querySelectorAll,
19084 mutationObserver: mutationObserverCtor,
19085 patch: patch
19086 };
19087 function on(type, fn, target) {
19088 if (target === void 0) target = document;
19089 var options = {
19090 capture: true,
19091 passive: true
19092 };
19093 target.addEventListener(type, fn, options);
19094 return function() {
19095 return target.removeEventListener(type, fn, options);
19096 };
19097 }
19098 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.";
19099 var _mirror = {
19100 map: {},
19101 getId: function getId() {
19102 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19103 return -1;
19104 },
19105 getNode: function getNode() {
19106 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19107 return null;
19108 },
19109 removeNodeFromMap: function removeNodeFromMap() {
19110 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19111 },
19112 has: function has() {
19113 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19114 return false;
19115 },
19116 reset: function reset() {
19117 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19118 }
19119 };
19120 if (typeof window !== "undefined" && window.Proxy && window.Reflect) {
19121 _mirror = new Proxy(_mirror, {
19122 get: function get(target, prop, receiver) {
19123 if (prop === "map") {
19124 console.error(DEPARTED_MIRROR_ACCESS_WARNING);
19125 }
19126 return Reflect.get(target, prop, receiver);
19127 }
19128 });
19129 }
19130 function throttle(func, wait, options) {
19131 if (options === void 0) options = {};
19132 var timeout = null;
19133 var previous = 0;
19134 return function() {
19135 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
19136 args[_key] = arguments[_key];
19137 }
19138 var now = Date.now();
19139 if (!previous && options.leading === false) {
19140 previous = now;
19141 }
19142 var remaining = wait - (now - previous);
19143 var context = this;
19144 if (remaining <= 0 || remaining > wait) {
19145 if (timeout) {
19146 clearTimeout(timeout);
19147 timeout = null;
19148 }
19149 previous = now;
19150 func.apply(context, args);
19151 } else if (!timeout && options.trailing !== false) {
19152 timeout = setTimeout(function() {
19153 previous = options.leading === false ? 0 : Date.now();
19154 timeout = null;
19155 func.apply(context, args);
19156 }, remaining);
19157 }
19158 };
19159 }
19160 function hookSetter(target, key, d, isRevoked, win) {
19161 if (win === void 0) win = window;
19162 var original = win.Object.getOwnPropertyDescriptor(target, key);
19163 win.Object.defineProperty(target, key, isRevoked ? d : {
19164 set: function set(value) {
19165 var _this = this;
19166 setTimeout(function() {
19167 d.set.call(_this, value);
19168 }, 0);
19169 if (original && original.set) {
19170 original.set.call(this, value);
19171 }
19172 }
19173 });
19174 return function() {
19175 return hookSetter(target, key, original || {}, true);
19176 };
19177 }
19178 var nowTimestamp = Date.now;
19179 if (!/* @__PURE__ */ /[1-9][0-9]{12}/.test(Date.now().toString())) {
19180 nowTimestamp = function() {
19181 return /* @__PURE__ */ new Date().getTime();
19182 };
19183 }
19184 function getWindowScroll(win) {
19185 var _a2, _b, _c, _d;
19186 var doc = win.document;
19187 return {
19188 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,
19189 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
19190 };
19191 }
19192 function getWindowHeight() {
19193 return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight;
19194 }
19195 function getWindowWidth() {
19196 return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth;
19197 }
19198 function closestElementOfNode(node2) {
19199 if (!node2) {
19200 return null;
19201 }
19202 var el = node2.nodeType === node2.ELEMENT_NODE ? node2 : index.parentElement(node2);
19203 return el;
19204 }
19205 function isBlocked(node2, blockClass, blockSelector, checkAncestors) {
19206 if (!node2) {
19207 return false;
19208 }
19209 var el = closestElementOfNode(node2);
19210 if (!el) {
19211 return false;
19212 }
19213 try {
19214 if (typeof blockClass === "string") {
19215 if (el.classList.contains(blockClass)) return true;
19216 if (checkAncestors && el.closest("." + blockClass) !== null) return true;
19217 } else {
19218 if (classMatchesRegex(el, blockClass, checkAncestors)) return true;
19219 }
19220 } catch (e2) {}
19221 if (blockSelector) {
19222 if (el.matches(blockSelector)) return true;
19223 if (checkAncestors && el.closest(blockSelector) !== null) return true;
19224 }
19225 return false;
19226 }
19227 function isSerialized(n2, mirror2) {
19228 return mirror2.getId(n2) !== -1;
19229 }
19230 function isIgnored(n2, mirror2, slimDOMOptions) {
19231 if (n2.tagName === "TITLE" && slimDOMOptions.headTitleMutations) {
19232 return true;
19233 }
19234 return mirror2.getId(n2) === IGNORED_NODE;
19235 }
19236 function isAncestorRemoved(target, mirror2) {
19237 if (isShadowRoot(target)) {
19238 return false;
19239 }
19240 var id = mirror2.getId(target);
19241 if (!mirror2.has(id)) {
19242 return true;
19243 }
19244 var parent = index.parentNode(target);
19245 if (parent && parent.nodeType === target.DOCUMENT_NODE) {
19246 return false;
19247 }
19248 if (!parent) {
19249 return true;
19250 }
19251 return isAncestorRemoved(parent, mirror2);
19252 }
19253 function legacy_isTouchEvent(event) {
19254 return Boolean(event.changedTouches);
19255 }
19256 function polyfill$1(win) {
19257 if (win === void 0) win = window;
19258 if ("NodeList" in win && !win.NodeList.prototype.forEach) {
19259 win.NodeList.prototype.forEach = Array.prototype.forEach;
19260 }
19261 if ("DOMTokenList" in win && !win.DOMTokenList.prototype.forEach) {
19262 win.DOMTokenList.prototype.forEach = Array.prototype.forEach;
19263 }
19264 }
19265 function isSerializedIframe(n2, mirror2) {
19266 return Boolean(n2.nodeName === "IFRAME" && mirror2.getMeta(n2));
19267 }
19268 function isSerializedStylesheet(n2, mirror2) {
19269 return Boolean(n2.nodeName === "LINK" && n2.nodeType === n2.ELEMENT_NODE && n2.getAttribute && n2.getAttribute("rel") === "stylesheet" && mirror2.getMeta(n2));
19270 }
19271 function hasShadowRoot(n2) {
19272 if (!n2) return false;
19273 if (_instanceof(n2, BaseRRNode) && "shadowRoot" in n2) {
19274 return Boolean(n2.shadowRoot);
19275 }
19276 return Boolean(index.shadowRoot(n2));
19277 }
19278 var StyleSheetMirror = /*#__PURE__*/ function() {
19279 function StyleSheetMirror() {
19280 __publicField(this, "id", 1);
19281 __publicField(this, "styleIDMap", /* @__PURE__ */ new WeakMap());
19282 __publicField(this, "idStyleMap", /* @__PURE__ */ new Map());
19283 }
19284 var _proto = StyleSheetMirror.prototype;
19285 _proto.getId = function getId(stylesheet) {
19286 var _this_styleIDMap_get;
19287 return (_this_styleIDMap_get = this.styleIDMap.get(stylesheet)) != null ? _this_styleIDMap_get : -1;
19288 };
19289 _proto.has = function has(stylesheet) {
19290 return this.styleIDMap.has(stylesheet);
19291 };
19292 /**
19293 * @returns If the stylesheet is in the mirror, returns the id of the stylesheet. If not, return the new assigned id.
19294 */ _proto.add = function add(stylesheet, id) {
19295 if (this.has(stylesheet)) return this.getId(stylesheet);
19296 var newId;
19297 if (id === void 0) {
19298 newId = this.id++;
19299 } else newId = id;
19300 this.styleIDMap.set(stylesheet, newId);
19301 this.idStyleMap.set(newId, stylesheet);
19302 return newId;
19303 };
19304 _proto.getStyle = function getStyle(id) {
19305 return this.idStyleMap.get(id) || null;
19306 };
19307 _proto.reset = function reset() {
19308 this.styleIDMap = /* @__PURE__ */ new WeakMap();
19309 this.idStyleMap = /* @__PURE__ */ new Map();
19310 this.id = 1;
19311 };
19312 _proto.generateId = function generateId() {
19313 return this.id++;
19314 };
19315 return StyleSheetMirror;
19316 }();
19317 function getShadowHost(n2) {
19318 var _a2;
19319 var shadowHost = null;
19320 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));
19321 return shadowHost;
19322 }
19323 function getRootShadowHost(n2) {
19324 var rootShadowHost = n2;
19325 var shadowHost;
19326 while(shadowHost = getShadowHost(rootShadowHost))rootShadowHost = shadowHost;
19327 return rootShadowHost;
19328 }
19329 function shadowHostInDom(n2) {
19330 var doc = n2.ownerDocument;
19331 if (!doc) return false;
19332 var shadowHost = getRootShadowHost(n2);
19333 return index.contains(doc, shadowHost);
19334 }
19335 function inDom(n2) {
19336 var doc = n2.ownerDocument;
19337 if (!doc) return false;
19338 return index.contains(doc, n2) || shadowHostInDom(n2);
19339 }
19340 var EventType = /* @__PURE__ */ function(EventType2) {
19341 EventType2[EventType2["DomContentLoaded"] = 0] = "DomContentLoaded";
19342 EventType2[EventType2["Load"] = 1] = "Load";
19343 EventType2[EventType2["FullSnapshot"] = 2] = "FullSnapshot";
19344 EventType2[EventType2["IncrementalSnapshot"] = 3] = "IncrementalSnapshot";
19345 EventType2[EventType2["Meta"] = 4] = "Meta";
19346 EventType2[EventType2["Custom"] = 5] = "Custom";
19347 EventType2[EventType2["Plugin"] = 6] = "Plugin";
19348 return EventType2;
19349 }(EventType || {});
19350 var IncrementalSource = /* @__PURE__ */ function(IncrementalSource2) {
19351 IncrementalSource2[IncrementalSource2["Mutation"] = 0] = "Mutation";
19352 IncrementalSource2[IncrementalSource2["MouseMove"] = 1] = "MouseMove";
19353 IncrementalSource2[IncrementalSource2["MouseInteraction"] = 2] = "MouseInteraction";
19354 IncrementalSource2[IncrementalSource2["Scroll"] = 3] = "Scroll";
19355 IncrementalSource2[IncrementalSource2["ViewportResize"] = 4] = "ViewportResize";
19356 IncrementalSource2[IncrementalSource2["Input"] = 5] = "Input";
19357 IncrementalSource2[IncrementalSource2["TouchMove"] = 6] = "TouchMove";
19358 IncrementalSource2[IncrementalSource2["MediaInteraction"] = 7] = "MediaInteraction";
19359 IncrementalSource2[IncrementalSource2["StyleSheetRule"] = 8] = "StyleSheetRule";
19360 IncrementalSource2[IncrementalSource2["CanvasMutation"] = 9] = "CanvasMutation";
19361 IncrementalSource2[IncrementalSource2["Font"] = 10] = "Font";
19362 IncrementalSource2[IncrementalSource2["Log"] = 11] = "Log";
19363 IncrementalSource2[IncrementalSource2["Drag"] = 12] = "Drag";
19364 IncrementalSource2[IncrementalSource2["StyleDeclaration"] = 13] = "StyleDeclaration";
19365 IncrementalSource2[IncrementalSource2["Selection"] = 14] = "Selection";
19366 IncrementalSource2[IncrementalSource2["AdoptedStyleSheet"] = 15] = "AdoptedStyleSheet";
19367 IncrementalSource2[IncrementalSource2["CustomElement"] = 16] = "CustomElement";
19368 return IncrementalSource2;
19369 }(IncrementalSource || {});
19370 var MouseInteractions = /* @__PURE__ */ function(MouseInteractions2) {
19371 MouseInteractions2[MouseInteractions2["MouseUp"] = 0] = "MouseUp";
19372 MouseInteractions2[MouseInteractions2["MouseDown"] = 1] = "MouseDown";
19373 MouseInteractions2[MouseInteractions2["Click"] = 2] = "Click";
19374 MouseInteractions2[MouseInteractions2["ContextMenu"] = 3] = "ContextMenu";
19375 MouseInteractions2[MouseInteractions2["DblClick"] = 4] = "DblClick";
19376 MouseInteractions2[MouseInteractions2["Focus"] = 5] = "Focus";
19377 MouseInteractions2[MouseInteractions2["Blur"] = 6] = "Blur";
19378 MouseInteractions2[MouseInteractions2["TouchStart"] = 7] = "TouchStart";
19379 MouseInteractions2[MouseInteractions2["TouchMove_Departed"] = 8] = "TouchMove_Departed";
19380 MouseInteractions2[MouseInteractions2["TouchEnd"] = 9] = "TouchEnd";
19381 MouseInteractions2[MouseInteractions2["TouchCancel"] = 10] = "TouchCancel";
19382 return MouseInteractions2;
19383 }(MouseInteractions || {});
19384 var PointerTypes = /* @__PURE__ */ function(PointerTypes2) {
19385 PointerTypes2[PointerTypes2["Mouse"] = 0] = "Mouse";
19386 PointerTypes2[PointerTypes2["Pen"] = 1] = "Pen";
19387 PointerTypes2[PointerTypes2["Touch"] = 2] = "Touch";
19388 return PointerTypes2;
19389 }(PointerTypes || {});
19390 var CanvasContext = /* @__PURE__ */ function(CanvasContext2) {
19391 CanvasContext2[CanvasContext2["2D"] = 0] = "2D";
19392 CanvasContext2[CanvasContext2["WebGL"] = 1] = "WebGL";
19393 CanvasContext2[CanvasContext2["WebGL2"] = 2] = "WebGL2";
19394 return CanvasContext2;
19395 }(CanvasContext || {});
19396 var MediaInteractions = /* @__PURE__ */ function(MediaInteractions2) {
19397 MediaInteractions2[MediaInteractions2["Play"] = 0] = "Play";
19398 MediaInteractions2[MediaInteractions2["Pause"] = 1] = "Pause";
19399 MediaInteractions2[MediaInteractions2["Seeked"] = 2] = "Seeked";
19400 MediaInteractions2[MediaInteractions2["VolumeChange"] = 3] = "VolumeChange";
19401 MediaInteractions2[MediaInteractions2["RateChange"] = 4] = "RateChange";
19402 return MediaInteractions2;
19403 }(MediaInteractions || {});
19404 var NodeType = /* @__PURE__ */ function(NodeType2) {
19405 NodeType2[NodeType2["Document"] = 0] = "Document";
19406 NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
19407 NodeType2[NodeType2["Element"] = 2] = "Element";
19408 NodeType2[NodeType2["Text"] = 3] = "Text";
19409 NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
19410 NodeType2[NodeType2["Comment"] = 5] = "Comment";
19411 return NodeType2;
19412 }(NodeType || {});
19413 function isNodeInLinkedList(n2) {
19414 return "__ln" in n2;
19415 }
19416 var DoubleLinkedList = /*#__PURE__*/ function() {
19417 function DoubleLinkedList() {
19418 __publicField(this, "length", 0);
19419 __publicField(this, "head", null);
19420 __publicField(this, "tail", null);
19421 }
19422 var _proto = DoubleLinkedList.prototype;
19423 _proto.get = function get(position) {
19424 if (position >= this.length) {
19425 throw new Error("Position outside of list range");
19426 }
19427 var current = this.head;
19428 for(var index2 = 0; index2 < position; index2++){
19429 current = (current == null ? void 0 : current.next) || null;
19430 }
19431 return current;
19432 };
19433 _proto.addNode = function addNode(n2) {
19434 var node2 = {
19435 value: n2,
19436 previous: null,
19437 next: null
19438 };
19439 n2.__ln = node2;
19440 if (n2.previousSibling && isNodeInLinkedList(n2.previousSibling)) {
19441 var current = n2.previousSibling.__ln.next;
19442 node2.next = current;
19443 node2.previous = n2.previousSibling.__ln;
19444 n2.previousSibling.__ln.next = node2;
19445 if (current) {
19446 current.previous = node2;
19447 }
19448 } else if (n2.nextSibling && isNodeInLinkedList(n2.nextSibling) && n2.nextSibling.__ln.previous) {
19449 var current1 = n2.nextSibling.__ln.previous;
19450 node2.previous = current1;
19451 node2.next = n2.nextSibling.__ln;
19452 n2.nextSibling.__ln.previous = node2;
19453 if (current1) {
19454 current1.next = node2;
19455 }
19456 } else {
19457 if (this.head) {
19458 this.head.previous = node2;
19459 }
19460 node2.next = this.head;
19461 this.head = node2;
19462 }
19463 if (node2.next === null) {
19464 this.tail = node2;
19465 }
19466 this.length++;
19467 };
19468 _proto.removeNode = function removeNode(n2) {
19469 var current = n2.__ln;
19470 if (!this.head) {
19471 return;
19472 }
19473 if (!current.previous) {
19474 this.head = current.next;
19475 if (this.head) {
19476 this.head.previous = null;
19477 } else {
19478 this.tail = null;
19479 }
19480 } else {
19481 current.previous.next = current.next;
19482 if (current.next) {
19483 current.next.previous = current.previous;
19484 } else {
19485 this.tail = current.previous;
19486 }
19487 }
19488 if (n2.__ln) {
19489 delete n2.__ln;
19490 }
19491 this.length--;
19492 };
19493 return DoubleLinkedList;
19494 }();
19495 var moveKey = function(id, parentId) {
19496 return id + "@" + parentId;
19497 };
19498 var MutationBuffer = /*#__PURE__*/ function() {
19499 function MutationBuffer() {
19500 var _this = this;
19501 __publicField(this, "frozen", false);
19502 __publicField(this, "locked", false);
19503 __publicField(this, "texts", []);
19504 __publicField(this, "attributes", []);
19505 __publicField(this, "attributeMap", /* @__PURE__ */ new WeakMap());
19506 __publicField(this, "removes", []);
19507 __publicField(this, "mapRemoves", []);
19508 __publicField(this, "movedMap", {});
19509 /**
19510 * the browser MutationObserver emits multiple mutations after
19511 * a delay for performance reasons, making tracing added nodes hard
19512 * in our `processMutations` callback function.
19513 * For example, if we append an element el_1 into body, and then append
19514 * another element el_2 into el_1, these two mutations may be passed to the
19515 * callback function together when the two operations were done.
19516 * Generally we need to trace child nodes of newly added nodes, but in this
19517 * case if we count el_2 as el_1's child node in the first mutation record,
19518 * then we will count el_2 again in the second mutation record which was
19519 * duplicated.
19520 * To avoid of duplicate counting added nodes, we use a Set to store
19521 * added nodes and its child nodes during iterate mutation records. Then
19522 * collect added nodes from the Set which have no duplicate copy. But
19523 * this also causes newly added nodes will not be serialized with id ASAP,
19524 * which means all the id related calculation should be lazy too.
19525 */ __publicField(this, "addedSet", /* @__PURE__ */ new Set());
19526 __publicField(this, "movedSet", /* @__PURE__ */ new Set());
19527 __publicField(this, "droppedSet", /* @__PURE__ */ new Set());
19528 __publicField(this, "removesSubTreeCache", /* @__PURE__ */ new Set());
19529 __publicField(this, "mutationCb");
19530 __publicField(this, "blockClass");
19531 __publicField(this, "blockSelector");
19532 __publicField(this, "maskTextClass");
19533 __publicField(this, "maskTextSelector");
19534 __publicField(this, "inlineStylesheet");
19535 __publicField(this, "maskInputOptions");
19536 __publicField(this, "maskTextFn");
19537 __publicField(this, "maskInputFn");
19538 __publicField(this, "keepIframeSrcFn");
19539 __publicField(this, "recordCanvas");
19540 __publicField(this, "inlineImages");
19541 __publicField(this, "slimDOMOptions");
19542 __publicField(this, "dataURLOptions");
19543 __publicField(this, "doc");
19544 __publicField(this, "mirror");
19545 __publicField(this, "iframeManager");
19546 __publicField(this, "stylesheetManager");
19547 __publicField(this, "shadowDomManager");
19548 __publicField(this, "canvasManager");
19549 __publicField(this, "processedNodeManager");
19550 __publicField(this, "unattachedDoc");
19551 __publicField(this, "processMutations", function(mutations) {
19552 mutations.forEach(_this.processMutation);
19553 _this.emit();
19554 });
19555 __publicField(this, "emit", function() {
19556 if (_this.frozen || _this.locked) {
19557 return;
19558 }
19559 var adds = [];
19560 var addedIds = /* @__PURE__ */ new Set();
19561 var addList = new DoubleLinkedList();
19562 var getNextId = function(n2) {
19563 var ns = n2;
19564 var nextId = IGNORED_NODE;
19565 while(nextId === IGNORED_NODE){
19566 ns = ns && ns.nextSibling;
19567 nextId = ns && _this.mirror.getId(ns);
19568 }
19569 return nextId;
19570 };
19571 var pushAdd = function(n2) {
19572 var parent = index.parentNode(n2);
19573 if (!parent || !inDom(n2)) {
19574 return;
19575 }
19576 var cssCaptured = false;
19577 if (n2.nodeType === Node.TEXT_NODE) {
19578 var parentTag = parent.tagName;
19579 if (parentTag === "TEXTAREA") {
19580 return;
19581 } else if (parentTag === "STYLE" && _this.addedSet.has(parent)) {
19582 cssCaptured = true;
19583 }
19584 }
19585 var parentId = isShadowRoot(parent) ? _this.mirror.getId(getShadowHost(n2)) : _this.mirror.getId(parent);
19586 var nextId = getNextId(n2);
19587 if (parentId === -1 || nextId === -1) {
19588 return addList.addNode(n2);
19589 }
19590 var sn = serializeNodeWithId(n2, {
19591 doc: _this.doc,
19592 mirror: _this.mirror,
19593 blockClass: _this.blockClass,
19594 blockSelector: _this.blockSelector,
19595 maskTextClass: _this.maskTextClass,
19596 maskTextSelector: _this.maskTextSelector,
19597 skipChild: true,
19598 newlyAddedElement: true,
19599 inlineStylesheet: _this.inlineStylesheet,
19600 maskInputOptions: _this.maskInputOptions,
19601 maskTextFn: _this.maskTextFn,
19602 maskInputFn: _this.maskInputFn,
19603 slimDOMOptions: _this.slimDOMOptions,
19604 dataURLOptions: _this.dataURLOptions,
19605 recordCanvas: _this.recordCanvas,
19606 inlineImages: _this.inlineImages,
19607 onSerialize: function(currentN) {
19608 if (isSerializedIframe(currentN, _this.mirror)) {
19609 _this.iframeManager.addIframe(currentN);
19610 }
19611 if (isSerializedStylesheet(currentN, _this.mirror)) {
19612 _this.stylesheetManager.trackLinkElement(currentN);
19613 }
19614 if (hasShadowRoot(n2)) {
19615 _this.shadowDomManager.addShadowRoot(index.shadowRoot(n2), _this.doc);
19616 }
19617 },
19618 onIframeLoad: function(iframe, childSn) {
19619 _this.iframeManager.attachIframe(iframe, childSn);
19620 _this.shadowDomManager.observeAttachShadow(iframe);
19621 },
19622 onStylesheetLoad: function(link, childSn) {
19623 _this.stylesheetManager.attachLinkElement(link, childSn);
19624 },
19625 cssCaptured: cssCaptured
19626 });
19627 if (sn) {
19628 adds.push({
19629 parentId: parentId,
19630 nextId: nextId,
19631 node: sn
19632 });
19633 addedIds.add(sn.id);
19634 }
19635 };
19636 while(_this.mapRemoves.length){
19637 _this.mirror.removeNodeFromMap(_this.mapRemoves.shift());
19638 }
19639 for(var _iterator = _create_for_of_iterator_helper_loose(_this.movedSet), _step; !(_step = _iterator()).done;){
19640 var n2 = _step.value;
19641 if (isParentRemoved(_this.removesSubTreeCache, n2, _this.mirror) && !_this.movedSet.has(index.parentNode(n2))) {
19642 continue;
19643 }
19644 pushAdd(n2);
19645 }
19646 for(var _iterator1 = _create_for_of_iterator_helper_loose(_this.addedSet), _step1; !(_step1 = _iterator1()).done;){
19647 var n21 = _step1.value;
19648 if (!isAncestorInSet(_this.droppedSet, n21) && !isParentRemoved(_this.removesSubTreeCache, n21, _this.mirror)) {
19649 pushAdd(n21);
19650 } else if (isAncestorInSet(_this.movedSet, n21)) {
19651 pushAdd(n21);
19652 } else {
19653 _this.droppedSet.add(n21);
19654 }
19655 }
19656 var candidate = null;
19657 while(addList.length){
19658 var node2 = null;
19659 if (candidate) {
19660 var parentId = _this.mirror.getId(index.parentNode(candidate.value));
19661 var nextId = getNextId(candidate.value);
19662 if (parentId !== -1 && nextId !== -1) {
19663 node2 = candidate;
19664 }
19665 }
19666 if (!node2) {
19667 var tailNode = addList.tail;
19668 while(tailNode){
19669 var _node = tailNode;
19670 tailNode = tailNode.previous;
19671 if (_node) {
19672 var parentId1 = _this.mirror.getId(index.parentNode(_node.value));
19673 var nextId1 = getNextId(_node.value);
19674 if (nextId1 === -1) continue;
19675 else if (parentId1 !== -1) {
19676 node2 = _node;
19677 break;
19678 } else {
19679 var unhandledNode = _node.value;
19680 var parent = index.parentNode(unhandledNode);
19681 if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
19682 var shadowHost = index.host(parent);
19683 var parentId2 = _this.mirror.getId(shadowHost);
19684 if (parentId2 !== -1) {
19685 node2 = _node;
19686 break;
19687 }
19688 }
19689 }
19690 }
19691 }
19692 }
19693 if (!node2) {
19694 while(addList.head){
19695 addList.removeNode(addList.head.value);
19696 }
19697 break;
19698 }
19699 candidate = node2.previous;
19700 addList.removeNode(node2.value);
19701 pushAdd(node2.value);
19702 }
19703 var payload = {
19704 texts: _this.texts.map(function(text) {
19705 var n2 = text.node;
19706 var parent = index.parentNode(n2);
19707 if (parent && parent.tagName === "TEXTAREA") {
19708 _this.genTextAreaValueMutation(parent);
19709 }
19710 return {
19711 id: _this.mirror.getId(n2),
19712 value: text.value
19713 };
19714 }).filter(function(text) {
19715 return !addedIds.has(text.id);
19716 }).filter(function(text) {
19717 return _this.mirror.has(text.id);
19718 }),
19719 attributes: _this.attributes.map(function(attribute) {
19720 var attributes = attribute.attributes;
19721 if (typeof attributes.style === "string") {
19722 var diffAsStr = JSON.stringify(attribute.styleDiff);
19723 var unchangedAsStr = JSON.stringify(attribute._unchangedStyles);
19724 if (diffAsStr.length < attributes.style.length) {
19725 if ((diffAsStr + unchangedAsStr).split("var(").length === attributes.style.split("var(").length) {
19726 attributes.style = attribute.styleDiff;
19727 }
19728 }
19729 }
19730 return {
19731 id: _this.mirror.getId(attribute.node),
19732 attributes: attributes
19733 };
19734 }).filter(function(attribute) {
19735 return !addedIds.has(attribute.id);
19736 }).filter(function(attribute) {
19737 return _this.mirror.has(attribute.id);
19738 }),
19739 removes: _this.removes,
19740 adds: adds
19741 };
19742 if (!payload.texts.length && !payload.attributes.length && !payload.removes.length && !payload.adds.length) {
19743 return;
19744 }
19745 _this.texts = [];
19746 _this.attributes = [];
19747 _this.attributeMap = /* @__PURE__ */ new WeakMap();
19748 _this.removes = [];
19749 _this.addedSet = /* @__PURE__ */ new Set();
19750 _this.movedSet = /* @__PURE__ */ new Set();
19751 _this.droppedSet = /* @__PURE__ */ new Set();
19752 _this.removesSubTreeCache = /* @__PURE__ */ new Set();
19753 _this.movedMap = {};
19754 _this.mutationCb(payload);
19755 });
19756 __publicField(this, "genTextAreaValueMutation", function(textarea) {
19757 var item = _this.attributeMap.get(textarea);
19758 if (!item) {
19759 item = {
19760 node: textarea,
19761 attributes: {},
19762 styleDiff: {},
19763 _unchangedStyles: {}
19764 };
19765 _this.attributes.push(item);
19766 _this.attributeMap.set(textarea, item);
19767 }
19768 var value = Array.from(index.childNodes(textarea), function(cn) {
19769 return index.textContent(cn) || "";
19770 }).join("");
19771 item.attributes.value = maskInputValue({
19772 element: textarea,
19773 maskInputOptions: _this.maskInputOptions,
19774 tagName: textarea.tagName,
19775 type: getInputType(textarea),
19776 value: value,
19777 maskInputFn: _this.maskInputFn
19778 });
19779 });
19780 __publicField(this, "processMutation", function(m) {
19781 if (isIgnored(m.target, _this.mirror, _this.slimDOMOptions)) {
19782 return;
19783 }
19784 switch(m.type){
19785 case "characterData":
19786 {
19787 var value = index.textContent(m.target);
19788 if (!isBlocked(m.target, _this.blockClass, _this.blockSelector, false) && value !== m.oldValue) {
19789 _this.texts.push({
19790 value: needMaskingText(m.target, _this.maskTextClass, _this.maskTextSelector, true) && value ? _this.maskTextFn ? _this.maskTextFn(value, closestElementOfNode(m.target)) : value.replace(/[\S]/g, "*") : value,
19791 node: m.target
19792 });
19793 }
19794 break;
19795 }
19796 case "attributes":
19797 {
19798 var target = m.target;
19799 var attributeName = m.attributeName;
19800 var value1 = m.target.getAttribute(attributeName);
19801 if (attributeName === "value") {
19802 var type = getInputType(target);
19803 value1 = maskInputValue({
19804 element: target,
19805 maskInputOptions: _this.maskInputOptions,
19806 tagName: target.tagName,
19807 type: type,
19808 value: value1,
19809 maskInputFn: _this.maskInputFn
19810 });
19811 }
19812 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || value1 === m.oldValue) {
19813 return;
19814 }
19815 var item = _this.attributeMap.get(m.target);
19816 if (target.tagName === "IFRAME" && attributeName === "src" && !_this.keepIframeSrcFn(value1)) {
19817 if (!target.contentDocument) {
19818 attributeName = "rr_src";
19819 } else {
19820 return;
19821 }
19822 }
19823 if (!item) {
19824 item = {
19825 node: m.target,
19826 attributes: {},
19827 styleDiff: {},
19828 _unchangedStyles: {}
19829 };
19830 _this.attributes.push(item);
19831 _this.attributeMap.set(m.target, item);
19832 }
19833 if (attributeName === "type" && target.tagName === "INPUT" && (m.oldValue || "").toLowerCase() === "password") {
19834 target.setAttribute("data-rr-is-password", "true");
19835 }
19836 if (!ignoreAttribute(target.tagName, attributeName)) {
19837 item.attributes[attributeName] = transformAttribute(_this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value1);
19838 if (attributeName === "style") {
19839 if (!_this.unattachedDoc) {
19840 try {
19841 _this.unattachedDoc = document.implementation.createHTMLDocument();
19842 } catch (e2) {
19843 _this.unattachedDoc = _this.doc;
19844 }
19845 }
19846 var old = _this.unattachedDoc.createElement("span");
19847 if (m.oldValue) {
19848 old.setAttribute("style", m.oldValue);
19849 }
19850 for(var _iterator = _create_for_of_iterator_helper_loose(Array.from(target.style)), _step; !(_step = _iterator()).done;){
19851 var pname = _step.value;
19852 var newValue = target.style.getPropertyValue(pname);
19853 var newPriority = target.style.getPropertyPriority(pname);
19854 if (newValue !== old.style.getPropertyValue(pname) || newPriority !== old.style.getPropertyPriority(pname)) {
19855 if (newPriority === "") {
19856 item.styleDiff[pname] = newValue;
19857 } else {
19858 item.styleDiff[pname] = [
19859 newValue,
19860 newPriority
19861 ];
19862 }
19863 } else {
19864 item._unchangedStyles[pname] = [
19865 newValue,
19866 newPriority
19867 ];
19868 }
19869 }
19870 for(var _iterator1 = _create_for_of_iterator_helper_loose(Array.from(old.style)), _step1; !(_step1 = _iterator1()).done;){
19871 var pname1 = _step1.value;
19872 if (target.style.getPropertyValue(pname1) === "") {
19873 item.styleDiff[pname1] = false;
19874 }
19875 }
19876 } else if (attributeName === "open" && target.tagName === "DIALOG") {
19877 if (target.matches("dialog:modal")) {
19878 item.attributes["rr_open_mode"] = "modal";
19879 } else {
19880 item.attributes["rr_open_mode"] = "non-modal";
19881 }
19882 }
19883 }
19884 break;
19885 }
19886 case "childList":
19887 {
19888 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, true)) return;
19889 if (m.target.tagName === "TEXTAREA") {
19890 _this.genTextAreaValueMutation(m.target);
19891 return;
19892 }
19893 m.addedNodes.forEach(function(n2) {
19894 return _this.genAdds(n2, m.target);
19895 });
19896 m.removedNodes.forEach(function(n2) {
19897 var nodeId = _this.mirror.getId(n2);
19898 var parentId = isShadowRoot(m.target) ? _this.mirror.getId(index.host(m.target)) : _this.mirror.getId(m.target);
19899 if (isBlocked(m.target, _this.blockClass, _this.blockSelector, false) || isIgnored(n2, _this.mirror, _this.slimDOMOptions) || !isSerialized(n2, _this.mirror)) {
19900 return;
19901 }
19902 if (_this.addedSet.has(n2)) {
19903 deepDelete(_this.addedSet, n2);
19904 _this.droppedSet.add(n2);
19905 } else if (_this.addedSet.has(m.target) && nodeId === -1) ;
19906 else if (isAncestorRemoved(m.target, _this.mirror)) ;
19907 else if (_this.movedSet.has(n2) && _this.movedMap[moveKey(nodeId, parentId)]) {
19908 deepDelete(_this.movedSet, n2);
19909 } else {
19910 _this.removes.push({
19911 parentId: parentId,
19912 id: nodeId,
19913 isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target) ? true : void 0
19914 });
19915 processRemoves(n2, _this.removesSubTreeCache);
19916 }
19917 _this.mapRemoves.push(n2);
19918 });
19919 break;
19920 }
19921 }
19922 });
19923 /**
19924 * Make sure you check if `n`'s parent is blocked before calling this function
19925 * */ __publicField(this, "genAdds", function(n2, target) {
19926 if (_this.processedNodeManager.inOtherBuffer(n2, _this)) return;
19927 if (_this.addedSet.has(n2) || _this.movedSet.has(n2)) return;
19928 if (_this.mirror.hasNode(n2)) {
19929 if (isIgnored(n2, _this.mirror, _this.slimDOMOptions)) {
19930 return;
19931 }
19932 _this.movedSet.add(n2);
19933 var targetId = null;
19934 if (target && _this.mirror.hasNode(target)) {
19935 targetId = _this.mirror.getId(target);
19936 }
19937 if (targetId && targetId !== -1) {
19938 _this.movedMap[moveKey(_this.mirror.getId(n2), targetId)] = true;
19939 }
19940 } else {
19941 _this.addedSet.add(n2);
19942 _this.droppedSet.delete(n2);
19943 }
19944 if (!isBlocked(n2, _this.blockClass, _this.blockSelector, false)) {
19945 index.childNodes(n2).forEach(function(childN) {
19946 return _this.genAdds(childN);
19947 });
19948 if (hasShadowRoot(n2)) {
19949 index.childNodes(index.shadowRoot(n2)).forEach(function(childN) {
19950 _this.processedNodeManager.add(childN, _this);
19951 _this.genAdds(childN, n2);
19952 });
19953 }
19954 }
19955 });
19956 }
19957 var _proto = MutationBuffer.prototype;
19958 _proto.init = function init(options) {
19959 var _this = this;
19960 [
19961 "mutationCb",
19962 "blockClass",
19963 "blockSelector",
19964 "maskTextClass",
19965 "maskTextSelector",
19966 "inlineStylesheet",
19967 "maskInputOptions",
19968 "maskTextFn",
19969 "maskInputFn",
19970 "keepIframeSrcFn",
19971 "recordCanvas",
19972 "inlineImages",
19973 "slimDOMOptions",
19974 "dataURLOptions",
19975 "doc",
19976 "mirror",
19977 "iframeManager",
19978 "stylesheetManager",
19979 "shadowDomManager",
19980 "canvasManager",
19981 "processedNodeManager"
19982 ].forEach(function(key) {
19983 _this[key] = options[key];
19984 });
19985 };
19986 _proto.freeze = function freeze() {
19987 this.frozen = true;
19988 this.canvasManager.freeze();
19989 };
19990 _proto.unfreeze = function unfreeze() {
19991 this.frozen = false;
19992 this.canvasManager.unfreeze();
19993 this.emit();
19994 };
19995 _proto.isFrozen = function isFrozen() {
19996 return this.frozen;
19997 };
19998 _proto.lock = function lock() {
19999 this.locked = true;
20000 this.canvasManager.lock();
20001 };
20002 _proto.unlock = function unlock() {
20003 this.locked = false;
20004 this.canvasManager.unlock();
20005 this.emit();
20006 };
20007 _proto.reset = function reset() {
20008 this.shadowDomManager.reset();
20009 this.canvasManager.reset();
20010 };
20011 return MutationBuffer;
20012 }();
20013 function deepDelete(addsSet, n2) {
20014 addsSet.delete(n2);
20015 index.childNodes(n2).forEach(function(childN) {
20016 return deepDelete(addsSet, childN);
20017 });
20018 }
20019 function processRemoves(n2, cache) {
20020 var queue = [
20021 n2
20022 ];
20023 while(queue.length){
20024 var next = queue.pop();
20025 if (cache.has(next)) continue;
20026 cache.add(next);
20027 index.childNodes(next).forEach(function(n22) {
20028 return queue.push(n22);
20029 });
20030 }
20031 return;
20032 }
20033 function isParentRemoved(removes, n2, mirror2) {
20034 if (removes.size === 0) return false;
20035 return _isParentRemoved(removes, n2);
20036 }
20037 function _isParentRemoved(removes, n2, _mirror2) {
20038 var node2 = index.parentNode(n2);
20039 if (!node2) return false;
20040 return removes.has(node2);
20041 }
20042 function isAncestorInSet(set, n2) {
20043 if (set.size === 0) return false;
20044 return _isAncestorInSet(set, n2);
20045 }
20046 function _isAncestorInSet(set, n2) {
20047 var parent = index.parentNode(n2);
20048 if (!parent) {
20049 return false;
20050 }
20051 if (set.has(parent)) {
20052 return true;
20053 }
20054 return _isAncestorInSet(set, parent);
20055 }
20056 var errorHandler;
20057 function registerErrorHandler(handler) {
20058 errorHandler = handler;
20059 }
20060 function unregisterErrorHandler() {
20061 errorHandler = void 0;
20062 }
20063 var callbackWrapper = function(cb) {
20064 if (!errorHandler) {
20065 return cb;
20066 }
20067 var rrwebWrapped = function() {
20068 for(var _len = arguments.length, rest = new Array(_len), _key = 0; _key < _len; _key++){
20069 rest[_key] = arguments[_key];
20070 }
20071 try {
20072 return cb.apply(void 0, [].concat(rest));
20073 } catch (error) {
20074 if (errorHandler && errorHandler(error) === true) {
20075 return;
20076 }
20077 throw error;
20078 }
20079 };
20080 return rrwebWrapped;
20081 };
20082 var mutationBuffers = [];
20083 function getEventTarget(event) {
20084 try {
20085 if ("composedPath" in event) {
20086 var path = event.composedPath();
20087 if (path.length) {
20088 return path[0];
20089 }
20090 } else if ("path" in event && event.path.length) {
20091 return event.path[0];
20092 }
20093 } catch (e) {}
20094 return event && event.target;
20095 }
20096 function initMutationObserver(options, rootEl) {
20097 var mutationBuffer = new MutationBuffer();
20098 mutationBuffers.push(mutationBuffer);
20099 mutationBuffer.init(options);
20100 var observer = new (mutationObserverCtor())(callbackWrapper(mutationBuffer.processMutations.bind(mutationBuffer)));
20101 observer.observe(rootEl, {
20102 attributes: true,
20103 attributeOldValue: true,
20104 characterData: true,
20105 characterDataOldValue: true,
20106 childList: true,
20107 subtree: true
20108 });
20109 return observer;
20110 }
20111 function initMoveObserver(param) {
20112 var mousemoveCb = param.mousemoveCb, sampling = param.sampling, doc = param.doc, mirror2 = param.mirror;
20113 if (sampling.mousemove === false) {
20114 return function() {};
20115 }
20116 var threshold = typeof sampling.mousemove === "number" ? sampling.mousemove : 50;
20117 var callbackThreshold = typeof sampling.mousemoveCallback === "number" ? sampling.mousemoveCallback : 500;
20118 var positions = [];
20119 var timeBaseline;
20120 var wrappedCb = throttle(callbackWrapper(function(source) {
20121 var totalOffset = Date.now() - timeBaseline;
20122 mousemoveCb(positions.map(function(p) {
20123 p.timeOffset -= totalOffset;
20124 return p;
20125 }), source);
20126 positions = [];
20127 timeBaseline = null;
20128 }), callbackThreshold);
20129 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
20130 var target = getEventTarget(evt);
20131 var _ref = legacy_isTouchEvent(evt) ? evt.changedTouches[0] : evt, clientX = _ref.clientX, clientY = _ref.clientY;
20132 if (!timeBaseline) {
20133 timeBaseline = nowTimestamp();
20134 }
20135 positions.push({
20136 x: clientX,
20137 y: clientY,
20138 id: mirror2.getId(target),
20139 timeOffset: nowTimestamp() - timeBaseline
20140 });
20141 wrappedCb(typeof DragEvent !== "undefined" && _instanceof(evt, DragEvent) ? IncrementalSource.Drag : _instanceof(evt, MouseEvent) ? IncrementalSource.MouseMove : IncrementalSource.TouchMove);
20142 }), threshold, {
20143 trailing: false
20144 }));
20145 var handlers = [
20146 on("mousemove", updatePosition, doc),
20147 on("touchmove", updatePosition, doc),
20148 on("drag", updatePosition, doc)
20149 ];
20150 return callbackWrapper(function() {
20151 handlers.forEach(function(h) {
20152 return h();
20153 });
20154 });
20155 }
20156 function initMouseInteractionObserver(param) {
20157 var mouseInteractionCb = param.mouseInteractionCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, sampling = param.sampling;
20158 if (sampling.mouseInteraction === false) {
20159 return function() {};
20160 }
20161 var disableMap = sampling.mouseInteraction === true || sampling.mouseInteraction === void 0 ? {} : sampling.mouseInteraction;
20162 var handlers = [];
20163 var currentPointerType = null;
20164 var getHandler = function(eventKey) {
20165 return function(event) {
20166 var target = getEventTarget(event);
20167 if (isBlocked(target, blockClass, blockSelector, true)) {
20168 return;
20169 }
20170 var pointerType = null;
20171 var thisEventKey = eventKey;
20172 if ("pointerType" in event) {
20173 switch(event.pointerType){
20174 case "mouse":
20175 pointerType = PointerTypes.Mouse;
20176 break;
20177 case "touch":
20178 pointerType = PointerTypes.Touch;
20179 break;
20180 case "pen":
20181 pointerType = PointerTypes.Pen;
20182 break;
20183 }
20184 if (pointerType === PointerTypes.Touch) {
20185 if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {
20186 thisEventKey = "TouchStart";
20187 } else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {
20188 thisEventKey = "TouchEnd";
20189 }
20190 } else if (pointerType === PointerTypes.Pen) ;
20191 } else if (legacy_isTouchEvent(event)) {
20192 pointerType = PointerTypes.Touch;
20193 }
20194 if (pointerType !== null) {
20195 currentPointerType = pointerType;
20196 if (thisEventKey.startsWith("Touch") && pointerType === PointerTypes.Touch || thisEventKey.startsWith("Mouse") && pointerType === PointerTypes.Mouse) {
20197 pointerType = null;
20198 }
20199 } else if (MouseInteractions[eventKey] === MouseInteractions.Click) {
20200 pointerType = currentPointerType;
20201 currentPointerType = null;
20202 }
20203 var e2 = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;
20204 if (!e2) {
20205 return;
20206 }
20207 var id = mirror2.getId(target);
20208 var clientX = e2.clientX, clientY = e2.clientY;
20209 callbackWrapper(mouseInteractionCb)(_extends({
20210 type: MouseInteractions[thisEventKey],
20211 id: id,
20212 x: clientX,
20213 y: clientY
20214 }, pointerType !== null && {
20215 pointerType: pointerType
20216 }));
20217 };
20218 };
20219 Object.keys(MouseInteractions).filter(function(key) {
20220 return Number.isNaN(Number(key)) && !key.endsWith("_Departed") && disableMap[key] !== false;
20221 }).forEach(function(eventKey) {
20222 var eventName = toLowerCase(eventKey);
20223 var handler = getHandler(eventKey);
20224 if (window.PointerEvent) {
20225 switch(MouseInteractions[eventKey]){
20226 case MouseInteractions.MouseDown:
20227 case MouseInteractions.MouseUp:
20228 eventName = eventName.replace("mouse", "pointer");
20229 break;
20230 case MouseInteractions.TouchStart:
20231 case MouseInteractions.TouchEnd:
20232 return;
20233 }
20234 }
20235 handlers.push(on(eventName, handler, doc));
20236 });
20237 return callbackWrapper(function() {
20238 handlers.forEach(function(h) {
20239 return h();
20240 });
20241 });
20242 }
20243 function initScrollObserver(param) {
20244 var scrollCb = param.scrollCb, doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, sampling = param.sampling;
20245 var updatePosition = callbackWrapper(throttle(callbackWrapper(function(evt) {
20246 var target = getEventTarget(evt);
20247 if (!target || isBlocked(target, blockClass, blockSelector, true)) {
20248 return;
20249 }
20250 var id = mirror2.getId(target);
20251 if (target === doc && doc.defaultView) {
20252 var scrollLeftTop = getWindowScroll(doc.defaultView);
20253 scrollCb({
20254 id: id,
20255 x: scrollLeftTop.left,
20256 y: scrollLeftTop.top
20257 });
20258 } else {
20259 scrollCb({
20260 id: id,
20261 x: target.scrollLeft,
20262 y: target.scrollTop
20263 });
20264 }
20265 }), sampling.scroll || 100));
20266 return on("scroll", updatePosition, doc);
20267 }
20268 function initViewportResizeObserver(param, param1) {
20269 var viewportResizeCb = param.viewportResizeCb;
20270 var win = param1.win;
20271 var lastH = -1;
20272 var lastW = -1;
20273 var updateDimension = callbackWrapper(throttle(callbackWrapper(function() {
20274 var height = getWindowHeight();
20275 var width = getWindowWidth();
20276 if (lastH !== height || lastW !== width) {
20277 viewportResizeCb({
20278 width: Number(width),
20279 height: Number(height)
20280 });
20281 lastH = height;
20282 lastW = width;
20283 }
20284 }), 200));
20285 return on("resize", updateDimension, win);
20286 }
20287 var INPUT_TAGS = [
20288 "INPUT",
20289 "TEXTAREA",
20290 "SELECT"
20291 ];
20292 var lastInputValueMap = /* @__PURE__ */ new WeakMap();
20293 function initInputObserver(param) {
20294 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;
20295 function eventHandler(event) {
20296 var target = getEventTarget(event);
20297 var userTriggered = event.isTrusted;
20298 var tagName = target && target.tagName;
20299 if (target && tagName === "OPTION") {
20300 target = index.parentElement(target);
20301 }
20302 if (!target || !tagName || INPUT_TAGS.indexOf(tagName) < 0 || isBlocked(target, blockClass, blockSelector, true)) {
20303 return;
20304 }
20305 if (target.classList.contains(ignoreClass) || ignoreSelector && target.matches(ignoreSelector)) {
20306 return;
20307 }
20308 var text = target.value;
20309 var isChecked = false;
20310 var type = getInputType(target) || "";
20311 if (type === "radio" || type === "checkbox") {
20312 isChecked = target.checked;
20313 } else if (maskInputOptions[tagName.toLowerCase()] || maskInputOptions[type]) {
20314 text = maskInputValue({
20315 element: target,
20316 maskInputOptions: maskInputOptions,
20317 tagName: tagName,
20318 type: type,
20319 value: text,
20320 maskInputFn: maskInputFn
20321 });
20322 }
20323 cbWithDedup(target, userTriggeredOnInput ? {
20324 text: text,
20325 isChecked: isChecked,
20326 userTriggered: userTriggered
20327 } : {
20328 text: text,
20329 isChecked: isChecked
20330 });
20331 var name = target.name;
20332 if (type === "radio" && name && isChecked) {
20333 doc.querySelectorAll('input[type="radio"][name="' + name + '"]').forEach(function(el) {
20334 if (el !== target) {
20335 var text2 = el.value;
20336 cbWithDedup(el, userTriggeredOnInput ? {
20337 text: text2,
20338 isChecked: !isChecked,
20339 userTriggered: false
20340 } : {
20341 text: text2,
20342 isChecked: !isChecked
20343 });
20344 }
20345 });
20346 }
20347 }
20348 function cbWithDedup(target, v2) {
20349 var lastInputValue = lastInputValueMap.get(target);
20350 if (!lastInputValue || lastInputValue.text !== v2.text || lastInputValue.isChecked !== v2.isChecked) {
20351 lastInputValueMap.set(target, v2);
20352 var id = mirror2.getId(target);
20353 callbackWrapper(inputCb)(_extends({}, v2, {
20354 id: id
20355 }));
20356 }
20357 }
20358 var events = sampling.input === "last" ? [
20359 "change"
20360 ] : [
20361 "input",
20362 "change"
20363 ];
20364 var handlers = events.map(function(eventName) {
20365 return on(eventName, callbackWrapper(eventHandler), doc);
20366 });
20367 var currentWindow = doc.defaultView;
20368 if (!currentWindow) {
20369 return function() {
20370 handlers.forEach(function(h) {
20371 return h();
20372 });
20373 };
20374 }
20375 var propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, "value");
20376 var hookProperties = [
20377 [
20378 currentWindow.HTMLInputElement.prototype,
20379 "value"
20380 ],
20381 [
20382 currentWindow.HTMLInputElement.prototype,
20383 "checked"
20384 ],
20385 [
20386 currentWindow.HTMLSelectElement.prototype,
20387 "value"
20388 ],
20389 [
20390 currentWindow.HTMLTextAreaElement.prototype,
20391 "value"
20392 ],
20393 // Some UI library use selectedIndex to set select value
20394 [
20395 currentWindow.HTMLSelectElement.prototype,
20396 "selectedIndex"
20397 ],
20398 [
20399 currentWindow.HTMLOptionElement.prototype,
20400 "selected"
20401 ]
20402 ];
20403 if (propertyDescriptor && propertyDescriptor.set) {
20404 var _handlers;
20405 (_handlers = handlers).push.apply(_handlers, [].concat(hookProperties.map(function(p) {
20406 return hookSetter(p[0], p[1], {
20407 set: function set() {
20408 callbackWrapper(eventHandler)({
20409 target: this,
20410 isTrusted: false
20411 });
20412 }
20413 }, false, currentWindow);
20414 })));
20415 }
20416 return callbackWrapper(function() {
20417 handlers.forEach(function(h) {
20418 return h();
20419 });
20420 });
20421 }
20422 function getNestedCSSRulePositions(rule2) {
20423 var positions = [];
20424 function recurse(childRule, pos) {
20425 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)) {
20426 var rules2 = Array.from(childRule.parentRule.cssRules);
20427 var index2 = rules2.indexOf(childRule);
20428 pos.unshift(index2);
20429 } else if (childRule.parentStyleSheet) {
20430 var rules21 = Array.from(childRule.parentStyleSheet.cssRules);
20431 var index21 = rules21.indexOf(childRule);
20432 pos.unshift(index21);
20433 }
20434 return pos;
20435 }
20436 return recurse(rule2, positions);
20437 }
20438 function getIdAndStyleId(sheet, mirror2, styleMirror) {
20439 var id, styleId;
20440 if (!sheet) return {};
20441 if (sheet.ownerNode) id = mirror2.getId(sheet.ownerNode);
20442 else styleId = styleMirror.getId(sheet);
20443 return {
20444 styleId: styleId,
20445 id: id
20446 };
20447 }
20448 function initStyleSheetObserver(param, param1) {
20449 var styleSheetRuleCb = param.styleSheetRuleCb, mirror2 = param.mirror, stylesheetManager = param.stylesheetManager;
20450 var win = param1.win;
20451 if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {
20452 return function() {};
20453 }
20454 var insertRule = win.CSSStyleSheet.prototype.insertRule;
20455 win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {
20456 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20457 var rule2 = argumentsList[0], index2 = argumentsList[1];
20458 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20459 if (id && id !== -1 || styleId && styleId !== -1) {
20460 styleSheetRuleCb({
20461 id: id,
20462 styleId: styleId,
20463 adds: [
20464 {
20465 rule: rule2,
20466 index: index2
20467 }
20468 ]
20469 });
20470 }
20471 return target.apply(thisArg, argumentsList);
20472 })
20473 });
20474 win.CSSStyleSheet.prototype.addRule = function(selector, styleBlock, index2) {
20475 if (index2 === void 0) index2 = this.cssRules.length;
20476 var rule2 = selector + " { " + styleBlock + " }";
20477 return win.CSSStyleSheet.prototype.insertRule.apply(this, [
20478 rule2,
20479 index2
20480 ]);
20481 };
20482 var deleteRule = win.CSSStyleSheet.prototype.deleteRule;
20483 win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {
20484 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20485 var index2 = argumentsList[0];
20486 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20487 if (id && id !== -1 || styleId && styleId !== -1) {
20488 styleSheetRuleCb({
20489 id: id,
20490 styleId: styleId,
20491 removes: [
20492 {
20493 index: index2
20494 }
20495 ]
20496 });
20497 }
20498 return target.apply(thisArg, argumentsList);
20499 })
20500 });
20501 win.CSSStyleSheet.prototype.removeRule = function(index2) {
20502 return win.CSSStyleSheet.prototype.deleteRule.apply(this, [
20503 index2
20504 ]);
20505 };
20506 var replace;
20507 if (win.CSSStyleSheet.prototype.replace) {
20508 replace = win.CSSStyleSheet.prototype.replace;
20509 win.CSSStyleSheet.prototype.replace = new Proxy(replace, {
20510 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20511 var text = argumentsList[0];
20512 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20513 if (id && id !== -1 || styleId && styleId !== -1) {
20514 styleSheetRuleCb({
20515 id: id,
20516 styleId: styleId,
20517 replace: text
20518 });
20519 }
20520 return target.apply(thisArg, argumentsList);
20521 })
20522 });
20523 }
20524 var replaceSync;
20525 if (win.CSSStyleSheet.prototype.replaceSync) {
20526 replaceSync = win.CSSStyleSheet.prototype.replaceSync;
20527 win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {
20528 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20529 var text = argumentsList[0];
20530 var _getIdAndStyleId = getIdAndStyleId(thisArg, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20531 if (id && id !== -1 || styleId && styleId !== -1) {
20532 styleSheetRuleCb({
20533 id: id,
20534 styleId: styleId,
20535 replaceSync: text
20536 });
20537 }
20538 return target.apply(thisArg, argumentsList);
20539 })
20540 });
20541 }
20542 var supportedNestedCSSRuleTypes = {};
20543 if (canMonkeyPatchNestedCSSRule("CSSGroupingRule")) {
20544 supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;
20545 } else {
20546 if (canMonkeyPatchNestedCSSRule("CSSMediaRule")) {
20547 supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;
20548 }
20549 if (canMonkeyPatchNestedCSSRule("CSSConditionRule")) {
20550 supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;
20551 }
20552 if (canMonkeyPatchNestedCSSRule("CSSSupportsRule")) {
20553 supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;
20554 }
20555 }
20556 var unmodifiedFunctions = {};
20557 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
20558 var typeKey = param[0], type = param[1];
20559 unmodifiedFunctions[typeKey] = {
20560 // eslint-disable-next-line @typescript-eslint/unbound-method
20561 insertRule: type.prototype.insertRule,
20562 // eslint-disable-next-line @typescript-eslint/unbound-method
20563 deleteRule: type.prototype.deleteRule
20564 };
20565 type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {
20566 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20567 var rule2 = argumentsList[0], index2 = argumentsList[1];
20568 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20569 if (id && id !== -1 || styleId && styleId !== -1) {
20570 styleSheetRuleCb({
20571 id: id,
20572 styleId: styleId,
20573 adds: [
20574 {
20575 rule: rule2,
20576 index: [].concat(getNestedCSSRulePositions(thisArg), [
20577 index2 || 0
20578 ])
20579 }
20580 ]
20581 });
20582 }
20583 return target.apply(thisArg, argumentsList);
20584 })
20585 });
20586 type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {
20587 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20588 var index2 = argumentsList[0];
20589 var _getIdAndStyleId = getIdAndStyleId(thisArg.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20590 if (id && id !== -1 || styleId && styleId !== -1) {
20591 styleSheetRuleCb({
20592 id: id,
20593 styleId: styleId,
20594 removes: [
20595 {
20596 index: [].concat(getNestedCSSRulePositions(thisArg), [
20597 index2
20598 ])
20599 }
20600 ]
20601 });
20602 }
20603 return target.apply(thisArg, argumentsList);
20604 })
20605 });
20606 });
20607 return callbackWrapper(function() {
20608 win.CSSStyleSheet.prototype.insertRule = insertRule;
20609 win.CSSStyleSheet.prototype.deleteRule = deleteRule;
20610 replace && (win.CSSStyleSheet.prototype.replace = replace);
20611 replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);
20612 Object.entries(supportedNestedCSSRuleTypes).forEach(function(param) {
20613 var typeKey = param[0], type = param[1];
20614 type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;
20615 type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;
20616 });
20617 });
20618 }
20619 function initAdoptedStyleSheetObserver(param, host2) {
20620 var mirror2 = param.mirror, stylesheetManager = param.stylesheetManager;
20621 var _a2, _b, _c;
20622 var hostId = null;
20623 if (host2.nodeName === "#document") hostId = mirror2.getId(host2);
20624 else hostId = mirror2.getId(index.host(host2));
20625 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;
20626 var originalPropertyDescriptor = (patchTarget == null ? void 0 : patchTarget.prototype) ? Object.getOwnPropertyDescriptor(patchTarget == null ? void 0 : patchTarget.prototype, "adoptedStyleSheets") : void 0;
20627 if (hostId === null || hostId === -1 || !patchTarget || !originalPropertyDescriptor) return function() {};
20628 Object.defineProperty(host2, "adoptedStyleSheets", {
20629 configurable: originalPropertyDescriptor.configurable,
20630 enumerable: originalPropertyDescriptor.enumerable,
20631 get: function get() {
20632 var _a3;
20633 return (_a3 = originalPropertyDescriptor.get) == null ? void 0 : _a3.call(this);
20634 },
20635 set: function set(sheets) {
20636 var _a3;
20637 var result2 = (_a3 = originalPropertyDescriptor.set) == null ? void 0 : _a3.call(this, sheets);
20638 if (hostId !== null && hostId !== -1) {
20639 try {
20640 stylesheetManager.adoptStyleSheets(sheets, hostId);
20641 } catch (e2) {}
20642 }
20643 return result2;
20644 }
20645 });
20646 return callbackWrapper(function() {
20647 Object.defineProperty(host2, "adoptedStyleSheets", {
20648 configurable: originalPropertyDescriptor.configurable,
20649 enumerable: originalPropertyDescriptor.enumerable,
20650 // eslint-disable-next-line @typescript-eslint/unbound-method
20651 get: originalPropertyDescriptor.get,
20652 // eslint-disable-next-line @typescript-eslint/unbound-method
20653 set: originalPropertyDescriptor.set
20654 });
20655 });
20656 }
20657 function initStyleDeclarationObserver(param, param1) {
20658 var styleDeclarationCb = param.styleDeclarationCb, mirror2 = param.mirror, ignoreCSSAttributes = param.ignoreCSSAttributes, stylesheetManager = param.stylesheetManager;
20659 var win = param1.win;
20660 var setProperty = win.CSSStyleDeclaration.prototype.setProperty;
20661 win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {
20662 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20663 var _a2;
20664 var property = argumentsList[0], value = argumentsList[1], priority = argumentsList[2];
20665 if (ignoreCSSAttributes.has(property)) {
20666 return setProperty.apply(thisArg, [
20667 property,
20668 value,
20669 priority
20670 ]);
20671 }
20672 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20673 if (id && id !== -1 || styleId && styleId !== -1) {
20674 styleDeclarationCb({
20675 id: id,
20676 styleId: styleId,
20677 set: {
20678 property: property,
20679 value: value,
20680 priority: priority
20681 },
20682 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
20683 index: getNestedCSSRulePositions(thisArg.parentRule)
20684 });
20685 }
20686 return target.apply(thisArg, argumentsList);
20687 })
20688 });
20689 var removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;
20690 win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {
20691 apply: callbackWrapper(function(target, thisArg, argumentsList) {
20692 var _a2;
20693 var property = argumentsList[0];
20694 if (ignoreCSSAttributes.has(property)) {
20695 return removeProperty.apply(thisArg, [
20696 property
20697 ]);
20698 }
20699 var _getIdAndStyleId = getIdAndStyleId((_a2 = thisArg.parentRule) == null ? void 0 : _a2.parentStyleSheet, mirror2, stylesheetManager.styleMirror), id = _getIdAndStyleId.id, styleId = _getIdAndStyleId.styleId;
20700 if (id && id !== -1 || styleId && styleId !== -1) {
20701 styleDeclarationCb({
20702 id: id,
20703 styleId: styleId,
20704 remove: {
20705 property: property
20706 },
20707 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
20708 index: getNestedCSSRulePositions(thisArg.parentRule)
20709 });
20710 }
20711 return target.apply(thisArg, argumentsList);
20712 })
20713 });
20714 return callbackWrapper(function() {
20715 win.CSSStyleDeclaration.prototype.setProperty = setProperty;
20716 win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;
20717 });
20718 }
20719 function initMediaInteractionObserver(param) {
20720 var mediaInteractionCb = param.mediaInteractionCb, blockClass = param.blockClass, blockSelector = param.blockSelector, mirror2 = param.mirror, sampling = param.sampling, doc = param.doc;
20721 var handler = callbackWrapper(function(type) {
20722 return throttle(callbackWrapper(function(event) {
20723 var target = getEventTarget(event);
20724 if (!target || isBlocked(target, blockClass, blockSelector, true)) {
20725 return;
20726 }
20727 var currentTime = target.currentTime, volume = target.volume, muted = target.muted, playbackRate = target.playbackRate, loop = target.loop;
20728 mediaInteractionCb({
20729 type: type,
20730 id: mirror2.getId(target),
20731 currentTime: currentTime,
20732 volume: volume,
20733 muted: muted,
20734 playbackRate: playbackRate,
20735 loop: loop
20736 });
20737 }), sampling.media || 500);
20738 });
20739 var handlers = [
20740 on("play", handler(MediaInteractions.Play), doc),
20741 on("pause", handler(MediaInteractions.Pause), doc),
20742 on("seeked", handler(MediaInteractions.Seeked), doc),
20743 on("volumechange", handler(MediaInteractions.VolumeChange), doc),
20744 on("ratechange", handler(MediaInteractions.RateChange), doc)
20745 ];
20746 return callbackWrapper(function() {
20747 handlers.forEach(function(h) {
20748 return h();
20749 });
20750 });
20751 }
20752 function initFontObserver(param) {
20753 var fontCb = param.fontCb, doc = param.doc;
20754 var win = doc.defaultView;
20755 if (!win) {
20756 return function() {};
20757 }
20758 var handlers = [];
20759 var fontMap = /* @__PURE__ */ new WeakMap();
20760 var originalFontFace = win.FontFace;
20761 win.FontFace = function FontFace2(family, source, descriptors) {
20762 var fontFace = new originalFontFace(family, source, descriptors);
20763 fontMap.set(fontFace, {
20764 family: family,
20765 buffer: typeof source !== "string",
20766 descriptors: descriptors,
20767 fontSource: typeof source === "string" ? source : JSON.stringify(Array.from(new Uint8Array(source)))
20768 });
20769 return fontFace;
20770 };
20771 var restoreHandler = patch(doc.fonts, "add", function(original) {
20772 return function(fontFace) {
20773 setTimeout(callbackWrapper(function() {
20774 var p = fontMap.get(fontFace);
20775 if (p) {
20776 fontCb(p);
20777 fontMap.delete(fontFace);
20778 }
20779 }), 0);
20780 return original.apply(this, [
20781 fontFace
20782 ]);
20783 };
20784 });
20785 handlers.push(function() {
20786 win.FontFace = originalFontFace;
20787 });
20788 handlers.push(restoreHandler);
20789 return callbackWrapper(function() {
20790 handlers.forEach(function(h) {
20791 return h();
20792 });
20793 });
20794 }
20795 function initSelectionObserver(param) {
20796 var doc = param.doc, mirror2 = param.mirror, blockClass = param.blockClass, blockSelector = param.blockSelector, selectionCb = param.selectionCb;
20797 var collapsed = true;
20798 var updateSelection = callbackWrapper(function() {
20799 var selection = doc.getSelection();
20800 if (!selection || collapsed && (selection == null ? void 0 : selection.isCollapsed)) return;
20801 collapsed = selection.isCollapsed || false;
20802 var ranges = [];
20803 var count = selection.rangeCount || 0;
20804 for(var i2 = 0; i2 < count; i2++){
20805 var range = selection.getRangeAt(i2);
20806 var startContainer = range.startContainer, startOffset = range.startOffset, endContainer = range.endContainer, endOffset = range.endOffset;
20807 var blocked = isBlocked(startContainer, blockClass, blockSelector, true) || isBlocked(endContainer, blockClass, blockSelector, true);
20808 if (blocked) continue;
20809 ranges.push({
20810 start: mirror2.getId(startContainer),
20811 startOffset: startOffset,
20812 end: mirror2.getId(endContainer),
20813 endOffset: endOffset
20814 });
20815 }
20816 selectionCb({
20817 ranges: ranges
20818 });
20819 });
20820 updateSelection();
20821 return on("selectionchange", updateSelection);
20822 }
20823 function initCustomElementObserver(param) {
20824 var doc = param.doc, customElementCb = param.customElementCb;
20825 var win = doc.defaultView;
20826 if (!win || !win.customElements) return function() {};
20827 var restoreHandler = patch(win.customElements, "define", function(original) {
20828 return function(name, constructor, options) {
20829 try {
20830 customElementCb({
20831 define: {
20832 name: name
20833 }
20834 });
20835 } catch (e2) {
20836 console.warn("Custom element callback failed for " + name);
20837 }
20838 return original.apply(this, [
20839 name,
20840 constructor,
20841 options
20842 ]);
20843 };
20844 });
20845 return restoreHandler;
20846 }
20847 function mergeHooks(o2, hooks) {
20848 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;
20849 o2.mutationCb = function() {
20850 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20851 p[_key] = arguments[_key];
20852 }
20853 if (hooks.mutation) {
20854 var _hooks;
20855 (_hooks = hooks).mutation.apply(_hooks, [].concat(p));
20856 }
20857 mutationCb.apply(void 0, [].concat(p));
20858 };
20859 o2.mousemoveCb = function() {
20860 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20861 p[_key] = arguments[_key];
20862 }
20863 if (hooks.mousemove) {
20864 var _hooks;
20865 (_hooks = hooks).mousemove.apply(_hooks, [].concat(p));
20866 }
20867 mousemoveCb.apply(void 0, [].concat(p));
20868 };
20869 o2.mouseInteractionCb = function() {
20870 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20871 p[_key] = arguments[_key];
20872 }
20873 if (hooks.mouseInteraction) {
20874 var _hooks;
20875 (_hooks = hooks).mouseInteraction.apply(_hooks, [].concat(p));
20876 }
20877 mouseInteractionCb.apply(void 0, [].concat(p));
20878 };
20879 o2.scrollCb = function() {
20880 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20881 p[_key] = arguments[_key];
20882 }
20883 if (hooks.scroll) {
20884 var _hooks;
20885 (_hooks = hooks).scroll.apply(_hooks, [].concat(p));
20886 }
20887 scrollCb.apply(void 0, [].concat(p));
20888 };
20889 o2.viewportResizeCb = function() {
20890 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20891 p[_key] = arguments[_key];
20892 }
20893 if (hooks.viewportResize) {
20894 var _hooks;
20895 (_hooks = hooks).viewportResize.apply(_hooks, [].concat(p));
20896 }
20897 viewportResizeCb.apply(void 0, [].concat(p));
20898 };
20899 o2.inputCb = function() {
20900 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20901 p[_key] = arguments[_key];
20902 }
20903 if (hooks.input) {
20904 var _hooks;
20905 (_hooks = hooks).input.apply(_hooks, [].concat(p));
20906 }
20907 inputCb.apply(void 0, [].concat(p));
20908 };
20909 o2.mediaInteractionCb = function() {
20910 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20911 p[_key] = arguments[_key];
20912 }
20913 if (hooks.mediaInteaction) {
20914 var _hooks;
20915 (_hooks = hooks).mediaInteaction.apply(_hooks, [].concat(p));
20916 }
20917 mediaInteractionCb.apply(void 0, [].concat(p));
20918 };
20919 o2.styleSheetRuleCb = function() {
20920 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20921 p[_key] = arguments[_key];
20922 }
20923 if (hooks.styleSheetRule) {
20924 var _hooks;
20925 (_hooks = hooks).styleSheetRule.apply(_hooks, [].concat(p));
20926 }
20927 styleSheetRuleCb.apply(void 0, [].concat(p));
20928 };
20929 o2.styleDeclarationCb = function() {
20930 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20931 p[_key] = arguments[_key];
20932 }
20933 if (hooks.styleDeclaration) {
20934 var _hooks;
20935 (_hooks = hooks).styleDeclaration.apply(_hooks, [].concat(p));
20936 }
20937 styleDeclarationCb.apply(void 0, [].concat(p));
20938 };
20939 o2.canvasMutationCb = function() {
20940 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20941 p[_key] = arguments[_key];
20942 }
20943 if (hooks.canvasMutation) {
20944 var _hooks;
20945 (_hooks = hooks).canvasMutation.apply(_hooks, [].concat(p));
20946 }
20947 canvasMutationCb.apply(void 0, [].concat(p));
20948 };
20949 o2.fontCb = function() {
20950 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20951 p[_key] = arguments[_key];
20952 }
20953 if (hooks.font) {
20954 var _hooks;
20955 (_hooks = hooks).font.apply(_hooks, [].concat(p));
20956 }
20957 fontCb.apply(void 0, [].concat(p));
20958 };
20959 o2.selectionCb = function() {
20960 for(var _len = arguments.length, p = new Array(_len), _key = 0; _key < _len; _key++){
20961 p[_key] = arguments[_key];
20962 }
20963 if (hooks.selection) {
20964 var _hooks;
20965 (_hooks = hooks).selection.apply(_hooks, [].concat(p));
20966 }
20967 selectionCb.apply(void 0, [].concat(p));
20968 };
20969 o2.customElementCb = function() {
20970 for(var _len = arguments.length, c2 = new Array(_len), _key = 0; _key < _len; _key++){
20971 c2[_key] = arguments[_key];
20972 }
20973 if (hooks.customElement) {
20974 var _hooks;
20975 (_hooks = hooks).customElement.apply(_hooks, [].concat(c2));
20976 }
20977 customElementCb.apply(void 0, [].concat(c2));
20978 };
20979 }
20980 function initObservers(o2, hooks) {
20981 if (hooks === void 0) hooks = {};
20982 var currentWindow = o2.doc.defaultView;
20983 if (!currentWindow) {
20984 return function() {};
20985 }
20986 mergeHooks(o2, hooks);
20987 var mutationObserver;
20988 if (o2.recordDOM) {
20989 mutationObserver = initMutationObserver(o2, o2.doc);
20990 }
20991 var mousemoveHandler = initMoveObserver(o2);
20992 var mouseInteractionHandler = initMouseInteractionObserver(o2);
20993 var scrollHandler = initScrollObserver(o2);
20994 var viewportResizeHandler = initViewportResizeObserver(o2, {
20995 win: currentWindow
20996 });
20997 var inputHandler = initInputObserver(o2);
20998 var mediaInteractionHandler = initMediaInteractionObserver(o2);
20999 var styleSheetObserver = function() {};
21000 var adoptedStyleSheetObserver = function() {};
21001 var styleDeclarationObserver = function() {};
21002 var fontObserver = function() {};
21003 if (o2.recordDOM) {
21004 styleSheetObserver = initStyleSheetObserver(o2, {
21005 win: currentWindow
21006 });
21007 adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o2, o2.doc);
21008 styleDeclarationObserver = initStyleDeclarationObserver(o2, {
21009 win: currentWindow
21010 });
21011 if (o2.collectFonts) {
21012 fontObserver = initFontObserver(o2);
21013 }
21014 }
21015 var selectionObserver = initSelectionObserver(o2);
21016 var customElementObserver = initCustomElementObserver(o2);
21017 var pluginHandlers = [];
21018 for(var _iterator = _create_for_of_iterator_helper_loose(o2.plugins), _step; !(_step = _iterator()).done;){
21019 var plugin3 = _step.value;
21020 pluginHandlers.push(plugin3.observer(plugin3.callback, currentWindow, plugin3.options));
21021 }
21022 return callbackWrapper(function() {
21023 mutationBuffers.forEach(function(b) {
21024 return b.reset();
21025 });
21026 mutationObserver == null ? void 0 : mutationObserver.disconnect();
21027 mousemoveHandler();
21028 mouseInteractionHandler();
21029 scrollHandler();
21030 viewportResizeHandler();
21031 inputHandler();
21032 mediaInteractionHandler();
21033 styleSheetObserver();
21034 adoptedStyleSheetObserver();
21035 styleDeclarationObserver();
21036 fontObserver();
21037 selectionObserver();
21038 customElementObserver();
21039 pluginHandlers.forEach(function(h) {
21040 return h();
21041 });
21042 });
21043 }
21044 function hasNestedCSSRule(prop) {
21045 return typeof window[prop] !== "undefined";
21046 }
21047 function canMonkeyPatchNestedCSSRule(prop) {
21048 return Boolean(typeof window[prop] !== "undefined" && // Note: Generally, this check _shouldn't_ be necessary
21049 // However, in some scenarios (e.g. jsdom) this can sometimes fail, so we check for it here
21050 window[prop].prototype && "insertRule" in window[prop].prototype && "deleteRule" in window[prop].prototype);
21051 }
21052 var CrossOriginIframeMirror = /*#__PURE__*/ function() {
21053 function CrossOriginIframeMirror(generateIdFn) {
21054 __publicField(this, "iframeIdToRemoteIdMap", /* @__PURE__ */ new WeakMap());
21055 __publicField(this, "iframeRemoteIdToIdMap", /* @__PURE__ */ new WeakMap());
21056 this.generateIdFn = generateIdFn;
21057 }
21058 var _proto = CrossOriginIframeMirror.prototype;
21059 _proto.getId = function getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {
21060 var idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);
21061 var remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);
21062 var id = idToRemoteIdMap.get(remoteId);
21063 if (!id) {
21064 id = this.generateIdFn();
21065 idToRemoteIdMap.set(remoteId, id);
21066 remoteIdToIdMap.set(id, remoteId);
21067 }
21068 return id;
21069 };
21070 _proto.getIds = function getIds(iframe, remoteId) {
21071 var _this = this;
21072 var idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);
21073 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
21074 return remoteId.map(function(id) {
21075 return _this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap);
21076 });
21077 };
21078 _proto.getRemoteId = function getRemoteId(iframe, id, map) {
21079 var remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);
21080 if (typeof id !== "number") return id;
21081 var remoteId = remoteIdToIdMap.get(id);
21082 if (!remoteId) return -1;
21083 return remoteId;
21084 };
21085 _proto.getRemoteIds = function getRemoteIds(iframe, ids) {
21086 var _this = this;
21087 var remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);
21088 return ids.map(function(id) {
21089 return _this.getRemoteId(iframe, id, remoteIdToIdMap);
21090 });
21091 };
21092 _proto.reset = function reset(iframe) {
21093 if (!iframe) {
21094 this.iframeIdToRemoteIdMap = /* @__PURE__ */ new WeakMap();
21095 this.iframeRemoteIdToIdMap = /* @__PURE__ */ new WeakMap();
21096 return;
21097 }
21098 this.iframeIdToRemoteIdMap.delete(iframe);
21099 this.iframeRemoteIdToIdMap.delete(iframe);
21100 };
21101 _proto.getIdToRemoteIdMap = function getIdToRemoteIdMap(iframe) {
21102 var idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);
21103 if (!idToRemoteIdMap) {
21104 idToRemoteIdMap = /* @__PURE__ */ new Map();
21105 this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);
21106 }
21107 return idToRemoteIdMap;
21108 };
21109 _proto.getRemoteIdToIdMap = function getRemoteIdToIdMap(iframe) {
21110 var remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);
21111 if (!remoteIdToIdMap) {
21112 remoteIdToIdMap = /* @__PURE__ */ new Map();
21113 this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);
21114 }
21115 return remoteIdToIdMap;
21116 };
21117 return CrossOriginIframeMirror;
21118 }();
21119 var IframeManager = /*#__PURE__*/ function() {
21120 function IframeManager(options) {
21121 __publicField(this, "iframes", /* @__PURE__ */ new WeakMap());
21122 __publicField(this, "crossOriginIframeMap", /* @__PURE__ */ new WeakMap());
21123 __publicField(this, "crossOriginIframeMirror", new CrossOriginIframeMirror(genId));
21124 __publicField(this, "crossOriginIframeStyleMirror");
21125 __publicField(this, "crossOriginIframeRootIdMap", /* @__PURE__ */ new WeakMap());
21126 __publicField(this, "mirror");
21127 __publicField(this, "mutationCb");
21128 __publicField(this, "wrappedEmit");
21129 __publicField(this, "loadListener");
21130 __publicField(this, "stylesheetManager");
21131 __publicField(this, "recordCrossOriginIframes");
21132 this.mutationCb = options.mutationCb;
21133 this.wrappedEmit = options.wrappedEmit;
21134 this.stylesheetManager = options.stylesheetManager;
21135 this.recordCrossOriginIframes = options.recordCrossOriginIframes;
21136 this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));
21137 this.mirror = options.mirror;
21138 if (this.recordCrossOriginIframes) {
21139 window.addEventListener("message", this.handleMessage.bind(this));
21140 }
21141 }
21142 var _proto = IframeManager.prototype;
21143 _proto.addIframe = function addIframe(iframeEl) {
21144 this.iframes.set(iframeEl, true);
21145 if (iframeEl.contentWindow) this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);
21146 };
21147 _proto.addLoadListener = function addLoadListener(cb) {
21148 this.loadListener = cb;
21149 };
21150 _proto.attachIframe = function attachIframe(iframeEl, childSn) {
21151 var _a2, _b;
21152 this.mutationCb({
21153 adds: [
21154 {
21155 parentId: this.mirror.getId(iframeEl),
21156 nextId: null,
21157 node: childSn
21158 }
21159 ],
21160 removes: [],
21161 texts: [],
21162 attributes: [],
21163 isAttachIframe: true
21164 });
21165 if (this.recordCrossOriginIframes) (_a2 = iframeEl.contentWindow) == null ? void 0 : _a2.addEventListener("message", this.handleMessage.bind(this));
21166 (_b = this.loadListener) == null ? void 0 : _b.call(this, iframeEl);
21167 if (iframeEl.contentDocument && iframeEl.contentDocument.adoptedStyleSheets && iframeEl.contentDocument.adoptedStyleSheets.length > 0) this.stylesheetManager.adoptStyleSheets(iframeEl.contentDocument.adoptedStyleSheets, this.mirror.getId(iframeEl.contentDocument));
21168 };
21169 _proto.handleMessage = function handleMessage(message) {
21170 var crossOriginMessageEvent = message;
21171 if (crossOriginMessageEvent.data.type !== "rrweb" || // To filter out the rrweb messages which are forwarded by some sites.
21172 crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin) return;
21173 var iframeSourceWindow = message.source;
21174 if (!iframeSourceWindow) return;
21175 var iframeEl = this.crossOriginIframeMap.get(message.source);
21176 if (!iframeEl) return;
21177 var transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);
21178 if (transformedEvent) this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);
21179 };
21180 _proto.transformCrossOriginEvent = function transformCrossOriginEvent(iframeEl, e2) {
21181 var _this = this;
21182 var _a2;
21183 switch(e2.type){
21184 case EventType.FullSnapshot:
21185 {
21186 this.crossOriginIframeMirror.reset(iframeEl);
21187 this.crossOriginIframeStyleMirror.reset(iframeEl);
21188 this.replaceIdOnNode(e2.data.node, iframeEl);
21189 var rootId = e2.data.node.id;
21190 this.crossOriginIframeRootIdMap.set(iframeEl, rootId);
21191 this.patchRootIdOnNode(e2.data.node, rootId);
21192 return {
21193 timestamp: e2.timestamp,
21194 type: EventType.IncrementalSnapshot,
21195 data: {
21196 source: IncrementalSource.Mutation,
21197 adds: [
21198 {
21199 parentId: this.mirror.getId(iframeEl),
21200 nextId: null,
21201 node: e2.data.node
21202 }
21203 ],
21204 removes: [],
21205 texts: [],
21206 attributes: [],
21207 isAttachIframe: true
21208 }
21209 };
21210 }
21211 case EventType.Meta:
21212 case EventType.Load:
21213 case EventType.DomContentLoaded:
21214 {
21215 return false;
21216 }
21217 case EventType.Plugin:
21218 {
21219 return e2;
21220 }
21221 case EventType.Custom:
21222 {
21223 this.replaceIds(e2.data.payload, iframeEl, [
21224 "id",
21225 "parentId",
21226 "previousId",
21227 "nextId"
21228 ]);
21229 return e2;
21230 }
21231 case EventType.IncrementalSnapshot:
21232 {
21233 switch(e2.data.source){
21234 case IncrementalSource.Mutation:
21235 {
21236 e2.data.adds.forEach(function(n2) {
21237 _this.replaceIds(n2, iframeEl, [
21238 "parentId",
21239 "nextId",
21240 "previousId"
21241 ]);
21242 _this.replaceIdOnNode(n2.node, iframeEl);
21243 var rootId = _this.crossOriginIframeRootIdMap.get(iframeEl);
21244 rootId && _this.patchRootIdOnNode(n2.node, rootId);
21245 });
21246 e2.data.removes.forEach(function(n2) {
21247 _this.replaceIds(n2, iframeEl, [
21248 "parentId",
21249 "id"
21250 ]);
21251 });
21252 e2.data.attributes.forEach(function(n2) {
21253 _this.replaceIds(n2, iframeEl, [
21254 "id"
21255 ]);
21256 });
21257 e2.data.texts.forEach(function(n2) {
21258 _this.replaceIds(n2, iframeEl, [
21259 "id"
21260 ]);
21261 });
21262 return e2;
21263 }
21264 case IncrementalSource.Drag:
21265 case IncrementalSource.TouchMove:
21266 case IncrementalSource.MouseMove:
21267 {
21268 e2.data.positions.forEach(function(p) {
21269 _this.replaceIds(p, iframeEl, [
21270 "id"
21271 ]);
21272 });
21273 return e2;
21274 }
21275 case IncrementalSource.ViewportResize:
21276 {
21277 return false;
21278 }
21279 case IncrementalSource.MediaInteraction:
21280 case IncrementalSource.MouseInteraction:
21281 case IncrementalSource.Scroll:
21282 case IncrementalSource.CanvasMutation:
21283 case IncrementalSource.Input:
21284 {
21285 this.replaceIds(e2.data, iframeEl, [
21286 "id"
21287 ]);
21288 return e2;
21289 }
21290 case IncrementalSource.StyleSheetRule:
21291 case IncrementalSource.StyleDeclaration:
21292 {
21293 this.replaceIds(e2.data, iframeEl, [
21294 "id"
21295 ]);
21296 this.replaceStyleIds(e2.data, iframeEl, [
21297 "styleId"
21298 ]);
21299 return e2;
21300 }
21301 case IncrementalSource.Font:
21302 {
21303 return e2;
21304 }
21305 case IncrementalSource.Selection:
21306 {
21307 e2.data.ranges.forEach(function(range) {
21308 _this.replaceIds(range, iframeEl, [
21309 "start",
21310 "end"
21311 ]);
21312 });
21313 return e2;
21314 }
21315 case IncrementalSource.AdoptedStyleSheet:
21316 {
21317 this.replaceIds(e2.data, iframeEl, [
21318 "id"
21319 ]);
21320 this.replaceStyleIds(e2.data, iframeEl, [
21321 "styleIds"
21322 ]);
21323 (_a2 = e2.data.styles) == null ? void 0 : _a2.forEach(function(style) {
21324 _this.replaceStyleIds(style, iframeEl, [
21325 "styleId"
21326 ]);
21327 });
21328 return e2;
21329 }
21330 }
21331 }
21332 }
21333 return false;
21334 };
21335 _proto.replace = function replace(iframeMirror, obj, iframeEl, keys) {
21336 for(var _iterator = _create_for_of_iterator_helper_loose(keys), _step; !(_step = _iterator()).done;){
21337 var key = _step.value;
21338 if (!Array.isArray(obj[key]) && typeof obj[key] !== "number") continue;
21339 if (Array.isArray(obj[key])) {
21340 obj[key] = iframeMirror.getIds(iframeEl, obj[key]);
21341 } else {
21342 obj[key] = iframeMirror.getId(iframeEl, obj[key]);
21343 }
21344 }
21345 return obj;
21346 };
21347 _proto.replaceIds = function replaceIds(obj, iframeEl, keys) {
21348 return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);
21349 };
21350 _proto.replaceStyleIds = function replaceStyleIds(obj, iframeEl, keys) {
21351 return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);
21352 };
21353 _proto.replaceIdOnNode = function replaceIdOnNode(node2, iframeEl) {
21354 var _this = this;
21355 this.replaceIds(node2, iframeEl, [
21356 "id",
21357 "rootId"
21358 ]);
21359 if ("childNodes" in node2) {
21360 node2.childNodes.forEach(function(child) {
21361 _this.replaceIdOnNode(child, iframeEl);
21362 });
21363 }
21364 };
21365 _proto.patchRootIdOnNode = function patchRootIdOnNode(node2, rootId) {
21366 var _this = this;
21367 if (node2.type !== NodeType.Document && !node2.rootId) node2.rootId = rootId;
21368 if ("childNodes" in node2) {
21369 node2.childNodes.forEach(function(child) {
21370 _this.patchRootIdOnNode(child, rootId);
21371 });
21372 }
21373 };
21374 return IframeManager;
21375 }();
21376 var ShadowDomManager = /*#__PURE__*/ function() {
21377 function ShadowDomManager(options) {
21378 __publicField(this, "shadowDoms", /* @__PURE__ */ new WeakSet());
21379 __publicField(this, "mutationCb");
21380 __publicField(this, "scrollCb");
21381 __publicField(this, "bypassOptions");
21382 __publicField(this, "mirror");
21383 __publicField(this, "restoreHandlers", []);
21384 this.mutationCb = options.mutationCb;
21385 this.scrollCb = options.scrollCb;
21386 this.bypassOptions = options.bypassOptions;
21387 this.mirror = options.mirror;
21388 this.init();
21389 }
21390 var _proto = ShadowDomManager.prototype;
21391 _proto.init = function init() {
21392 this.reset();
21393 this.patchAttachShadow(Element, document);
21394 };
21395 _proto.addShadowRoot = function addShadowRoot(shadowRoot2, doc) {
21396 var _this = this;
21397 if (!isNativeShadowDom(shadowRoot2)) return;
21398 if (this.shadowDoms.has(shadowRoot2)) return;
21399 this.shadowDoms.add(shadowRoot2);
21400 var observer = initMutationObserver(_extends({}, this.bypassOptions, {
21401 doc: doc,
21402 mutationCb: this.mutationCb,
21403 mirror: this.mirror,
21404 shadowDomManager: this
21405 }), shadowRoot2);
21406 this.restoreHandlers.push(function() {
21407 return observer.disconnect();
21408 });
21409 this.restoreHandlers.push(initScrollObserver(_extends({}, this.bypassOptions, {
21410 scrollCb: this.scrollCb,
21411 // https://gist.github.com/praveenpuglia/0832da687ed5a5d7a0907046c9ef1813
21412 // scroll is not allowed to pass the boundary, so we need to listen the shadow document
21413 doc: shadowRoot2,
21414 mirror: this.mirror
21415 })));
21416 setTimeout(function() {
21417 if (shadowRoot2.adoptedStyleSheets && shadowRoot2.adoptedStyleSheets.length > 0) _this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot2.adoptedStyleSheets, _this.mirror.getId(index.host(shadowRoot2)));
21418 _this.restoreHandlers.push(initAdoptedStyleSheetObserver({
21419 mirror: _this.mirror,
21420 stylesheetManager: _this.bypassOptions.stylesheetManager
21421 }, shadowRoot2));
21422 }, 0);
21423 };
21424 /**
21425 * Monkey patch 'attachShadow' of an IFrameElement to observe newly added shadow doms.
21426 */ _proto.observeAttachShadow = function observeAttachShadow(iframeElement) {
21427 if (!iframeElement.contentWindow || !iframeElement.contentDocument) return;
21428 this.patchAttachShadow(iframeElement.contentWindow.Element, iframeElement.contentDocument);
21429 };
21430 /**
21431 * Patch 'attachShadow' to observe newly added shadow doms.
21432 */ _proto.patchAttachShadow = function patchAttachShadow(element, doc) {
21433 var manager = this;
21434 this.restoreHandlers.push(patch(element.prototype, "attachShadow", function(original) {
21435 return function(option) {
21436 var sRoot = original.call(this, option);
21437 var shadowRootEl = index.shadowRoot(this);
21438 if (shadowRootEl && inDom(this)) manager.addShadowRoot(shadowRootEl, doc);
21439 return sRoot;
21440 };
21441 }));
21442 };
21443 _proto.reset = function reset() {
21444 this.restoreHandlers.forEach(function(handler) {
21445 try {
21446 handler();
21447 } catch (e2) {}
21448 });
21449 this.restoreHandlers = [];
21450 this.shadowDoms = /* @__PURE__ */ new WeakSet();
21451 };
21452 return ShadowDomManager;
21453 }();
21454 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
21455 var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
21456 for(var i$1 = 0; i$1 < chars.length; i$1++){
21457 lookup[chars.charCodeAt(i$1)] = i$1;
21458 }
21459 var encode = function encode(arraybuffer) {
21460 var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = "";
21461 for(i2 = 0; i2 < len; i2 += 3){
21462 base64 += chars[bytes[i2] >> 2];
21463 base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4];
21464 base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6];
21465 base64 += chars[bytes[i2 + 2] & 63];
21466 }
21467 if (len % 3 === 2) {
21468 base64 = base64.substring(0, base64.length - 1) + "=";
21469 } else if (len % 3 === 1) {
21470 base64 = base64.substring(0, base64.length - 2) + "==";
21471 }
21472 return base64;
21473 };
21474 var canvasVarMap = /* @__PURE__ */ new Map();
21475 function variableListFor$1(ctx, ctor) {
21476 var contextMap = canvasVarMap.get(ctx);
21477 if (!contextMap) {
21478 contextMap = /* @__PURE__ */ new Map();
21479 canvasVarMap.set(ctx, contextMap);
21480 }
21481 if (!contextMap.has(ctor)) {
21482 contextMap.set(ctor, []);
21483 }
21484 return contextMap.get(ctor);
21485 }
21486 var saveWebGLVar = function(value, win, ctx) {
21487 if (!value || !(isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object")) return;
21488 var name = value.constructor.name;
21489 var list2 = variableListFor$1(ctx, name);
21490 var index2 = list2.indexOf(value);
21491 if (index2 === -1) {
21492 index2 = list2.length;
21493 list2.push(value);
21494 }
21495 return index2;
21496 };
21497 function serializeArg(value, win, ctx) {
21498 if (_instanceof(value, Array)) {
21499 return value.map(function(arg) {
21500 return serializeArg(arg, win, ctx);
21501 });
21502 } else if (value === null) {
21503 return value;
21504 } 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)) {
21505 var name = value.constructor.name;
21506 return {
21507 rr_type: name,
21508 args: [
21509 Object.values(value)
21510 ]
21511 };
21512 } else if (// SharedArrayBuffer disabled on most browsers due to spectre.
21513 // More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer
21514 // value instanceof SharedArrayBuffer ||
21515 _instanceof(value, ArrayBuffer)) {
21516 var name1 = value.constructor.name;
21517 var base64 = encode(value);
21518 return {
21519 rr_type: name1,
21520 base64: base64
21521 };
21522 } else if (_instanceof(value, DataView)) {
21523 var name2 = value.constructor.name;
21524 return {
21525 rr_type: name2,
21526 args: [
21527 serializeArg(value.buffer, win, ctx),
21528 value.byteOffset,
21529 value.byteLength
21530 ]
21531 };
21532 } else if (_instanceof(value, HTMLImageElement)) {
21533 var name3 = value.constructor.name;
21534 var src = value.src;
21535 return {
21536 rr_type: name3,
21537 src: src
21538 };
21539 } else if (_instanceof(value, HTMLCanvasElement)) {
21540 var name4 = "HTMLImageElement";
21541 var src1 = value.toDataURL();
21542 return {
21543 rr_type: name4,
21544 src: src1
21545 };
21546 } else if (_instanceof(value, ImageData)) {
21547 var name5 = value.constructor.name;
21548 return {
21549 rr_type: name5,
21550 args: [
21551 serializeArg(value.data, win, ctx),
21552 value.width,
21553 value.height
21554 ]
21555 };
21556 } else if (isInstanceOfWebGLObject(value, win) || (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") {
21557 var name6 = value.constructor.name;
21558 var index2 = saveWebGLVar(value, win, ctx);
21559 return {
21560 rr_type: name6,
21561 index: index2
21562 };
21563 }
21564 return value;
21565 }
21566 var serializeArgs = function(args, win, ctx) {
21567 return args.map(function(arg) {
21568 return serializeArg(arg, win, ctx);
21569 });
21570 };
21571 var isInstanceOfWebGLObject = function(value, win) {
21572 var webGLConstructorNames = [
21573 "WebGLActiveInfo",
21574 "WebGLBuffer",
21575 "WebGLFramebuffer",
21576 "WebGLProgram",
21577 "WebGLRenderbuffer",
21578 "WebGLShader",
21579 "WebGLShaderPrecisionFormat",
21580 "WebGLTexture",
21581 "WebGLUniformLocation",
21582 "WebGLVertexArrayObject",
21583 // In old Chrome versions, value won't be an instanceof WebGLVertexArrayObject.
21584 "WebGLVertexArrayObjectOES"
21585 ];
21586 var supportedWebGLConstructorNames = webGLConstructorNames.filter(function(name) {
21587 return typeof win[name] === "function";
21588 });
21589 return Boolean(supportedWebGLConstructorNames.find(function(name) {
21590 return _instanceof(value, win[name]);
21591 }));
21592 };
21593 function initCanvas2DMutationObserver(cb, win, blockClass, blockSelector) {
21594 var _loop = function() {
21595 var prop = _step.value;
21596 try {
21597 if (typeof win.CanvasRenderingContext2D.prototype[prop] !== "function") {
21598 return "continue";
21599 }
21600 var restoreHandler = patch(win.CanvasRenderingContext2D.prototype, prop, function(original) {
21601 return function() {
21602 var _this = this;
21603 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
21604 args[_key] = arguments[_key];
21605 }
21606 if (!isBlocked(this.canvas, blockClass, blockSelector, true)) {
21607 setTimeout(function() {
21608 var recordArgs = serializeArgs(args, win, _this);
21609 cb(_this.canvas, {
21610 type: CanvasContext["2D"],
21611 property: prop,
21612 args: recordArgs
21613 });
21614 }, 0);
21615 }
21616 return original.apply(this, args);
21617 };
21618 });
21619 handlers.push(restoreHandler);
21620 } catch (e) {
21621 var hookHandler = hookSetter(win.CanvasRenderingContext2D.prototype, prop, {
21622 set: function set(v2) {
21623 cb(this.canvas, {
21624 type: CanvasContext["2D"],
21625 property: prop,
21626 args: [
21627 v2
21628 ],
21629 setter: true
21630 });
21631 }
21632 });
21633 handlers.push(hookHandler);
21634 }
21635 };
21636 var handlers = [];
21637 var props2D = Object.getOwnPropertyNames(win.CanvasRenderingContext2D.prototype);
21638 for(var _iterator = _create_for_of_iterator_helper_loose(props2D), _step; !(_step = _iterator()).done;)_loop();
21639 return function() {
21640 handlers.forEach(function(h) {
21641 return h();
21642 });
21643 };
21644 }
21645 function getNormalizedContextName(contextType) {
21646 return contextType === "experimental-webgl" ? "webgl" : contextType;
21647 }
21648 function initCanvasContextObserver(win, blockClass, blockSelector, setPreserveDrawingBufferToTrue) {
21649 var handlers = [];
21650 try {
21651 var restoreHandler = patch(win.HTMLCanvasElement.prototype, "getContext", function(original) {
21652 return function(contextType) {
21653 for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
21654 args[_key - 1] = arguments[_key];
21655 }
21656 if (!isBlocked(this, blockClass, blockSelector, true)) {
21657 var ctxName = getNormalizedContextName(contextType);
21658 if (!("__context" in this)) this.__context = ctxName;
21659 if (setPreserveDrawingBufferToTrue && [
21660 "webgl",
21661 "webgl2"
21662 ].includes(ctxName)) {
21663 if (args[0] && _type_of(args[0]) === "object") {
21664 var contextAttributes = args[0];
21665 if (!contextAttributes.preserveDrawingBuffer) {
21666 contextAttributes.preserveDrawingBuffer = true;
21667 }
21668 } else {
21669 args.splice(0, 1, {
21670 preserveDrawingBuffer: true
21671 });
21672 }
21673 }
21674 }
21675 return original.apply(this, [].concat([
21676 contextType
21677 ], args));
21678 };
21679 });
21680 handlers.push(restoreHandler);
21681 } catch (e) {
21682 console.error("failed to patch HTMLCanvasElement.prototype.getContext");
21683 }
21684 return function() {
21685 handlers.forEach(function(h) {
21686 return h();
21687 });
21688 };
21689 }
21690 function patchGLPrototype(prototype, type, cb, blockClass, blockSelector, win) {
21691 var _loop = function() {
21692 var prop = _step.value;
21693 if (//prop.startsWith('get') || // e.g. getProgramParameter, but too risky
21694 [
21695 "isContextLost",
21696 "canvas",
21697 "drawingBufferWidth",
21698 "drawingBufferHeight"
21699 ].includes(prop)) {
21700 return "continue";
21701 }
21702 try {
21703 if (typeof prototype[prop] !== "function") {
21704 return "continue";
21705 }
21706 var restoreHandler = patch(prototype, prop, function(original) {
21707 return function() {
21708 for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
21709 args[_key] = arguments[_key];
21710 }
21711 var result2 = original.apply(this, args);
21712 saveWebGLVar(result2, win, this);
21713 if ("tagName" in this.canvas && !isBlocked(this.canvas, blockClass, blockSelector, true)) {
21714 var recordArgs = serializeArgs(args, win, this);
21715 var mutation = {
21716 type: type,
21717 property: prop,
21718 args: recordArgs
21719 };
21720 cb(this.canvas, mutation);
21721 }
21722 return result2;
21723 };
21724 });
21725 handlers.push(restoreHandler);
21726 } catch (e) {
21727 var hookHandler = hookSetter(prototype, prop, {
21728 set: function set(v2) {
21729 cb(this.canvas, {
21730 type: type,
21731 property: prop,
21732 args: [
21733 v2
21734 ],
21735 setter: true
21736 });
21737 }
21738 });
21739 handlers.push(hookHandler);
21740 }
21741 };
21742 var handlers = [];
21743 var props = Object.getOwnPropertyNames(prototype);
21744 for(var _iterator = _create_for_of_iterator_helper_loose(props), _step; !(_step = _iterator()).done;)_loop();
21745 return handlers;
21746 }
21747 function initCanvasWebGLMutationObserver(cb, win, blockClass, blockSelector) {
21748 var _handlers;
21749 var handlers = [];
21750 (_handlers = handlers).push.apply(_handlers, [].concat(patchGLPrototype(win.WebGLRenderingContext.prototype, CanvasContext.WebGL, cb, blockClass, blockSelector, win)));
21751 if (typeof win.WebGL2RenderingContext !== "undefined") {
21752 var _handlers1;
21753 (_handlers1 = handlers).push.apply(_handlers1, [].concat(patchGLPrototype(win.WebGL2RenderingContext.prototype, CanvasContext.WebGL2, cb, blockClass, blockSelector, win)));
21754 }
21755 return function() {
21756 handlers.forEach(function(h) {
21757 return h();
21758 });
21759 };
21760 }
21761 var encodedJs = "KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=";
21762 var decodeBase64 = function(base64) {
21763 return Uint8Array.from(atob(base64), function(c2) {
21764 return c2.charCodeAt(0);
21765 });
21766 };
21767 var blob = typeof window !== "undefined" && window.Blob && new Blob([
21768 decodeBase64(encodedJs)
21769 ], {
21770 type: "text/javascript;charset=utf-8"
21771 });
21772 function WorkerWrapper(options) {
21773 var objURL;
21774 try {
21775 objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
21776 if (!objURL) throw "";
21777 var worker = new Worker(objURL, {
21778 name: options == null ? void 0 : options.name
21779 });
21780 worker.addEventListener("error", function() {
21781 (window.URL || window.webkitURL).revokeObjectURL(objURL);
21782 });
21783 return worker;
21784 } catch (e2) {
21785 return new Worker("data:text/javascript;base64," + encodedJs, {
21786 name: options == null ? void 0 : options.name
21787 });
21788 } finally{
21789 objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
21790 }
21791 }
21792 var CanvasManager = /*#__PURE__*/ function() {
21793 function CanvasManager(options) {
21794 var _this = this;
21795 __publicField(this, "pendingCanvasMutations", /* @__PURE__ */ new Map());
21796 __publicField(this, "rafStamps", {
21797 latestId: 0,
21798 invokeId: null
21799 });
21800 __publicField(this, "mirror");
21801 __publicField(this, "mutationCb");
21802 __publicField(this, "resetObservers");
21803 __publicField(this, "frozen", false);
21804 __publicField(this, "locked", false);
21805 __publicField(this, "processMutation", function(target, mutation) {
21806 var newFrame = _this.rafStamps.invokeId && _this.rafStamps.latestId !== _this.rafStamps.invokeId;
21807 if (newFrame || !_this.rafStamps.invokeId) _this.rafStamps.invokeId = _this.rafStamps.latestId;
21808 if (!_this.pendingCanvasMutations.has(target)) {
21809 _this.pendingCanvasMutations.set(target, []);
21810 }
21811 _this.pendingCanvasMutations.get(target).push(mutation);
21812 });
21813 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;
21814 this.mutationCb = options.mutationCb;
21815 this.mirror = options.mirror;
21816 if (recordCanvas && sampling === "all") this.initCanvasMutationObserver(win, blockClass, blockSelector);
21817 if (recordCanvas && typeof sampling === "number") this.initCanvasFPSObserver(sampling, win, blockClass, blockSelector, {
21818 dataURLOptions: dataURLOptions
21819 });
21820 }
21821 var _proto = CanvasManager.prototype;
21822 _proto.reset = function reset() {
21823 this.pendingCanvasMutations.clear();
21824 this.resetObservers && this.resetObservers();
21825 };
21826 _proto.freeze = function freeze() {
21827 this.frozen = true;
21828 };
21829 _proto.unfreeze = function unfreeze() {
21830 this.frozen = false;
21831 };
21832 _proto.lock = function lock() {
21833 this.locked = true;
21834 };
21835 _proto.unlock = function unlock() {
21836 this.locked = false;
21837 };
21838 _proto.initCanvasFPSObserver = function initCanvasFPSObserver(fps, win, blockClass, blockSelector, options) {
21839 var _this = this;
21840 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, true);
21841 var snapshotInProgressMap = /* @__PURE__ */ new Map();
21842 var worker = new WorkerWrapper();
21843 worker.onmessage = function(e2) {
21844 var id = e2.data.id;
21845 snapshotInProgressMap.set(id, false);
21846 if (!("base64" in e2.data)) return;
21847 var _e2_data = e2.data, base64 = _e2_data.base64, type = _e2_data.type, width = _e2_data.width, height = _e2_data.height;
21848 _this.mutationCb({
21849 id: id,
21850 type: CanvasContext["2D"],
21851 commands: [
21852 {
21853 property: "clearRect",
21854 // wipe canvas
21855 args: [
21856 0,
21857 0,
21858 width,
21859 height
21860 ]
21861 },
21862 {
21863 property: "drawImage",
21864 // draws (semi-transparent) image
21865 args: [
21866 {
21867 rr_type: "ImageBitmap",
21868 args: [
21869 {
21870 rr_type: "Blob",
21871 data: [
21872 {
21873 rr_type: "ArrayBuffer",
21874 base64: base64
21875 }
21876 ],
21877 type: type
21878 }
21879 ]
21880 },
21881 0,
21882 0
21883 ]
21884 }
21885 ]
21886 });
21887 };
21888 var timeBetweenSnapshots = 1e3 / fps;
21889 var lastSnapshotTime = 0;
21890 var rafId;
21891 var getCanvas = function() {
21892 var matchedCanvas = [];
21893 win.document.querySelectorAll("canvas").forEach(function(canvas) {
21894 if (!isBlocked(canvas, blockClass, blockSelector, true)) {
21895 matchedCanvas.push(canvas);
21896 }
21897 });
21898 return matchedCanvas;
21899 };
21900 var takeCanvasSnapshots = function(timestamp) {
21901 if (lastSnapshotTime && timestamp - lastSnapshotTime < timeBetweenSnapshots) {
21902 rafId = requestAnimationFrame(takeCanvasSnapshots);
21903 return;
21904 }
21905 lastSnapshotTime = timestamp;
21906 var _this1 = _this;
21907 getCanvas().forEach(/*#__PURE__*/ _async_to_generator(function(canvas) {
21908 var _a2, id, context, bitmap;
21909 return _ts_generator(this, function(_state) {
21910 switch(_state.label){
21911 case 0:
21912 id = _this1.mirror.getId(canvas);
21913 if (snapshotInProgressMap.get(id)) return [
21914 2
21915 ];
21916 if (canvas.width === 0 || canvas.height === 0) return [
21917 2
21918 ];
21919 snapshotInProgressMap.set(id, true);
21920 if ([
21921 "webgl",
21922 "webgl2"
21923 ].includes(canvas.__context)) {
21924 context = canvas.getContext(canvas.__context);
21925 if (((_a2 = context == null ? void 0 : context.getContextAttributes()) == null ? void 0 : _a2.preserveDrawingBuffer) === false) {
21926 context.clear(context.COLOR_BUFFER_BIT);
21927 }
21928 }
21929 return [
21930 4,
21931 createImageBitmap(canvas)
21932 ];
21933 case 1:
21934 bitmap = _state.sent();
21935 worker.postMessage({
21936 id: id,
21937 bitmap: bitmap,
21938 width: canvas.width,
21939 height: canvas.height,
21940 dataURLOptions: options.dataURLOptions
21941 }, [
21942 bitmap
21943 ]);
21944 return [
21945 2
21946 ];
21947 }
21948 });
21949 }));
21950 rafId = requestAnimationFrame(takeCanvasSnapshots);
21951 };
21952 rafId = requestAnimationFrame(takeCanvasSnapshots);
21953 this.resetObservers = function() {
21954 canvasContextReset();
21955 cancelAnimationFrame(rafId);
21956 };
21957 };
21958 _proto.initCanvasMutationObserver = function initCanvasMutationObserver(win, blockClass, blockSelector) {
21959 this.startRAFTimestamping();
21960 this.startPendingCanvasMutationFlusher();
21961 var canvasContextReset = initCanvasContextObserver(win, blockClass, blockSelector, false);
21962 var canvas2DReset = initCanvas2DMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
21963 var canvasWebGL1and2Reset = initCanvasWebGLMutationObserver(this.processMutation.bind(this), win, blockClass, blockSelector);
21964 this.resetObservers = function() {
21965 canvasContextReset();
21966 canvas2DReset();
21967 canvasWebGL1and2Reset();
21968 };
21969 };
21970 _proto.startPendingCanvasMutationFlusher = function startPendingCanvasMutationFlusher() {
21971 var _this = this;
21972 requestAnimationFrame(function() {
21973 return _this.flushPendingCanvasMutations();
21974 });
21975 };
21976 _proto.startRAFTimestamping = function startRAFTimestamping() {
21977 var _this = this;
21978 var setLatestRAFTimestamp = function(timestamp) {
21979 _this.rafStamps.latestId = timestamp;
21980 requestAnimationFrame(setLatestRAFTimestamp);
21981 };
21982 requestAnimationFrame(setLatestRAFTimestamp);
21983 };
21984 _proto.flushPendingCanvasMutations = function flushPendingCanvasMutations() {
21985 var _this = this;
21986 this.pendingCanvasMutations.forEach(function(_values, canvas) {
21987 var id = _this.mirror.getId(canvas);
21988 _this.flushPendingCanvasMutationFor(canvas, id);
21989 });
21990 requestAnimationFrame(function() {
21991 return _this.flushPendingCanvasMutations();
21992 });
21993 };
21994 _proto.flushPendingCanvasMutationFor = function flushPendingCanvasMutationFor(canvas, id) {
21995 if (this.frozen || this.locked) {
21996 return;
21997 }
21998 var valuesWithType = this.pendingCanvasMutations.get(canvas);
21999 if (!valuesWithType || id === -1) return;
22000 var values = valuesWithType.map(function(value) {
22001 value.type; var rest = _object_without_properties_loose(value, [
22002 "type"
22003 ]);
22004 return rest;
22005 });
22006 var type = valuesWithType[0].type;
22007 this.mutationCb({
22008 id: id,
22009 type: type,
22010 commands: values
22011 });
22012 this.pendingCanvasMutations.delete(canvas);
22013 };
22014 return CanvasManager;
22015 }();
22016 var StylesheetManager = /*#__PURE__*/ function() {
22017 function StylesheetManager(options) {
22018 __publicField(this, "trackedLinkElements", /* @__PURE__ */ new WeakSet());
22019 __publicField(this, "mutationCb");
22020 __publicField(this, "adoptedStyleSheetCb");
22021 __publicField(this, "styleMirror", new StyleSheetMirror());
22022 this.mutationCb = options.mutationCb;
22023 this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;
22024 }
22025 var _proto = StylesheetManager.prototype;
22026 _proto.attachLinkElement = function attachLinkElement(linkEl, childSn) {
22027 if ("_cssText" in childSn.attributes) this.mutationCb({
22028 adds: [],
22029 removes: [],
22030 texts: [],
22031 attributes: [
22032 {
22033 id: childSn.id,
22034 attributes: childSn.attributes
22035 }
22036 ]
22037 });
22038 this.trackLinkElement(linkEl);
22039 };
22040 _proto.trackLinkElement = function trackLinkElement(linkEl) {
22041 if (this.trackedLinkElements.has(linkEl)) return;
22042 this.trackedLinkElements.add(linkEl);
22043 this.trackStylesheetInLinkElement(linkEl);
22044 };
22045 _proto.adoptStyleSheets = function adoptStyleSheets(sheets, hostId) {
22046 var _this, _loop = function() {
22047 var sheet = _step.value;
22048 var styleId = void 0;
22049 if (!_this.styleMirror.has(sheet)) {
22050 styleId = _this.styleMirror.add(sheet);
22051 styles.push({
22052 styleId: styleId,
22053 rules: Array.from(sheet.rules || CSSRule, function(r2, index2) {
22054 return {
22055 rule: stringifyRule(r2, sheet.href),
22056 index: index2
22057 };
22058 })
22059 });
22060 } else styleId = _this.styleMirror.getId(sheet);
22061 adoptedStyleSheetData.styleIds.push(styleId);
22062 };
22063 if (sheets.length === 0) return;
22064 var adoptedStyleSheetData = {
22065 id: hostId,
22066 styleIds: []
22067 };
22068 var styles = [];
22069 for(var _iterator = _create_for_of_iterator_helper_loose(sheets), _step; !(_step = _iterator()).done;)_this = this, _loop();
22070 if (styles.length > 0) adoptedStyleSheetData.styles = styles;
22071 this.adoptedStyleSheetCb(adoptedStyleSheetData);
22072 };
22073 _proto.reset = function reset() {
22074 this.styleMirror.reset();
22075 this.trackedLinkElements = /* @__PURE__ */ new WeakSet();
22076 };
22077 // TODO: take snapshot on stylesheet reload by applying event listener
22078 _proto.trackStylesheetInLinkElement = function trackStylesheetInLinkElement(_linkEl) {};
22079 return StylesheetManager;
22080 }();
22081 var ProcessedNodeManager = /*#__PURE__*/ function() {
22082 function ProcessedNodeManager() {
22083 __publicField(this, "nodeMap", /* @__PURE__ */ new WeakMap());
22084 __publicField(this, "active", false);
22085 }
22086 var _proto = ProcessedNodeManager.prototype;
22087 _proto.inOtherBuffer = function inOtherBuffer(node2, thisBuffer) {
22088 var buffers = this.nodeMap.get(node2);
22089 return buffers && Array.from(buffers).some(function(buffer) {
22090 return buffer !== thisBuffer;
22091 });
22092 };
22093 _proto.add = function add(node2, buffer) {
22094 var _this = this;
22095 if (!this.active) {
22096 this.active = true;
22097 requestAnimationFrame(function() {
22098 _this.nodeMap = /* @__PURE__ */ new WeakMap();
22099 _this.active = false;
22100 });
22101 }
22102 this.nodeMap.set(node2, (this.nodeMap.get(node2) || /* @__PURE__ */ new Set()).add(buffer));
22103 };
22104 _proto.destroy = function destroy() {};
22105 return ProcessedNodeManager;
22106 }();
22107 var wrappedEmit;
22108 var takeFullSnapshot$1;
22109 var canvasManager;
22110 var recording = false;
22111 try {
22112 if (Array.from([
22113 1
22114 ], function(x2) {
22115 return x2 * 2;
22116 })[0] !== 2) {
22117 var cleanFrame = document.createElement("iframe");
22118 document.body.appendChild(cleanFrame);
22119 Array.from = ((_a = cleanFrame.contentWindow) == null ? void 0 : _a.Array.from) || Array.from;
22120 document.body.removeChild(cleanFrame);
22121 }
22122 } catch (err) {
22123 console.debug("Unable to override Array.from", err);
22124 }
22125 var mirror = createMirror$2();
22126 function record(options) {
22127 if (options === void 0) options = {};
22128 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() {
22129 return false;
22130 } : _options_keepIframeSrcFn, _options_ignoreCSSAttributes = options.ignoreCSSAttributes, ignoreCSSAttributes = _options_ignoreCSSAttributes === void 0 ? /* @__PURE__ */ new Set([]) : _options_ignoreCSSAttributes, errorHandler2 = options.errorHandler;
22131 registerErrorHandler(errorHandler2);
22132 var inEmittingFrame = recordCrossOriginIframes ? window.parent === window : true;
22133 var passEmitsToParent = false;
22134 if (!inEmittingFrame) {
22135 try {
22136 if (window.parent.document) {
22137 passEmitsToParent = false;
22138 }
22139 } catch (e2) {
22140 passEmitsToParent = true;
22141 }
22142 }
22143 if (inEmittingFrame && !emit) {
22144 throw new Error("emit function is required");
22145 }
22146 if (!inEmittingFrame && !passEmitsToParent) {
22147 return function() {};
22148 }
22149 if (mousemoveWait !== void 0 && sampling.mousemove === void 0) {
22150 sampling.mousemove = mousemoveWait;
22151 }
22152 mirror.reset();
22153 var maskInputOptions = maskAllInputs === true ? {
22154 color: true,
22155 date: true,
22156 "datetime-local": true,
22157 email: true,
22158 month: true,
22159 number: true,
22160 range: true,
22161 search: true,
22162 tel: true,
22163 text: true,
22164 time: true,
22165 url: true,
22166 week: true,
22167 textarea: true,
22168 select: true,
22169 password: true,
22170 hidden: true
22171 } : _maskInputOptions !== void 0 ? _maskInputOptions : {
22172 password: true
22173 };
22174 var slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === "all" ? {
22175 script: true,
22176 comment: true,
22177 headFavicon: true,
22178 headWhitespace: true,
22179 headMetaSocial: true,
22180 headMetaRobots: true,
22181 headMetaHttpEquiv: true,
22182 headMetaVerification: true,
22183 // the following are off for slimDOMOptions === true,
22184 // as they destroy some (hidden) info:
22185 headMetaAuthorship: _slimDOMOptions === "all",
22186 headMetaDescKeywords: _slimDOMOptions === "all",
22187 headTitleMutations: _slimDOMOptions === "all"
22188 } : _slimDOMOptions ? _slimDOMOptions : {};
22189 polyfill$1();
22190 var lastFullSnapshotEvent;
22191 var incrementalSnapshotCount = 0;
22192 var eventProcessor = function(e2) {
22193 for(var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;){
22194 var plugin3 = _step.value;
22195 if (plugin3.eventProcessor) {
22196 e2 = plugin3.eventProcessor(e2);
22197 }
22198 }
22199 if (packFn && // Disable packing events which will be emitted to parent frames.
22200 !passEmitsToParent) {
22201 e2 = packFn(e2);
22202 }
22203 return e2;
22204 };
22205 wrappedEmit = function(r2, isCheckout) {
22206 var _a2;
22207 var e2 = r2;
22208 e2.timestamp = nowTimestamp();
22209 if (((_a2 = mutationBuffers[0]) == null ? void 0 : _a2.isFrozen()) && e2.type !== EventType.FullSnapshot && !(e2.type === EventType.IncrementalSnapshot && e2.data.source === IncrementalSource.Mutation)) {
22210 mutationBuffers.forEach(function(buf) {
22211 return buf.unfreeze();
22212 });
22213 }
22214 if (inEmittingFrame) {
22215 emit == null ? void 0 : emit(eventProcessor(e2), isCheckout);
22216 } else if (passEmitsToParent) {
22217 var message = {
22218 type: "rrweb",
22219 event: eventProcessor(e2),
22220 origin: window.location.origin,
22221 isCheckout: isCheckout
22222 };
22223 window.parent.postMessage(message, "*");
22224 }
22225 if (e2.type === EventType.FullSnapshot) {
22226 lastFullSnapshotEvent = e2;
22227 incrementalSnapshotCount = 0;
22228 } else if (e2.type === EventType.IncrementalSnapshot) {
22229 if (e2.data.source === IncrementalSource.Mutation && e2.data.isAttachIframe) {
22230 return;
22231 }
22232 incrementalSnapshotCount++;
22233 var exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;
22234 var exceedTime = checkoutEveryNms && e2.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;
22235 if (exceedCount || exceedTime) {
22236 takeFullSnapshot$1(true);
22237 }
22238 }
22239 };
22240 var wrappedMutationEmit = function(m) {
22241 wrappedEmit({
22242 type: EventType.IncrementalSnapshot,
22243 data: _extends({
22244 source: IncrementalSource.Mutation
22245 }, m)
22246 });
22247 };
22248 var wrappedScrollEmit = function(p) {
22249 return wrappedEmit({
22250 type: EventType.IncrementalSnapshot,
22251 data: _extends({
22252 source: IncrementalSource.Scroll
22253 }, p)
22254 });
22255 };
22256 var wrappedCanvasMutationEmit = function(p) {
22257 return wrappedEmit({
22258 type: EventType.IncrementalSnapshot,
22259 data: _extends({
22260 source: IncrementalSource.CanvasMutation
22261 }, p)
22262 });
22263 };
22264 var wrappedAdoptedStyleSheetEmit = function(a2) {
22265 return wrappedEmit({
22266 type: EventType.IncrementalSnapshot,
22267 data: _extends({
22268 source: IncrementalSource.AdoptedStyleSheet
22269 }, a2)
22270 });
22271 };
22272 var stylesheetManager = new StylesheetManager({
22273 mutationCb: wrappedMutationEmit,
22274 adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit
22275 });
22276 var iframeManager = new IframeManager({
22277 mirror: mirror,
22278 mutationCb: wrappedMutationEmit,
22279 stylesheetManager: stylesheetManager,
22280 recordCrossOriginIframes: recordCrossOriginIframes,
22281 wrappedEmit: wrappedEmit
22282 });
22283 for(var _iterator = _create_for_of_iterator_helper_loose(plugins || []), _step; !(_step = _iterator()).done;){
22284 var plugin3 = _step.value;
22285 if (plugin3.getMirror) plugin3.getMirror({
22286 nodeMirror: mirror,
22287 crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,
22288 crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror
22289 });
22290 }
22291 var processedNodeManager = new ProcessedNodeManager();
22292 canvasManager = new CanvasManager({
22293 recordCanvas: recordCanvas,
22294 mutationCb: wrappedCanvasMutationEmit,
22295 win: window,
22296 blockClass: blockClass,
22297 blockSelector: blockSelector,
22298 mirror: mirror,
22299 sampling: sampling.canvas,
22300 dataURLOptions: dataURLOptions
22301 });
22302 var shadowDomManager = new ShadowDomManager({
22303 mutationCb: wrappedMutationEmit,
22304 scrollCb: wrappedScrollEmit,
22305 bypassOptions: {
22306 blockClass: blockClass,
22307 blockSelector: blockSelector,
22308 maskTextClass: maskTextClass,
22309 maskTextSelector: maskTextSelector,
22310 inlineStylesheet: inlineStylesheet,
22311 maskInputOptions: maskInputOptions,
22312 dataURLOptions: dataURLOptions,
22313 maskTextFn: maskTextFn,
22314 maskInputFn: maskInputFn,
22315 recordCanvas: recordCanvas,
22316 inlineImages: inlineImages,
22317 sampling: sampling,
22318 slimDOMOptions: slimDOMOptions,
22319 iframeManager: iframeManager,
22320 stylesheetManager: stylesheetManager,
22321 canvasManager: canvasManager,
22322 keepIframeSrcFn: keepIframeSrcFn,
22323 processedNodeManager: processedNodeManager
22324 },
22325 mirror: mirror
22326 });
22327 takeFullSnapshot$1 = function(isCheckout) {
22328 if (isCheckout === void 0) isCheckout = false;
22329 if (!recordDOM) {
22330 return;
22331 }
22332 wrappedEmit({
22333 type: EventType.Meta,
22334 data: {
22335 href: window.location.href,
22336 width: getWindowWidth(),
22337 height: getWindowHeight()
22338 }
22339 }, isCheckout);
22340 stylesheetManager.reset();
22341 shadowDomManager.init();
22342 mutationBuffers.forEach(function(buf) {
22343 return buf.lock();
22344 });
22345 var node2 = snapshot(document, {
22346 mirror: mirror,
22347 blockClass: blockClass,
22348 blockSelector: blockSelector,
22349 maskTextClass: maskTextClass,
22350 maskTextSelector: maskTextSelector,
22351 inlineStylesheet: inlineStylesheet,
22352 maskAllInputs: maskInputOptions,
22353 maskTextFn: maskTextFn,
22354 maskInputFn: maskInputFn,
22355 slimDOM: slimDOMOptions,
22356 dataURLOptions: dataURLOptions,
22357 recordCanvas: recordCanvas,
22358 inlineImages: inlineImages,
22359 onSerialize: function(n2) {
22360 if (isSerializedIframe(n2, mirror)) {
22361 iframeManager.addIframe(n2);
22362 }
22363 if (isSerializedStylesheet(n2, mirror)) {
22364 stylesheetManager.trackLinkElement(n2);
22365 }
22366 if (hasShadowRoot(n2)) {
22367 shadowDomManager.addShadowRoot(index.shadowRoot(n2), document);
22368 }
22369 },
22370 onIframeLoad: function(iframe, childSn) {
22371 iframeManager.attachIframe(iframe, childSn);
22372 shadowDomManager.observeAttachShadow(iframe);
22373 },
22374 onStylesheetLoad: function(linkEl, childSn) {
22375 stylesheetManager.attachLinkElement(linkEl, childSn);
22376 },
22377 keepIframeSrcFn: keepIframeSrcFn
22378 });
22379 if (!node2) {
22380 return console.warn("Failed to snapshot the document");
22381 }
22382 wrappedEmit({
22383 type: EventType.FullSnapshot,
22384 data: {
22385 node: node2,
22386 initialOffset: getWindowScroll(window)
22387 }
22388 }, isCheckout);
22389 mutationBuffers.forEach(function(buf) {
22390 return buf.unlock();
22391 });
22392 if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0) stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));
22393 };
22394 try {
22395 var handlers = [];
22396 var observe = function(doc) {
22397 var _a2;
22398 return callbackWrapper(initObservers)({
22399 mutationCb: wrappedMutationEmit,
22400 mousemoveCb: function(positions, source) {
22401 return wrappedEmit({
22402 type: EventType.IncrementalSnapshot,
22403 data: {
22404 source: source,
22405 positions: positions
22406 }
22407 });
22408 },
22409 mouseInteractionCb: function(d) {
22410 return wrappedEmit({
22411 type: EventType.IncrementalSnapshot,
22412 data: _extends({
22413 source: IncrementalSource.MouseInteraction
22414 }, d)
22415 });
22416 },
22417 scrollCb: wrappedScrollEmit,
22418 viewportResizeCb: function(d) {
22419 return wrappedEmit({
22420 type: EventType.IncrementalSnapshot,
22421 data: _extends({
22422 source: IncrementalSource.ViewportResize
22423 }, d)
22424 });
22425 },
22426 inputCb: function(v2) {
22427 return wrappedEmit({
22428 type: EventType.IncrementalSnapshot,
22429 data: _extends({
22430 source: IncrementalSource.Input
22431 }, v2)
22432 });
22433 },
22434 mediaInteractionCb: function(p) {
22435 return wrappedEmit({
22436 type: EventType.IncrementalSnapshot,
22437 data: _extends({
22438 source: IncrementalSource.MediaInteraction
22439 }, p)
22440 });
22441 },
22442 styleSheetRuleCb: function(r2) {
22443 return wrappedEmit({
22444 type: EventType.IncrementalSnapshot,
22445 data: _extends({
22446 source: IncrementalSource.StyleSheetRule
22447 }, r2)
22448 });
22449 },
22450 styleDeclarationCb: function(r2) {
22451 return wrappedEmit({
22452 type: EventType.IncrementalSnapshot,
22453 data: _extends({
22454 source: IncrementalSource.StyleDeclaration
22455 }, r2)
22456 });
22457 },
22458 canvasMutationCb: wrappedCanvasMutationEmit,
22459 fontCb: function(p) {
22460 return wrappedEmit({
22461 type: EventType.IncrementalSnapshot,
22462 data: _extends({
22463 source: IncrementalSource.Font
22464 }, p)
22465 });
22466 },
22467 selectionCb: function(p) {
22468 wrappedEmit({
22469 type: EventType.IncrementalSnapshot,
22470 data: _extends({
22471 source: IncrementalSource.Selection
22472 }, p)
22473 });
22474 },
22475 customElementCb: function(c2) {
22476 wrappedEmit({
22477 type: EventType.IncrementalSnapshot,
22478 data: _extends({
22479 source: IncrementalSource.CustomElement
22480 }, c2)
22481 });
22482 },
22483 blockClass: blockClass,
22484 ignoreClass: ignoreClass,
22485 ignoreSelector: ignoreSelector,
22486 maskTextClass: maskTextClass,
22487 maskTextSelector: maskTextSelector,
22488 maskInputOptions: maskInputOptions,
22489 inlineStylesheet: inlineStylesheet,
22490 sampling: sampling,
22491 recordDOM: recordDOM,
22492 recordCanvas: recordCanvas,
22493 inlineImages: inlineImages,
22494 userTriggeredOnInput: userTriggeredOnInput,
22495 collectFonts: collectFonts,
22496 doc: doc,
22497 maskInputFn: maskInputFn,
22498 maskTextFn: maskTextFn,
22499 keepIframeSrcFn: keepIframeSrcFn,
22500 blockSelector: blockSelector,
22501 slimDOMOptions: slimDOMOptions,
22502 dataURLOptions: dataURLOptions,
22503 mirror: mirror,
22504 iframeManager: iframeManager,
22505 stylesheetManager: stylesheetManager,
22506 shadowDomManager: shadowDomManager,
22507 processedNodeManager: processedNodeManager,
22508 canvasManager: canvasManager,
22509 ignoreCSSAttributes: ignoreCSSAttributes,
22510 plugins: ((_a2 = plugins == null ? void 0 : plugins.filter(function(p) {
22511 return p.observer;
22512 })) == null ? void 0 : _a2.map(function(p) {
22513 return {
22514 observer: p.observer,
22515 options: p.options,
22516 callback: function(payload) {
22517 return wrappedEmit({
22518 type: EventType.Plugin,
22519 data: {
22520 plugin: p.name,
22521 payload: payload
22522 }
22523 });
22524 }
22525 };
22526 })) || []
22527 }, hooks);
22528 };
22529 iframeManager.addLoadListener(function(iframeEl) {
22530 try {
22531 handlers.push(observe(iframeEl.contentDocument));
22532 } catch (error) {
22533 console.warn(error);
22534 }
22535 });
22536 var init = function() {
22537 takeFullSnapshot$1();
22538 handlers.push(observe(document));
22539 recording = true;
22540 };
22541 if (document.readyState === "interactive" || document.readyState === "complete") {
22542 init();
22543 } else {
22544 handlers.push(on("DOMContentLoaded", function() {
22545 wrappedEmit({
22546 type: EventType.DomContentLoaded,
22547 data: {}
22548 });
22549 if (recordAfter === "DOMContentLoaded") init();
22550 }));
22551 handlers.push(on("load", function() {
22552 wrappedEmit({
22553 type: EventType.Load,
22554 data: {}
22555 });
22556 if (recordAfter === "load") init();
22557 }, window));
22558 }
22559 return function() {
22560 handlers.forEach(function(handler) {
22561 try {
22562 handler();
22563 } catch (error) {
22564 var msg = String(error).toLowerCase();
22565 if (!msg.includes("cross-origin")) {
22566 console.warn(error);
22567 }
22568 }
22569 });
22570 processedNodeManager.destroy();
22571 recording = false;
22572 unregisterErrorHandler();
22573 };
22574 } catch (error) {
22575 console.warn(error);
22576 }
22577 }
22578 record.addCustomEvent = function(tag, payload) {
22579 if (!recording) {
22580 throw new Error("please add custom event after start recording");
22581 }
22582 wrappedEmit({
22583 type: EventType.Custom,
22584 data: {
22585 tag: tag,
22586 payload: payload
22587 }
22588 });
22589 };
22590 record.freezePage = function() {
22591 mutationBuffers.forEach(function(buf) {
22592 return buf.freeze();
22593 });
22594 };
22595 record.takeFullSnapshot = function(isCheckout) {
22596 if (!recording) {
22597 throw new Error("please take full snapshot after start recording");
22598 }
22599 takeFullSnapshot$1(isCheckout);
22600 };
22601 record.mirror = mirror;
22602 var n;
22603 !function(t2) {
22604 t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped";
22605 }(n || (n = {}));
22606 record.addCustomEvent;
22607 record.freezePage;
22608 record.takeFullSnapshot;
22609
22610 var setImmediate = win['setImmediate'];
22611 var builtInProp, cycle, schedulingQueue,
22612 ToString = Object.prototype.toString,
22613 timer = (typeof setImmediate !== 'undefined') ?
22614 function timer(fn) { return setImmediate(fn); } :
22615 setTimeout;
22616
22617 // dammit, IE8.
22618 try {
22619 Object.defineProperty({},'x',{});
22620 builtInProp = function builtInProp(obj,name,val,config) {
22621 return Object.defineProperty(obj,name,{
22622 value: val,
22623 writable: true,
22624 configurable: config !== false
22625 });
22626 };
22627 }
22628 catch (err) {
22629 builtInProp = function builtInProp(obj,name,val) {
22630 obj[name] = val;
22631 return obj;
22632 };
22633 }
22634
22635 // Note: using a queue instead of array for efficiency
22636 schedulingQueue = (function Queue() {
22637 var first, last, item;
22638
22639 function Item(fn,self) {
22640 this.fn = fn;
22641 this.self = self;
22642 this.next = void 0;
22643 }
22644
22645 return {
22646 add: function add(fn,self) {
22647 item = new Item(fn,self);
22648 if (last) {
22649 last.next = item;
22650 }
22651 else {
22652 first = item;
22653 }
22654 last = item;
22655 item = void 0;
22656 },
22657 drain: function drain() {
22658 var f = first;
22659 first = last = cycle = void 0;
22660
22661 while (f) {
22662 f.fn.call(f.self);
22663 f = f.next;
22664 }
22665 }
22666 };
22667 })();
22668
22669 function schedule(fn,self) {
22670 schedulingQueue.add(fn,self);
22671 if (!cycle) {
22672 cycle = timer(schedulingQueue.drain);
22673 }
22674 }
22675
22676 // promise duck typing
22677 function isThenable(o) {
22678 var _then, oType = typeof o;
22679
22680 if (o !== null && (oType === 'object' || oType === 'function')) {
22681 _then = o.then;
22682 }
22683 return typeof _then === 'function' ? _then : false;
22684 }
22685
22686 function notify() {
22687 for (var i=0; i<this.chain.length; i++) {
22688 notifyIsolated(
22689 this,
22690 (this.state === 1) ? this.chain[i].success : this.chain[i].failure,
22691 this.chain[i]
22692 );
22693 }
22694 this.chain.length = 0;
22695 }
22696
22697 // NOTE: This is a separate function to isolate
22698 // the `try..catch` so that other code can be
22699 // optimized better
22700 function notifyIsolated(self,cb,chain) {
22701 var ret, _then;
22702 try {
22703 if (cb === false) {
22704 chain.reject(self.msg);
22705 }
22706 else {
22707 if (cb === true) {
22708 ret = self.msg;
22709 }
22710 else {
22711 ret = cb.call(void 0,self.msg);
22712 }
22713
22714 if (ret === chain.promise) {
22715 chain.reject(TypeError('Promise-chain cycle'));
22716 }
22717 // eslint-disable-next-line no-cond-assign
22718 else if (_then = isThenable(ret)) {
22719 _then.call(ret,chain.resolve,chain.reject);
22720 }
22721 else {
22722 chain.resolve(ret);
22723 }
22724 }
22725 }
22726 catch (err) {
22727 chain.reject(err);
22728 }
22729 }
22730
22731 function resolve(msg) {
22732 var _then, self = this;
22733
22734 // already triggered?
22735 if (self.triggered) { return; }
22736
22737 self.triggered = true;
22738
22739 // unwrap
22740 if (self.def) {
22741 self = self.def;
22742 }
22743
22744 try {
22745 // eslint-disable-next-line no-cond-assign
22746 if (_then = isThenable(msg)) {
22747 schedule(function(){
22748 var defWrapper = new MakeDefWrapper(self);
22749 try {
22750 _then.call(msg,
22751 function $resolve$(){ resolve.apply(defWrapper,arguments); },
22752 function $reject$(){ reject.apply(defWrapper,arguments); }
22753 );
22754 }
22755 catch (err) {
22756 reject.call(defWrapper,err);
22757 }
22758 });
22759 }
22760 else {
22761 self.msg = msg;
22762 self.state = 1;
22763 if (self.chain.length > 0) {
22764 schedule(notify,self);
22765 }
22766 }
22767 }
22768 catch (err) {
22769 reject.call(new MakeDefWrapper(self),err);
22770 }
22771 }
22772
22773 function reject(msg) {
22774 var self = this;
22775
22776 // already triggered?
22777 if (self.triggered) { return; }
22778
22779 self.triggered = true;
22780
22781 // unwrap
22782 if (self.def) {
22783 self = self.def;
22784 }
22785
22786 self.msg = msg;
22787 self.state = 2;
22788 if (self.chain.length > 0) {
22789 schedule(notify,self);
22790 }
22791 }
22792
22793 function iteratePromises(Constructor,arr,resolver,rejecter) {
22794 for (var idx=0; idx<arr.length; idx++) {
22795 (function IIFE(idx){
22796 Constructor.resolve(arr[idx])
22797 .then(
22798 function $resolver$(msg){
22799 resolver(idx,msg);
22800 },
22801 rejecter
22802 );
22803 })(idx);
22804 }
22805 }
22806
22807 function MakeDefWrapper(self) {
22808 this.def = self;
22809 this.triggered = false;
22810 }
22811
22812 function MakeDef(self) {
22813 this.promise = self;
22814 this.state = 0;
22815 this.triggered = false;
22816 this.chain = [];
22817 this.msg = void 0;
22818 }
22819
22820 function NpoPromise(executor) {
22821 if (typeof executor !== 'function') {
22822 throw TypeError('Not a function');
22823 }
22824
22825 if (this['__NPO__'] !== 0) {
22826 throw TypeError('Not a promise');
22827 }
22828
22829 // instance shadowing the inherited "brand"
22830 // to signal an already "initialized" promise
22831 this['__NPO__'] = 1;
22832
22833 var def = new MakeDef(this);
22834
22835 this['then'] = function then(success,failure) {
22836 var o = {
22837 success: typeof success === 'function' ? success : true,
22838 failure: typeof failure === 'function' ? failure : false
22839 };
22840 // Note: `then(..)` itself can be borrowed to be used against
22841 // a different promise constructor for making the chained promise,
22842 // by substituting a different `this` binding.
22843 o.promise = new this.constructor(function extractChain(resolve,reject) {
22844 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22845 throw TypeError('Not a function');
22846 }
22847
22848 o.resolve = resolve;
22849 o.reject = reject;
22850 });
22851 def.chain.push(o);
22852
22853 if (def.state !== 0) {
22854 schedule(notify,def);
22855 }
22856
22857 return o.promise;
22858 };
22859 this['catch'] = function $catch$(failure) {
22860 return this.then(void 0,failure);
22861 };
22862
22863 try {
22864 executor.call(
22865 void 0,
22866 function publicResolve(msg){
22867 resolve.call(def,msg);
22868 },
22869 function publicReject(msg) {
22870 reject.call(def,msg);
22871 }
22872 );
22873 }
22874 catch (err) {
22875 reject.call(def,err);
22876 }
22877 }
22878
22879 var PromisePrototype = builtInProp({},'constructor',NpoPromise,
22880 /*configurable=*/false
22881 );
22882
22883 // Note: Android 4 cannot use `Object.defineProperty(..)` here
22884 NpoPromise.prototype = PromisePrototype;
22885
22886 // built-in "brand" to signal an "uninitialized" promise
22887 builtInProp(PromisePrototype,'__NPO__',0,
22888 /*configurable=*/false
22889 );
22890
22891 builtInProp(NpoPromise,'resolve',function Promise$resolve(msg) {
22892 var Constructor = this;
22893
22894 // spec mandated checks
22895 // note: best "isPromise" check that's practical for now
22896 if (msg && typeof msg === 'object' && msg['__NPO__'] === 1) {
22897 return msg;
22898 }
22899
22900 return new Constructor(function executor(resolve,reject){
22901 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22902 throw TypeError('Not a function');
22903 }
22904
22905 resolve(msg);
22906 });
22907 });
22908
22909 builtInProp(NpoPromise,'reject',function Promise$reject(msg) {
22910 return new this(function executor(resolve,reject){
22911 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22912 throw TypeError('Not a function');
22913 }
22914
22915 reject(msg);
22916 });
22917 });
22918
22919 builtInProp(NpoPromise,'all',function Promise$all(arr) {
22920 var Constructor = this;
22921
22922 // spec mandated checks
22923 if (ToString.call(arr) !== '[object Array]') {
22924 return Constructor.reject(TypeError('Not an array'));
22925 }
22926 if (arr.length === 0) {
22927 return Constructor.resolve([]);
22928 }
22929
22930 return new Constructor(function executor(resolve,reject){
22931 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22932 throw TypeError('Not a function');
22933 }
22934
22935 var len = arr.length, msgs = Array(len), count = 0;
22936
22937 iteratePromises(Constructor,arr,function resolver(idx,msg) {
22938 msgs[idx] = msg;
22939 if (++count === len) {
22940 resolve(msgs);
22941 }
22942 },reject);
22943 });
22944 });
22945
22946 builtInProp(NpoPromise,'race',function Promise$race(arr) {
22947 var Constructor = this;
22948
22949 // spec mandated checks
22950 if (ToString.call(arr) !== '[object Array]') {
22951 return Constructor.reject(TypeError('Not an array'));
22952 }
22953
22954 return new Constructor(function executor(resolve,reject){
22955 if (typeof resolve !== 'function' || typeof reject !== 'function') {
22956 throw TypeError('Not a function');
22957 }
22958
22959 iteratePromises(Constructor,arr,function resolver(idx,msg){
22960 resolve(msg);
22961 },reject);
22962 });
22963 });
22964
22965 var PromisePolyfill;
22966 if (typeof Promise !== 'undefined' && Promise.toString().indexOf('[native code]') !== -1) {
22967 PromisePolyfill = Promise;
22968 } else {
22969 PromisePolyfill = NpoPromise;
22970 }
22971
22972 var Config = {
22973 DEBUG: false,
22974 LIB_VERSION: '2.71.1'
22975 };
22976
22977 /* eslint camelcase: "off", eqeqeq: "off" */
22978
22979 // Maximum allowed session recording length
22980 var MAX_RECORDING_MS = 24 * 60 * 60 * 1000; // 24 hours
22981 // Maximum allowed value for minimum session recording length
22982 var MAX_VALUE_FOR_MIN_RECORDING_MS = 8 * 1000; // 8 seconds
22983
22984 /*
22985 * Saved references to long variable names, so that closure compiler can
22986 * minimize file size.
22987 */
22988
22989 var ArrayProto = Array.prototype,
22990 FuncProto = Function.prototype,
22991 ObjProto = Object.prototype,
22992 slice = ArrayProto.slice,
22993 toString = ObjProto.toString,
22994 hasOwnProperty = ObjProto.hasOwnProperty,
22995 windowConsole = win.console,
22996 navigator = win.navigator,
22997 document$1 = win.document,
22998 windowOpera = win.opera,
22999 screen = win.screen,
23000 userAgent = navigator.userAgent;
23001
23002 var nativeBind = FuncProto.bind,
23003 nativeForEach = ArrayProto.forEach,
23004 nativeIndexOf = ArrayProto.indexOf,
23005 nativeMap = ArrayProto.map,
23006 nativeIsArray = Array.isArray,
23007 breaker = {};
23008
23009 var _ = {
23010 trim: function(str) {
23011 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
23012 return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
23013 }
23014 };
23015
23016 // Console override
23017 var console$1 = {
23018 /** @type {function(...*)} */
23019 log: function() {
23020 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
23021 try {
23022 windowConsole.log.apply(windowConsole, arguments);
23023 } catch (err) {
23024 _.each(arguments, function(arg) {
23025 windowConsole.log(arg);
23026 });
23027 }
23028 }
23029 },
23030 /** @type {function(...*)} */
23031 warn: function() {
23032 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
23033 var args = ['Mixpanel warning:'].concat(_.toArray(arguments));
23034 try {
23035 windowConsole.warn.apply(windowConsole, args);
23036 } catch (err) {
23037 _.each(args, function(arg) {
23038 windowConsole.warn(arg);
23039 });
23040 }
23041 }
23042 },
23043 /** @type {function(...*)} */
23044 error: function() {
23045 if (Config.DEBUG && !_.isUndefined(windowConsole) && windowConsole) {
23046 var args = ['Mixpanel error:'].concat(_.toArray(arguments));
23047 try {
23048 windowConsole.error.apply(windowConsole, args);
23049 } catch (err) {
23050 _.each(args, function(arg) {
23051 windowConsole.error(arg);
23052 });
23053 }
23054 }
23055 },
23056 /** @type {function(...*)} */
23057 critical: function() {
23058 if (!_.isUndefined(windowConsole) && windowConsole) {
23059 var args = ['Mixpanel error:'].concat(_.toArray(arguments));
23060 try {
23061 windowConsole.error.apply(windowConsole, args);
23062 } catch (err) {
23063 _.each(args, function(arg) {
23064 windowConsole.error(arg);
23065 });
23066 }
23067 }
23068 }
23069 };
23070
23071 var log_func_with_prefix = function(func, prefix) {
23072 return function() {
23073 arguments[0] = '[' + prefix + '] ' + arguments[0];
23074 return func.apply(console$1, arguments);
23075 };
23076 };
23077 var console_with_prefix = function(prefix) {
23078 return {
23079 log: log_func_with_prefix(console$1.log, prefix),
23080 error: log_func_with_prefix(console$1.error, prefix),
23081 critical: log_func_with_prefix(console$1.critical, prefix)
23082 };
23083 };
23084
23085
23086 var safewrap = function(f) {
23087 return function() {
23088 try {
23089 return f.apply(this, arguments);
23090 } catch (e) {
23091 console$1.critical('Implementation error. Please turn on debug and contact support@mixpanel.com.');
23092 if (Config.DEBUG){
23093 console$1.critical(e);
23094 }
23095 }
23096 };
23097 };
23098
23099 var safewrapClass = function(klass) {
23100 var proto = klass.prototype;
23101 for (var func in proto) {
23102 if (typeof(proto[func]) === 'function') {
23103 proto[func] = safewrap(proto[func]);
23104 }
23105 }
23106 };
23107
23108
23109 // UNDERSCORE
23110 // Embed part of the Underscore Library
23111 _.bind = function(func, context) {
23112 var args, bound;
23113 if (nativeBind && func.bind === nativeBind) {
23114 return nativeBind.apply(func, slice.call(arguments, 1));
23115 }
23116 if (!_.isFunction(func)) {
23117 throw new TypeError();
23118 }
23119 args = slice.call(arguments, 2);
23120 bound = function() {
23121 if (!(this instanceof bound)) {
23122 return func.apply(context, args.concat(slice.call(arguments)));
23123 }
23124 var ctor = {};
23125 ctor.prototype = func.prototype;
23126 var self = new ctor();
23127 ctor.prototype = null;
23128 var result = func.apply(self, args.concat(slice.call(arguments)));
23129 if (Object(result) === result) {
23130 return result;
23131 }
23132 return self;
23133 };
23134 return bound;
23135 };
23136
23137 /**
23138 * @param {*=} obj
23139 * @param {function(...*)=} iterator
23140 * @param {Object=} context
23141 */
23142 _.each = function(obj, iterator, context) {
23143 if (obj === null || obj === undefined) {
23144 return;
23145 }
23146 if (nativeForEach && obj.forEach === nativeForEach) {
23147 obj.forEach(iterator, context);
23148 } else if (obj.length === +obj.length) {
23149 for (var i = 0, l = obj.length; i < l; i++) {
23150 if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) {
23151 return;
23152 }
23153 }
23154 } else {
23155 for (var key in obj) {
23156 if (hasOwnProperty.call(obj, key)) {
23157 if (iterator.call(context, obj[key], key, obj) === breaker) {
23158 return;
23159 }
23160 }
23161 }
23162 }
23163 };
23164
23165 _.extend = function(obj) {
23166 _.each(slice.call(arguments, 1), function(source) {
23167 for (var prop in source) {
23168 if (source[prop] !== void 0) {
23169 obj[prop] = source[prop];
23170 }
23171 }
23172 });
23173 return obj;
23174 };
23175
23176 _.isArray = nativeIsArray || function(obj) {
23177 return toString.call(obj) === '[object Array]';
23178 };
23179
23180 // from a comment on http://dbj.org/dbj/?p=286
23181 // fails on only one very rare and deliberate custom object:
23182 // var bomb = { toString : undefined, valueOf: function(o) { return "function BOMBA!"; }};
23183 _.isFunction = function(f) {
23184 try {
23185 return /^\s*\bfunction\b/.test(f);
23186 } catch (x) {
23187 return false;
23188 }
23189 };
23190
23191 _.isArguments = function(obj) {
23192 return !!(obj && hasOwnProperty.call(obj, 'callee'));
23193 };
23194
23195 _.toArray = function(iterable) {
23196 if (!iterable) {
23197 return [];
23198 }
23199 if (iterable.toArray) {
23200 return iterable.toArray();
23201 }
23202 if (_.isArray(iterable)) {
23203 return slice.call(iterable);
23204 }
23205 if (_.isArguments(iterable)) {
23206 return slice.call(iterable);
23207 }
23208 return _.values(iterable);
23209 };
23210
23211 _.map = function(arr, callback, context) {
23212 if (nativeMap && arr.map === nativeMap) {
23213 return arr.map(callback, context);
23214 } else {
23215 var results = [];
23216 _.each(arr, function(item) {
23217 results.push(callback.call(context, item));
23218 });
23219 return results;
23220 }
23221 };
23222
23223 _.keys = function(obj) {
23224 var results = [];
23225 if (obj === null) {
23226 return results;
23227 }
23228 _.each(obj, function(value, key) {
23229 results[results.length] = key;
23230 });
23231 return results;
23232 };
23233
23234 _.values = function(obj) {
23235 var results = [];
23236 if (obj === null) {
23237 return results;
23238 }
23239 _.each(obj, function(value) {
23240 results[results.length] = value;
23241 });
23242 return results;
23243 };
23244
23245 _.include = function(obj, target) {
23246 var found = false;
23247 if (obj === null) {
23248 return found;
23249 }
23250 if (nativeIndexOf && obj.indexOf === nativeIndexOf) {
23251 return obj.indexOf(target) != -1;
23252 }
23253 _.each(obj, function(value) {
23254 if (found || (found = (value === target))) {
23255 return breaker;
23256 }
23257 });
23258 return found;
23259 };
23260
23261 _.includes = function(str, needle) {
23262 return str.indexOf(needle) !== -1;
23263 };
23264
23265 // Underscore Addons
23266 _.inherit = function(subclass, superclass) {
23267 subclass.prototype = new superclass();
23268 subclass.prototype.constructor = subclass;
23269 subclass.superclass = superclass.prototype;
23270 return subclass;
23271 };
23272
23273 _.isObject = function(obj) {
23274 return (obj === Object(obj) && !_.isArray(obj));
23275 };
23276
23277 _.isEmptyObject = function(obj) {
23278 if (_.isObject(obj)) {
23279 for (var key in obj) {
23280 if (hasOwnProperty.call(obj, key)) {
23281 return false;
23282 }
23283 }
23284 return true;
23285 }
23286 return false;
23287 };
23288
23289 _.isUndefined = function(obj) {
23290 return obj === void 0;
23291 };
23292
23293 _.isString = function(obj) {
23294 return toString.call(obj) == '[object String]';
23295 };
23296
23297 _.isDate = function(obj) {
23298 return toString.call(obj) == '[object Date]';
23299 };
23300
23301 _.isNumber = function(obj) {
23302 return toString.call(obj) == '[object Number]';
23303 };
23304
23305 _.isElement = function(obj) {
23306 return !!(obj && obj.nodeType === 1);
23307 };
23308
23309 _.encodeDates = function(obj) {
23310 _.each(obj, function(v, k) {
23311 if (_.isDate(v)) {
23312 obj[k] = _.formatDate(v);
23313 } else if (_.isObject(v)) {
23314 obj[k] = _.encodeDates(v); // recurse
23315 }
23316 });
23317 return obj;
23318 };
23319
23320 _.timestamp = function() {
23321 Date.now = Date.now || function() {
23322 return +new Date;
23323 };
23324 return Date.now();
23325 };
23326
23327 _.formatDate = function(d) {
23328 // YYYY-MM-DDTHH:MM:SS in UTC
23329 function pad(n) {
23330 return n < 10 ? '0' + n : n;
23331 }
23332 return d.getUTCFullYear() + '-' +
23333 pad(d.getUTCMonth() + 1) + '-' +
23334 pad(d.getUTCDate()) + 'T' +
23335 pad(d.getUTCHours()) + ':' +
23336 pad(d.getUTCMinutes()) + ':' +
23337 pad(d.getUTCSeconds());
23338 };
23339
23340 _.strip_empty_properties = function(p) {
23341 var ret = {};
23342 _.each(p, function(v, k) {
23343 if (_.isString(v) && v.length > 0) {
23344 ret[k] = v;
23345 }
23346 });
23347 return ret;
23348 };
23349
23350 /*
23351 * this function returns a copy of object after truncating it. If
23352 * passed an Array or Object it will iterate through obj and
23353 * truncate all the values recursively.
23354 */
23355 _.truncate = function(obj, length) {
23356 var ret;
23357
23358 if (typeof(obj) === 'string') {
23359 ret = obj.slice(0, length);
23360 } else if (_.isArray(obj)) {
23361 ret = [];
23362 _.each(obj, function(val) {
23363 ret.push(_.truncate(val, length));
23364 });
23365 } else if (_.isObject(obj)) {
23366 ret = {};
23367 _.each(obj, function(val, key) {
23368 ret[key] = _.truncate(val, length);
23369 });
23370 } else {
23371 ret = obj;
23372 }
23373
23374 return ret;
23375 };
23376
23377 _.JSONEncode = (function() {
23378 return function(mixed_val) {
23379 var value = mixed_val;
23380 var quote = function(string) {
23381 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
23382 var meta = { // table of character substitutions
23383 '\b': '\\b',
23384 '\t': '\\t',
23385 '\n': '\\n',
23386 '\f': '\\f',
23387 '\r': '\\r',
23388 '"': '\\"',
23389 '\\': '\\\\'
23390 };
23391
23392 escapable.lastIndex = 0;
23393 return escapable.test(string) ?
23394 '"' + string.replace(escapable, function(a) {
23395 var c = meta[a];
23396 return typeof c === 'string' ? c :
23397 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
23398 }) + '"' :
23399 '"' + string + '"';
23400 };
23401
23402 var str = function(key, holder) {
23403 var gap = '';
23404 var indent = ' ';
23405 var i = 0; // The loop counter.
23406 var k = ''; // The member key.
23407 var v = ''; // The member value.
23408 var length = 0;
23409 var mind = gap;
23410 var partial = [];
23411 var value = holder[key];
23412
23413 // If the value has a toJSON method, call it to obtain a replacement value.
23414 if (value && typeof value === 'object' &&
23415 typeof value.toJSON === 'function') {
23416 value = value.toJSON(key);
23417 }
23418
23419 // What happens next depends on the value's type.
23420 switch (typeof value) {
23421 case 'string':
23422 return quote(value);
23423
23424 case 'number':
23425 // JSON numbers must be finite. Encode non-finite numbers as null.
23426 return isFinite(value) ? String(value) : 'null';
23427
23428 case 'boolean':
23429 case 'null':
23430 // If the value is a boolean or null, convert it to a string. Note:
23431 // typeof null does not produce 'null'. The case is included here in
23432 // the remote chance that this gets fixed someday.
23433
23434 return String(value);
23435
23436 case 'object':
23437 // If the type is 'object', we might be dealing with an object or an array or
23438 // null.
23439 // Due to a specification blunder in ECMAScript, typeof null is 'object',
23440 // so watch out for that case.
23441 if (!value) {
23442 return 'null';
23443 }
23444
23445 // Make an array to hold the partial results of stringifying this object value.
23446 gap += indent;
23447 partial = [];
23448
23449 // Is the value an array?
23450 if (toString.apply(value) === '[object Array]') {
23451 // The value is an array. Stringify every element. Use null as a placeholder
23452 // for non-JSON values.
23453
23454 length = value.length;
23455 for (i = 0; i < length; i += 1) {
23456 partial[i] = str(i, value) || 'null';
23457 }
23458
23459 // Join all of the elements together, separated with commas, and wrap them in
23460 // brackets.
23461 v = partial.length === 0 ? '[]' :
23462 gap ? '[\n' + gap +
23463 partial.join(',\n' + gap) + '\n' +
23464 mind + ']' :
23465 '[' + partial.join(',') + ']';
23466 gap = mind;
23467 return v;
23468 }
23469
23470 // Iterate through all of the keys in the object.
23471 for (k in value) {
23472 if (hasOwnProperty.call(value, k)) {
23473 v = str(k, value);
23474 if (v) {
23475 partial.push(quote(k) + (gap ? ': ' : ':') + v);
23476 }
23477 }
23478 }
23479
23480 // Join all of the member texts together, separated with commas,
23481 // and wrap them in braces.
23482 v = partial.length === 0 ? '{}' :
23483 gap ? '{' + partial.join(',') + '' +
23484 mind + '}' : '{' + partial.join(',') + '}';
23485 gap = mind;
23486 return v;
23487 }
23488 };
23489
23490 // Make a fake root object containing our value under the key of ''.
23491 // Return the result of stringifying the value.
23492 return str('', {
23493 '': value
23494 });
23495 };
23496 })();
23497
23498 /**
23499 * From https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
23500 * Slightly modified to throw a real Error rather than a POJO
23501 */
23502 _.JSONDecode = (function() {
23503 var at, // The index of the current character
23504 ch, // The current character
23505 escapee = {
23506 '"': '"',
23507 '\\': '\\',
23508 '/': '/',
23509 'b': '\b',
23510 'f': '\f',
23511 'n': '\n',
23512 'r': '\r',
23513 't': '\t'
23514 },
23515 text,
23516 error = function(m) {
23517 var e = new SyntaxError(m);
23518 e.at = at;
23519 e.text = text;
23520 throw e;
23521 },
23522 next = function(c) {
23523 // If a c parameter is provided, verify that it matches the current character.
23524 if (c && c !== ch) {
23525 error('Expected \'' + c + '\' instead of \'' + ch + '\'');
23526 }
23527 // Get the next character. When there are no more characters,
23528 // return the empty string.
23529 ch = text.charAt(at);
23530 at += 1;
23531 return ch;
23532 },
23533 number = function() {
23534 // Parse a number value.
23535 var number,
23536 string = '';
23537
23538 if (ch === '-') {
23539 string = '-';
23540 next('-');
23541 }
23542 while (ch >= '0' && ch <= '9') {
23543 string += ch;
23544 next();
23545 }
23546 if (ch === '.') {
23547 string += '.';
23548 while (next() && ch >= '0' && ch <= '9') {
23549 string += ch;
23550 }
23551 }
23552 if (ch === 'e' || ch === 'E') {
23553 string += ch;
23554 next();
23555 if (ch === '-' || ch === '+') {
23556 string += ch;
23557 next();
23558 }
23559 while (ch >= '0' && ch <= '9') {
23560 string += ch;
23561 next();
23562 }
23563 }
23564 number = +string;
23565 if (!isFinite(number)) {
23566 error('Bad number');
23567 } else {
23568 return number;
23569 }
23570 },
23571
23572 string = function() {
23573 // Parse a string value.
23574 var hex,
23575 i,
23576 string = '',
23577 uffff;
23578 // When parsing for string values, we must look for " and \ characters.
23579 if (ch === '"') {
23580 while (next()) {
23581 if (ch === '"') {
23582 next();
23583 return string;
23584 }
23585 if (ch === '\\') {
23586 next();
23587 if (ch === 'u') {
23588 uffff = 0;
23589 for (i = 0; i < 4; i += 1) {
23590 hex = parseInt(next(), 16);
23591 if (!isFinite(hex)) {
23592 break;
23593 }
23594 uffff = uffff * 16 + hex;
23595 }
23596 string += String.fromCharCode(uffff);
23597 } else if (typeof escapee[ch] === 'string') {
23598 string += escapee[ch];
23599 } else {
23600 break;
23601 }
23602 } else {
23603 string += ch;
23604 }
23605 }
23606 }
23607 error('Bad string');
23608 },
23609 white = function() {
23610 // Skip whitespace.
23611 while (ch && ch <= ' ') {
23612 next();
23613 }
23614 },
23615 word = function() {
23616 // true, false, or null.
23617 switch (ch) {
23618 case 't':
23619 next('t');
23620 next('r');
23621 next('u');
23622 next('e');
23623 return true;
23624 case 'f':
23625 next('f');
23626 next('a');
23627 next('l');
23628 next('s');
23629 next('e');
23630 return false;
23631 case 'n':
23632 next('n');
23633 next('u');
23634 next('l');
23635 next('l');
23636 return null;
23637 }
23638 error('Unexpected "' + ch + '"');
23639 },
23640 value, // Placeholder for the value function.
23641 array = function() {
23642 // Parse an array value.
23643 var array = [];
23644
23645 if (ch === '[') {
23646 next('[');
23647 white();
23648 if (ch === ']') {
23649 next(']');
23650 return array; // empty array
23651 }
23652 while (ch) {
23653 array.push(value());
23654 white();
23655 if (ch === ']') {
23656 next(']');
23657 return array;
23658 }
23659 next(',');
23660 white();
23661 }
23662 }
23663 error('Bad array');
23664 },
23665 object = function() {
23666 // Parse an object value.
23667 var key,
23668 object = {};
23669
23670 if (ch === '{') {
23671 next('{');
23672 white();
23673 if (ch === '}') {
23674 next('}');
23675 return object; // empty object
23676 }
23677 while (ch) {
23678 key = string();
23679 white();
23680 next(':');
23681 if (Object.hasOwnProperty.call(object, key)) {
23682 error('Duplicate key "' + key + '"');
23683 }
23684 object[key] = value();
23685 white();
23686 if (ch === '}') {
23687 next('}');
23688 return object;
23689 }
23690 next(',');
23691 white();
23692 }
23693 }
23694 error('Bad object');
23695 };
23696
23697 value = function() {
23698 // Parse a JSON value. It could be an object, an array, a string,
23699 // a number, or a word.
23700 white();
23701 switch (ch) {
23702 case '{':
23703 return object();
23704 case '[':
23705 return array();
23706 case '"':
23707 return string();
23708 case '-':
23709 return number();
23710 default:
23711 return ch >= '0' && ch <= '9' ? number() : word();
23712 }
23713 };
23714
23715 // Return the json_parse function. It will have access to all of the
23716 // above functions and variables.
23717 return function(source) {
23718 var result;
23719
23720 text = source;
23721 at = 0;
23722 ch = ' ';
23723 result = value();
23724 white();
23725 if (ch) {
23726 error('Syntax error');
23727 }
23728
23729 return result;
23730 };
23731 })();
23732
23733 _.base64Encode = function(data) {
23734 var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
23735 var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
23736 ac = 0,
23737 enc = '',
23738 tmp_arr = [];
23739
23740 if (!data) {
23741 return data;
23742 }
23743
23744 data = _.utf8Encode(data);
23745
23746 do { // pack three octets into four hexets
23747 o1 = data.charCodeAt(i++);
23748 o2 = data.charCodeAt(i++);
23749 o3 = data.charCodeAt(i++);
23750
23751 bits = o1 << 16 | o2 << 8 | o3;
23752
23753 h1 = bits >> 18 & 0x3f;
23754 h2 = bits >> 12 & 0x3f;
23755 h3 = bits >> 6 & 0x3f;
23756 h4 = bits & 0x3f;
23757
23758 // use hexets to index into b64, and append result to encoded string
23759 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
23760 } while (i < data.length);
23761
23762 enc = tmp_arr.join('');
23763
23764 switch (data.length % 3) {
23765 case 1:
23766 enc = enc.slice(0, -2) + '==';
23767 break;
23768 case 2:
23769 enc = enc.slice(0, -1) + '=';
23770 break;
23771 }
23772
23773 return enc;
23774 };
23775
23776 _.utf8Encode = function(string) {
23777 string = (string + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
23778
23779 var utftext = '',
23780 start,
23781 end;
23782 var stringl = 0,
23783 n;
23784
23785 start = end = 0;
23786 stringl = string.length;
23787
23788 for (n = 0; n < stringl; n++) {
23789 var c1 = string.charCodeAt(n);
23790 var enc = null;
23791
23792 if (c1 < 128) {
23793 end++;
23794 } else if ((c1 > 127) && (c1 < 2048)) {
23795 enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
23796 } else {
23797 enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
23798 }
23799 if (enc !== null) {
23800 if (end > start) {
23801 utftext += string.substring(start, end);
23802 }
23803 utftext += enc;
23804 start = end = n + 1;
23805 }
23806 }
23807
23808 if (end > start) {
23809 utftext += string.substring(start, string.length);
23810 }
23811
23812 return utftext;
23813 };
23814
23815 _.UUID = function() {
23816 try {
23817 // use native Crypto API when available
23818 return win['crypto']['randomUUID']();
23819 } catch (err) {
23820 // fall back to generating our own UUID
23821 // based on https://gist.github.com/scwood/3bff42cc005cc20ab7ec98f0d8e1d59d
23822 var uuid = new Array(36);
23823 for (var i = 0; i < 36; i++) {
23824 uuid[i] = Math.floor(Math.random() * 16);
23825 }
23826 uuid[14] = 4; // set bits 12-15 of time-high-and-version to 0100
23827 uuid[19] = uuid[19] &= -5; // set bit 6 of clock-seq-and-reserved to zero
23828 uuid[19] = uuid[19] |= (1 << 3); // set bit 7 of clock-seq-and-reserved to one
23829 uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
23830
23831 return _.map(uuid, function(x) {
23832 return x.toString(16);
23833 }).join('');
23834 }
23835 };
23836
23837 // _.isBlockedUA()
23838 // This is to block various web spiders from executing our JS and
23839 // sending false tracking data
23840 var BLOCKED_UA_STRS = [
23841 'ahrefsbot',
23842 'ahrefssiteaudit',
23843 'amazonbot',
23844 'baiduspider',
23845 'bingbot',
23846 'bingpreview',
23847 'chrome-lighthouse',
23848 'facebookexternal',
23849 'petalbot',
23850 'pinterest',
23851 'screaming frog',
23852 'yahoo! slurp',
23853 'yandex',
23854
23855 // a whole bunch of goog-specific crawlers
23856 // https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
23857 'adsbot-google',
23858 'apis-google',
23859 'duplexweb-google',
23860 'feedfetcher-google',
23861 'google favicon',
23862 'google web preview',
23863 'google-read-aloud',
23864 'googlebot',
23865 'googleweblight',
23866 'mediapartners-google',
23867 'storebot-google'
23868 ];
23869 _.isBlockedUA = function(ua) {
23870 var i;
23871 ua = ua.toLowerCase();
23872 for (i = 0; i < BLOCKED_UA_STRS.length; i++) {
23873 if (ua.indexOf(BLOCKED_UA_STRS[i]) !== -1) {
23874 return true;
23875 }
23876 }
23877 return false;
23878 };
23879
23880 /**
23881 * @param {Object=} formdata
23882 * @param {string=} arg_separator
23883 */
23884 _.HTTPBuildQuery = function(formdata, arg_separator) {
23885 var use_val, use_key, tmp_arr = [];
23886
23887 if (_.isUndefined(arg_separator)) {
23888 arg_separator = '&';
23889 }
23890
23891 _.each(formdata, function(val, key) {
23892 use_val = encodeURIComponent(val.toString());
23893 use_key = encodeURIComponent(key);
23894 tmp_arr[tmp_arr.length] = use_key + '=' + use_val;
23895 });
23896
23897 return tmp_arr.join(arg_separator);
23898 };
23899
23900 _.getQueryParam = function(url, param) {
23901 // Expects a raw URL
23902
23903 param = param.replace(/[[]/g, '\\[').replace(/[\]]/g, '\\]');
23904 var regexS = '[\\?&]' + param + '=([^&#]*)',
23905 regex = new RegExp(regexS),
23906 results = regex.exec(url);
23907 if (results === null || (results && typeof(results[1]) !== 'string' && results[1].length)) {
23908 return '';
23909 } else {
23910 var result = results[1];
23911 try {
23912 result = decodeURIComponent(result);
23913 } catch(err) {
23914 console$1.error('Skipping decoding for malformed query param: ' + result);
23915 }
23916 return result.replace(/\+/g, ' ');
23917 }
23918 };
23919
23920
23921 // _.cookie
23922 // Methods partially borrowed from quirksmode.org/js/cookies.html
23923 _.cookie = {
23924 get: function(name) {
23925 var nameEQ = name + '=';
23926 var ca = document$1.cookie.split(';');
23927 for (var i = 0; i < ca.length; i++) {
23928 var c = ca[i];
23929 while (c.charAt(0) == ' ') {
23930 c = c.substring(1, c.length);
23931 }
23932 if (c.indexOf(nameEQ) === 0) {
23933 return decodeURIComponent(c.substring(nameEQ.length, c.length));
23934 }
23935 }
23936 return null;
23937 },
23938
23939 parse: function(name) {
23940 var cookie;
23941 try {
23942 cookie = _.JSONDecode(_.cookie.get(name)) || {};
23943 } catch (err) {
23944 // noop
23945 }
23946 return cookie;
23947 },
23948
23949 set_seconds: function(name, value, seconds, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
23950 var cdomain = '',
23951 expires = '',
23952 secure = '';
23953
23954 if (domain_override) {
23955 cdomain = '; domain=' + domain_override;
23956 } else if (is_cross_subdomain) {
23957 var domain = extract_domain(document$1.location.hostname);
23958 cdomain = domain ? '; domain=.' + domain : '';
23959 }
23960
23961 if (seconds) {
23962 var date = new Date();
23963 date.setTime(date.getTime() + (seconds * 1000));
23964 expires = '; expires=' + date.toGMTString();
23965 }
23966
23967 if (is_cross_site) {
23968 is_secure = true;
23969 secure = '; SameSite=None';
23970 }
23971 if (is_secure) {
23972 secure += '; secure';
23973 }
23974
23975 document$1.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
23976 },
23977
23978 set: function(name, value, days, is_cross_subdomain, is_secure, is_cross_site, domain_override) {
23979 var cdomain = '', expires = '', secure = '';
23980
23981 if (domain_override) {
23982 cdomain = '; domain=' + domain_override;
23983 } else if (is_cross_subdomain) {
23984 var domain = extract_domain(document$1.location.hostname);
23985 cdomain = domain ? '; domain=.' + domain : '';
23986 }
23987
23988 if (days) {
23989 var date = new Date();
23990 date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
23991 expires = '; expires=' + date.toGMTString();
23992 }
23993
23994 if (is_cross_site) {
23995 is_secure = true;
23996 secure = '; SameSite=None';
23997 }
23998 if (is_secure) {
23999 secure += '; secure';
24000 }
24001
24002 var new_cookie_val = name + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
24003 document$1.cookie = new_cookie_val;
24004 return new_cookie_val;
24005 },
24006
24007 remove: function(name, is_cross_subdomain, domain_override) {
24008 _.cookie.set(name, '', -1, is_cross_subdomain, false, false, domain_override);
24009 }
24010 };
24011
24012 var _testStorageSupported = function (storage) {
24013 var supported = true;
24014 try {
24015 var key = '__mplss_' + cheap_guid(8),
24016 val = 'xyz';
24017 storage.setItem(key, val);
24018 if (storage.getItem(key) !== val) {
24019 supported = false;
24020 }
24021 storage.removeItem(key);
24022 } catch (err) {
24023 supported = false;
24024 }
24025 return supported;
24026 };
24027
24028 var _localStorageSupported = null;
24029 var localStorageSupported = function(storage, forceCheck) {
24030 if (_localStorageSupported !== null && !forceCheck) {
24031 return _localStorageSupported;
24032 }
24033 return _localStorageSupported = _testStorageSupported(storage || win.localStorage);
24034 };
24035
24036 var _sessionStorageSupported = null;
24037 var sessionStorageSupported = function(storage, forceCheck) {
24038 if (_sessionStorageSupported !== null && !forceCheck) {
24039 return _sessionStorageSupported;
24040 }
24041 return _sessionStorageSupported = _testStorageSupported(storage || win.sessionStorage);
24042 };
24043
24044 function _storageWrapper(storage, name, is_supported_fn) {
24045 var log_error = function(msg) {
24046 console$1.error(name + ' error: ' + msg);
24047 };
24048
24049 return {
24050 is_supported: function(forceCheck) {
24051 var supported = is_supported_fn(storage, forceCheck);
24052 if (!supported) {
24053 console$1.error(name + ' unsupported');
24054 }
24055 return supported;
24056 },
24057 error: log_error,
24058 get: function(key) {
24059 try {
24060 return storage.getItem(key);
24061 } catch (err) {
24062 log_error(err);
24063 }
24064 return null;
24065 },
24066 parse: function(key) {
24067 try {
24068 return _.JSONDecode(storage.getItem(key)) || {};
24069 } catch (err) {
24070 // noop
24071 }
24072 return null;
24073 },
24074 set: function(key, value) {
24075 try {
24076 storage.setItem(key, value);
24077 } catch (err) {
24078 log_error(err);
24079 }
24080 },
24081 remove: function(key) {
24082 try {
24083 storage.removeItem(key);
24084 } catch (err) {
24085 log_error(err);
24086 }
24087 }
24088 };
24089 }
24090
24091 _.localStorage = _storageWrapper(win.localStorage, 'localStorage', localStorageSupported);
24092 _.sessionStorage = _storageWrapper(win.sessionStorage, 'sessionStorage', sessionStorageSupported);
24093
24094 _.register_event = (function() {
24095 // written by Dean Edwards, 2005
24096 // with input from Tino Zijdel - crisp@xs4all.nl
24097 // with input from Carl Sverre - mail@carlsverre.com
24098 // with input from Mixpanel
24099 // http://dean.edwards.name/weblog/2005/10/add-event/
24100 // https://gist.github.com/1930440
24101
24102 /**
24103 * @param {Object} element
24104 * @param {string} type
24105 * @param {function(...*)} handler
24106 * @param {boolean=} oldSchool
24107 * @param {boolean=} useCapture
24108 */
24109 var register_event = function(element, type, handler, oldSchool, useCapture) {
24110 if (!element) {
24111 console$1.error('No valid element provided to register_event');
24112 return;
24113 }
24114
24115 if (element.addEventListener && !oldSchool) {
24116 element.addEventListener(type, handler, !!useCapture);
24117 } else {
24118 var ontype = 'on' + type;
24119 var old_handler = element[ontype]; // can be undefined
24120 element[ontype] = makeHandler(element, handler, old_handler);
24121 }
24122 };
24123
24124 function makeHandler(element, new_handler, old_handlers) {
24125 var handler = function(event) {
24126 event = event || fixEvent(win.event);
24127
24128 // this basically happens in firefox whenever another script
24129 // overwrites the onload callback and doesn't pass the event
24130 // object to previously defined callbacks. All the browsers
24131 // that don't define window.event implement addEventListener
24132 // so the dom_loaded handler will still be fired as usual.
24133 if (!event) {
24134 return undefined;
24135 }
24136
24137 var ret = true;
24138 var old_result, new_result;
24139
24140 if (_.isFunction(old_handlers)) {
24141 old_result = old_handlers(event);
24142 }
24143 new_result = new_handler.call(element, event);
24144
24145 if ((false === old_result) || (false === new_result)) {
24146 ret = false;
24147 }
24148
24149 return ret;
24150 };
24151
24152 return handler;
24153 }
24154
24155 function fixEvent(event) {
24156 if (event) {
24157 event.preventDefault = fixEvent.preventDefault;
24158 event.stopPropagation = fixEvent.stopPropagation;
24159 }
24160 return event;
24161 }
24162 fixEvent.preventDefault = function() {
24163 this.returnValue = false;
24164 };
24165 fixEvent.stopPropagation = function() {
24166 this.cancelBubble = true;
24167 };
24168
24169 return register_event;
24170 })();
24171
24172
24173 var TOKEN_MATCH_REGEX = new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$');
24174
24175 _.dom_query = (function() {
24176 /* document.getElementsBySelector(selector)
24177 - returns an array of element objects from the current document
24178 matching the CSS selector. Selectors can contain element names,
24179 class names and ids and can be nested. For example:
24180
24181 elements = document.getElementsBySelector('div#main p a.external')
24182
24183 Will return an array of all 'a' elements with 'external' in their
24184 class attribute that are contained inside 'p' elements that are
24185 contained inside the 'div' element which has id="main"
24186
24187 New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
24188 See http://www.w3.org/TR/css3-selectors/#attribute-selectors
24189
24190 Version 0.4 - Simon Willison, March 25th 2003
24191 -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
24192 -- Opera 7 fails
24193
24194 Version 0.5 - Carl Sverre, Jan 7th 2013
24195 -- Now uses jQuery-esque `hasClass` for testing class name
24196 equality. This fixes a bug related to '-' characters being
24197 considered not part of a 'word' in regex.
24198 */
24199
24200 function getAllChildren(e) {
24201 // Returns all children of element. Workaround required for IE5/Windows. Ugh.
24202 return e.all ? e.all : e.getElementsByTagName('*');
24203 }
24204
24205 var bad_whitespace = /[\t\r\n]/g;
24206
24207 function hasClass(elem, selector) {
24208 var className = ' ' + selector + ' ';
24209 return ((' ' + elem.className + ' ').replace(bad_whitespace, ' ').indexOf(className) >= 0);
24210 }
24211
24212 function getElementsBySelector(selector) {
24213 // Attempt to fail gracefully in lesser browsers
24214 if (!document$1.getElementsByTagName) {
24215 return [];
24216 }
24217 // Split selector in to tokens
24218 var tokens = selector.split(' ');
24219 var token, bits, tagName, found, foundCount, i, j, k, elements, currentContextIndex;
24220 var currentContext = [document$1];
24221 for (i = 0; i < tokens.length; i++) {
24222 token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, '');
24223 if (token.indexOf('#') > -1) {
24224 // Token is an ID selector
24225 bits = token.split('#');
24226 tagName = bits[0];
24227 var id = bits[1];
24228 var element = document$1.getElementById(id);
24229 if (!element || (tagName && element.nodeName.toLowerCase() != tagName)) {
24230 // element not found or tag with that ID not found, return false
24231 return [];
24232 }
24233 // Set currentContext to contain just this element
24234 currentContext = [element];
24235 continue; // Skip to next token
24236 }
24237 if (token.indexOf('.') > -1) {
24238 // Token contains a class selector
24239 bits = token.split('.');
24240 tagName = bits[0];
24241 var className = bits[1];
24242 if (!tagName) {
24243 tagName = '*';
24244 }
24245 // Get elements matching tag, filter them for class selector
24246 found = [];
24247 foundCount = 0;
24248 for (j = 0; j < currentContext.length; j++) {
24249 if (tagName == '*') {
24250 elements = getAllChildren(currentContext[j]);
24251 } else {
24252 elements = currentContext[j].getElementsByTagName(tagName);
24253 }
24254 for (k = 0; k < elements.length; k++) {
24255 found[foundCount++] = elements[k];
24256 }
24257 }
24258 currentContext = [];
24259 currentContextIndex = 0;
24260 for (j = 0; j < found.length; j++) {
24261 if (found[j].className &&
24262 _.isString(found[j].className) && // some SVG elements have classNames which are not strings
24263 hasClass(found[j], className)
24264 ) {
24265 currentContext[currentContextIndex++] = found[j];
24266 }
24267 }
24268 continue; // Skip to next token
24269 }
24270 // Code to deal with attribute selectors
24271 var token_match = token.match(TOKEN_MATCH_REGEX);
24272 if (token_match) {
24273 tagName = token_match[1];
24274 var attrName = token_match[2];
24275 var attrOperator = token_match[3];
24276 var attrValue = token_match[4];
24277 if (!tagName) {
24278 tagName = '*';
24279 }
24280 // Grab all of the tagName elements within current context
24281 found = [];
24282 foundCount = 0;
24283 for (j = 0; j < currentContext.length; j++) {
24284 if (tagName == '*') {
24285 elements = getAllChildren(currentContext[j]);
24286 } else {
24287 elements = currentContext[j].getElementsByTagName(tagName);
24288 }
24289 for (k = 0; k < elements.length; k++) {
24290 found[foundCount++] = elements[k];
24291 }
24292 }
24293 currentContext = [];
24294 currentContextIndex = 0;
24295 var checkFunction; // This function will be used to filter the elements
24296 switch (attrOperator) {
24297 case '=': // Equality
24298 checkFunction = function(e) {
24299 return (e.getAttribute(attrName) == attrValue);
24300 };
24301 break;
24302 case '~': // Match one of space seperated words
24303 checkFunction = function(e) {
24304 return (e.getAttribute(attrName).match(new RegExp('\\b' + attrValue + '\\b')));
24305 };
24306 break;
24307 case '|': // Match start with value followed by optional hyphen
24308 checkFunction = function(e) {
24309 return (e.getAttribute(attrName).match(new RegExp('^' + attrValue + '-?')));
24310 };
24311 break;
24312 case '^': // Match starts with value
24313 checkFunction = function(e) {
24314 return (e.getAttribute(attrName).indexOf(attrValue) === 0);
24315 };
24316 break;
24317 case '$': // Match ends with value - fails with "Warning" in Opera 7
24318 checkFunction = function(e) {
24319 return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length);
24320 };
24321 break;
24322 case '*': // Match ends with value
24323 checkFunction = function(e) {
24324 return (e.getAttribute(attrName).indexOf(attrValue) > -1);
24325 };
24326 break;
24327 default:
24328 // Just test for existence of attribute
24329 checkFunction = function(e) {
24330 return e.getAttribute(attrName);
24331 };
24332 }
24333 currentContext = [];
24334 currentContextIndex = 0;
24335 for (j = 0; j < found.length; j++) {
24336 if (checkFunction(found[j])) {
24337 currentContext[currentContextIndex++] = found[j];
24338 }
24339 }
24340 // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
24341 continue; // Skip to next token
24342 }
24343 // If we get here, token is JUST an element (not a class or ID selector)
24344 tagName = token;
24345 found = [];
24346 foundCount = 0;
24347 for (j = 0; j < currentContext.length; j++) {
24348 elements = currentContext[j].getElementsByTagName(tagName);
24349 for (k = 0; k < elements.length; k++) {
24350 found[foundCount++] = elements[k];
24351 }
24352 }
24353 currentContext = found;
24354 }
24355 return currentContext;
24356 }
24357
24358 return function(query) {
24359 if (_.isElement(query)) {
24360 return [query];
24361 } else if (_.isObject(query) && !_.isUndefined(query.length)) {
24362 return query;
24363 } else {
24364 return getElementsBySelector.call(this, query);
24365 }
24366 };
24367 })();
24368
24369 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'];
24370 var CLICK_IDS = ['dclid', 'fbclid', 'gclid', 'ko_click_id', 'li_fat_id', 'msclkid', 'sccid', 'ttclid', 'twclid', 'wbraid'];
24371
24372 _.info = {
24373 campaignParams: function(default_value) {
24374 var kw = '',
24375 params = {};
24376 _.each(CAMPAIGN_KEYWORDS, function(kwkey) {
24377 kw = _.getQueryParam(document$1.URL, kwkey);
24378 if (kw.length) {
24379 params[kwkey] = kw;
24380 } else if (default_value !== undefined) {
24381 params[kwkey] = default_value;
24382 }
24383 });
24384
24385 return params;
24386 },
24387
24388 clickParams: function() {
24389 var id = '',
24390 params = {};
24391 _.each(CLICK_IDS, function(idkey) {
24392 id = _.getQueryParam(document$1.URL, idkey);
24393 if (id.length) {
24394 params[idkey] = id;
24395 }
24396 });
24397
24398 return params;
24399 },
24400
24401 marketingParams: function() {
24402 return _.extend(_.info.campaignParams(), _.info.clickParams());
24403 },
24404
24405 searchEngine: function(referrer) {
24406 if (referrer.search('https?://(.*)google.([^/?]*)') === 0) {
24407 return 'google';
24408 } else if (referrer.search('https?://(.*)bing.com') === 0) {
24409 return 'bing';
24410 } else if (referrer.search('https?://(.*)yahoo.com') === 0) {
24411 return 'yahoo';
24412 } else if (referrer.search('https?://(.*)duckduckgo.com') === 0) {
24413 return 'duckduckgo';
24414 } else {
24415 return null;
24416 }
24417 },
24418
24419 searchInfo: function(referrer) {
24420 var search = _.info.searchEngine(referrer),
24421 param = (search != 'yahoo') ? 'q' : 'p',
24422 ret = {};
24423
24424 if (search !== null) {
24425 ret['$search_engine'] = search;
24426
24427 var keyword = _.getQueryParam(referrer, param);
24428 if (keyword.length) {
24429 ret['mp_keyword'] = keyword;
24430 }
24431 }
24432
24433 return ret;
24434 },
24435
24436 /**
24437 * This function detects which browser is running this script.
24438 * The order of the checks are important since many user agents
24439 * include key words used in later checks.
24440 */
24441 browser: function(user_agent, vendor, opera) {
24442 vendor = vendor || ''; // vendor is undefined for at least IE9
24443 if (opera || _.includes(user_agent, ' OPR/')) {
24444 if (_.includes(user_agent, 'Mini')) {
24445 return 'Opera Mini';
24446 }
24447 return 'Opera';
24448 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
24449 return 'BlackBerry';
24450 } else if (_.includes(user_agent, 'IEMobile') || _.includes(user_agent, 'WPDesktop')) {
24451 return 'Internet Explorer Mobile';
24452 } else if (_.includes(user_agent, 'SamsungBrowser/')) {
24453 // https://developer.samsung.com/internet/user-agent-string-format
24454 return 'Samsung Internet';
24455 } else if (_.includes(user_agent, 'Edge') || _.includes(user_agent, 'Edg/')) {
24456 return 'Microsoft Edge';
24457 } else if (_.includes(user_agent, 'FBIOS')) {
24458 return 'Facebook Mobile';
24459 } else if (_.includes(user_agent, 'Whale/')) {
24460 // https://user-agents.net/browsers/whale-browser
24461 return 'Whale Browser';
24462 } else if (_.includes(user_agent, 'Chrome')) {
24463 return 'Chrome';
24464 } else if (_.includes(user_agent, 'CriOS')) {
24465 return 'Chrome iOS';
24466 } else if (_.includes(user_agent, 'UCWEB') || _.includes(user_agent, 'UCBrowser')) {
24467 return 'UC Browser';
24468 } else if (_.includes(user_agent, 'FxiOS')) {
24469 return 'Firefox iOS';
24470 } else if (_.includes(vendor, 'Apple')) {
24471 if (_.includes(user_agent, 'Mobile')) {
24472 return 'Mobile Safari';
24473 }
24474 return 'Safari';
24475 } else if (_.includes(user_agent, 'Android')) {
24476 return 'Android Mobile';
24477 } else if (_.includes(user_agent, 'Konqueror')) {
24478 return 'Konqueror';
24479 } else if (_.includes(user_agent, 'Firefox')) {
24480 return 'Firefox';
24481 } else if (_.includes(user_agent, 'MSIE') || _.includes(user_agent, 'Trident/')) {
24482 return 'Internet Explorer';
24483 } else if (_.includes(user_agent, 'Gecko')) {
24484 return 'Mozilla';
24485 } else {
24486 return '';
24487 }
24488 },
24489
24490 /**
24491 * This function detects which browser version is running this script,
24492 * parsing major and minor version (e.g., 42.1). User agent strings from:
24493 * http://www.useragentstring.com/pages/useragentstring.php
24494 */
24495 browserVersion: function(userAgent, vendor, opera) {
24496 var browser = _.info.browser(userAgent, vendor, opera);
24497 var versionRegexs = {
24498 'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
24499 'Microsoft Edge': /Edge?\/(\d+(\.\d+)?)/,
24500 'Chrome': /Chrome\/(\d+(\.\d+)?)/,
24501 'Chrome iOS': /CriOS\/(\d+(\.\d+)?)/,
24502 'UC Browser' : /(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,
24503 'Safari': /Version\/(\d+(\.\d+)?)/,
24504 'Mobile Safari': /Version\/(\d+(\.\d+)?)/,
24505 'Opera': /(Opera|OPR)\/(\d+(\.\d+)?)/,
24506 'Firefox': /Firefox\/(\d+(\.\d+)?)/,
24507 'Firefox iOS': /FxiOS\/(\d+(\.\d+)?)/,
24508 'Konqueror': /Konqueror:(\d+(\.\d+)?)/,
24509 'BlackBerry': /BlackBerry (\d+(\.\d+)?)/,
24510 'Android Mobile': /android\s(\d+(\.\d+)?)/,
24511 'Samsung Internet': /SamsungBrowser\/(\d+(\.\d+)?)/,
24512 'Internet Explorer': /(rv:|MSIE )(\d+(\.\d+)?)/,
24513 'Mozilla': /rv:(\d+(\.\d+)?)/,
24514 'Whale Browser': /Whale\/(\d+(\.\d+)?)/
24515 };
24516 var regex = versionRegexs[browser];
24517 if (regex === undefined) {
24518 return null;
24519 }
24520 var matches = userAgent.match(regex);
24521 if (!matches) {
24522 return null;
24523 }
24524 return parseFloat(matches[matches.length - 2]);
24525 },
24526
24527 os: function() {
24528 var a = userAgent;
24529 if (/Windows/i.test(a)) {
24530 if (/Phone/.test(a) || /WPDesktop/.test(a)) {
24531 return 'Windows Phone';
24532 }
24533 return 'Windows';
24534 } else if (/(iPhone|iPad|iPod)/.test(a)) {
24535 return 'iOS';
24536 } else if (/Android/.test(a)) {
24537 return 'Android';
24538 } else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) {
24539 return 'BlackBerry';
24540 } else if (/Mac/i.test(a)) {
24541 return 'Mac OS X';
24542 } else if (/Linux/.test(a)) {
24543 return 'Linux';
24544 } else if (/CrOS/.test(a)) {
24545 return 'Chrome OS';
24546 } else {
24547 return '';
24548 }
24549 },
24550
24551 device: function(user_agent) {
24552 if (/Windows Phone/i.test(user_agent) || /WPDesktop/.test(user_agent)) {
24553 return 'Windows Phone';
24554 } else if (/iPad/.test(user_agent)) {
24555 return 'iPad';
24556 } else if (/iPod/.test(user_agent)) {
24557 return 'iPod Touch';
24558 } else if (/iPhone/.test(user_agent)) {
24559 return 'iPhone';
24560 } else if (/(BlackBerry|PlayBook|BB10)/i.test(user_agent)) {
24561 return 'BlackBerry';
24562 } else if (/Android/.test(user_agent)) {
24563 return 'Android';
24564 } else {
24565 return '';
24566 }
24567 },
24568
24569 referringDomain: function(referrer) {
24570 var split = referrer.split('/');
24571 if (split.length >= 3) {
24572 return split[2];
24573 }
24574 return '';
24575 },
24576
24577 currentUrl: function() {
24578 return win.location.href;
24579 },
24580
24581 properties: function(extra_props) {
24582 if (typeof extra_props !== 'object') {
24583 extra_props = {};
24584 }
24585 return _.extend(_.strip_empty_properties({
24586 '$os': _.info.os(),
24587 '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera),
24588 '$referrer': document$1.referrer,
24589 '$referring_domain': _.info.referringDomain(document$1.referrer),
24590 '$device': _.info.device(userAgent)
24591 }), {
24592 '$current_url': _.info.currentUrl(),
24593 '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera),
24594 '$screen_height': screen.height,
24595 '$screen_width': screen.width,
24596 'mp_lib': 'web',
24597 '$lib_version': Config.LIB_VERSION,
24598 '$insert_id': cheap_guid(),
24599 'time': _.timestamp() / 1000 // epoch time in seconds
24600 }, _.strip_empty_properties(extra_props));
24601 },
24602
24603 people_properties: function() {
24604 return _.extend(_.strip_empty_properties({
24605 '$os': _.info.os(),
24606 '$browser': _.info.browser(userAgent, navigator.vendor, windowOpera)
24607 }), {
24608 '$browser_version': _.info.browserVersion(userAgent, navigator.vendor, windowOpera)
24609 });
24610 },
24611
24612 mpPageViewProperties: function() {
24613 return _.strip_empty_properties({
24614 'current_page_title': document$1.title,
24615 'current_domain': win.location.hostname,
24616 'current_url_path': win.location.pathname,
24617 'current_url_protocol': win.location.protocol,
24618 'current_url_search': win.location.search
24619 });
24620 }
24621 };
24622
24623 /**
24624 * Returns a throttled function that will only run at most every `waitMs` and returns a promise that resolves with the next invocation.
24625 * Throttled calls will build up a batch of args and invoke the callback with all args since the last invocation.
24626 */
24627 var batchedThrottle = function (fn, waitMs) {
24628 var timeoutPromise = null;
24629 var throttledItems = [];
24630 return function (item) {
24631 var self = this;
24632 throttledItems.push(item);
24633
24634 if (!timeoutPromise) {
24635 timeoutPromise = new PromisePolyfill(function (resolve) {
24636 setTimeout(function () {
24637 var returnValue = fn.apply(self, [throttledItems]);
24638 timeoutPromise = null;
24639 throttledItems = [];
24640 resolve(returnValue);
24641 }, waitMs);
24642 });
24643 }
24644 return timeoutPromise;
24645 };
24646 };
24647
24648 var cheap_guid = function(maxlen) {
24649 var guid = Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10);
24650 return maxlen ? guid.substring(0, maxlen) : guid;
24651 };
24652
24653 /**
24654 * Generates a W3C traceparent header for easy interop with distributed tracing systems i.e Open Telemetry
24655 * https://www.w3.org/TR/trace-context/#traceparent-header
24656 */
24657 var generateTraceparent = function() {
24658 var traceID = _.UUID().replace(/-/g, '');
24659 var parentID = _.UUID().replace(/-/g, '').substring(0, 16);
24660
24661 // Sampled trace
24662 var traceFlags = '01';
24663
24664 return '00-' + traceID + '-' + parentID + '-' + traceFlags;
24665 };
24666
24667 // naive way to extract domain name (example.com) from full hostname (my.sub.example.com)
24668 var SIMPLE_DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]*\.[a-z]+$/i;
24669 // this next one attempts to account for some ccSLDs, e.g. extracting oxford.ac.uk from www.oxford.ac.uk
24670 var DOMAIN_MATCH_REGEX = /[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i;
24671 /**
24672 * Attempts to extract main domain name from full hostname, using a few blunt heuristics. For
24673 * common TLDs like .com/.org that always have a simple SLD.TLD structure (example.com), we
24674 * simply extract the last two .-separated parts of the hostname (SIMPLE_DOMAIN_MATCH_REGEX).
24675 * For others, we attempt to account for short ccSLD+TLD combos (.ac.uk) with the legacy
24676 * DOMAIN_MATCH_REGEX (kept to maintain backwards compatibility with existing Mixpanel
24677 * integrations). The only _reliable_ way to extract domain from hostname is with an up-to-date
24678 * list like at https://publicsuffix.org/ so for cases that this helper fails at, the SDK
24679 * offers the 'cookie_domain' config option to set it explicitly.
24680 * @example
24681 * extract_domain('my.sub.example.com')
24682 * // 'example.com'
24683 */
24684 var extract_domain = function(hostname) {
24685 var domain_regex = DOMAIN_MATCH_REGEX;
24686 var parts = hostname.split('.');
24687 var tld = parts[parts.length - 1];
24688 if (tld.length > 4 || tld === 'com' || tld === 'org') {
24689 domain_regex = SIMPLE_DOMAIN_MATCH_REGEX;
24690 }
24691 var matches = hostname.match(domain_regex);
24692 return matches ? matches[0] : '';
24693 };
24694
24695 /**
24696 * Check whether we have network connection. default to true for browsers that don't support navigator.onLine (IE)
24697 * @returns {boolean}
24698 */
24699 var isOnline = function() {
24700 var onLine = win.navigator['onLine'];
24701 return _.isUndefined(onLine) || onLine;
24702 };
24703
24704 var NOOP_FUNC = function () {};
24705
24706 var JSONStringify = null, JSONParse = null;
24707 if (typeof JSON !== 'undefined') {
24708 JSONStringify = JSON.stringify;
24709 JSONParse = JSON.parse;
24710 }
24711 JSONStringify = JSONStringify || _.JSONEncode;
24712 JSONParse = JSONParse || _.JSONDecode;
24713
24714 // UNMINIFIED EXPORTS (for closure compiler)
24715 _['info'] = _.info;
24716 _['info']['browser'] = _.info.browser;
24717 _['info']['browserVersion'] = _.info.browserVersion;
24718 _['info']['device'] = _.info.device;
24719 _['info']['properties'] = _.info.properties;
24720 _['isBlockedUA'] = _.isBlockedUA;
24721 _['isEmptyObject'] = _.isEmptyObject;
24722 _['isObject'] = _.isObject;
24723 _['JSONDecode'] = _.JSONDecode;
24724 _['JSONEncode'] = _.JSONEncode;
24725 _['toArray'] = _.toArray;
24726 _['NPO'] = NpoPromise;
24727
24728 var MIXPANEL_DB_NAME = 'mixpanelBrowserDb';
24729
24730 var RECORDING_EVENTS_STORE_NAME = 'mixpanelRecordingEvents';
24731 var RECORDING_REGISTRY_STORE_NAME = 'mixpanelRecordingRegistry';
24732
24733 // note: increment the version number when adding new object stores
24734 var DB_VERSION = 1;
24735 var OBJECT_STORES = [RECORDING_EVENTS_STORE_NAME, RECORDING_REGISTRY_STORE_NAME];
24736
24737 /**
24738 * @type {import('./wrapper').StorageWrapper}
24739 */
24740 var IDBStorageWrapper = function (storeName) {
24741 /**
24742 * @type {Promise<IDBDatabase>|null}
24743 */
24744 this.dbPromise = null;
24745 this.storeName = storeName;
24746 };
24747
24748 IDBStorageWrapper.prototype._openDb = function () {
24749 return new PromisePolyfill(function (resolve, reject) {
24750 var openRequest = win.indexedDB.open(MIXPANEL_DB_NAME, DB_VERSION);
24751 openRequest['onerror'] = function () {
24752 reject(openRequest.error);
24753 };
24754
24755 openRequest['onsuccess'] = function () {
24756 resolve(openRequest.result);
24757 };
24758
24759 openRequest['onupgradeneeded'] = function (ev) {
24760 var db = ev.target.result;
24761
24762 OBJECT_STORES.forEach(function (storeName) {
24763 db.createObjectStore(storeName);
24764 });
24765 };
24766 });
24767 };
24768
24769 IDBStorageWrapper.prototype.init = function () {
24770 if (!win.indexedDB) {
24771 return PromisePolyfill.reject('indexedDB is not supported in this browser');
24772 }
24773
24774 if (!this.dbPromise) {
24775 this.dbPromise = this._openDb();
24776 }
24777
24778 return this.dbPromise
24779 .then(function (dbOrError) {
24780 if (dbOrError instanceof win['IDBDatabase']) {
24781 return PromisePolyfill.resolve();
24782 } else {
24783 return PromisePolyfill.reject(dbOrError);
24784 }
24785 });
24786 };
24787
24788 IDBStorageWrapper.prototype.isInitialized = function () {
24789 return !!this.dbPromise;
24790 };
24791
24792 /**
24793 * @param {IDBTransactionMode} mode
24794 * @param {function(IDBObjectStore): void} storeCb
24795 */
24796 IDBStorageWrapper.prototype.makeTransaction = function (mode, storeCb) {
24797 var storeName = this.storeName;
24798 var doTransaction = function (db) {
24799 return new PromisePolyfill(function (resolve, reject) {
24800 var transaction = db.transaction(storeName, mode);
24801 transaction.oncomplete = function () {
24802 resolve(transaction);
24803 };
24804 transaction.onabort = transaction.onerror = function () {
24805 reject(transaction.error);
24806 };
24807
24808 storeCb(transaction.objectStore(storeName));
24809 });
24810 };
24811
24812 return this.dbPromise
24813 .then(doTransaction)
24814 .catch(function (err) {
24815 if (err && err['name'] === 'InvalidStateError') {
24816 // try reopening the DB if the connection is closed
24817 this.dbPromise = this._openDb();
24818 return this.dbPromise.then(doTransaction);
24819 } else {
24820 return PromisePolyfill.reject(err);
24821 }
24822 }.bind(this));
24823 };
24824
24825 IDBStorageWrapper.prototype.setItem = function (key, value) {
24826 return this.makeTransaction('readwrite', function (objectStore) {
24827 objectStore.put(value, key);
24828 });
24829 };
24830
24831 IDBStorageWrapper.prototype.getItem = function (key) {
24832 var req;
24833 return this.makeTransaction('readonly', function (objectStore) {
24834 req = objectStore.get(key);
24835 }).then(function () {
24836 return req.result;
24837 });
24838 };
24839
24840 IDBStorageWrapper.prototype.removeItem = function (key) {
24841 return this.makeTransaction('readwrite', function (objectStore) {
24842 objectStore.delete(key);
24843 });
24844 };
24845
24846 IDBStorageWrapper.prototype.getAll = function () {
24847 var req;
24848 return this.makeTransaction('readonly', function (objectStore) {
24849 req = objectStore.getAll();
24850 }).then(function () {
24851 return req.result;
24852 });
24853 };
24854
24855 /**
24856 * GDPR utils
24857 *
24858 * The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection
24859 * and privacy for all individuals within the European Union. It addresses the export of personal
24860 * data outside the EU. The GDPR aims primarily to give control back to citizens and residents
24861 * over their personal data and to simplify the regulatory environment for international business
24862 * by unifying the regulation within the EU.
24863 *
24864 * This set of utilities is intended to enable opt in/out functionality in the Mixpanel JS SDK.
24865 * These functions are used internally by the SDK and are not intended to be publicly exposed.
24866 */
24867
24868
24869 /**
24870 * A function used to track a Mixpanel event (e.g. MixpanelLib.track)
24871 * @callback trackFunction
24872 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
24873 * @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.
24874 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
24875 */
24876
24877 /** Public **/
24878
24879 var GDPR_DEFAULT_PERSISTENCE_PREFIX = '__mp_opt_in_out_';
24880
24881 /**
24882 * Opt the user in to data tracking and cookies/localstorage for the given token
24883 * @param {string} token - Mixpanel project tracking token
24884 * @param {Object} [options]
24885 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
24886 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
24887 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
24888 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24889 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24890 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
24891 * @param {string} [options.cookieDomain] - custom cookie domain
24892 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
24893 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
24894 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
24895 */
24896 function optIn(token, options) {
24897 _optInOut(true, token, options);
24898 }
24899
24900 /**
24901 * Opt the user out of data tracking and cookies/localstorage for the given token
24902 * @param {string} token - Mixpanel project tracking token
24903 * @param {Object} [options]
24904 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24905 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24906 * @param {Number} [options.cookieExpiration] - number of days until the opt-out cookie expires
24907 * @param {string} [options.cookieDomain] - custom cookie domain
24908 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
24909 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-out cookie is set as cross-subdomain or not
24910 * @param {boolean} [options.secureCookie] - whether the opt-out cookie is set as secure or not
24911 */
24912 function optOut(token, options) {
24913 _optInOut(false, token, options);
24914 }
24915
24916 /**
24917 * Check whether the user has opted in to data tracking and cookies/localstorage for the given token
24918 * @param {string} token - Mixpanel project tracking token
24919 * @param {Object} [options]
24920 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24921 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24922 * @returns {boolean} whether the user has opted in to the given opt type
24923 */
24924 function hasOptedIn(token, options) {
24925 return _getStorageValue(token, options) === '1';
24926 }
24927
24928 /**
24929 * Check whether the user has opted out of data tracking and cookies/localstorage for the given token
24930 * @param {string} token - Mixpanel project tracking token
24931 * @param {Object} [options]
24932 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24933 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24934 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
24935 * @returns {boolean} whether the user has opted out of the given opt type
24936 */
24937 function hasOptedOut(token, options) {
24938 if (_hasDoNotTrackFlagOn(options)) {
24939 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"');
24940 return true;
24941 }
24942 var optedOut = _getStorageValue(token, options) === '0';
24943 if (optedOut) {
24944 console$1.warn('You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data.');
24945 }
24946 return optedOut;
24947 }
24948
24949 /**
24950 * Wrap a MixpanelLib method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
24951 * If the user has opted out, return early instead of executing the method.
24952 * If a callback argument was provided, execute it passing the 0 error code.
24953 * @param {function} method - wrapped method to be executed if the user has not opted out
24954 * @returns {*} the result of executing method OR undefined if the user has opted out
24955 */
24956 function addOptOutCheckMixpanelLib(method) {
24957 return _addOptOutCheck(method, function(name) {
24958 return this.get_config(name);
24959 });
24960 }
24961
24962 /**
24963 * Wrap a MixpanelPeople method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
24964 * If the user has opted out, return early instead of executing the method.
24965 * If a callback argument was provided, execute it passing the 0 error code.
24966 * @param {function} method - wrapped method to be executed if the user has not opted out
24967 * @returns {*} the result of executing method OR undefined if the user has opted out
24968 */
24969 function addOptOutCheckMixpanelPeople(method) {
24970 return _addOptOutCheck(method, function(name) {
24971 return this._get_config(name);
24972 });
24973 }
24974
24975 /**
24976 * Wrap a MixpanelGroup method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
24977 * If the user has opted out, return early instead of executing the method.
24978 * If a callback argument was provided, execute it passing the 0 error code.
24979 * @param {function} method - wrapped method to be executed if the user has not opted out
24980 * @returns {*} the result of executing method OR undefined if the user has opted out
24981 */
24982 function addOptOutCheckMixpanelGroup(method) {
24983 return _addOptOutCheck(method, function(name) {
24984 return this._get_config(name);
24985 });
24986 }
24987
24988 /**
24989 * Clear the user's opt in/out status of data tracking and cookies/localstorage for the given token
24990 * @param {string} token - Mixpanel project tracking token
24991 * @param {Object} [options]
24992 * @param {string} [options.persistenceType] Persistence mechanism used - cookie or localStorage
24993 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
24994 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
24995 * @param {string} [options.cookieDomain] - custom cookie domain
24996 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
24997 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
24998 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
24999 */
25000 function clearOptInOut(token, options) {
25001 options = options || {};
25002 _getStorage(options).remove(
25003 _getStorageKey(token, options), !!options.crossSubdomainCookie, options.cookieDomain
25004 );
25005 }
25006
25007 /** Private **/
25008
25009 /**
25010 * Get storage util
25011 * @param {Object} [options]
25012 * @param {string} [options.persistenceType]
25013 * @returns {object} either _.cookie or _.localstorage
25014 */
25015 function _getStorage(options) {
25016 options = options || {};
25017 return options.persistenceType === 'localStorage' ? _.localStorage : _.cookie;
25018 }
25019
25020 /**
25021 * Get the name of the cookie that is used for the given opt type (tracking, cookie, etc.)
25022 * @param {string} token - Mixpanel project tracking token
25023 * @param {Object} [options]
25024 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
25025 * @returns {string} the name of the cookie for the given opt type
25026 */
25027 function _getStorageKey(token, options) {
25028 options = options || {};
25029 return (options.persistencePrefix || GDPR_DEFAULT_PERSISTENCE_PREFIX) + token;
25030 }
25031
25032 /**
25033 * Get the value of the cookie that is used for the given opt type (tracking, cookie, etc.)
25034 * @param {string} token - Mixpanel project tracking token
25035 * @param {Object} [options]
25036 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
25037 * @returns {string} the value of the cookie for the given opt type
25038 */
25039 function _getStorageValue(token, options) {
25040 return _getStorage(options).get(_getStorageKey(token, options));
25041 }
25042
25043 /**
25044 * Check whether the user has set the DNT/doNotTrack setting to true in their browser
25045 * @param {Object} [options]
25046 * @param {string} [options.window] - alternate window object to check; used to force various DNT settings in browser tests
25047 * @param {boolean} [options.ignoreDnt] - flag to ignore browser DNT settings and always return false
25048 * @returns {boolean} whether the DNT setting is true
25049 */
25050 function _hasDoNotTrackFlagOn(options) {
25051 if (options && options.ignoreDnt) {
25052 return false;
25053 }
25054 var win$1 = (options && options.window) || win;
25055 var nav = win$1['navigator'] || {};
25056 var hasDntOn = false;
25057
25058 _.each([
25059 nav['doNotTrack'], // standard
25060 nav['msDoNotTrack'],
25061 win$1['doNotTrack']
25062 ], function(dntValue) {
25063 if (_.includes([true, 1, '1', 'yes'], dntValue)) {
25064 hasDntOn = true;
25065 }
25066 });
25067
25068 return hasDntOn;
25069 }
25070
25071 /**
25072 * Set cookie/localstorage for the user indicating that they are opted in or out for the given opt type
25073 * @param {boolean} optValue - whether to opt the user in or out for the given opt type
25074 * @param {string} token - Mixpanel project tracking token
25075 * @param {Object} [options]
25076 * @param {trackFunction} [options.track] - function used for tracking a Mixpanel event to record the opt-in action
25077 * @param {string} [options.trackEventName] - event name to be used for tracking the opt-in action
25078 * @param {Object} [options.trackProperties] - set of properties to be tracked along with the opt-in action
25079 * @param {string} [options.persistencePrefix=__mp_opt_in_out] - custom prefix to be used in the cookie/localstorage name
25080 * @param {Number} [options.cookieExpiration] - number of days until the opt-in cookie expires
25081 * @param {string} [options.cookieDomain] - custom cookie domain
25082 * @param {boolean} [options.crossSiteCookie] - whether the opt-in cookie is set as cross-site-enabled
25083 * @param {boolean} [options.crossSubdomainCookie] - whether the opt-in cookie is set as cross-subdomain or not
25084 * @param {boolean} [options.secureCookie] - whether the opt-in cookie is set as secure or not
25085 */
25086 function _optInOut(optValue, token, options) {
25087 if (!_.isString(token) || !token.length) {
25088 console$1.error('gdpr.' + (optValue ? 'optIn' : 'optOut') + ' called with an invalid token');
25089 return;
25090 }
25091
25092 options = options || {};
25093
25094 _getStorage(options).set(
25095 _getStorageKey(token, options),
25096 optValue ? 1 : 0,
25097 _.isNumber(options.cookieExpiration) ? options.cookieExpiration : null,
25098 !!options.crossSubdomainCookie,
25099 !!options.secureCookie,
25100 !!options.crossSiteCookie,
25101 options.cookieDomain
25102 );
25103
25104 if (options.track && optValue) { // only track event if opting in (optValue=true)
25105 options.track(options.trackEventName || '$opt_in', options.trackProperties, {
25106 'send_immediately': true
25107 });
25108 }
25109 }
25110
25111 /**
25112 * Wrap a method with a check for whether the user is opted out of data tracking and cookies/localstorage for the given token
25113 * If the user has opted out, return early instead of executing the method.
25114 * If a callback argument was provided, execute it passing the 0 error code.
25115 * @param {function} method - wrapped method to be executed if the user has not opted out
25116 * @param {function} getConfigValue - getter function for the Mixpanel API token and other options to be used with opt-out check
25117 * @returns {*} the result of executing method OR undefined if the user has opted out
25118 */
25119 function _addOptOutCheck(method, getConfigValue) {
25120 return function() {
25121 var optedOut = false;
25122
25123 try {
25124 var token = getConfigValue.call(this, 'token');
25125 var ignoreDnt = getConfigValue.call(this, 'ignore_dnt');
25126 var persistenceType = getConfigValue.call(this, 'opt_out_tracking_persistence_type');
25127 var persistencePrefix = getConfigValue.call(this, 'opt_out_tracking_cookie_prefix');
25128 var win = getConfigValue.call(this, 'window'); // used to override window during browser tests
25129
25130 if (token) { // if there was an issue getting the token, continue method execution as normal
25131 optedOut = hasOptedOut(token, {
25132 ignoreDnt: ignoreDnt,
25133 persistenceType: persistenceType,
25134 persistencePrefix: persistencePrefix,
25135 window: win
25136 });
25137 }
25138 } catch(err) {
25139 console$1.error('Unexpected error when checking tracking opt-out status: ' + err);
25140 }
25141
25142 if (!optedOut) {
25143 return method.apply(this, arguments);
25144 }
25145
25146 var callback = arguments[arguments.length - 1];
25147 if (typeof(callback) === 'function') {
25148 callback(0);
25149 }
25150
25151 return;
25152 };
25153 }
25154
25155 var logger$6 = console_with_prefix('lock');
25156
25157 /**
25158 * SharedLock: a mutex built on HTML5 localStorage, to ensure that only one browser
25159 * window/tab at a time will be able to access shared resources.
25160 *
25161 * Based on the Alur and Taubenfeld fast lock
25162 * (http://www.cs.rochester.edu/research/synchronization/pseudocode/fastlock.html)
25163 * with an added timeout to ensure there will be eventual progress in the event
25164 * that a window is closed in the middle of the callback.
25165 *
25166 * Implementation based on the original version by David Wolever (https://github.com/wolever)
25167 * at https://gist.github.com/wolever/5fd7573d1ef6166e8f8c4af286a69432.
25168 *
25169 * @example
25170 * const myLock = new SharedLock('some-key');
25171 * myLock.withLock(function() {
25172 * console.log('I hold the mutex!');
25173 * });
25174 *
25175 * @constructor
25176 */
25177 var SharedLock = function(key, options) {
25178 options = options || {};
25179
25180 this.storageKey = key;
25181 this.storage = options.storage || win.localStorage;
25182 this.pollIntervalMS = options.pollIntervalMS || 100;
25183 this.timeoutMS = options.timeoutMS || 2000;
25184
25185 // dependency-inject promise implementation for testing purposes
25186 this.promiseImpl = options.promiseImpl || PromisePolyfill;
25187 };
25188
25189 // pass in a specific pid to test contention scenarios; otherwise
25190 // it is chosen randomly for each acquisition attempt
25191 SharedLock.prototype.withLock = function(lockedCB, pid) {
25192 var Promise = this.promiseImpl;
25193 return new Promise(_.bind(function (resolve, reject) {
25194 var i = pid || (new Date().getTime() + '|' + Math.random());
25195 var startTime = new Date().getTime();
25196 var key = this.storageKey;
25197 var pollIntervalMS = this.pollIntervalMS;
25198 var timeoutMS = this.timeoutMS;
25199 var storage = this.storage;
25200
25201 var keyX = key + ':X';
25202 var keyY = key + ':Y';
25203 var keyZ = key + ':Z';
25204
25205 var delay = function(cb) {
25206 if (new Date().getTime() - startTime > timeoutMS) {
25207 logger$6.error('Timeout waiting for mutex on ' + key + '; clearing lock. [' + i + ']');
25208 storage.removeItem(keyZ);
25209 storage.removeItem(keyY);
25210 loop();
25211 return;
25212 }
25213 setTimeout(function() {
25214 try {
25215 cb();
25216 } catch(err) {
25217 reject(err);
25218 }
25219 }, pollIntervalMS * (Math.random() + 0.1));
25220 };
25221
25222 var waitFor = function(predicate, cb) {
25223 if (predicate()) {
25224 cb();
25225 } else {
25226 delay(function() {
25227 waitFor(predicate, cb);
25228 });
25229 }
25230 };
25231
25232 var getSetY = function() {
25233 var valY = storage.getItem(keyY);
25234 if (valY && valY !== i) { // if Y == i then this process already has the lock (useful for test cases)
25235 return false;
25236 } else {
25237 storage.setItem(keyY, i);
25238 if (storage.getItem(keyY) === i) {
25239 return true;
25240 } else {
25241 if (!localStorageSupported(storage, true)) {
25242 reject(new Error('localStorage support dropped while acquiring lock'));
25243 }
25244 return false;
25245 }
25246 }
25247 };
25248
25249 var loop = function() {
25250 storage.setItem(keyX, i);
25251
25252 waitFor(getSetY, function() {
25253 if (storage.getItem(keyX) === i) {
25254 criticalSection();
25255 return;
25256 }
25257
25258 delay(function() {
25259 if (storage.getItem(keyY) !== i) {
25260 loop();
25261 return;
25262 }
25263 waitFor(function() {
25264 return !storage.getItem(keyZ);
25265 }, criticalSection);
25266 });
25267 });
25268 };
25269
25270 var criticalSection = function() {
25271 storage.setItem(keyZ, '1');
25272 var removeLock = function () {
25273 storage.removeItem(keyZ);
25274 if (storage.getItem(keyY) === i) {
25275 storage.removeItem(keyY);
25276 }
25277 if (storage.getItem(keyX) === i) {
25278 storage.removeItem(keyX);
25279 }
25280 };
25281
25282 lockedCB()
25283 .then(function (ret) {
25284 removeLock();
25285 resolve(ret);
25286 })
25287 .catch(function (err) {
25288 removeLock();
25289 reject(err);
25290 });
25291 };
25292
25293 try {
25294 if (localStorageSupported(storage, true)) {
25295 loop();
25296 } else {
25297 throw new Error('localStorage support check failed');
25298 }
25299 } catch(err) {
25300 reject(err);
25301 }
25302 }, this));
25303 };
25304
25305 /**
25306 * @type {import('./wrapper').StorageWrapper}
25307 */
25308 var LocalStorageWrapper = function (storageOverride) {
25309 this.storage = storageOverride || win.localStorage;
25310 };
25311
25312 LocalStorageWrapper.prototype.init = function () {
25313 return PromisePolyfill.resolve();
25314 };
25315
25316 LocalStorageWrapper.prototype.isInitialized = function () {
25317 return true;
25318 };
25319
25320 LocalStorageWrapper.prototype.setItem = function (key, value) {
25321 return new PromisePolyfill(_.bind(function (resolve, reject) {
25322 try {
25323 this.storage.setItem(key, JSONStringify(value));
25324 } catch (e) {
25325 reject(e);
25326 }
25327 resolve();
25328 }, this));
25329 };
25330
25331 LocalStorageWrapper.prototype.getItem = function (key) {
25332 return new PromisePolyfill(_.bind(function (resolve, reject) {
25333 var item;
25334 try {
25335 item = JSONParse(this.storage.getItem(key));
25336 } catch (e) {
25337 reject(e);
25338 }
25339 resolve(item);
25340 }, this));
25341 };
25342
25343 LocalStorageWrapper.prototype.removeItem = function (key) {
25344 return new PromisePolyfill(_.bind(function (resolve, reject) {
25345 try {
25346 this.storage.removeItem(key);
25347 } catch (e) {
25348 reject(e);
25349 }
25350 resolve();
25351 }, this));
25352 };
25353
25354 var logger$5 = console_with_prefix('batch');
25355
25356 /**
25357 * RequestQueue: queue for batching API requests with localStorage backup for retries.
25358 * Maintains an in-memory queue which represents the source of truth for the current
25359 * page, but also writes all items out to a copy in the browser's localStorage, which
25360 * can be read on subsequent pageloads and retried. For batchability, all the request
25361 * items in the queue should be of the same type (events, people updates, group updates)
25362 * so they can be sent in a single request to the same API endpoint.
25363 *
25364 * LocalStorage keying and locking: In order for reloads and subsequent pageloads of
25365 * the same site to access the same persisted data, they must share the same localStorage
25366 * key (for instance based on project token and queue type). Therefore access to the
25367 * localStorage entry is guarded by an asynchronous mutex (SharedLock) to prevent
25368 * simultaneously open windows/tabs from overwriting each other's data (which would lead
25369 * to data loss in some situations).
25370 * @constructor
25371 */
25372 var RequestQueue = function (storageKey, options) {
25373 options = options || {};
25374 this.storageKey = storageKey;
25375 this.usePersistence = options.usePersistence;
25376 if (this.usePersistence) {
25377 this.queueStorage = options.queueStorage || new LocalStorageWrapper();
25378 this.lock = new SharedLock(storageKey, {
25379 storage: options.sharedLockStorage || win.localStorage,
25380 timeoutMS: options.sharedLockTimeoutMS,
25381 });
25382 }
25383 this.reportError = options.errorReporter || _.bind(logger$5.error, logger$5);
25384
25385 this.pid = options.pid || null; // pass pid to test out storage lock contention scenarios
25386
25387 this.memQueue = [];
25388 this.initialized = false;
25389
25390 if (options.enqueueThrottleMs) {
25391 this.enqueuePersisted = batchedThrottle(_.bind(this._enqueuePersisted, this), options.enqueueThrottleMs);
25392 } else {
25393 this.enqueuePersisted = _.bind(function (queueEntry) {
25394 return this._enqueuePersisted([queueEntry]);
25395 }, this);
25396 }
25397 };
25398
25399 RequestQueue.prototype.ensureInit = function () {
25400 if (this.initialized || !this.usePersistence) {
25401 return PromisePolyfill.resolve();
25402 }
25403
25404 return this.queueStorage
25405 .init()
25406 .then(_.bind(function () {
25407 this.initialized = true;
25408 }, this))
25409 .catch(_.bind(function (err) {
25410 this.reportError('Error initializing queue persistence. Disabling persistence', err);
25411 this.initialized = true;
25412 this.usePersistence = false;
25413 }, this));
25414 };
25415
25416 /**
25417 * Add one item to queues (memory and localStorage). The queued entry includes
25418 * the given item along with an auto-generated ID and a "flush-after" timestamp.
25419 * It is expected that the item will be sent over the network and dequeued
25420 * before the flush-after time; if this doesn't happen it is considered orphaned
25421 * (e.g., the original tab where it was enqueued got closed before it could be
25422 * sent) and the item can be sent by any tab that finds it in localStorage.
25423 *
25424 * The final callback param is called with a param indicating success or
25425 * failure of the enqueue operation; it is asynchronous because the localStorage
25426 * lock is asynchronous.
25427 */
25428 RequestQueue.prototype.enqueue = function (item, flushInterval) {
25429 var queueEntry = {
25430 'id': cheap_guid(),
25431 'flushAfter': new Date().getTime() + flushInterval * 2,
25432 'payload': item
25433 };
25434
25435 if (!this.usePersistence) {
25436 this.memQueue.push(queueEntry);
25437 return PromisePolyfill.resolve(true);
25438 } else {
25439 return this.enqueuePersisted(queueEntry);
25440 }
25441 };
25442
25443 RequestQueue.prototype._enqueuePersisted = function (queueEntries) {
25444 var enqueueItem = _.bind(function () {
25445 return this.ensureInit()
25446 .then(_.bind(function () {
25447 return this.readFromStorage();
25448 }, this))
25449 .then(_.bind(function (storedQueue) {
25450 return this.saveToStorage(storedQueue.concat(queueEntries));
25451 }, this))
25452 .then(_.bind(function (succeeded) {
25453 // only add to in-memory queue when storage succeeds
25454 if (succeeded) {
25455 this.memQueue = this.memQueue.concat(queueEntries);
25456 }
25457
25458 return succeeded;
25459 }, this))
25460 .catch(_.bind(function (err) {
25461 this.reportError('Error enqueueing items', err, queueEntries);
25462 return false;
25463 }, this));
25464 }, this);
25465
25466 return this.lock
25467 .withLock(enqueueItem, this.pid)
25468 .catch(_.bind(function (err) {
25469 this.reportError('Error acquiring storage lock', err);
25470 return false;
25471 }, this));
25472 };
25473
25474 /**
25475 * Read out the given number of queue entries. If this.memQueue
25476 * has fewer than batchSize items, then look for "orphaned" items
25477 * in the persisted queue (items where the 'flushAfter' time has
25478 * already passed).
25479 */
25480 RequestQueue.prototype.fillBatch = function (batchSize) {
25481 var batch = this.memQueue.slice(0, batchSize);
25482 if (this.usePersistence && batch.length < batchSize) {
25483 // don't need lock just to read events; localStorage is thread-safe
25484 // and the worst that could happen is a duplicate send of some
25485 // orphaned events, which will be deduplicated on the server side
25486 return this.ensureInit()
25487 .then(_.bind(function () {
25488 return this.readFromStorage();
25489 }, this))
25490 .then(_.bind(function (storedQueue) {
25491 if (storedQueue.length) {
25492 // item IDs already in batch; don't duplicate out of storage
25493 var idsInBatch = {}; // poor man's Set
25494 _.each(batch, function (item) {
25495 idsInBatch[item['id']] = true;
25496 });
25497
25498 for (var i = 0; i < storedQueue.length; i++) {
25499 var item = storedQueue[i];
25500 if (new Date().getTime() > item['flushAfter'] && !idsInBatch[item['id']]) {
25501 item.orphaned = true;
25502 batch.push(item);
25503 if (batch.length >= batchSize) {
25504 break;
25505 }
25506 }
25507 }
25508 }
25509
25510 return batch;
25511 }, this));
25512 } else {
25513 return PromisePolyfill.resolve(batch);
25514 }
25515 };
25516
25517 /**
25518 * Remove items with matching 'id' from array (immutably)
25519 * also remove any item without a valid id (e.g., malformed
25520 * storage entries).
25521 */
25522 var filterOutIDsAndInvalid = function (items, idSet) {
25523 var filteredItems = [];
25524 _.each(items, function (item) {
25525 if (item['id'] && !idSet[item['id']]) {
25526 filteredItems.push(item);
25527 }
25528 });
25529 return filteredItems;
25530 };
25531
25532 /**
25533 * Remove items with matching IDs from both in-memory queue
25534 * and persisted queue
25535 */
25536 RequestQueue.prototype.removeItemsByID = function (ids) {
25537 var idSet = {}; // poor man's Set
25538 _.each(ids, function (id) {
25539 idSet[id] = true;
25540 });
25541
25542 this.memQueue = filterOutIDsAndInvalid(this.memQueue, idSet);
25543 if (!this.usePersistence) {
25544 return PromisePolyfill.resolve(true);
25545 } else {
25546 var removeFromStorage = _.bind(function () {
25547 return this.ensureInit()
25548 .then(_.bind(function () {
25549 return this.readFromStorage();
25550 }, this))
25551 .then(_.bind(function (storedQueue) {
25552 storedQueue = filterOutIDsAndInvalid(storedQueue, idSet);
25553 return this.saveToStorage(storedQueue);
25554 }, this))
25555 .then(_.bind(function () {
25556 return this.readFromStorage();
25557 }, this))
25558 .then(_.bind(function (storedQueue) {
25559 // an extra check: did storage report success but somehow
25560 // the items are still there?
25561 for (var i = 0; i < storedQueue.length; i++) {
25562 var item = storedQueue[i];
25563 if (item['id'] && !!idSet[item['id']]) {
25564 throw new Error('Item not removed from storage');
25565 }
25566 }
25567 return true;
25568 }, this))
25569 .catch(_.bind(function (err) {
25570 this.reportError('Error removing items', err, ids);
25571 return false;
25572 }, this));
25573 }, this);
25574
25575 return this.lock
25576 .withLock(removeFromStorage, this.pid)
25577 .catch(_.bind(function (err) {
25578 this.reportError('Error acquiring storage lock', err);
25579 if (!localStorageSupported(this.lock.storage, true)) {
25580 // Looks like localStorage writes have stopped working sometime after
25581 // initialization (probably full), and so nobody can acquire locks
25582 // anymore. Consider it temporarily safe to remove items without the
25583 // lock, since nobody's writing successfully anyway.
25584 return removeFromStorage()
25585 .then(_.bind(function (success) {
25586 if (!success) {
25587 // OK, we couldn't even write out the smaller queue. Try clearing it
25588 // entirely.
25589 return this.queueStorage.removeItem(this.storageKey).then(function () {
25590 return success;
25591 });
25592 }
25593 return success;
25594 }, this))
25595 .catch(_.bind(function (err) {
25596 this.reportError('Error clearing queue', err);
25597 return false;
25598 }, this));
25599 } else {
25600 return false;
25601 }
25602 }, this));
25603 }
25604 };
25605
25606 // internal helper for RequestQueue.updatePayloads
25607 var updatePayloads = function (existingItems, itemsToUpdate) {
25608 var newItems = [];
25609 _.each(existingItems, function (item) {
25610 var id = item['id'];
25611 if (id in itemsToUpdate) {
25612 var newPayload = itemsToUpdate[id];
25613 if (newPayload !== null) {
25614 item['payload'] = newPayload;
25615 newItems.push(item);
25616 }
25617 } else {
25618 // no update
25619 newItems.push(item);
25620 }
25621 });
25622 return newItems;
25623 };
25624
25625 /**
25626 * Update payloads of given items in both in-memory queue and
25627 * persisted queue. Items set to null are removed from queues.
25628 */
25629 RequestQueue.prototype.updatePayloads = function (itemsToUpdate) {
25630 this.memQueue = updatePayloads(this.memQueue, itemsToUpdate);
25631 if (!this.usePersistence) {
25632 return PromisePolyfill.resolve(true);
25633 } else {
25634 return this.lock
25635 .withLock(_.bind(function lockAcquired() {
25636 return this.ensureInit()
25637 .then(_.bind(function () {
25638 return this.readFromStorage();
25639 }, this))
25640 .then(_.bind(function (storedQueue) {
25641 storedQueue = updatePayloads(storedQueue, itemsToUpdate);
25642 return this.saveToStorage(storedQueue);
25643 }, this))
25644 .catch(_.bind(function (err) {
25645 this.reportError('Error updating items', itemsToUpdate, err);
25646 return false;
25647 }, this));
25648 }, this), this.pid)
25649 .catch(_.bind(function (err) {
25650 this.reportError('Error acquiring storage lock', err);
25651 return false;
25652 }, this));
25653 }
25654 };
25655
25656 /**
25657 * Read and parse items array from localStorage entry, handling
25658 * malformed/missing data if necessary.
25659 */
25660 RequestQueue.prototype.readFromStorage = function () {
25661 return this.ensureInit()
25662 .then(_.bind(function () {
25663 return this.queueStorage.getItem(this.storageKey);
25664 }, this))
25665 .then(_.bind(function (storageEntry) {
25666 if (storageEntry) {
25667 if (!_.isArray(storageEntry)) {
25668 this.reportError('Invalid storage entry:', storageEntry);
25669 storageEntry = null;
25670 }
25671 }
25672 return storageEntry || [];
25673 }, this))
25674 .catch(_.bind(function (err) {
25675 this.reportError('Error retrieving queue', err);
25676 return [];
25677 }, this));
25678 };
25679
25680 /**
25681 * Serialize the given items array to localStorage.
25682 */
25683 RequestQueue.prototype.saveToStorage = function (queue) {
25684 return this.ensureInit()
25685 .then(_.bind(function () {
25686 return this.queueStorage.setItem(this.storageKey, queue);
25687 }, this))
25688 .then(function () {
25689 return true;
25690 })
25691 .catch(_.bind(function (err) {
25692 this.reportError('Error saving queue', err);
25693 return false;
25694 }, this));
25695 };
25696
25697 /**
25698 * Clear out queues (memory and localStorage).
25699 */
25700 RequestQueue.prototype.clear = function () {
25701 this.memQueue = [];
25702
25703 if (this.usePersistence) {
25704 return this.ensureInit()
25705 .then(_.bind(function () {
25706 return this.queueStorage.removeItem(this.storageKey);
25707 }, this));
25708 } else {
25709 return PromisePolyfill.resolve();
25710 }
25711 };
25712
25713 // maximum interval between request retries after exponential backoff
25714 var MAX_RETRY_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
25715
25716 var logger$4 = console_with_prefix('batch');
25717
25718 /**
25719 * RequestBatcher: manages the queueing, flushing, retry etc of requests of one
25720 * type (events, people, groups).
25721 * Uses RequestQueue to manage the backing store.
25722 * @constructor
25723 */
25724 var RequestBatcher = function(storageKey, options) {
25725 this.errorReporter = options.errorReporter;
25726 this.queue = new RequestQueue(storageKey, {
25727 errorReporter: _.bind(this.reportError, this),
25728 queueStorage: options.queueStorage,
25729 sharedLockStorage: options.sharedLockStorage,
25730 sharedLockTimeoutMS: options.sharedLockTimeoutMS,
25731 usePersistence: options.usePersistence,
25732 enqueueThrottleMs: options.enqueueThrottleMs
25733 });
25734
25735 this.libConfig = options.libConfig;
25736 this.sendRequest = options.sendRequestFunc;
25737 this.beforeSendHook = options.beforeSendHook;
25738 this.stopAllBatching = options.stopAllBatchingFunc;
25739
25740 // seed variable batch size + flush interval with configured values
25741 this.batchSize = this.libConfig['batch_size'];
25742 this.flushInterval = this.libConfig['batch_flush_interval_ms'];
25743
25744 this.stopped = !this.libConfig['batch_autostart'];
25745 this.consecutiveRemovalFailures = 0;
25746
25747 // extra client-side dedupe
25748 this.itemIdsSentSuccessfully = {};
25749
25750 // Make the flush occur at the interval specified by flushIntervalMs, default behavior will attempt consecutive flushes
25751 // as long as the queue is not empty. This is useful for high-frequency events like Session Replay where we might end up
25752 // in a request loop and get ratelimited by the server.
25753 this.flushOnlyOnInterval = options.flushOnlyOnInterval || false;
25754
25755 this._flushPromise = null;
25756 };
25757
25758 /**
25759 * Add one item to queue.
25760 */
25761 RequestBatcher.prototype.enqueue = function(item) {
25762 return this.queue.enqueue(item, this.flushInterval);
25763 };
25764
25765 /**
25766 * Start flushing batches at the configured time interval. Must call
25767 * this method upon SDK init in order to send anything over the network.
25768 */
25769 RequestBatcher.prototype.start = function() {
25770 this.stopped = false;
25771 this.consecutiveRemovalFailures = 0;
25772 return this.flush();
25773 };
25774
25775 /**
25776 * Stop flushing batches. Can be restarted by calling start().
25777 */
25778 RequestBatcher.prototype.stop = function() {
25779 this.stopped = true;
25780 if (this.timeoutID) {
25781 clearTimeout(this.timeoutID);
25782 this.timeoutID = null;
25783 }
25784 };
25785
25786 /**
25787 * Clear out queue.
25788 */
25789 RequestBatcher.prototype.clear = function() {
25790 return this.queue.clear();
25791 };
25792
25793 /**
25794 * Restore batch size configuration to whatever is set in the main SDK.
25795 */
25796 RequestBatcher.prototype.resetBatchSize = function() {
25797 this.batchSize = this.libConfig['batch_size'];
25798 };
25799
25800 /**
25801 * Restore flush interval time configuration to whatever is set in the main SDK.
25802 */
25803 RequestBatcher.prototype.resetFlush = function() {
25804 this.scheduleFlush(this.libConfig['batch_flush_interval_ms']);
25805 };
25806
25807 /**
25808 * Schedule the next flush in the given number of milliseconds.
25809 */
25810 RequestBatcher.prototype.scheduleFlush = function(flushMS) {
25811 this.flushInterval = flushMS;
25812 if (!this.stopped) { // don't schedule anymore if batching has been stopped
25813 this.timeoutID = setTimeout(_.bind(function() {
25814 if (!this.stopped) {
25815 this._flushPromise = this.flush();
25816 }
25817 }, this), this.flushInterval);
25818 }
25819 };
25820
25821 /**
25822 * Send a request using the sendRequest callback, but promisified.
25823 * TODO: sendRequest should be promisified in the first place.
25824 */
25825 RequestBatcher.prototype.sendRequestPromise = function(data, options) {
25826 return new PromisePolyfill(_.bind(function(resolve) {
25827 this.sendRequest(data, options, resolve);
25828 }, this));
25829 };
25830
25831
25832 /**
25833 * Flush one batch to network. Depending on success/failure modes, it will either
25834 * remove the batch from the queue or leave it in for retry, and schedule the next
25835 * flush. In cases of most network or API failures, it will back off exponentially
25836 * when retrying.
25837 * @param {Object} [options]
25838 * @param {boolean} [options.sendBeacon] - whether to send batch with
25839 * navigator.sendBeacon (only useful for sending batches before page unloads, as
25840 * sendBeacon offers no callbacks or status indications)
25841 */
25842 RequestBatcher.prototype.flush = function(options) {
25843 if (this.requestInProgress) {
25844 logger$4.log('Flush: Request already in progress');
25845 return PromisePolyfill.resolve();
25846 }
25847
25848 this.requestInProgress = true;
25849
25850 options = options || {};
25851 var timeoutMS = this.libConfig['batch_request_timeout_ms'];
25852 var startTime = new Date().getTime();
25853 var currentBatchSize = this.batchSize;
25854
25855 return this.queue.fillBatch(currentBatchSize)
25856 .then(_.bind(function(batch) {
25857
25858 // if there's more items in the queue than the batch size, attempt
25859 // to flush again after the current batch is done.
25860 var attemptSecondaryFlush = batch.length === currentBatchSize;
25861 var dataForRequest = [];
25862 var transformedItems = {};
25863 _.each(batch, function(item) {
25864 var payload = item['payload'];
25865 if (this.beforeSendHook && !item.orphaned) {
25866 payload = this.beforeSendHook(payload);
25867 }
25868 if (payload) {
25869 // mp_sent_by_lib_version prop captures which lib version actually
25870 // sends each event (regardless of which version originally queued
25871 // it for sending)
25872 if (payload['event'] && payload['properties']) {
25873 payload['properties'] = _.extend(
25874 {},
25875 payload['properties'],
25876 {'mp_sent_by_lib_version': Config.LIB_VERSION}
25877 );
25878 }
25879 var addPayload = true;
25880 var itemId = item['id'];
25881 if (itemId) {
25882 if ((this.itemIdsSentSuccessfully[itemId] || 0) > 5) {
25883 this.reportError('[dupe] item ID sent too many times, not sending', {
25884 item: item,
25885 batchSize: batch.length,
25886 timesSent: this.itemIdsSentSuccessfully[itemId]
25887 });
25888 addPayload = false;
25889 }
25890 } else {
25891 this.reportError('[dupe] found item with no ID', {item: item});
25892 }
25893
25894 if (addPayload) {
25895 dataForRequest.push(payload);
25896 }
25897 }
25898 transformedItems[item['id']] = payload;
25899 }, this);
25900
25901 if (dataForRequest.length < 1) {
25902 this.requestInProgress = false;
25903 this.resetFlush();
25904 return PromisePolyfill.resolve(); // nothing to do
25905 }
25906
25907 var removeItemsFromQueue = _.bind(function () {
25908 return this.queue
25909 .removeItemsByID(
25910 _.map(batch, function (item) {
25911 return item['id'];
25912 })
25913 )
25914 .then(_.bind(function (succeeded) {
25915 // client-side dedupe
25916 _.each(batch, _.bind(function(item) {
25917 var itemId = item['id'];
25918 if (itemId) {
25919 this.itemIdsSentSuccessfully[itemId] = this.itemIdsSentSuccessfully[itemId] || 0;
25920 this.itemIdsSentSuccessfully[itemId]++;
25921 if (this.itemIdsSentSuccessfully[itemId] > 5) {
25922 this.reportError('[dupe] item ID sent too many times', {
25923 item: item,
25924 batchSize: batch.length,
25925 timesSent: this.itemIdsSentSuccessfully[itemId]
25926 });
25927 }
25928 } else {
25929 this.reportError('[dupe] found item with no ID while removing', {item: item});
25930 }
25931 }, this));
25932
25933 if (succeeded) {
25934 this.consecutiveRemovalFailures = 0;
25935 if (this.flushOnlyOnInterval && !attemptSecondaryFlush) {
25936 this.resetFlush(); // schedule next batch with a delay
25937 return PromisePolyfill.resolve();
25938 } else {
25939 return this.flush(); // handle next batch if the queue isn't empty
25940 }
25941 } else {
25942 if (++this.consecutiveRemovalFailures > 5) {
25943 this.reportError('Too many queue failures; disabling batching system.');
25944 this.stopAllBatching();
25945 } else {
25946 this.resetFlush();
25947 }
25948 return PromisePolyfill.resolve();
25949 }
25950 }, this));
25951 }, this);
25952
25953 var batchSendCallback = _.bind(function(res) {
25954 this.requestInProgress = false;
25955
25956 try {
25957
25958 // handle API response in a try-catch to make sure we can reset the
25959 // flush operation if something goes wrong
25960
25961 if (options.unloading) {
25962 // update persisted data to include hook transformations
25963 return this.queue.updatePayloads(transformedItems);
25964 } else if (
25965 _.isObject(res) &&
25966 res.error === 'timeout' &&
25967 new Date().getTime() - startTime >= timeoutMS
25968 ) {
25969 this.reportError('Network timeout; retrying');
25970 return this.flush();
25971 } else if (
25972 _.isObject(res) &&
25973 (
25974 res.httpStatusCode >= 500
25975 || res.httpStatusCode === 429
25976 || (res.httpStatusCode <= 0 && !isOnline())
25977 || res.error === 'timeout'
25978 )
25979 ) {
25980 // network or API error, or 429 Too Many Requests, retry
25981 var retryMS = this.flushInterval * 2;
25982 if (res.retryAfter) {
25983 retryMS = (parseInt(res.retryAfter, 10) * 1000) || retryMS;
25984 }
25985 retryMS = Math.min(MAX_RETRY_INTERVAL_MS, retryMS);
25986 this.reportError('Error; retry in ' + retryMS + ' ms');
25987 this.scheduleFlush(retryMS);
25988 return PromisePolyfill.resolve();
25989 } else if (_.isObject(res) && res.httpStatusCode === 413) {
25990 // 413 Payload Too Large
25991 if (batch.length > 1) {
25992 var halvedBatchSize = Math.max(1, Math.floor(currentBatchSize / 2));
25993 this.batchSize = Math.min(this.batchSize, halvedBatchSize, batch.length - 1);
25994 this.reportError('413 response; reducing batch size to ' + this.batchSize);
25995 this.resetFlush();
25996 return PromisePolyfill.resolve();
25997 } else {
25998 this.reportError('Single-event request too large; dropping', batch);
25999 this.resetBatchSize();
26000 return removeItemsFromQueue();
26001 }
26002 } else {
26003 // successful network request+response; remove each item in batch from queue
26004 // (even if it was e.g. a 400, in which case retrying won't help)
26005 return removeItemsFromQueue();
26006 }
26007 } catch(err) {
26008 this.reportError('Error handling API response', err);
26009 this.resetFlush();
26010 }
26011 }, this);
26012 var requestOptions = {
26013 method: 'POST',
26014 verbose: true,
26015 ignore_json_errors: true, // eslint-disable-line camelcase
26016 timeout_ms: timeoutMS // eslint-disable-line camelcase
26017 };
26018 if (options.unloading) {
26019 requestOptions.transport = 'sendBeacon';
26020 }
26021 logger$4.log('MIXPANEL REQUEST:', dataForRequest);
26022 return this.sendRequestPromise(dataForRequest, requestOptions).then(batchSendCallback);
26023 }, this))
26024 .catch(_.bind(function(err) {
26025 this.reportError('Error flushing request queue', err);
26026 this.resetFlush();
26027 }, this));
26028 };
26029
26030 /**
26031 * Log error to global logger and optional user-defined logger.
26032 */
26033 RequestBatcher.prototype.reportError = function(msg, err) {
26034 logger$4.error.apply(logger$4.error, arguments);
26035 if (this.errorReporter) {
26036 try {
26037 if (!(err instanceof Error)) {
26038 err = new Error(msg);
26039 }
26040 this.errorReporter(msg, err);
26041 } catch(err) {
26042 logger$4.error(err);
26043 }
26044 }
26045 };
26046
26047 /**
26048 * @param {import('./session-recording').SerializedRecording} serializedRecording
26049 * @returns {boolean}
26050 */
26051 var isRecordingExpired = function(serializedRecording) {
26052 var now = Date.now();
26053 return !serializedRecording || now > serializedRecording['maxExpires'] || now > serializedRecording['idleExpires'];
26054 };
26055
26056 var RECORD_ENQUEUE_THROTTLE_MS = 250;
26057
26058 var logger$3 = console_with_prefix('recorder');
26059 var CompressionStream = win['CompressionStream'];
26060
26061 var RECORDER_BATCHER_LIB_CONFIG = {
26062 'batch_size': 1000,
26063 'batch_flush_interval_ms': 10 * 1000,
26064 'batch_request_timeout_ms': 90 * 1000,
26065 'batch_autostart': true
26066 };
26067
26068 var ACTIVE_SOURCES = new Set([
26069 IncrementalSource.MouseMove,
26070 IncrementalSource.MouseInteraction,
26071 IncrementalSource.Scroll,
26072 IncrementalSource.ViewportResize,
26073 IncrementalSource.Input,
26074 IncrementalSource.TouchMove,
26075 IncrementalSource.MediaInteraction,
26076 IncrementalSource.Drag,
26077 IncrementalSource.Selection,
26078 ]);
26079
26080 function isUserEvent(ev) {
26081 return ev.type === EventType.IncrementalSnapshot && ACTIVE_SOURCES.has(ev.data.source);
26082 }
26083
26084 /**
26085 * @typedef {Object} SerializedRecording
26086 * @property {number} idleExpires
26087 * @property {number} maxExpires
26088 * @property {number} replayStartTime
26089 * @property {number} seqNo
26090 * @property {string} batchStartUrl
26091 * @property {string} replayId
26092 * @property {string} tabId
26093 * @property {string} replayStartUrl
26094 */
26095
26096 /**
26097 * @typedef {Object} SessionRecordingOptions
26098 * @property {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
26099 * @property {String} [options.replayId] - unique uuid for a single replay
26100 * @property {Function} [options.onIdleTimeout] - callback when a recording reaches idle timeout
26101 * @property {Function} [options.onMaxLengthReached] - callback when a recording reaches its maximum length
26102 * @property {Function} [options.rrwebRecord] - rrweb's `record` function
26103 * @property {Function} [options.onBatchSent] - callback when a batch of events is sent to the server
26104 * @property {Storage} [options.sharedLockStorage] - optional storage for shared lock, used for test dependency injection
26105 * optional properties for deserialization:
26106 * @property {number} idleExpires
26107 * @property {number} maxExpires
26108 * @property {number} replayStartTime
26109 * @property {number} seqNo
26110 * @property {string} batchStartUrl
26111 * @property {string} replayStartUrl
26112 */
26113
26114 /**
26115 * @typedef {Object} UserIdInfo
26116 * @property {string} distinct_id
26117 * @property {string} user_id
26118 * @property {string} device_id
26119 */
26120
26121
26122 /**
26123 * This class encapsulates a single session recording and its lifecycle.
26124 * @param {SessionRecordingOptions} options
26125 */
26126 var SessionRecording = function(options) {
26127 this._mixpanel = options.mixpanelInstance;
26128 this._onIdleTimeout = options.onIdleTimeout || NOOP_FUNC;
26129 this._onMaxLengthReached = options.onMaxLengthReached || NOOP_FUNC;
26130 this._onBatchSent = options.onBatchSent || NOOP_FUNC;
26131 this._rrwebRecord = options.rrwebRecord || null;
26132
26133 // internal rrweb stopRecording function
26134 this._stopRecording = null;
26135 this.replayId = options.replayId;
26136
26137 this.batchStartUrl = options.batchStartUrl || null;
26138 this.replayStartUrl = options.replayStartUrl || null;
26139 this.idleExpires = options.idleExpires || null;
26140 this.maxExpires = options.maxExpires || null;
26141 this.replayStartTime = options.replayStartTime || null;
26142 this.seqNo = options.seqNo || 0;
26143
26144 this.idleTimeoutId = null;
26145 this.maxTimeoutId = null;
26146
26147 this.recordMaxMs = MAX_RECORDING_MS;
26148 this.recordMinMs = 0;
26149
26150 // disable persistence if localStorage is not supported
26151 // request-queue will automatically disable persistence if indexedDB fails to initialize
26152 var usePersistence = localStorageSupported(options.sharedLockStorage, true) && !this.getConfig('disable_persistence');
26153
26154 // each replay has its own batcher key to avoid conflicts between rrweb events of different recordings
26155 this.batcherKey = '__mprec_' + this.getConfig('name') + '_' + this.getConfig('token') + '_' + this.replayId;
26156 this.queueStorage = new IDBStorageWrapper(RECORDING_EVENTS_STORE_NAME);
26157 this.batcher = new RequestBatcher(this.batcherKey, {
26158 errorReporter: this.reportError.bind(this),
26159 flushOnlyOnInterval: true,
26160 libConfig: RECORDER_BATCHER_LIB_CONFIG,
26161 sendRequestFunc: this.flushEventsWithOptOut.bind(this),
26162 queueStorage: this.queueStorage,
26163 sharedLockStorage: options.sharedLockStorage,
26164 usePersistence: usePersistence,
26165 stopAllBatchingFunc: this.stopRecording.bind(this),
26166
26167 // increased throttle and shared lock timeout because recording events are very high frequency.
26168 // this will minimize the amount of lock contention between enqueued events.
26169 // for session recordings there is a lock for each tab anyway, so there's no risk of deadlock between tabs.
26170 enqueueThrottleMs: RECORD_ENQUEUE_THROTTLE_MS,
26171 sharedLockTimeoutMS: 10 * 1000,
26172 });
26173 };
26174
26175 /**
26176 * @returns {UserIdInfo}
26177 */
26178 SessionRecording.prototype.getUserIdInfo = function () {
26179 if (this.finalFlushUserIdInfo) {
26180 return this.finalFlushUserIdInfo;
26181 }
26182
26183 var userIdInfo = {
26184 'distinct_id': String(this._mixpanel.get_distinct_id()),
26185 };
26186
26187 // send ID management props if they exist
26188 var deviceId = this._mixpanel.get_property('$device_id');
26189 if (deviceId) {
26190 userIdInfo['$device_id'] = deviceId;
26191 }
26192 var userId = this._mixpanel.get_property('$user_id');
26193 if (userId) {
26194 userIdInfo['$user_id'] = userId;
26195 }
26196 return userIdInfo;
26197 };
26198
26199 SessionRecording.prototype.unloadPersistedData = function () {
26200 this.batcher.stop();
26201 return this.batcher.flush()
26202 .then(function () {
26203 return this.queueStorage.removeItem(this.batcherKey);
26204 }.bind(this));
26205 };
26206
26207 SessionRecording.prototype.getConfig = function(configVar) {
26208 return this._mixpanel.get_config(configVar);
26209 };
26210
26211 // Alias for getConfig, used by the common addOptOutCheckMixpanelLib function which
26212 // reaches into this class instance and expects the snake case version of the function.
26213 // eslint-disable-next-line camelcase
26214 SessionRecording.prototype.get_config = function(configVar) {
26215 return this.getConfig(configVar);
26216 };
26217
26218 SessionRecording.prototype.startRecording = function (shouldStopBatcher) {
26219 if (this._rrwebRecord === null) {
26220 this.reportError('rrweb record function not provided. ');
26221 return;
26222 }
26223
26224 if (this._stopRecording !== null) {
26225 logger$3.log('Recording already in progress, skipping startRecording.');
26226 return;
26227 }
26228
26229 this.recordMaxMs = this.getConfig('record_max_ms');
26230 if (this.recordMaxMs > MAX_RECORDING_MS) {
26231 this.recordMaxMs = MAX_RECORDING_MS;
26232 logger$3.critical('record_max_ms cannot be greater than ' + MAX_RECORDING_MS + 'ms. Capping value.');
26233 }
26234
26235 if (!this.maxExpires) {
26236 this.maxExpires = new Date().getTime() + this.recordMaxMs;
26237 }
26238
26239 this.recordMinMs = this.getConfig('record_min_ms');
26240 if (this.recordMinMs > MAX_VALUE_FOR_MIN_RECORDING_MS) {
26241 this.recordMinMs = MAX_VALUE_FOR_MIN_RECORDING_MS;
26242 logger$3.critical('record_min_ms cannot be greater than ' + MAX_VALUE_FOR_MIN_RECORDING_MS + 'ms. Capping value.');
26243 }
26244
26245 if (!this.replayStartTime) {
26246 this.replayStartTime = new Date().getTime();
26247 this.batchStartUrl = _.info.currentUrl();
26248 this.replayStartUrl = _.info.currentUrl();
26249 }
26250
26251 if (shouldStopBatcher || this.recordMinMs > 0) {
26252 // the primary case for shouldStopBatcher is when we're starting recording after a reset
26253 // and don't want to send anything over the network until there's
26254 // actual user activity
26255 // this also applies if the minimum recording length has not been hit yet
26256 // so that we don't send data until we know the recording will be long enough
26257 this.batcher.stop();
26258 } else {
26259 this.batcher.start();
26260 }
26261
26262 var resetIdleTimeout = function () {
26263 clearTimeout(this.idleTimeoutId);
26264 var idleTimeoutMs = this.getConfig('record_idle_timeout_ms');
26265 this.idleTimeoutId = setTimeout(this._onIdleTimeout, idleTimeoutMs);
26266 this.idleExpires = new Date().getTime() + idleTimeoutMs;
26267 }.bind(this);
26268 resetIdleTimeout();
26269
26270 var blockSelector = this.getConfig('record_block_selector');
26271 if (blockSelector === '' || blockSelector === null) {
26272 blockSelector = undefined;
26273 }
26274
26275 try {
26276 this._stopRecording = this._rrwebRecord({
26277 'emit': function (ev) {
26278 if (this.idleExpires && this.idleExpires < ev.timestamp) {
26279 this._onIdleTimeout();
26280 return;
26281 }
26282 if (isUserEvent(ev)) {
26283 if (this.batcher.stopped && new Date().getTime() - this.replayStartTime >= this.recordMinMs) {
26284 // start flushing again after user activity
26285 this.batcher.start();
26286 }
26287 resetIdleTimeout();
26288 }
26289 // promise only used to await during tests
26290 this.__enqueuePromise = this.batcher.enqueue(ev);
26291 }.bind(this),
26292 'blockClass': this.getConfig('record_block_class'),
26293 'blockSelector': blockSelector,
26294 'collectFonts': this.getConfig('record_collect_fonts'),
26295 'dataURLOptions': { // canvas image options (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL)
26296 'type': 'image/webp',
26297 'quality': 0.6
26298 },
26299 'maskAllInputs': true,
26300 'maskTextClass': this.getConfig('record_mask_text_class'),
26301 'maskTextSelector': this.getConfig('record_mask_text_selector'),
26302 'recordCanvas': this.getConfig('record_canvas'),
26303 'sampling': {
26304 'canvas': 15
26305 }
26306 });
26307 } catch (err) {
26308 this.reportError('Unexpected error when starting rrweb recording.', err);
26309 }
26310
26311 if (typeof this._stopRecording !== 'function') {
26312 this.reportError('rrweb failed to start, skipping this recording.');
26313 this._stopRecording = null;
26314 this.stopRecording(); // stop batcher looping and any timeouts
26315 return;
26316 }
26317
26318 var maxTimeoutMs = this.maxExpires - new Date().getTime();
26319 this.maxTimeoutId = setTimeout(this._onMaxLengthReached.bind(this), maxTimeoutMs);
26320 };
26321
26322 SessionRecording.prototype.stopRecording = function (skipFlush) {
26323 // store the user ID info in case this is getting called in mixpanel.reset()
26324 this.finalFlushUserIdInfo = this.getUserIdInfo();
26325
26326 if (!this.isRrwebStopped()) {
26327 try {
26328 this._stopRecording();
26329 } catch (err) {
26330 this.reportError('Error with rrweb stopRecording', err);
26331 }
26332 this._stopRecording = null;
26333 }
26334
26335 var flushPromise;
26336 if (this.batcher.stopped) {
26337 // never got user activity to flush after reset, so just clear the batcher
26338 flushPromise = this.batcher.clear();
26339 } else if (!skipFlush) {
26340 // flush any remaining events from running batcher
26341 flushPromise = this.batcher.flush();
26342 }
26343 this.batcher.stop();
26344
26345 clearTimeout(this.idleTimeoutId);
26346 clearTimeout(this.maxTimeoutId);
26347 return flushPromise;
26348 };
26349
26350 SessionRecording.prototype.isRrwebStopped = function () {
26351 return this._stopRecording === null;
26352 };
26353
26354
26355 /**
26356 * Flushes the current batch of events to the server, but passes an opt-out callback to make sure
26357 * we stop recording and dump any queued events if the user has opted out.
26358 */
26359 SessionRecording.prototype.flushEventsWithOptOut = function (data, options, cb) {
26360 var onOptOut = function (code) {
26361 // addOptOutCheckMixpanelLib invokes this function with code=0 when the user has opted out
26362 if (code === 0) {
26363 this.stopRecording();
26364 cb({error: 'Tracking has been opted out, stopping recording.'});
26365 }
26366 }.bind(this);
26367
26368 this._flushEvents(data, options, cb, onOptOut);
26369 };
26370
26371 /**
26372 * @returns {SerializedRecording}
26373 */
26374 SessionRecording.prototype.serialize = function () {
26375 // don't break if mixpanel instance was destroyed at some point
26376 var tabId;
26377 try {
26378 tabId = this._mixpanel.get_tab_id();
26379 } catch (e) {
26380 this.reportError('Error getting tab ID for serialization ', e);
26381 tabId = null;
26382 }
26383
26384 return {
26385 'replayId': this.replayId,
26386 'seqNo': this.seqNo,
26387 'replayStartTime': this.replayStartTime,
26388 'batchStartUrl': this.batchStartUrl,
26389 'replayStartUrl': this.replayStartUrl,
26390 'idleExpires': this.idleExpires,
26391 'maxExpires': this.maxExpires,
26392 'tabId': tabId,
26393 };
26394 };
26395
26396
26397 /**
26398 * @static
26399 * @param {SerializedRecording} serializedRecording
26400 * @param {SessionRecordingOptions} options
26401 * @returns {SessionRecording}
26402 */
26403 SessionRecording.deserialize = function (serializedRecording, options) {
26404 var recording = new SessionRecording(_.extend({}, options, {
26405 replayId: serializedRecording['replayId'],
26406 batchStartUrl: serializedRecording['batchStartUrl'],
26407 replayStartUrl: serializedRecording['replayStartUrl'],
26408 idleExpires: serializedRecording['idleExpires'],
26409 maxExpires: serializedRecording['maxExpires'],
26410 replayStartTime: serializedRecording['replayStartTime'],
26411 seqNo: serializedRecording['seqNo'],
26412 sharedLockStorage: options.sharedLockStorage,
26413 }));
26414
26415 return recording;
26416 };
26417
26418 SessionRecording.prototype._sendRequest = function(currentReplayId, reqParams, reqBody, callback) {
26419 var onSuccess = function (response, responseBody) {
26420 // Update batch specific props only if the request was successful to guarantee ordering.
26421 // RequestBatcher will always flush the next batch after the previous one succeeds.
26422 // extra check to see if the replay ID has changed so that we don't increment the seqNo on the wrong replay
26423 if (response.status === 200 && this.replayId === currentReplayId) {
26424 this.seqNo++;
26425 this.batchStartUrl = _.info.currentUrl();
26426 }
26427
26428 this._onBatchSent();
26429 callback({
26430 status: 0,
26431 httpStatusCode: response.status,
26432 responseBody: responseBody,
26433 retryAfter: response.headers.get('Retry-After')
26434 });
26435 }.bind(this);
26436 var apiHost = (this._mixpanel.get_api_host && this._mixpanel.get_api_host('record')) || this.getConfig('api_host');
26437 win['fetch'](apiHost + '/' + this.getConfig('api_routes')['record'] + '?' + new URLSearchParams(reqParams), {
26438 'method': 'POST',
26439 'headers': {
26440 'Authorization': 'Basic ' + btoa(this.getConfig('token') + ':'),
26441 'Content-Type': 'application/octet-stream'
26442 },
26443 'body': reqBody,
26444 }).then(function (response) {
26445 response.json().then(function (responseBody) {
26446 onSuccess(response, responseBody);
26447 }).catch(function (error) {
26448 callback({error: error});
26449 });
26450 }).catch(function (error) {
26451 callback({error: error, httpStatusCode: 0});
26452 });
26453 };
26454
26455 SessionRecording.prototype._flushEvents = addOptOutCheckMixpanelLib(function (data, options, callback) {
26456 var numEvents = data.length;
26457
26458 if (numEvents > 0) {
26459 var replayId = this.replayId;
26460
26461 // each rrweb event has a timestamp - leverage those to get time properties
26462 var batchStartTime = Infinity;
26463 var batchEndTime = -Infinity;
26464 var hasFullSnapshot = false;
26465 for (var i = 0; i < numEvents; i++) {
26466 batchStartTime = Math.min(batchStartTime, data[i].timestamp);
26467 batchEndTime = Math.max(batchEndTime, data[i].timestamp);
26468 if (data[i].type === EventType.FullSnapshot) {
26469 hasFullSnapshot = true;
26470 }
26471 }
26472
26473 if (this.seqNo === 0) {
26474 if (!hasFullSnapshot) {
26475 callback({error: 'First batch does not contain a full snapshot. Aborting recording.'});
26476 this.stopRecording(true);
26477 return;
26478 }
26479 this.replayStartTime = batchStartTime;
26480 } else if (!this.replayStartTime) {
26481 this.reportError('Replay start time not set but seqNo is not 0. Using current batch start time as a fallback.');
26482 this.replayStartTime = batchStartTime;
26483 }
26484
26485 var replayLengthMs = batchEndTime - this.replayStartTime;
26486
26487 var reqParams = {
26488 '$current_url': this.batchStartUrl,
26489 '$lib_version': Config.LIB_VERSION,
26490 'batch_start_time': batchStartTime / 1000,
26491 'mp_lib': 'web',
26492 'replay_id': replayId,
26493 'replay_length_ms': replayLengthMs,
26494 'replay_start_time': this.replayStartTime / 1000,
26495 'replay_start_url': this.replayStartUrl,
26496 'seq': this.seqNo
26497 };
26498 var eventsJson = JSON.stringify(data);
26499 Object.assign(reqParams, this.getUserIdInfo());
26500
26501 if (CompressionStream) {
26502 var jsonStream = new Blob([eventsJson], {type: 'application/json'}).stream();
26503 var gzipStream = jsonStream.pipeThrough(new CompressionStream('gzip'));
26504 new Response(gzipStream)
26505 .blob()
26506 .then(function(compressedBlob) {
26507 reqParams['format'] = 'gzip';
26508 this._sendRequest(replayId, reqParams, compressedBlob, callback);
26509 }.bind(this));
26510 } else {
26511 reqParams['format'] = 'body';
26512 this._sendRequest(replayId, reqParams, eventsJson, callback);
26513 }
26514 }
26515 });
26516
26517
26518 SessionRecording.prototype.reportError = function(msg, err) {
26519 logger$3.error.apply(logger$3.error, arguments);
26520 try {
26521 if (!err && !(msg instanceof Error)) {
26522 msg = new Error(msg);
26523 }
26524 this.getConfig('error_reporter')(msg, err);
26525 } catch(err) {
26526 logger$3.error(err);
26527 }
26528 };
26529
26530 /**
26531 * Module for handling the storage and retrieval of recording metadata as well as any active recordings.
26532 * Makes sure that only one tab can be recording at a time.
26533 */
26534 var RecordingRegistry = function (options) {
26535 /** @type {IDBStorageWrapper} */
26536 this.idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
26537 this.errorReporter = options.errorReporter;
26538 this.mixpanelInstance = options.mixpanelInstance;
26539 this.sharedLockStorage = options.sharedLockStorage;
26540 };
26541
26542 RecordingRegistry.prototype.isPersistenceEnabled = function() {
26543 return !this.mixpanelInstance.get_config('disable_persistence');
26544 };
26545
26546 RecordingRegistry.prototype.handleError = function (err) {
26547 this.errorReporter('IndexedDB error: ', err);
26548 };
26549
26550 /**
26551 * @param {import('./session-recording').SerializedRecording} serializedRecording
26552 */
26553 RecordingRegistry.prototype.setActiveRecording = function (serializedRecording) {
26554 if (!this.isPersistenceEnabled()) {
26555 return PromisePolyfill.resolve();
26556 }
26557
26558 var tabId = serializedRecording['tabId'];
26559 if (!tabId) {
26560 console.warn('No tab ID is set, cannot persist recording metadata.');
26561 return PromisePolyfill.resolve();
26562 }
26563
26564 return this.idb.init()
26565 .then(function () {
26566 return this.idb.setItem(tabId, serializedRecording);
26567 }.bind(this))
26568 .catch(this.handleError.bind(this));
26569 };
26570
26571 /**
26572 * @returns {Promise<import('./session-recording').SerializedRecording>}
26573 */
26574 RecordingRegistry.prototype.getActiveRecording = function () {
26575 if (!this.isPersistenceEnabled()) {
26576 return PromisePolyfill.resolve(null);
26577 }
26578
26579 return this.idb.init()
26580 .then(function () {
26581 return this.idb.getItem(this.mixpanelInstance.get_tab_id());
26582 }.bind(this))
26583 .then(function (serializedRecording) {
26584 return isRecordingExpired(serializedRecording) ? null : serializedRecording;
26585 }.bind(this))
26586 .catch(this.handleError.bind(this));
26587 };
26588
26589 RecordingRegistry.prototype.clearActiveRecording = function () {
26590 if (this.isPersistenceEnabled()) {
26591 // mark recording as expired instead of deleting it in case the page unloads mid-flush and doesn't make it to ingestion.
26592 // this will ensure the next pageload will flush the remaining events, but not try to continue the recording.
26593 return this.markActiveRecordingExpired();
26594 } else {
26595 return this.deleteActiveRecording();
26596 }
26597 };
26598
26599 RecordingRegistry.prototype.markActiveRecordingExpired = function () {
26600 return this.getActiveRecording()
26601 .then(function (serializedRecording) {
26602 if (serializedRecording) {
26603 serializedRecording['maxExpires'] = 0;
26604 return this.setActiveRecording(serializedRecording);
26605 }
26606 }.bind(this))
26607 .catch(this.handleError.bind(this));
26608 };
26609
26610 RecordingRegistry.prototype.deleteActiveRecording = function () {
26611 // avoid initializing IDB if this registry instance hasn't already written a recording
26612 if (this.idb.isInitialized()) {
26613 return this.idb.removeItem(this.mixpanelInstance.get_tab_id())
26614 .catch(this.handleError.bind(this));
26615 } else {
26616 return PromisePolyfill.resolve();
26617 }
26618 };
26619
26620 /**
26621 * Flush any inactive recordings from the registry to minimize data loss.
26622 * The main idea here is that we can flush remaining rrweb events on the next page load if a tab is closed mid-batch.
26623 */
26624 RecordingRegistry.prototype.flushInactiveRecordings = function () {
26625 if (!this.isPersistenceEnabled()) {
26626 return PromisePolyfill.resolve([]);
26627 }
26628
26629 return this.idb.init()
26630 .then(function() {
26631 return this.idb.getAll();
26632 }.bind(this))
26633 .then(function (serializedRecordings) {
26634 // clean up any expired recordings from the registry, non-expired ones may be active in other tabs
26635 var unloadPromises = serializedRecordings
26636 .filter(function (serializedRecording) {
26637 return isRecordingExpired(serializedRecording);
26638 })
26639 .map(function (serializedRecording) {
26640 var sessionRecording = SessionRecording.deserialize(serializedRecording, {
26641 mixpanelInstance: this.mixpanelInstance,
26642 sharedLockStorage: this.sharedLockStorage
26643 });
26644 return sessionRecording.unloadPersistedData()
26645 .then(function () {
26646 // expired recording was successfully flushed, we can clean it up from the registry
26647 return this.idb.removeItem(serializedRecording['tabId']);
26648 }.bind(this))
26649 .catch(this.handleError.bind(this));
26650 }.bind(this));
26651
26652 return PromisePolyfill.all(unloadPromises);
26653 }.bind(this))
26654 .catch(this.handleError.bind(this));
26655 };
26656
26657 var logger$2 = console_with_prefix('recorder');
26658
26659 /**
26660 * Recorder API: bundles rrweb and and exposes methods to start and stop recordings.
26661 * @param {Object} [options.mixpanelInstance] - reference to the core MixpanelLib
26662 */
26663 var MixpanelRecorder = function(mixpanelInstance, rrwebRecord, sharedLockStorage) {
26664 this.mixpanelInstance = mixpanelInstance;
26665 this.rrwebRecord = rrwebRecord || record;
26666 this.sharedLockStorage = sharedLockStorage;
26667
26668 /**
26669 * @member {import('./registry').RecordingRegistry}
26670 */
26671 this.recordingRegistry = new RecordingRegistry({
26672 mixpanelInstance: this.mixpanelInstance,
26673 errorReporter: logger$2.error,
26674 sharedLockStorage: sharedLockStorage
26675 });
26676 this._flushInactivePromise = this.recordingRegistry.flushInactiveRecordings();
26677
26678 this.activeRecording = null;
26679 this.stopRecordingInProgress = false;
26680 };
26681
26682 MixpanelRecorder.prototype.startRecording = function(options) {
26683 options = options || {};
26684 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
26685 logger$2.log('Recording already in progress, skipping startRecording.');
26686 return;
26687 }
26688
26689 var onIdleTimeout = function () {
26690 logger$2.log('Idle timeout reached, restarting recording.');
26691 this.resetRecording();
26692 }.bind(this);
26693
26694 var onMaxLengthReached = function () {
26695 logger$2.log('Max recording length reached, stopping recording.');
26696 this.resetRecording();
26697 }.bind(this);
26698
26699 var onBatchSent = function () {
26700 this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
26701 this['__flushPromise'] = this.activeRecording.batcher._flushPromise;
26702 }.bind(this);
26703
26704 /**
26705 * @type {import('./session-recording').SessionRecordingOptions}
26706 */
26707 var sessionRecordingOptions = {
26708 mixpanelInstance: this.mixpanelInstance,
26709 onBatchSent: onBatchSent,
26710 onIdleTimeout: onIdleTimeout,
26711 onMaxLengthReached: onMaxLengthReached,
26712 replayId: _.UUID(),
26713 rrwebRecord: this.rrwebRecord,
26714 sharedLockStorage: this.sharedLockStorage
26715 };
26716
26717 if (options.activeSerializedRecording) {
26718 this.activeRecording = SessionRecording.deserialize(options.activeSerializedRecording, sessionRecordingOptions);
26719 } else {
26720 this.activeRecording = new SessionRecording(sessionRecordingOptions);
26721 }
26722
26723 this.activeRecording.startRecording(options.shouldStopBatcher);
26724 return this.recordingRegistry.setActiveRecording(this.activeRecording.serialize());
26725 };
26726
26727 MixpanelRecorder.prototype.stopRecording = function() {
26728 // Prevents activeSerializedRecording from being reused when stopping the recording.
26729 this.stopRecordingInProgress = true;
26730 return this._stopCurrentRecording(false, true).then(function() {
26731 return this.recordingRegistry.clearActiveRecording();
26732 }.bind(this)).then(function() {
26733 this.stopRecordingInProgress = false;
26734 }.bind(this));
26735 };
26736
26737 MixpanelRecorder.prototype.pauseRecording = function() {
26738 return this._stopCurrentRecording(false);
26739 };
26740
26741 MixpanelRecorder.prototype._stopCurrentRecording = function(skipFlush, disableActiveRecording) {
26742 if (this.activeRecording) {
26743 var stopRecordingPromise = this.activeRecording.stopRecording(skipFlush);
26744 if (disableActiveRecording) {
26745 this.activeRecording = null;
26746 }
26747 return stopRecordingPromise;
26748 }
26749 return PromisePolyfill.resolve();
26750 };
26751
26752 MixpanelRecorder.prototype.resumeRecording = function (startNewIfInactive) {
26753 if (this.activeRecording && this.activeRecording.isRrwebStopped()) {
26754 this.activeRecording.startRecording(false);
26755 return PromisePolyfill.resolve(null);
26756 }
26757
26758 return this.recordingRegistry.getActiveRecording()
26759 .then(function (activeSerializedRecording) {
26760 if (activeSerializedRecording && !this.stopRecordingInProgress) {
26761 return this.startRecording({activeSerializedRecording: activeSerializedRecording});
26762 } else if (startNewIfInactive) {
26763 return this.startRecording({shouldStopBatcher: false});
26764 } else {
26765 logger$2.log('No resumable recording found.');
26766 return null;
26767 }
26768 }.bind(this));
26769 };
26770
26771
26772 MixpanelRecorder.prototype.resetRecording = function () {
26773 this.stopRecording();
26774 this.startRecording({shouldStopBatcher: true});
26775 };
26776
26777 MixpanelRecorder.prototype.getActiveReplayId = function () {
26778 if (this.activeRecording && !this.activeRecording.isRrwebStopped()) {
26779 return this.activeRecording.replayId;
26780 } else {
26781 return null;
26782 }
26783 };
26784
26785 // getter so that older mixpanel-core versions can still retrieve the replay ID
26786 // when pulling the latest recorder bundle from the CDN
26787 Object.defineProperty(MixpanelRecorder.prototype, 'replayId', {
26788 get: function () {
26789 return this.getActiveReplayId();
26790 }
26791 });
26792
26793 win['__mp_recorder'] = MixpanelRecorder;
26794
26795 // stateless utils
26796 // mostly from https://github.com/mixpanel/mixpanel-js/blob/989ada50f518edab47b9c4fd9535f9fbd5ec5fc0/src/autotrack-utils.js
26797
26798
26799 var EV_CHANGE = 'change';
26800 var EV_CLICK = 'click';
26801 var EV_HASHCHANGE = 'hashchange';
26802 var EV_INPUT = 'input';
26803 var EV_LOAD = 'load';
26804 var EV_MP_LOCATION_CHANGE = 'mp_locationchange';
26805 var EV_POPSTATE = 'popstate';
26806 // TODO scrollend isn't available in Safari: document or polyfill?
26807 var EV_SCROLLEND = 'scrollend';
26808 var EV_SCROLL = 'scroll';
26809 var EV_SELECT = 'select';
26810 var EV_SUBMIT = 'submit';
26811 var EV_TOGGLE = 'toggle';
26812 var EV_VISIBILITYCHANGE = 'visibilitychange';
26813
26814 var CLICK_EVENT_PROPS = [
26815 'clientX', 'clientY',
26816 'offsetX', 'offsetY',
26817 'pageX', 'pageY',
26818 'screenX', 'screenY',
26819 'x', 'y'
26820 ];
26821 var OPT_IN_CLASSES = ['mp-include'];
26822 var OPT_OUT_CLASSES = ['mp-no-track'];
26823 var SENSITIVE_DATA_CLASSES = OPT_OUT_CLASSES.concat(['mp-sensitive']);
26824 var TRACKED_ATTRS = [
26825 'aria-label', 'aria-labelledby', 'aria-describedby',
26826 'href', 'name', 'role', 'title', 'type'
26827 ];
26828
26829 var INTERACTIVE_ARIA_ROLES = {
26830 'button': true,
26831 'checkbox': true,
26832 'combobox': true,
26833 'grid': true,
26834 'link': true,
26835 'listbox': true,
26836 'menu': true,
26837 'menubar': true,
26838 'menuitem': true,
26839 'menuitemcheckbox': true,
26840 'menuitemradio': true,
26841 'navigation': true,
26842 'option': true,
26843 'radio': true,
26844 'radiogroup': true,
26845 'searchbox': true,
26846 'slider': true,
26847 'spinbutton': true,
26848 'switch': true,
26849 'tab': true,
26850 'tablist': true,
26851 'textbox': true,
26852 'tree': true,
26853 'treegrid': true,
26854 'treeitem': true
26855 };
26856
26857 var ALWAYS_NON_INTERACTIVE_TAGS = {
26858 // Document metadata
26859 'base': true,
26860 'head': true,
26861 'html': true,
26862 'link': true,
26863 'meta': true,
26864 'script': true,
26865 'style': true,
26866 'title': true,
26867 // Text formatting
26868 'br': true,
26869 'hr': true,
26870 'wbr': true,
26871 // Other
26872 'noscript': true,
26873 'picture': true,
26874 'source': true,
26875 'template': true,
26876 'track': true
26877 };
26878
26879 // Common container tags that need additional checks
26880 var TEXT_CONTAINER_TAGS = {
26881 'article': true,
26882 'div': true,
26883 'h1': true,
26884 'h2': true,
26885 'h3': true,
26886 'h4': true,
26887 'h5': true,
26888 'h6': true,
26889 'p': true,
26890 'section': true,
26891 'span': true
26892 };
26893
26894 var EVENT_HANDLER_ATTRIBUTES = [
26895 'onclick', 'onmousedown', 'onmouseup', 'onpointerdown', 'onpointerup', 'ontouchend', 'ontouchstart'
26896 ];
26897
26898 var MAX_DEPTH = 5;
26899
26900 var logger$1 = console_with_prefix('autocapture');
26901
26902
26903 function getClasses(el) {
26904 var classes = {};
26905 var classList = getClassName(el).split(' ');
26906 for (var i = 0; i < classList.length; i++) {
26907 var cls = classList[i];
26908 if (cls) {
26909 classes[cls] = true;
26910 }
26911 }
26912 return classes;
26913 }
26914
26915 /*
26916 * Get the className of an element, accounting for edge cases where element.className is an object
26917 * @param {Element} el - element to get the className of
26918 * @returns {string} the element's class
26919 */
26920 function getClassName(el) {
26921 switch(typeof el.className) {
26922 case 'string':
26923 return el.className;
26924 case 'object': // handle cases where className might be SVGAnimatedString or some other type
26925 return el.className.baseVal || el.getAttribute('class') || '';
26926 default: // future proof
26927 return '';
26928 }
26929 }
26930
26931 function getPreviousElementSibling(el) {
26932 if (el.previousElementSibling) {
26933 return el.previousElementSibling;
26934 } else {
26935 do {
26936 el = el.previousSibling;
26937 } while (el && !isElementNode(el));
26938 return el;
26939 }
26940 }
26941
26942 function getPropertiesFromElement(el, ev, blockAttrsSet, extraAttrs, allowElementCallback, allowSelectors) {
26943 var props = {
26944 '$classes': getClassName(el).split(' '),
26945 '$tag_name': el.tagName.toLowerCase()
26946 };
26947 var elId = el.id;
26948 if (elId) {
26949 props['$id'] = elId;
26950 }
26951
26952 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors)) {
26953 _.each(TRACKED_ATTRS.concat(extraAttrs), function(attr) {
26954 if (el.hasAttribute(attr) && !blockAttrsSet[attr]) {
26955 var attrVal = el.getAttribute(attr);
26956 if (shouldTrackValue(attrVal)) {
26957 props['$attr-' + attr] = attrVal;
26958 }
26959 }
26960 });
26961 }
26962
26963 var nthChild = 1;
26964 var nthOfType = 1;
26965 var currentElem = el;
26966 while (currentElem = getPreviousElementSibling(currentElem)) { // eslint-disable-line no-cond-assign
26967 nthChild++;
26968 if (currentElem.tagName === el.tagName) {
26969 nthOfType++;
26970 }
26971 }
26972 props['$nth_child'] = nthChild;
26973 props['$nth_of_type'] = nthOfType;
26974
26975 return props;
26976 }
26977
26978 function getPropsForDOMEvent(ev, config) {
26979 var allowElementCallback = config.allowElementCallback;
26980 var allowSelectors = config.allowSelectors || [];
26981 var blockAttrs = config.blockAttrs || [];
26982 var blockElementCallback = config.blockElementCallback;
26983 var blockSelectors = config.blockSelectors || [];
26984 var captureTextContent = config.captureTextContent || false;
26985 var captureExtraAttrs = config.captureExtraAttrs || [];
26986 var capturedForHeatMap = config.capturedForHeatMap || false;
26987
26988 // convert array to set every time, as the config may have changed
26989 var blockAttrsSet = {};
26990 _.each(blockAttrs, function(attr) {
26991 blockAttrsSet[attr] = true;
26992 });
26993
26994 var props = null;
26995
26996 var target = typeof ev.target === 'undefined' ? ev.srcElement : ev.target;
26997 if (isTextNode(target)) { // defeat Safari bug (see: http://www.quirksmode.org/js/events_properties.html)
26998 target = target.parentNode;
26999 }
27000
27001 if (
27002 shouldTrackDomEvent(target, ev) &&
27003 isElementAllowed(target, ev, allowElementCallback, allowSelectors) &&
27004 !isElementBlocked(target, ev, blockElementCallback, blockSelectors)
27005 ) {
27006 var targetElementList = [target];
27007 var curEl = target;
27008 while (curEl.parentNode && !isTag(curEl, 'body')) {
27009 targetElementList.push(curEl.parentNode);
27010 curEl = curEl.parentNode;
27011 }
27012
27013 var elementsJson = [];
27014 var href, explicitNoTrack = false;
27015 _.each(targetElementList, function(el) {
27016 var shouldTrackDetails = shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors);
27017
27018 // if the element or a parent element is an anchor tag
27019 // include the href as a property
27020 if (!blockAttrsSet['href'] && el.tagName.toLowerCase() === 'a') {
27021 href = el.getAttribute('href');
27022 href = shouldTrackDetails && shouldTrackValue(href) && href;
27023 }
27024
27025 if (isElementBlocked(el, ev, blockElementCallback, blockSelectors)) {
27026 explicitNoTrack = true;
27027 }
27028
27029 elementsJson.push(getPropertiesFromElement(el, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors));
27030 }, this);
27031
27032 if (!explicitNoTrack) {
27033 var docElement = document$1['documentElement'];
27034 props = {
27035 '$event_type': ev.type,
27036 '$host': win.location.host,
27037 '$pathname': win.location.pathname,
27038 '$elements': elementsJson,
27039 '$el_attr__href': href,
27040 '$viewportHeight': Math.max(docElement['clientHeight'], win['innerHeight'] || 0),
27041 '$viewportWidth': Math.max(docElement['clientWidth'], win['innerWidth'] || 0),
27042 '$pageHeight': document$1['body']['offsetHeight'] || 0,
27043 '$pageWidth': document$1['body']['offsetWidth'] || 0,
27044 };
27045 _.each(captureExtraAttrs, function(attr) {
27046 if (!blockAttrsSet[attr] && target.hasAttribute(attr)) {
27047 var attrVal = target.getAttribute(attr);
27048 if (shouldTrackValue(attrVal)) {
27049 props['$el_attr__' + attr] = attrVal;
27050 }
27051 }
27052 });
27053
27054 if (captureTextContent) {
27055 elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
27056 if (elementText && elementText.length) {
27057 props['$el_text'] = elementText;
27058 }
27059 }
27060
27061 if (ev.type === EV_CLICK) {
27062 _.each(CLICK_EVENT_PROPS, function(prop) {
27063 if (prop in ev) {
27064 props['$' + prop] = ev[prop];
27065 }
27066 });
27067 if (capturedForHeatMap) {
27068 props['$captured_for_heatmap'] = true;
27069 }
27070 target = guessRealClickTarget(ev);
27071 }
27072 // prioritize text content from "real" click target if different from original target
27073 if (captureTextContent) {
27074 var elementText = getSafeText(target, ev, allowElementCallback, allowSelectors);
27075 if (elementText && elementText.length) {
27076 props['$el_text'] = elementText;
27077 }
27078 }
27079
27080 if (target) {
27081 // target may have been recalculated; check allowlists and blocklists again
27082 if (
27083 !isElementAllowed(target, ev, allowElementCallback, allowSelectors) ||
27084 isElementBlocked(target, ev, blockElementCallback, blockSelectors)
27085 ) {
27086 return null;
27087 }
27088
27089 var targetProps = getPropertiesFromElement(target, ev, blockAttrsSet, captureExtraAttrs, allowElementCallback, allowSelectors);
27090 props['$target'] = targetProps;
27091 // pull up more props onto main event props
27092 props['$el_classes'] = targetProps['$classes'];
27093 _.extend(props, _.strip_empty_properties({
27094 '$el_id': targetProps['$id'],
27095 '$el_tag_name': targetProps['$tag_name']
27096 }));
27097 }
27098 }
27099 }
27100
27101 return props;
27102 }
27103
27104
27105 /**
27106 * Get the direct text content of an element, protecting against sensitive data collection.
27107 * Concats textContent of each of the element's text node children; this avoids potential
27108 * collection of sensitive data that could happen if we used element.textContent and the
27109 * element had sensitive child elements, since element.textContent includes child content.
27110 * Scrubs values that look like they could be sensitive (i.e. cc or ssn number).
27111 * @param {Element} el - element to get the text of
27112 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
27113 * @returns {string} the element's direct text content
27114 */
27115 function getSafeText(el, ev, allowElementCallback, allowSelectors) {
27116 var elText = '';
27117
27118 if (shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) && el.childNodes && el.childNodes.length) {
27119 _.each(el.childNodes, function(child) {
27120 if (isTextNode(child) && child.textContent) {
27121 elText += _.trim(child.textContent)
27122 // scrub potentially sensitive values
27123 .split(/(\s+)/).filter(shouldTrackValue).join('')
27124 // normalize whitespace
27125 .replace(/[\r\n]/g, ' ').replace(/[ ]+/g, ' ')
27126 // truncate
27127 .substring(0, 255);
27128 }
27129 });
27130 }
27131
27132 return _.trim(elText);
27133 }
27134
27135 function guessRealClickTarget(ev) {
27136 var target = ev.target;
27137 var composedPath = ev['composedPath']();
27138 for (var i = 0; i < composedPath.length; i++) {
27139 var node = composedPath[i];
27140 if (
27141 isTag(node, 'a') ||
27142 isTag(node, 'button') ||
27143 isTag(node, 'input') ||
27144 isTag(node, 'select') ||
27145 (node.getAttribute && node.getAttribute('role') === 'button')
27146 ) {
27147 target = node;
27148 break;
27149 }
27150 if (node === target) {
27151 break;
27152 }
27153 }
27154 return target;
27155 }
27156
27157 function isElementAllowed(el, ev, allowElementCallback, allowSelectors) {
27158 if (allowElementCallback) {
27159 try {
27160 if (!allowElementCallback(el, ev)) {
27161 return false;
27162 }
27163 } catch (err) {
27164 logger$1.critical('Error while checking element in allowElementCallback', err);
27165 return false;
27166 }
27167 }
27168
27169 if (!allowSelectors.length) {
27170 // no allowlist; all elements are fair game
27171 return true;
27172 }
27173
27174 for (var i = 0; i < allowSelectors.length; i++) {
27175 var sel = allowSelectors[i];
27176 try {
27177 if (el['matches'](sel)) {
27178 return true;
27179 }
27180 } catch (err) {
27181 logger$1.critical('Error while checking selector: ' + sel, err);
27182 }
27183 }
27184 return false;
27185 }
27186
27187 function isElementBlocked(el, ev, blockElementCallback, blockSelectors) {
27188 var i;
27189
27190 if (blockElementCallback) {
27191 try {
27192 if (blockElementCallback(el, ev)) {
27193 return true;
27194 }
27195 } catch (err) {
27196 logger$1.critical('Error while checking element in blockElementCallback', err);
27197 return true;
27198 }
27199 }
27200
27201 if (blockSelectors && blockSelectors.length) {
27202 // programmatically prevent tracking of elements that match CSS selectors
27203 for (i = 0; i < blockSelectors.length; i++) {
27204 var sel = blockSelectors[i];
27205 try {
27206 if (el['matches'](sel)) {
27207 return true;
27208 }
27209 } catch (err) {
27210 logger$1.critical('Error while checking selector: ' + sel, err);
27211 }
27212 }
27213 }
27214
27215 // allow users to programmatically prevent tracking of elements by adding default classes such as 'mp-no-track'
27216 var classes = getClasses(el);
27217 for (i = 0; i < OPT_OUT_CLASSES.length; i++) {
27218 if (classes[OPT_OUT_CLASSES[i]]) {
27219 return true;
27220 }
27221 }
27222
27223 return false;
27224 }
27225
27226 /*
27227 * Check whether a DOM node has nodeType Node.ELEMENT_NODE
27228 * @param {Node} node - node to check
27229 * @returns {boolean} whether node is of the correct nodeType
27230 */
27231 function isElementNode(node) {
27232 return node && node.nodeType === 1; // Node.ELEMENT_NODE - use integer constant for browser portability
27233 }
27234
27235 /*
27236 * Check whether an element is of a given tag type.
27237 * Due to potential reference discrepancies (such as the webcomponents.js polyfill),
27238 * we want to match tagNames instead of specific references because something like
27239 * element === document.body won't always work because element might not be a native
27240 * element.
27241 * @param {Element} el - element to check
27242 * @param {string} tag - tag name (e.g., "div")
27243 * @returns {boolean} whether el is of the given tag type
27244 */
27245 function isTag(el, tag) {
27246 return el && el.tagName && el.tagName.toLowerCase() === tag.toLowerCase();
27247 }
27248
27249 /*
27250 * Check whether a DOM node is a TEXT_NODE
27251 * @param {Node} node - node to check
27252 * @returns {boolean} whether node is of type Node.TEXT_NODE
27253 */
27254 function isTextNode(node) {
27255 return node && node.nodeType === 3; // Node.TEXT_NODE - use integer constant for browser portability
27256 }
27257
27258 function minDOMApisSupported() {
27259 try {
27260 var testEl = document$1.createElement('div');
27261 return !!testEl['matches'];
27262 } catch (err) {
27263 return false;
27264 }
27265 }
27266
27267 function weakSetSupported() {
27268 return typeof WeakSet !== 'undefined';
27269 }
27270
27271 /*
27272 * Check whether a DOM event should be "tracked" or if it may contain sensitive data
27273 * using a variety of heuristics.
27274 * @param {Element} el - element to check
27275 * @param {Event} ev - event to check
27276 * @returns {boolean} whether the event should be tracked
27277 */
27278 function shouldTrackDomEvent(el, ev) {
27279 if (!el || isTag(el, 'html') || !isElementNode(el)) {
27280 return false;
27281 }
27282 var tag = el.tagName.toLowerCase();
27283 switch (tag) {
27284 case 'form':
27285 return ev.type === EV_SUBMIT;
27286 case 'input':
27287 if (['button', 'submit'].indexOf(el.getAttribute('type')) === -1) {
27288 return ev.type === EV_CHANGE;
27289 } else {
27290 return ev.type === EV_CLICK;
27291 }
27292 case 'select':
27293 case 'textarea':
27294 return ev.type === EV_CHANGE;
27295 default:
27296 return ev.type === EV_CLICK;
27297 }
27298 }
27299
27300 /*
27301 * Check whether a DOM element should be "tracked" or if it may contain sensitive data
27302 * using a variety of heuristics.
27303 * @param {Element} el - element to check
27304 * @param {Array<string>} allowSelectors - CSS selectors for elements that should be included
27305 * @returns {boolean} whether the element should be tracked
27306 */
27307 function shouldTrackElementDetails(el, ev, allowElementCallback, allowSelectors) {
27308 var i;
27309
27310 if (!isElementAllowed(el, ev, allowElementCallback, allowSelectors)) {
27311 return false;
27312 }
27313
27314 for (var curEl = el; curEl.parentNode && !isTag(curEl, 'body'); curEl = curEl.parentNode) {
27315 var classes = getClasses(curEl);
27316 for (i = 0; i < SENSITIVE_DATA_CLASSES.length; i++) {
27317 if (classes[SENSITIVE_DATA_CLASSES[i]]) {
27318 return false;
27319 }
27320 }
27321 }
27322
27323 var elClasses = getClasses(el);
27324 for (i = 0; i < OPT_IN_CLASSES.length; i++) {
27325 if (elClasses[OPT_IN_CLASSES[i]]) {
27326 return true;
27327 }
27328 }
27329
27330 // don't send data from inputs or similar elements since there will always be
27331 // a risk of clientside javascript placing sensitive data in attributes
27332 if (
27333 isTag(el, 'input') ||
27334 isTag(el, 'select') ||
27335 isTag(el, 'textarea') ||
27336 el.getAttribute('contenteditable') === 'true'
27337 ) {
27338 return false;
27339 }
27340
27341 // don't include hidden or password fields
27342 var type = el.type || '';
27343 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"]
27344 switch(type.toLowerCase()) {
27345 case 'hidden':
27346 return false;
27347 case 'password':
27348 return false;
27349 }
27350 }
27351
27352 // filter out data from fields that look like sensitive fields
27353 var name = el.name || el.id || '';
27354 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"]
27355 var sensitiveNameRegex = /^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;
27356 if (sensitiveNameRegex.test(name.replace(/[^a-zA-Z0-9]/g, ''))) {
27357 return false;
27358 }
27359 }
27360
27361 return true;
27362 }
27363
27364
27365 /*
27366 * Check whether a string value should be "tracked" or if it may contain sensitive data
27367 * using a variety of heuristics.
27368 * @param {string} value - string value to check
27369 * @returns {boolean} whether the element should be tracked
27370 */
27371 function shouldTrackValue(value) {
27372 if (value === null || _.isUndefined(value)) {
27373 return false;
27374 }
27375
27376 if (typeof value === 'string') {
27377 value = _.trim(value);
27378
27379 // check to see if input value looks like a credit card number
27380 // see: https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s20.html
27381 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}))$/;
27382 if (ccRegex.test((value || '').replace(/[- ]/g, ''))) {
27383 return false;
27384 }
27385
27386 // check to see if input value looks like a social security number
27387 var ssnRegex = /(^\d{3}-?\d{2}-?\d{4}$)/;
27388 if (ssnRegex.test(value)) {
27389 return false;
27390 }
27391 }
27392
27393 return true;
27394 }
27395
27396 /**
27397 * Creates a cross-browser compatible scroll end function with appropriate event listener.
27398 * For browsers that support scrollend, returns the original function with scrollend event.
27399 * For browsers without scrollend support, returns a debounced function that triggers
27400 * 100ms after the last scroll event to simulate scrollend behavior.
27401 * @param {Function} originalFunction - The function to call when scrolling ends
27402 * @returns {Object} Object containing listener function and eventType string
27403 * @returns {Function} returns.listener - The wrapped function to use as event listener
27404 * @returns {string} returns.eventType - The event type to listen for ('scrollend' or 'scroll')
27405 */
27406 function getPolyfillScrollEndFunction(originalFunction) {
27407 var supportsScrollEnd = 'onscrollend' in win;
27408 var polyfillFunction = safewrap(originalFunction);
27409 var polyfillEvent = EV_SCROLLEND;
27410 if (!supportsScrollEnd) {
27411 // Polyfill for browsers without scrollend support: wait 100ms after the last scroll event
27412 // https://developer.chrome.com/blog/scrollend-a-new-javascript-event
27413 var scrollTimer = null;
27414 var scrollDelayMs = 100;
27415
27416 polyfillFunction = safewrap(function() {
27417 clearTimeout(scrollTimer);
27418 scrollTimer = setTimeout(originalFunction, scrollDelayMs);
27419 });
27420
27421 polyfillEvent = EV_SCROLL;
27422 }
27423
27424 return {
27425 listener: polyfillFunction,
27426 eventType: polyfillEvent
27427 };
27428 }
27429
27430 function hasInlineEventHandlers(element) {
27431 for (var i = 0; i < EVENT_HANDLER_ATTRIBUTES.length; i++) {
27432 if (element.hasAttribute(EVENT_HANDLER_ATTRIBUTES[i])) {
27433 return true;
27434 }
27435 }
27436 return false;
27437 }
27438
27439 function hasInteractiveAriaRole(element) {
27440 var role = element.getAttribute('role');
27441 if (!role) return false;
27442
27443 // Handle invalid markup where multiple roles might be specified
27444 // Only the first token is recognized per ARIA spec
27445 var primaryRole = role.trim().split(/\s+/)[0].toLowerCase();
27446
27447 return INTERACTIVE_ARIA_ROLES[primaryRole];
27448 }
27449
27450 function hasAnyInteractivityIndicators(element) {
27451 var tagName = element.tagName.toLowerCase();
27452
27453 // Check for interactive HTML elements
27454 if (tagName === 'button' ||
27455 tagName === 'input' ||
27456 tagName === 'select' ||
27457 tagName === 'textarea' ||
27458 tagName === 'details' ||
27459 tagName === 'dialog') {
27460 return true;
27461 }
27462
27463 if (element.isContentEditable) {
27464 return true;
27465 }
27466
27467 if (element.onclick || element.onmousedown || element.onmouseup || element.ontouchstart || element.ontouchend) {
27468 return true;
27469 }
27470
27471 if (hasInlineEventHandlers(element)) {
27472 return true;
27473 }
27474
27475 if (hasInteractiveAriaRole(element)) {
27476 return true;
27477 }
27478
27479 if (tagName === 'a' && element.hasAttribute('href')) {
27480 return true;
27481 }
27482
27483 if (element.hasAttribute('tabindex')) {
27484 return true;
27485 }
27486
27487 return false;
27488 }
27489
27490
27491 function isDefinitelyNonInteractive(element) {
27492 if (!element || !element.tagName) {
27493 return true;
27494 }
27495
27496 var tagName = element.tagName.toLowerCase();
27497
27498 // These tags are definitely non-interactive
27499 if (ALWAYS_NON_INTERACTIVE_TAGS[tagName]) {
27500 return true;
27501 }
27502
27503 // For all other elements, we can only be certain they're non-interactive if they lack ALL indicators of interactivity
27504 // Check for any signs of interactivity
27505 if (hasAnyInteractivityIndicators(element)) {
27506 return false;
27507 }
27508
27509 // Check parent chain for interactive context
27510 var parent = element.parentElement;
27511 var depth = 0;
27512
27513 while (parent && depth < MAX_DEPTH) {
27514 if (hasAnyInteractivityIndicators(parent)) {
27515 return false; // Element is inside an interactive parent
27516 }
27517
27518 if (parent.getRootNode && parent.getRootNode() !== document$1) {
27519 var root = parent.getRootNode();
27520 if (root.host && hasAnyInteractivityIndicators(root.host)) {
27521 return false; // Inside an interactive shadow host
27522 }
27523 }
27524
27525 parent = parent.parentElement;
27526 depth++;
27527 }
27528
27529 // Pure text containers without any interactive context
27530 if (TEXT_CONTAINER_TAGS[tagName]) {
27531 // These are non-interactive ONLY if they have no interactive indicators (already checked as part of hasAnyInteractivityIndicators)
27532 return true;
27533 }
27534
27535 // Default: we can't be certain it's non-interactive
27536 return false;
27537 }
27538
27539 /** @const */ var DEFAULT_RAGE_CLICK_THRESHOLD_PX = 30;
27540 /** @const */ var DEFAULT_RAGE_CLICK_TIMEOUT_MS = 1000;
27541 /** @const */ var DEFAULT_RAGE_CLICK_CLICK_COUNT = 4;
27542
27543 function RageClickTracker() {
27544 this.clicks = [];
27545 }
27546
27547 RageClickTracker.prototype.isRageClick = function(x, y, options) {
27548 options = options || {};
27549 var thresholdPx = options['threshold_px'] || DEFAULT_RAGE_CLICK_THRESHOLD_PX;
27550 var timeoutMs = options['timeout_ms'] || DEFAULT_RAGE_CLICK_TIMEOUT_MS;
27551 var clickCount = options['click_count'] || DEFAULT_RAGE_CLICK_CLICK_COUNT;
27552 var timestamp = Date.now();
27553
27554 var lastClick = this.clicks[this.clicks.length - 1];
27555 if (
27556 lastClick &&
27557 timestamp - lastClick.timestamp < timeoutMs &&
27558 Math.sqrt(Math.pow(x - lastClick.x, 2) + Math.pow(y - lastClick.y, 2)) < thresholdPx
27559 ) {
27560 this.clicks.push({ x: x, y: y, timestamp: timestamp });
27561 if (this.clicks.length >= clickCount) {
27562 this.clicks = [];
27563 return true;
27564 }
27565 } else {
27566 this.clicks = [{ x: x, y: y, timestamp: timestamp }];
27567 }
27568 return false;
27569 };
27570
27571 function ShadowDOMObserver(changeCallback, observerConfig) {
27572 this.changeCallback = changeCallback || function() {};
27573 this.observerConfig = observerConfig;
27574
27575 this.observedShadowRoots = null;
27576 this.shadowObservers = [];
27577 }
27578
27579 ShadowDOMObserver.prototype.getEventTarget = function(event) {
27580 if (!this.observedShadowRoots) {
27581 return;
27582 }
27583 var path = this.getComposedPath(event);
27584 if (path && path.length) {
27585 return path[0];
27586 }
27587
27588 return event['target'] || event['srcElement'];
27589 };
27590
27591
27592 ShadowDOMObserver.prototype.getComposedPath = function(event) {
27593 if ('composedPath' in event) {
27594 return event['composedPath']();
27595 }
27596
27597 return [];
27598 };
27599 ShadowDOMObserver.prototype.observeFromEvent = function(event) {
27600 if (!this.observedShadowRoots) {
27601 return;
27602 }
27603
27604 var path = this.getComposedPath(event);
27605
27606 // Check each element in path for shadow roots
27607 for (var i = 0; i < path.length; i++) {
27608 var element = path[i];
27609
27610 if (element && element.shadowRoot) {
27611 this.observeShadowRoot(element.shadowRoot);
27612 }
27613 }
27614 };
27615
27616
27617 ShadowDOMObserver.prototype.observeShadowRoot = function(shadowRoot) {
27618 if (!this.observedShadowRoots || this.observedShadowRoots.has(shadowRoot)) {
27619 return;
27620 }
27621
27622 var self = this;
27623
27624 try {
27625 this.observedShadowRoots.add(shadowRoot);
27626
27627 var observer = new window.MutationObserver(function() {
27628 self.changeCallback();
27629 });
27630
27631 observer.observe(shadowRoot, this.observerConfig);
27632 this.shadowObservers.push(observer);
27633 } catch (e) {
27634 logger$1.critical('Error while observing shadow root', e);
27635 }
27636 };
27637
27638
27639 ShadowDOMObserver.prototype.start = function() {
27640 if (this.observedShadowRoots) {
27641 return;
27642 }
27643
27644 if (!weakSetSupported()) {
27645 logger$1.critical('Shadow DOM observation unavailable: WeakSet not supported');
27646 return;
27647 }
27648
27649 this.observedShadowRoots = new WeakSet();
27650 };
27651
27652 ShadowDOMObserver.prototype.stop = function() {
27653 if (!this.observedShadowRoots) {
27654 return;
27655 }
27656
27657 for (var i = 0; i < this.shadowObservers.length; i++) {
27658 try {
27659 this.shadowObservers[i].disconnect();
27660 } catch (e) {
27661 logger$1.critical('Error while disconnecting shadow DOM observer', e);
27662 }
27663 }
27664 this.shadowObservers = [];
27665 this.observedShadowRoots = null;
27666 };
27667
27668 /** @const */ var DEFAULT_DEAD_CLICK_TIMEOUT_MS = 500;
27669 /** @const */ var INTERACTION_EVENTS = [EV_CHANGE, EV_INPUT, EV_SUBMIT, EV_SELECT, EV_TOGGLE];
27670 /** @const */ var LAYOUT_EVENTS = [EV_SCROLLEND];
27671 /** @const */ var NAVIGATION_EVENTS = [EV_HASHCHANGE];
27672 /** @const */ var MUTATION_OBSERVER_CONFIG = {
27673 characterData: true,
27674 childList: true,
27675 subtree: true,
27676 attributes: true,
27677 attributeFilter: ['style', 'class', 'hidden', 'checked', 'selected', 'value', 'display', 'visibility']
27678 };
27679
27680
27681 function DeadClickTracker(onDeadClickCallback) {
27682 this.eventListeners = [];
27683 this.mutationObserver = null;
27684 this.shadowDOMObserver = null;
27685
27686 this.isTracking = false;
27687 this.lastChangeEventTimestamp = 0;
27688 this.pendingClicks = [];
27689 this.onDeadClickCallback = onDeadClickCallback;
27690 this.processingActive = false;
27691 this.processingTimeout = null;
27692 }
27693
27694
27695 DeadClickTracker.prototype.addClick = function(event) {
27696 var element = this.shadowDOMObserver && this.shadowDOMObserver.getEventTarget(event);
27697
27698 if (!element) {
27699 element = event['target'] || event['srcElement'];
27700 }
27701
27702 if (!element || isDefinitelyNonInteractive(element)) {
27703 return false;
27704 }
27705
27706 if (this.shadowDOMObserver) {
27707 this.shadowDOMObserver.observeFromEvent(event);
27708 }
27709 this.pendingClicks.push({
27710 element: element,
27711 event: event,
27712 timestamp: Date.now()
27713 });
27714 return true;
27715 };
27716
27717 DeadClickTracker.prototype.trackClick = function(event, config) {
27718 if (!this.isTracking) {
27719 return false;
27720 }
27721
27722 var added = this.addClick(event);
27723 if (added) {
27724 this.triggerProcessing(config);
27725 }
27726 return added;
27727 };
27728
27729 DeadClickTracker.prototype.getDeadClicks = function(config) {
27730 if (this.pendingClicks.length === 0) {
27731 return [];
27732 }
27733
27734 var timeoutMs = config['timeout_ms'];
27735 var now = Date.now();
27736 var clicksToEvaluate = this.pendingClicks.slice(); // Copy array
27737 this.pendingClicks = []; // Clear original
27738
27739 var deadClicks = [];
27740
27741 for (var i = 0; i < clicksToEvaluate.length; i++) {
27742 var click = clicksToEvaluate[i];
27743
27744 if (now - click.timestamp >= timeoutMs) {
27745 // Click has exceeded timeout, check if it's dead by looking for changes after this specific click
27746 if (!this.hasChangesAfter(click.timestamp)) {
27747 deadClicks.push(click);
27748 }
27749 } else {
27750 // Still pending - add back
27751 this.pendingClicks.push(click);
27752 }
27753 }
27754
27755 return deadClicks;
27756 };
27757
27758 DeadClickTracker.prototype.hasChangesAfter = function(timestamp) {
27759 // 100ms tolerance for race condition between when we record the click and the change event
27760 return this.lastChangeEventTimestamp >= (timestamp - 100);
27761 };
27762
27763 DeadClickTracker.prototype.recordChangeEvent = function() {
27764 this.lastChangeEventTimestamp = Date.now();
27765 };
27766
27767 DeadClickTracker.prototype.triggerProcessing = function(config) {
27768 // Prevent multiple concurrent processing chains
27769 if (this.processingActive) {
27770 return;
27771 }
27772 this.processingActive = true;
27773 this.processRecursively(config);
27774 };
27775
27776 DeadClickTracker.prototype.processRecursively = function(config) {
27777 if (!this.isTracking || !this.onDeadClickCallback) {
27778 this.processingActive = false;
27779 return;
27780 }
27781
27782 var timeoutMs = config['timeout_ms'];
27783 var self = this;
27784
27785 this.processingTimeout = setTimeout(function() {
27786 if (!self.processingActive) {
27787 return;
27788 }
27789
27790 var deadClicks = self.getDeadClicks(config);
27791
27792 for (var i = 0; i < deadClicks.length; i++) {
27793 self.onDeadClickCallback(deadClicks[i].event);
27794 }
27795
27796 if (self.pendingClicks.length > 0) {
27797 self.processRecursively(config);
27798 } else {
27799 self.processingActive = false;
27800 }
27801 }, timeoutMs);
27802 };
27803
27804 DeadClickTracker.prototype.startTracking = function() {
27805 if (this.isTracking) {
27806 return;
27807 }
27808
27809 this.isTracking = true;
27810
27811 var self = this;
27812
27813 INTERACTION_EVENTS.forEach(function(event) {
27814 var handler = function() {
27815 self.recordChangeEvent();
27816 };
27817 document.addEventListener(event, handler, { capture: true, passive: true });
27818 self.eventListeners.push({ target: document, event: event, handler: handler, options: { capture: true, passive: true } });
27819 });
27820 NAVIGATION_EVENTS.forEach(function(event) {
27821 var handler = function() {
27822 self.recordChangeEvent();
27823 };
27824 window.addEventListener(event, handler);
27825 self.eventListeners.push({ target: window, event: event, handler: handler });
27826 });
27827 LAYOUT_EVENTS.forEach(function(event) {
27828 var handler = function() {
27829 self.recordChangeEvent();
27830 };
27831 window.addEventListener(event, handler, { passive: true });
27832 self.eventListeners.push({ target: window, event: event, handler: handler, options: { passive: true } });
27833 });
27834 var selectionHandler = function() {
27835 self.recordChangeEvent();
27836 };
27837 document.addEventListener('selectionchange', selectionHandler);
27838 self.eventListeners.push({ target: document, event: 'selectionchange', handler: selectionHandler });
27839
27840 // Set up MutationObserver
27841 if (window.MutationObserver) {
27842 try {
27843 this.mutationObserver = new window.MutationObserver(function() {
27844 self.recordChangeEvent();
27845 });
27846
27847 this.mutationObserver.observe(document.body || document.documentElement, MUTATION_OBSERVER_CONFIG);
27848 } catch (e) {
27849 logger$1.critical('Error while setting up mutation observer', e);
27850 }
27851 }
27852
27853 // Set up Shadow DOM observer
27854 if (window.customElements) {
27855 try {
27856 this.shadowDOMObserver = new ShadowDOMObserver(
27857 function() {
27858 self.recordChangeEvent();
27859 },
27860 MUTATION_OBSERVER_CONFIG
27861 );
27862 this.shadowDOMObserver.start();
27863 } catch (e) {
27864 logger$1.critical('Error while setting up shadow DOM observer', e);
27865 this.shadowDOMObserver = null;
27866 }
27867 }
27868 };
27869
27870 DeadClickTracker.prototype.stopTracking = function() {
27871 if (!this.isTracking) {
27872 return;
27873 }
27874
27875 this.isTracking = false;
27876 this.pendingClicks = [];
27877 this.lastChangeEventTimestamp = 0;
27878 this.processingActive = false;
27879
27880 if (this.processingTimeout) {
27881 clearTimeout(this.processingTimeout);
27882 this.processingTimeout = null;
27883 }
27884
27885 // Remove all event listeners
27886 for (var i = 0; i < this.eventListeners.length; i++) {
27887 var listener = this.eventListeners[i];
27888 try {
27889 listener.target.removeEventListener(listener.event, listener.handler, listener.options);
27890 } catch (e) {
27891 logger$1.critical('Error while removing event listener', e);
27892 }
27893 }
27894 this.eventListeners = [];
27895
27896 if (this.mutationObserver) {
27897 try {
27898 this.mutationObserver.disconnect();
27899 } catch (e) {
27900 logger$1.critical('Error while disconnecting mutation observer', e);
27901 }
27902 this.mutationObserver = null;
27903 }
27904
27905 if (this.shadowDOMObserver) {
27906 try {
27907 this.shadowDOMObserver.stop();
27908 } catch (e) {
27909 logger$1.critical('Error while stopping shadow DOM observer', e);
27910 }
27911 this.shadowDOMObserver = null;
27912 }
27913 };
27914
27915 var AUTOCAPTURE_CONFIG_KEY = 'autocapture';
27916 var LEGACY_PAGEVIEW_CONFIG_KEY = 'track_pageview';
27917
27918 var PAGEVIEW_OPTION_FULL_URL = 'full-url';
27919 var PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING = 'url-with-path-and-query-string';
27920 var PAGEVIEW_OPTION_URL_WITH_PATH = 'url-with-path';
27921
27922 var CONFIG_ALLOW_ELEMENT_CALLBACK = 'allow_element_callback';
27923 var CONFIG_ALLOW_SELECTORS = 'allow_selectors';
27924 var CONFIG_ALLOW_URL_REGEXES = 'allow_url_regexes';
27925 var CONFIG_BLOCK_ATTRS = 'block_attrs';
27926 var CONFIG_BLOCK_ELEMENT_CALLBACK = 'block_element_callback';
27927 var CONFIG_BLOCK_SELECTORS = 'block_selectors';
27928 var CONFIG_BLOCK_URL_REGEXES = 'block_url_regexes';
27929 var CONFIG_CAPTURE_EXTRA_ATTRS = 'capture_extra_attrs';
27930 var CONFIG_CAPTURE_TEXT_CONTENT = 'capture_text_content';
27931 var CONFIG_SCROLL_CAPTURE_ALL = 'scroll_capture_all';
27932 var CONFIG_SCROLL_CHECKPOINTS = 'scroll_depth_percent_checkpoints';
27933 var CONFIG_TRACK_CLICK = 'click';
27934 var CONFIG_TRACK_DEAD_CLICK = 'dead_click';
27935 var CONFIG_TRACK_INPUT = 'input';
27936 var CONFIG_TRACK_PAGEVIEW = 'pageview';
27937 var CONFIG_TRACK_RAGE_CLICK = 'rage_click';
27938 var CONFIG_TRACK_SCROLL = 'scroll';
27939 var CONFIG_TRACK_PAGE_LEAVE = 'page_leave';
27940 var CONFIG_TRACK_SUBMIT = 'submit';
27941
27942 var CONFIG_DEFAULTS$1 = {};
27943 CONFIG_DEFAULTS$1[CONFIG_ALLOW_SELECTORS] = [];
27944 CONFIG_DEFAULTS$1[CONFIG_ALLOW_URL_REGEXES] = [];
27945 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ATTRS] = [];
27946 CONFIG_DEFAULTS$1[CONFIG_BLOCK_ELEMENT_CALLBACK] = null;
27947 CONFIG_DEFAULTS$1[CONFIG_BLOCK_SELECTORS] = [];
27948 CONFIG_DEFAULTS$1[CONFIG_BLOCK_URL_REGEXES] = [];
27949 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_EXTRA_ATTRS] = [];
27950 CONFIG_DEFAULTS$1[CONFIG_CAPTURE_TEXT_CONTENT] = false;
27951 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CAPTURE_ALL] = false;
27952 CONFIG_DEFAULTS$1[CONFIG_SCROLL_CHECKPOINTS] = [25, 50, 75, 100];
27953 CONFIG_DEFAULTS$1[CONFIG_TRACK_CLICK] = true;
27954 CONFIG_DEFAULTS$1[CONFIG_TRACK_DEAD_CLICK] = true;
27955 CONFIG_DEFAULTS$1[CONFIG_TRACK_INPUT] = true;
27956 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGEVIEW] = PAGEVIEW_OPTION_FULL_URL;
27957 CONFIG_DEFAULTS$1[CONFIG_TRACK_RAGE_CLICK] = true;
27958 CONFIG_DEFAULTS$1[CONFIG_TRACK_SCROLL] = true;
27959 CONFIG_DEFAULTS$1[CONFIG_TRACK_PAGE_LEAVE] = false;
27960 CONFIG_DEFAULTS$1[CONFIG_TRACK_SUBMIT] = true;
27961
27962 var DEFAULT_PROPS = {
27963 '$mp_autocapture': true
27964 };
27965
27966 var MP_EV_CLICK = '$mp_click';
27967 var MP_EV_DEAD_CLICK = '$mp_dead_click';
27968 var MP_EV_INPUT = '$mp_input_change';
27969 var MP_EV_RAGE_CLICK = '$mp_rage_click';
27970 var MP_EV_SCROLL = '$mp_scroll';
27971 var MP_EV_SUBMIT = '$mp_submit';
27972 var MP_EV_PAGE_LEAVE = '$mp_page_leave';
27973
27974 /**
27975 * Autocapture: manages automatic event tracking
27976 * @constructor
27977 */
27978 var Autocapture = function(mp) {
27979 this.mp = mp;
27980 this.maxScrollViewDepth = 0;
27981 this.hasTrackedScrollSession = false;
27982 this.previousScrollHeight = 0;
27983 };
27984
27985 Autocapture.prototype.init = function() {
27986 if (!minDOMApisSupported()) {
27987 logger$1.critical('Autocapture unavailable: missing required DOM APIs');
27988 return;
27989 }
27990 this.initPageListeners();
27991 this.initPageviewTracking();
27992 this.initClickTracking();
27993 this.initDeadClickTracking();
27994 this.initInputTracking();
27995 this.initScrollTracking();
27996 this.initSubmitTracking();
27997 this.initRageClickTracking();
27998 this.initPageLeaveTracking();
27999 };
28000
28001 Autocapture.prototype.getFullConfig = function() {
28002 var autocaptureConfig = this.mp.get_config(AUTOCAPTURE_CONFIG_KEY);
28003 if (!autocaptureConfig) {
28004 // Autocapture is completely off
28005 return {};
28006 } else if (_.isObject(autocaptureConfig)) {
28007 return _.extend({}, CONFIG_DEFAULTS$1, autocaptureConfig);
28008 } else {
28009 // Autocapture config is non-object truthy value, return default
28010 return CONFIG_DEFAULTS$1;
28011 }
28012 };
28013
28014 Autocapture.prototype.getConfig = function(key) {
28015 return this.getFullConfig()[key];
28016 };
28017
28018 Autocapture.prototype.currentUrlBlocked = function() {
28019 var i;
28020 var currentUrl = _.info.currentUrl();
28021
28022 var allowUrlRegexes = this.getConfig(CONFIG_ALLOW_URL_REGEXES) || [];
28023 if (allowUrlRegexes.length) {
28024 // we're using an allowlist, only track if current URL matches
28025 var allowed = false;
28026 for (i = 0; i < allowUrlRegexes.length; i++) {
28027 var allowRegex = allowUrlRegexes[i];
28028 try {
28029 if (currentUrl.match(allowRegex)) {
28030 allowed = true;
28031 break;
28032 }
28033 } catch (err) {
28034 logger$1.critical('Error while checking block URL regex: ' + allowRegex, err);
28035 return true;
28036 }
28037 }
28038 if (!allowed) {
28039 // wasn't allowed by any regex
28040 return true;
28041 }
28042 }
28043
28044 var blockUrlRegexes = this.getConfig(CONFIG_BLOCK_URL_REGEXES) || [];
28045 if (!blockUrlRegexes || !blockUrlRegexes.length) {
28046 return false;
28047 }
28048
28049 for (i = 0; i < blockUrlRegexes.length; i++) {
28050 try {
28051 if (currentUrl.match(blockUrlRegexes[i])) {
28052 return true;
28053 }
28054 } catch (err) {
28055 logger$1.critical('Error while checking block URL regex: ' + blockUrlRegexes[i], err);
28056 return true;
28057 }
28058 }
28059 return false;
28060 };
28061
28062 Autocapture.prototype.pageviewTrackingConfig = function() {
28063 // supports both autocapture config and old track_pageview config
28064 if (this.mp.get_config(AUTOCAPTURE_CONFIG_KEY)) {
28065 return this.getConfig(CONFIG_TRACK_PAGEVIEW);
28066 } else {
28067 return this.mp.get_config(LEGACY_PAGEVIEW_CONFIG_KEY);
28068 }
28069 };
28070
28071 // helper for event handlers
28072 Autocapture.prototype.trackDomEvent = function(ev, mpEventName) {
28073 if (this.currentUrlBlocked()) {
28074 return;
28075 }
28076
28077 var isCapturedForHeatMap = this.mp.is_recording_heatmap_data() && (
28078 (mpEventName === MP_EV_CLICK && !this.getConfig(CONFIG_TRACK_CLICK)) ||
28079 (mpEventName === MP_EV_RAGE_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK)) ||
28080 (mpEventName === MP_EV_DEAD_CLICK && !this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK))
28081 );
28082
28083 var props = getPropsForDOMEvent(ev, {
28084 allowElementCallback: this.getConfig(CONFIG_ALLOW_ELEMENT_CALLBACK),
28085 allowSelectors: this.getConfig(CONFIG_ALLOW_SELECTORS),
28086 blockAttrs: this.getConfig(CONFIG_BLOCK_ATTRS),
28087 blockElementCallback: this.getConfig(CONFIG_BLOCK_ELEMENT_CALLBACK),
28088 blockSelectors: this.getConfig(CONFIG_BLOCK_SELECTORS),
28089 captureExtraAttrs: this.getConfig(CONFIG_CAPTURE_EXTRA_ATTRS),
28090 captureTextContent: this.getConfig(CONFIG_CAPTURE_TEXT_CONTENT),
28091 capturedForHeatMap: isCapturedForHeatMap,
28092 });
28093 if (props) {
28094 _.extend(props, DEFAULT_PROPS);
28095 this.mp.track(mpEventName, props);
28096 }
28097 };
28098
28099 Autocapture.prototype.initPageListeners = function() {
28100 win.removeEventListener(EV_POPSTATE, this.listenerPopstate);
28101 win.removeEventListener(EV_HASHCHANGE, this.listenerHashchange);
28102
28103 if (!this.pageviewTrackingConfig() && !this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config('record_heatmap_data')) {
28104 // These are all the configs that use these listeners
28105 return;
28106 }
28107
28108 this.listenerPopstate = function() {
28109 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
28110 };
28111 this.listenerHashchange = function() {
28112 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
28113 };
28114
28115 win.addEventListener(EV_POPSTATE, this.listenerPopstate);
28116 win.addEventListener(EV_HASHCHANGE, this.listenerHashchange);
28117 var nativePushState = win.history.pushState;
28118 if (typeof nativePushState === 'function') {
28119 win.history.pushState = function(state, unused, url) {
28120 nativePushState.call(win.history, state, unused, url);
28121 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
28122 };
28123 }
28124 var nativeReplaceState = win.history.replaceState;
28125 if (typeof nativeReplaceState === 'function') {
28126 win.history.replaceState = function(state, unused, url) {
28127 nativeReplaceState.call(win.history, state, unused, url);
28128 win.dispatchEvent(new Event(EV_MP_LOCATION_CHANGE));
28129 };
28130 }
28131 };
28132
28133 Autocapture.prototype._getClickTrackingConfig = function(configKey) {
28134 var config = this.getConfig(configKey);
28135
28136 if (!config) {
28137 return null; // click tracking disabled
28138 }
28139
28140 if (config === true) {
28141 return {}; // use defaults
28142 }
28143
28144 if (typeof config === 'object') {
28145 return config; // use custom configuration
28146 }
28147
28148 return {}; // fallback to defaults for any other truthy value
28149 };
28150
28151 Autocapture.prototype._trackPageLeave = function(ev, currentUrl, currentScrollHeight) {
28152 if (this.hasTrackedScrollSession) {
28153 // User has navigated away already ending their impression.
28154 return;
28155 }
28156
28157 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.is_recording_heatmap_data()) {
28158 return;
28159 }
28160
28161 this.hasTrackedScrollSession = true;
28162 var viewportHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
28163 var scrollPercentage = Math.round(Math.max(this.maxScrollViewDepth - viewportHeight, 0) / (currentScrollHeight - viewportHeight) * 100);
28164 var foldLinePercentage = Math.round((viewportHeight / currentScrollHeight) * 100);
28165 if (currentScrollHeight <= viewportHeight) {
28166 // If the content fits within the viewport, consider it fully scrolled
28167 scrollPercentage = 100;
28168 foldLinePercentage = 100;
28169 }
28170
28171 var props = _.extend({
28172 '$max_scroll_view_depth': this.maxScrollViewDepth,
28173 '$max_scroll_percentage': scrollPercentage,
28174 '$fold_line_percentage': foldLinePercentage,
28175 '$scroll_height': currentScrollHeight,
28176 '$event_type': ev.type,
28177 '$current_url': currentUrl || _.info.currentUrl(),
28178 '$viewportHeight': viewportHeight, // This is the fold line
28179 '$viewportWidth': Math.max(document$1.documentElement.clientWidth, win.innerWidth || 0),
28180 '$captured_for_heatmap': this.mp.is_recording_heatmap_data()
28181 }, DEFAULT_PROPS);
28182
28183 // Send with beacon transport to ensure event is sent before unload
28184 this.mp.track(MP_EV_PAGE_LEAVE, props, {transport: 'sendBeacon'});
28185 };
28186
28187 Autocapture.prototype._initScrollDepthTracking = function() {
28188 win.removeEventListener(EV_SCROLL, this.listenerScrollDepth);
28189 win.removeEventListener(EV_SCROLLEND, this.listenerScrollDepth);
28190
28191 if (!this.mp.get_config('record_heatmap_data')) {
28192 return;
28193 }
28194
28195 logger$1.log('Initializing scroll depth tracking');
28196
28197 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
28198
28199 var updateScrollDepth = function() {
28200 if (this.currentUrlBlocked()) {
28201 return;
28202 }
28203 var scrollViewHeight = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0) + win.scrollY;
28204 if (scrollViewHeight > this.maxScrollViewDepth) {
28205 this.maxScrollViewDepth = scrollViewHeight;
28206 }
28207 this.previousScrollHeight = document$1.body.scrollHeight;
28208 }.bind(this);
28209
28210 var scrollEndPolyfill = getPolyfillScrollEndFunction(updateScrollDepth);
28211 this.listenerScrollDepth = scrollEndPolyfill.listener;
28212 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScrollDepth);
28213 };
28214
28215 Autocapture.prototype.initClickTracking = function() {
28216 win.removeEventListener(EV_CLICK, this.listenerClick);
28217
28218 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.get_config('record_heatmap_data')) {
28219 return;
28220 }
28221 logger$1.log('Initializing click tracking');
28222
28223 this.listenerClick = function(ev) {
28224 if (!this.getConfig(CONFIG_TRACK_CLICK) && !this.mp.is_recording_heatmap_data()) {
28225 return;
28226 }
28227 this.trackDomEvent(ev, MP_EV_CLICK);
28228 }.bind(this);
28229 win.addEventListener(EV_CLICK, this.listenerClick);
28230 };
28231
28232 Autocapture.prototype.initDeadClickTracking = function() {
28233 var deadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
28234
28235 if (!deadClickConfig && !this.mp.get_config('record_heatmap_data')) {
28236 this.stopDeadClickTracking();
28237 return;
28238 }
28239
28240 logger$1.log('Initializing dead click tracking');
28241 if (!this._deadClickTracker) {
28242 this._deadClickTracker = new DeadClickTracker(function(deadClickEvent) {
28243 this.trackDomEvent(deadClickEvent, MP_EV_DEAD_CLICK);
28244 }.bind(this));
28245 this._deadClickTracker.startTracking();
28246 }
28247
28248 if (!this.listenerDeadClick) {
28249 this.listenerDeadClick = function(ev) {
28250 var currentDeadClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_DEAD_CLICK);
28251 if (!currentDeadClickConfig && !this.mp.is_recording_heatmap_data()) {
28252 return;
28253 }
28254 if (this.currentUrlBlocked()) {
28255 return;
28256 }
28257 // Normalize config to ensure timeout_ms is always set
28258 var normalizedConfig = currentDeadClickConfig || {};
28259 if (!normalizedConfig['timeout_ms']) {
28260 normalizedConfig['timeout_ms'] = DEFAULT_DEAD_CLICK_TIMEOUT_MS;
28261 }
28262 this._deadClickTracker.trackClick(ev, normalizedConfig);
28263 }.bind(this);
28264 win.addEventListener(EV_CLICK, this.listenerDeadClick);
28265 }
28266 };
28267
28268 Autocapture.prototype.initInputTracking = function() {
28269 win.removeEventListener(EV_CHANGE, this.listenerChange);
28270
28271 if (!this.getConfig(CONFIG_TRACK_INPUT)) {
28272 return;
28273 }
28274 logger$1.log('Initializing input tracking');
28275
28276 this.listenerChange = function(ev) {
28277 if (!this.getConfig(CONFIG_TRACK_INPUT)) {
28278 return;
28279 }
28280 this.trackDomEvent(ev, MP_EV_INPUT);
28281 }.bind(this);
28282 win.addEventListener(EV_CHANGE, this.listenerChange);
28283 };
28284
28285 Autocapture.prototype.initPageviewTracking = function() {
28286 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
28287
28288 if (!this.pageviewTrackingConfig()) {
28289 return;
28290 }
28291 logger$1.log('Initializing pageview tracking');
28292
28293 var previousTrackedUrl = '';
28294 var tracked = false;
28295 if (!this.currentUrlBlocked()) {
28296 tracked = this.mp.track_pageview(DEFAULT_PROPS);
28297 }
28298 if (tracked) {
28299 previousTrackedUrl = _.info.currentUrl();
28300 }
28301
28302 this.listenerLocationchange = safewrap(function() {
28303 if (this.currentUrlBlocked()) {
28304 return;
28305 }
28306
28307 var currentUrl = _.info.currentUrl();
28308 var shouldTrack = false;
28309 var didPathChange = currentUrl.split('#')[0].split('?')[0] !== previousTrackedUrl.split('#')[0].split('?')[0];
28310 var trackPageviewOption = this.pageviewTrackingConfig();
28311 if (trackPageviewOption === PAGEVIEW_OPTION_FULL_URL) {
28312 shouldTrack = currentUrl !== previousTrackedUrl;
28313 } else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH_AND_QUERY_STRING) {
28314 shouldTrack = currentUrl.split('#')[0] !== previousTrackedUrl.split('#')[0];
28315 } else if (trackPageviewOption === PAGEVIEW_OPTION_URL_WITH_PATH) {
28316 shouldTrack = didPathChange;
28317 }
28318
28319 if (shouldTrack) {
28320 var tracked = this.mp.track_pageview(DEFAULT_PROPS);
28321 if (tracked) {
28322 previousTrackedUrl = currentUrl;
28323 }
28324 if (didPathChange) {
28325 this.lastScrollCheckpoint = 0;
28326 logger$1.log('Path change: re-initializing scroll depth checkpoints');
28327 }
28328 }
28329 }.bind(this));
28330 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerLocationchange);
28331 };
28332
28333 Autocapture.prototype.initRageClickTracking = function() {
28334 win.removeEventListener(EV_CLICK, this.listenerRageClick);
28335
28336 var rageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
28337 if (!rageClickConfig && !this.mp.get_config('record_heatmap_data')) {
28338 return;
28339 }
28340
28341 logger$1.log('Initializing rage click tracking');
28342 if (!this._rageClickTracker) {
28343 this._rageClickTracker = new RageClickTracker();
28344 }
28345
28346 this.listenerRageClick = function(ev) {
28347 var currentRageClickConfig = this._getClickTrackingConfig(CONFIG_TRACK_RAGE_CLICK);
28348 if (!currentRageClickConfig && !this.mp.is_recording_heatmap_data()) {
28349 return;
28350 }
28351
28352 if (this.currentUrlBlocked()) {
28353 return;
28354 }
28355
28356 if (this._rageClickTracker.isRageClick(ev['pageX'], ev['pageY'], currentRageClickConfig)) {
28357 this.trackDomEvent(ev, MP_EV_RAGE_CLICK);
28358 }
28359 }.bind(this);
28360 win.addEventListener(EV_CLICK, this.listenerRageClick);
28361 };
28362
28363 Autocapture.prototype.initScrollTracking = function() {
28364 win.removeEventListener(EV_SCROLLEND, this.listenerScroll);
28365 win.removeEventListener(EV_SCROLL, this.listenerScroll);
28366
28367
28368 if (!this.getConfig(CONFIG_TRACK_SCROLL)) {
28369 return;
28370 }
28371 logger$1.log('Initializing scroll tracking');
28372 this.lastScrollCheckpoint = 0;
28373
28374 var scrollTrackFunction = function() {
28375 if (!this.getConfig(CONFIG_TRACK_SCROLL)) {
28376 return;
28377 }
28378 if (this.currentUrlBlocked()) {
28379 return;
28380 }
28381
28382 var shouldTrack = this.getConfig(CONFIG_SCROLL_CAPTURE_ALL);
28383 var scrollCheckpoints = (this.getConfig(CONFIG_SCROLL_CHECKPOINTS) || [])
28384 .slice()
28385 .sort(function(a, b) { return a - b; });
28386
28387 var scrollTop = win.scrollY;
28388 var props = _.extend({'$scroll_top': scrollTop}, DEFAULT_PROPS);
28389 try {
28390 var scrollHeight = document$1.body.scrollHeight;
28391 var scrollPercentage = Math.round((scrollTop / (scrollHeight - win.innerHeight)) * 100);
28392 props['$scroll_height'] = scrollHeight;
28393 props['$scroll_percentage'] = scrollPercentage;
28394 if (scrollPercentage > this.lastScrollCheckpoint) {
28395 for (var i = 0; i < scrollCheckpoints.length; i++) {
28396 var checkpoint = scrollCheckpoints[i];
28397 if (
28398 scrollPercentage >= checkpoint &&
28399 this.lastScrollCheckpoint < checkpoint
28400 ) {
28401 props['$scroll_checkpoint'] = checkpoint;
28402 this.lastScrollCheckpoint = checkpoint;
28403 shouldTrack = true;
28404 }
28405 }
28406 }
28407 } catch (err) {
28408 logger$1.critical('Error while calculating scroll percentage', err);
28409 }
28410 if (shouldTrack) {
28411 this.mp.track(MP_EV_SCROLL, props);
28412 }
28413 }.bind(this);
28414
28415 var scrollEndPolyfill = getPolyfillScrollEndFunction(scrollTrackFunction);
28416 this.listenerScroll = scrollEndPolyfill.listener;
28417 win.addEventListener(scrollEndPolyfill.eventType, this.listenerScroll);
28418 };
28419
28420 Autocapture.prototype.initSubmitTracking = function() {
28421 win.removeEventListener(EV_SUBMIT, this.listenerSubmit);
28422
28423 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) {
28424 return;
28425 }
28426 logger$1.log('Initializing submit tracking');
28427
28428 this.listenerSubmit = function(ev) {
28429 if (!this.getConfig(CONFIG_TRACK_SUBMIT)) {
28430 return;
28431 }
28432 this.trackDomEvent(ev, MP_EV_SUBMIT);
28433 }.bind(this);
28434 win.addEventListener(EV_SUBMIT, this.listenerSubmit);
28435 };
28436
28437 Autocapture.prototype.initPageLeaveTracking = function() {
28438 // Capture page_leave both when the user navigates away from the page (visibilitychange) as well
28439 // as when they navigate to a different page within the SPA (popstate/pushstate/hashchange).
28440 document$1.removeEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
28441 win.removeEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
28442 win.removeEventListener(EV_LOAD, this.listenerPageLoad);
28443
28444 if (!this.getConfig(CONFIG_TRACK_PAGE_LEAVE) && !this.mp.get_config('record_heatmap_data')) {
28445 return;
28446 }
28447
28448 logger$1.log('Initializing page visibility tracking.');
28449 this._initScrollDepthTracking();
28450 var previousTrackedUrl = _.info.currentUrl();
28451
28452 // Initialize previousScrollHeight on `load` which handles async loading
28453 // https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
28454 this.listenerPageLoad = function() {
28455 this.previousScrollHeight = document$1.body.scrollHeight;
28456 }.bind(this);
28457 win.addEventListener(EV_LOAD, this.listenerPageLoad);
28458
28459 // Track page navigation events similar to how initPageviewTracking does it
28460 this.listenerPageLeaveLocationchange = safewrap(function(ev) {
28461 if (this.currentUrlBlocked()) {
28462 return;
28463 }
28464
28465 var currentUrl = _.info.currentUrl();
28466 // Track all URL changes including query string or fragment changes as separate scroll sessions
28467 var shouldTrack = currentUrl !== previousTrackedUrl;
28468
28469 if (shouldTrack) {
28470 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
28471 previousTrackedUrl = currentUrl;
28472 // Fragment navigation should call scroll(end) and trigger listener, don't add window.scrollY here.
28473 this.maxScrollViewDepth = Math.max(document$1.documentElement.clientHeight, win.innerHeight || 0);
28474 this.previousScrollHeight = document$1.body.scrollHeight;
28475 this.hasTrackedScrollSession = false;
28476 }
28477 }.bind(this));
28478 win.addEventListener(EV_MP_LOCATION_CHANGE, this.listenerPageLeaveLocationchange);
28479
28480 this.listenerPageLeaveVisibilitychange = function(ev) {
28481 if (document$1.hidden) {
28482 this._trackPageLeave(ev, previousTrackedUrl, this.previousScrollHeight);
28483 }
28484 }.bind(this);
28485 document$1.addEventListener(EV_VISIBILITYCHANGE, this.listenerPageLeaveVisibilitychange);
28486 };
28487
28488 Autocapture.prototype.stopDeadClickTracking = function() {
28489 if (this.listenerDeadClick) {
28490 win.removeEventListener(EV_CLICK, this.listenerDeadClick);
28491 this.listenerDeadClick = null;
28492 }
28493
28494 if (this._deadClickTracker) {
28495 this._deadClickTracker.stopTracking();
28496 this._deadClickTracker = null;
28497 }
28498 };
28499
28500 // TODO integrate error_reporter from mixpanel instance
28501 safewrapClass(Autocapture);
28502
28503 var logger = console_with_prefix('flags');
28504
28505 var FLAGS_CONFIG_KEY = 'flags';
28506
28507 var CONFIG_CONTEXT = 'context';
28508 var CONFIG_DEFAULTS = {};
28509 CONFIG_DEFAULTS[CONFIG_CONTEXT] = {};
28510
28511 /**
28512 * FeatureFlagManager: support for Mixpanel's feature flagging product
28513 * @constructor
28514 */
28515 var FeatureFlagManager = function(initOptions) {
28516 this.fetch = win['fetch'];
28517 this.getFullApiRoute = initOptions.getFullApiRoute;
28518 this.getMpConfig = initOptions.getConfigFunc;
28519 this.setMpConfig = initOptions.setConfigFunc;
28520 this.getMpProperty = initOptions.getPropertyFunc;
28521 this.track = initOptions.trackingFunc;
28522 };
28523
28524 FeatureFlagManager.prototype.init = function() {
28525 if (!this.minApisSupported()) {
28526 logger.critical('Feature Flags unavailable: missing minimum required APIs');
28527 return;
28528 }
28529
28530 this.flags = null;
28531 this.fetchFlags();
28532
28533 this.trackedFeatures = new Set();
28534 };
28535
28536 FeatureFlagManager.prototype.getFullConfig = function() {
28537 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
28538 if (!ffConfig) {
28539 // flags are completely off
28540 return {};
28541 } else if (_.isObject(ffConfig)) {
28542 return _.extend({}, CONFIG_DEFAULTS, ffConfig);
28543 } else {
28544 // config is non-object truthy value, return default
28545 return CONFIG_DEFAULTS;
28546 }
28547 };
28548
28549 FeatureFlagManager.prototype.getConfig = function(key) {
28550 return this.getFullConfig()[key];
28551 };
28552
28553 FeatureFlagManager.prototype.isSystemEnabled = function() {
28554 return !!this.getMpConfig(FLAGS_CONFIG_KEY);
28555 };
28556
28557 FeatureFlagManager.prototype.updateContext = function(newContext, options) {
28558 if (!this.isSystemEnabled()) {
28559 logger.critical('Feature Flags not enabled, cannot update context');
28560 return Promise.resolve();
28561 }
28562
28563 var ffConfig = this.getMpConfig(FLAGS_CONFIG_KEY);
28564 if (!_.isObject(ffConfig)) {
28565 ffConfig = {};
28566 }
28567 var oldContext = (options && options['replace']) ? {} : this.getConfig(CONFIG_CONTEXT);
28568 ffConfig[CONFIG_CONTEXT] = _.extend({}, oldContext, newContext);
28569
28570 this.setMpConfig(FLAGS_CONFIG_KEY, ffConfig);
28571 return this.fetchFlags();
28572 };
28573
28574 FeatureFlagManager.prototype.areFlagsReady = function() {
28575 if (!this.isSystemEnabled()) {
28576 logger.error('Feature Flags not enabled');
28577 }
28578 return !!this.flags;
28579 };
28580
28581 FeatureFlagManager.prototype.fetchFlags = function() {
28582 if (!this.isSystemEnabled()) {
28583 return Promise.resolve();
28584 }
28585
28586 var distinctId = this.getMpProperty('distinct_id');
28587 var deviceId = this.getMpProperty('$device_id');
28588 var traceparent = generateTraceparent();
28589 logger.log('Fetching flags for distinct ID: ' + distinctId);
28590
28591 var context = _.extend({'distinct_id': distinctId, 'device_id': deviceId}, this.getConfig(CONFIG_CONTEXT));
28592 var searchParams = new URLSearchParams();
28593 searchParams.set('context', JSON.stringify(context));
28594 searchParams.set('token', this.getMpConfig('token'));
28595 searchParams.set('mp_lib', 'web');
28596 searchParams.set('$lib_version', Config.LIB_VERSION);
28597 var url = this.getFullApiRoute() + '?' + searchParams.toString();
28598
28599 this._fetchInProgressStartTime = Date.now();
28600 this.fetchPromise = this.fetch.call(win, url, {
28601 'method': 'GET',
28602 'headers': {
28603 'Authorization': 'Basic ' + btoa(this.getMpConfig('token') + ':'),
28604 'traceparent': traceparent
28605 }
28606 }).then(function(response) {
28607 this.markFetchComplete();
28608 return response.json().then(function(responseBody) {
28609 var responseFlags = responseBody['flags'];
28610 if (!responseFlags) {
28611 throw new Error('No flags in API response');
28612 }
28613 var flags = new Map();
28614 _.each(responseFlags, function(data, key) {
28615 flags.set(key, {
28616 'key': data['variant_key'],
28617 'value': data['variant_value'],
28618 'experiment_id': data['experiment_id'],
28619 'is_experiment_active': data['is_experiment_active'],
28620 'is_qa_tester': data['is_qa_tester']
28621 });
28622 });
28623 this.flags = flags;
28624 this._traceparent = traceparent;
28625 }.bind(this)).catch(function(error) {
28626 this.markFetchComplete();
28627 logger.error(error);
28628 }.bind(this));
28629 }.bind(this)).catch(function(error) {
28630 this.markFetchComplete();
28631 logger.error(error);
28632 }.bind(this));
28633
28634 return this.fetchPromise;
28635 };
28636
28637 FeatureFlagManager.prototype.markFetchComplete = function() {
28638 if (!this._fetchInProgressStartTime) {
28639 logger.error('Fetch in progress started time not set, cannot mark fetch complete');
28640 return;
28641 }
28642 this._fetchStartTime = this._fetchInProgressStartTime;
28643 this._fetchCompleteTime = Date.now();
28644 this._fetchLatency = this._fetchCompleteTime - this._fetchStartTime;
28645 this._fetchInProgressStartTime = null;
28646 };
28647
28648 FeatureFlagManager.prototype.getVariant = function(featureName, fallback) {
28649 if (!this.fetchPromise) {
28650 return new Promise(function(resolve) {
28651 logger.critical('Feature Flags not initialized');
28652 resolve(fallback);
28653 });
28654 }
28655
28656 return this.fetchPromise.then(function() {
28657 return this.getVariantSync(featureName, fallback);
28658 }.bind(this)).catch(function(error) {
28659 logger.error(error);
28660 return fallback;
28661 });
28662 };
28663
28664 FeatureFlagManager.prototype.getVariantSync = function(featureName, fallback) {
28665 if (!this.areFlagsReady()) {
28666 logger.log('Flags not loaded yet');
28667 return fallback;
28668 }
28669 var feature = this.flags.get(featureName);
28670 if (!feature) {
28671 logger.log('No flag found: "' + featureName + '"');
28672 return fallback;
28673 }
28674 this.trackFeatureCheck(featureName, feature);
28675 return feature;
28676 };
28677
28678 FeatureFlagManager.prototype.getVariantValue = function(featureName, fallbackValue) {
28679 return this.getVariant(featureName, {'value': fallbackValue}).then(function(feature) {
28680 return feature['value'];
28681 }).catch(function(error) {
28682 logger.error(error);
28683 return fallbackValue;
28684 });
28685 };
28686
28687 // TODO remove deprecated method
28688 FeatureFlagManager.prototype.getFeatureData = function(featureName, fallbackValue) {
28689 logger.critical('mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead.');
28690 return this.getVariantValue(featureName, fallbackValue);
28691 };
28692
28693 FeatureFlagManager.prototype.getVariantValueSync = function(featureName, fallbackValue) {
28694 return this.getVariantSync(featureName, {'value': fallbackValue})['value'];
28695 };
28696
28697 FeatureFlagManager.prototype.isEnabled = function(featureName, fallbackValue) {
28698 return this.getVariantValue(featureName).then(function() {
28699 return this.isEnabledSync(featureName, fallbackValue);
28700 }.bind(this)).catch(function(error) {
28701 logger.error(error);
28702 return fallbackValue;
28703 });
28704 };
28705
28706 FeatureFlagManager.prototype.isEnabledSync = function(featureName, fallbackValue) {
28707 fallbackValue = fallbackValue || false;
28708 var val = this.getVariantValueSync(featureName, fallbackValue);
28709 if (val !== true && val !== false) {
28710 logger.error('Feature flag "' + featureName + '" value: ' + val + ' is not a boolean; returning fallback value: ' + fallbackValue);
28711 val = fallbackValue;
28712 }
28713 return val;
28714 };
28715
28716 FeatureFlagManager.prototype.trackFeatureCheck = function(featureName, feature) {
28717 if (this.trackedFeatures.has(featureName)) {
28718 return;
28719 }
28720 this.trackedFeatures.add(featureName);
28721
28722 var trackingProperties = {
28723 'Experiment name': featureName,
28724 'Variant name': feature['key'],
28725 '$experiment_type': 'feature_flag',
28726 'Variant fetch start time': new Date(this._fetchStartTime).toISOString(),
28727 'Variant fetch complete time': new Date(this._fetchCompleteTime).toISOString(),
28728 'Variant fetch latency (ms)': this._fetchLatency,
28729 'Variant fetch traceparent': this._traceparent,
28730 };
28731
28732 if (feature['experiment_id'] !== 'undefined') {
28733 trackingProperties['$experiment_id'] = feature['experiment_id'];
28734 }
28735 if (feature['is_experiment_active'] !== 'undefined') {
28736 trackingProperties['$is_experiment_active'] = feature['is_experiment_active'];
28737 }
28738 if (feature['is_qa_tester'] !== 'undefined') {
28739 trackingProperties['$is_qa_tester'] = feature['is_qa_tester'];
28740 }
28741
28742 this.track('$experiment_started', trackingProperties);
28743 };
28744
28745 FeatureFlagManager.prototype.minApisSupported = function() {
28746 return !!this.fetch &&
28747 typeof Promise !== 'undefined' &&
28748 typeof Map !== 'undefined' &&
28749 typeof Set !== 'undefined';
28750 };
28751
28752 safewrapClass(FeatureFlagManager);
28753
28754 FeatureFlagManager.prototype['are_flags_ready'] = FeatureFlagManager.prototype.areFlagsReady;
28755 FeatureFlagManager.prototype['get_variant'] = FeatureFlagManager.prototype.getVariant;
28756 FeatureFlagManager.prototype['get_variant_sync'] = FeatureFlagManager.prototype.getVariantSync;
28757 FeatureFlagManager.prototype['get_variant_value'] = FeatureFlagManager.prototype.getVariantValue;
28758 FeatureFlagManager.prototype['get_variant_value_sync'] = FeatureFlagManager.prototype.getVariantValueSync;
28759 FeatureFlagManager.prototype['is_enabled'] = FeatureFlagManager.prototype.isEnabled;
28760 FeatureFlagManager.prototype['is_enabled_sync'] = FeatureFlagManager.prototype.isEnabledSync;
28761 FeatureFlagManager.prototype['update_context'] = FeatureFlagManager.prototype.updateContext;
28762
28763 // Deprecated method
28764 FeatureFlagManager.prototype['get_feature_data'] = FeatureFlagManager.prototype.getFeatureData;
28765
28766 /* eslint camelcase: "off" */
28767
28768
28769 /**
28770 * DomTracker Object
28771 * @constructor
28772 */
28773 var DomTracker = function() {};
28774
28775
28776 // interface
28777 DomTracker.prototype.create_properties = function() {};
28778 DomTracker.prototype.event_handler = function() {};
28779 DomTracker.prototype.after_track_handler = function() {};
28780
28781 DomTracker.prototype.init = function(mixpanel_instance) {
28782 this.mp = mixpanel_instance;
28783 return this;
28784 };
28785
28786 /**
28787 * @param {Object|string} query
28788 * @param {string} event_name
28789 * @param {Object=} properties
28790 * @param {function=} user_callback
28791 */
28792 DomTracker.prototype.track = function(query, event_name, properties, user_callback) {
28793 var that = this;
28794 var elements = _.dom_query(query);
28795
28796 if (elements.length === 0) {
28797 console$1.error('The DOM query (' + query + ') returned 0 elements');
28798 return;
28799 }
28800
28801 _.each(elements, function(element) {
28802 _.register_event(element, this.override_event, function(e) {
28803 var options = {};
28804 var props = that.create_properties(properties, this);
28805 var timeout = that.mp.get_config('track_links_timeout');
28806
28807 that.event_handler(e, this, options);
28808
28809 // in case the mixpanel servers don't get back to us in time
28810 window.setTimeout(that.track_callback(user_callback, props, options, true), timeout);
28811
28812 // fire the tracking event
28813 that.mp.track(event_name, props, that.track_callback(user_callback, props, options));
28814 });
28815 }, this);
28816
28817 return true;
28818 };
28819
28820 /**
28821 * @param {function} user_callback
28822 * @param {Object} props
28823 * @param {boolean=} timeout_occured
28824 */
28825 DomTracker.prototype.track_callback = function(user_callback, props, options, timeout_occured) {
28826 timeout_occured = timeout_occured || false;
28827 var that = this;
28828
28829 return function() {
28830 // options is referenced from both callbacks, so we can have
28831 // a 'lock' of sorts to ensure only one fires
28832 if (options.callback_fired) { return; }
28833 options.callback_fired = true;
28834
28835 if (user_callback && user_callback(timeout_occured, props) === false) {
28836 // user can prevent the default functionality by
28837 // returning false from their callback
28838 return;
28839 }
28840
28841 that.after_track_handler(props, options, timeout_occured);
28842 };
28843 };
28844
28845 DomTracker.prototype.create_properties = function(properties, element) {
28846 var props;
28847
28848 if (typeof(properties) === 'function') {
28849 props = properties(element);
28850 } else {
28851 props = _.extend({}, properties);
28852 }
28853
28854 return props;
28855 };
28856
28857 /**
28858 * LinkTracker Object
28859 * @constructor
28860 * @extends DomTracker
28861 */
28862 var LinkTracker = function() {
28863 this.override_event = 'click';
28864 };
28865 _.inherit(LinkTracker, DomTracker);
28866
28867 LinkTracker.prototype.create_properties = function(properties, element) {
28868 var props = LinkTracker.superclass.create_properties.apply(this, arguments);
28869
28870 if (element.href) { props['url'] = element.href; }
28871
28872 return props;
28873 };
28874
28875 LinkTracker.prototype.event_handler = function(evt, element, options) {
28876 options.new_tab = (
28877 evt.which === 2 ||
28878 evt.metaKey ||
28879 evt.ctrlKey ||
28880 element.target === '_blank'
28881 );
28882 options.href = element.href;
28883
28884 if (!options.new_tab) {
28885 evt.preventDefault();
28886 }
28887 };
28888
28889 LinkTracker.prototype.after_track_handler = function(props, options) {
28890 if (options.new_tab) { return; }
28891
28892 setTimeout(function() {
28893 window.location = options.href;
28894 }, 0);
28895 };
28896
28897 /**
28898 * FormTracker Object
28899 * @constructor
28900 * @extends DomTracker
28901 */
28902 var FormTracker = function() {
28903 this.override_event = 'submit';
28904 };
28905 _.inherit(FormTracker, DomTracker);
28906
28907 FormTracker.prototype.event_handler = function(evt, element, options) {
28908 options.element = element;
28909 evt.preventDefault();
28910 };
28911
28912 FormTracker.prototype.after_track_handler = function(props, options) {
28913 setTimeout(function() {
28914 options.element.submit();
28915 }, 0);
28916 };
28917
28918 /* eslint camelcase: "off" */
28919
28920
28921 /** @const */ var SET_ACTION = '$set';
28922 /** @const */ var SET_ONCE_ACTION = '$set_once';
28923 /** @const */ var UNSET_ACTION = '$unset';
28924 /** @const */ var ADD_ACTION = '$add';
28925 /** @const */ var APPEND_ACTION = '$append';
28926 /** @const */ var UNION_ACTION = '$union';
28927 /** @const */ var REMOVE_ACTION = '$remove';
28928 /** @const */ var DELETE_ACTION = '$delete';
28929
28930 // Common internal methods for mixpanel.people and mixpanel.group APIs.
28931 // These methods shouldn't involve network I/O.
28932 var apiActions = {
28933 set_action: function(prop, to) {
28934 var data = {};
28935 var $set = {};
28936 if (_.isObject(prop)) {
28937 _.each(prop, function(v, k) {
28938 if (!this._is_reserved_property(k)) {
28939 $set[k] = v;
28940 }
28941 }, this);
28942 } else {
28943 $set[prop] = to;
28944 }
28945
28946 data[SET_ACTION] = $set;
28947 return data;
28948 },
28949
28950 unset_action: function(prop) {
28951 var data = {};
28952 var $unset = [];
28953 if (!_.isArray(prop)) {
28954 prop = [prop];
28955 }
28956
28957 _.each(prop, function(k) {
28958 if (!this._is_reserved_property(k)) {
28959 $unset.push(k);
28960 }
28961 }, this);
28962
28963 data[UNSET_ACTION] = $unset;
28964 return data;
28965 },
28966
28967 set_once_action: function(prop, to) {
28968 var data = {};
28969 var $set_once = {};
28970 if (_.isObject(prop)) {
28971 _.each(prop, function(v, k) {
28972 if (!this._is_reserved_property(k)) {
28973 $set_once[k] = v;
28974 }
28975 }, this);
28976 } else {
28977 $set_once[prop] = to;
28978 }
28979 data[SET_ONCE_ACTION] = $set_once;
28980 return data;
28981 },
28982
28983 union_action: function(list_name, values) {
28984 var data = {};
28985 var $union = {};
28986 if (_.isObject(list_name)) {
28987 _.each(list_name, function(v, k) {
28988 if (!this._is_reserved_property(k)) {
28989 $union[k] = _.isArray(v) ? v : [v];
28990 }
28991 }, this);
28992 } else {
28993 $union[list_name] = _.isArray(values) ? values : [values];
28994 }
28995 data[UNION_ACTION] = $union;
28996 return data;
28997 },
28998
28999 append_action: function(list_name, value) {
29000 var data = {};
29001 var $append = {};
29002 if (_.isObject(list_name)) {
29003 _.each(list_name, function(v, k) {
29004 if (!this._is_reserved_property(k)) {
29005 $append[k] = v;
29006 }
29007 }, this);
29008 } else {
29009 $append[list_name] = value;
29010 }
29011 data[APPEND_ACTION] = $append;
29012 return data;
29013 },
29014
29015 remove_action: function(list_name, value) {
29016 var data = {};
29017 var $remove = {};
29018 if (_.isObject(list_name)) {
29019 _.each(list_name, function(v, k) {
29020 if (!this._is_reserved_property(k)) {
29021 $remove[k] = v;
29022 }
29023 }, this);
29024 } else {
29025 $remove[list_name] = value;
29026 }
29027 data[REMOVE_ACTION] = $remove;
29028 return data;
29029 },
29030
29031 delete_action: function() {
29032 var data = {};
29033 data[DELETE_ACTION] = '';
29034 return data;
29035 }
29036 };
29037
29038 /* eslint camelcase: "off" */
29039
29040 /**
29041 * Mixpanel Group Object
29042 * @constructor
29043 */
29044 var MixpanelGroup = function() {};
29045
29046 _.extend(MixpanelGroup.prototype, apiActions);
29047
29048 MixpanelGroup.prototype._init = function(mixpanel_instance, group_key, group_id) {
29049 this._mixpanel = mixpanel_instance;
29050 this._group_key = group_key;
29051 this._group_id = group_id;
29052 };
29053
29054 /**
29055 * Set properties on a group.
29056 *
29057 * ### Usage:
29058 *
29059 * mixpanel.get_group('company', 'mixpanel').set('Location', '405 Howard');
29060 *
29061 * // or set multiple properties at once
29062 * mixpanel.get_group('company', 'mixpanel').set({
29063 * 'Location': '405 Howard',
29064 * 'Founded' : 2009,
29065 * });
29066 * // properties can be strings, integers, dates, or lists
29067 *
29068 * @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.
29069 * @param {*} [to] A value to set on the given property name
29070 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29071 */
29072 MixpanelGroup.prototype.set = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
29073 var data = this.set_action(prop, to);
29074 if (_.isObject(prop)) {
29075 callback = to;
29076 }
29077 return this._send_request(data, callback);
29078 });
29079
29080 /**
29081 * Set properties on a group, only if they do not yet exist.
29082 * This will not overwrite previous group property values, unlike
29083 * group.set().
29084 *
29085 * ### Usage:
29086 *
29087 * mixpanel.get_group('company', 'mixpanel').set_once('Location', '405 Howard');
29088 *
29089 * // or set multiple properties at once
29090 * mixpanel.get_group('company', 'mixpanel').set_once({
29091 * 'Location': '405 Howard',
29092 * 'Founded' : 2009,
29093 * });
29094 * // properties can be strings, integers, lists or dates
29095 *
29096 * @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.
29097 * @param {*} [to] A value to set on the given property name
29098 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29099 */
29100 MixpanelGroup.prototype.set_once = addOptOutCheckMixpanelGroup(function(prop, to, callback) {
29101 var data = this.set_once_action(prop, to);
29102 if (_.isObject(prop)) {
29103 callback = to;
29104 }
29105 return this._send_request(data, callback);
29106 });
29107
29108 /**
29109 * Unset properties on a group permanently.
29110 *
29111 * ### Usage:
29112 *
29113 * mixpanel.get_group('company', 'mixpanel').unset('Founded');
29114 *
29115 * @param {String} prop The name of the property.
29116 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29117 */
29118 MixpanelGroup.prototype.unset = addOptOutCheckMixpanelGroup(function(prop, callback) {
29119 var data = this.unset_action(prop);
29120 return this._send_request(data, callback);
29121 });
29122
29123 /**
29124 * Merge a given list with a list-valued group property, excluding duplicate values.
29125 *
29126 * ### Usage:
29127 *
29128 * // merge a value to a list, creating it if needed
29129 * mixpanel.get_group('company', 'mixpanel').union('Location', ['San Francisco', 'London']);
29130 *
29131 * @param {String} list_name Name of the property.
29132 * @param {Array} values Values to merge with the given property
29133 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29134 */
29135 MixpanelGroup.prototype.union = addOptOutCheckMixpanelGroup(function(list_name, values, callback) {
29136 if (_.isObject(list_name)) {
29137 callback = values;
29138 }
29139 var data = this.union_action(list_name, values);
29140 return this._send_request(data, callback);
29141 });
29142
29143 /**
29144 * Permanently delete a group.
29145 *
29146 * ### Usage:
29147 *
29148 * mixpanel.get_group('company', 'mixpanel').delete();
29149 *
29150 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29151 */
29152 MixpanelGroup.prototype['delete'] = addOptOutCheckMixpanelGroup(function(callback) {
29153 // bracket notation above prevents a minification error related to reserved words
29154 var data = this.delete_action();
29155 return this._send_request(data, callback);
29156 });
29157
29158 /**
29159 * Remove a property from a group. The value will be ignored if doesn't exist.
29160 *
29161 * ### Usage:
29162 *
29163 * mixpanel.get_group('company', 'mixpanel').remove('Location', 'London');
29164 *
29165 * @param {String} list_name Name of the property.
29166 * @param {Object} value Value to remove from the given group property
29167 * @param {Function} [callback] If provided, the callback will be called after the tracking event
29168 */
29169 MixpanelGroup.prototype.remove = addOptOutCheckMixpanelGroup(function(list_name, value, callback) {
29170 var data = this.remove_action(list_name, value);
29171 return this._send_request(data, callback);
29172 });
29173
29174 MixpanelGroup.prototype._send_request = function(data, callback) {
29175 data['$group_key'] = this._group_key;
29176 data['$group_id'] = this._group_id;
29177 data['$token'] = this._get_config('token');
29178
29179 var date_encoded_data = _.encodeDates(data);
29180 return this._mixpanel._track_or_batch({
29181 type: 'groups',
29182 data: date_encoded_data,
29183 endpoint: this._mixpanel.get_api_host('groups') + '/' + this._get_config('api_routes')['groups'],
29184 batcher: this._mixpanel.request_batchers.groups
29185 }, callback);
29186 };
29187
29188 MixpanelGroup.prototype._is_reserved_property = function(prop) {
29189 return prop === '$group_key' || prop === '$group_id';
29190 };
29191
29192 MixpanelGroup.prototype._get_config = function(conf) {
29193 return this._mixpanel.get_config(conf);
29194 };
29195
29196 MixpanelGroup.prototype.toString = function() {
29197 return this._mixpanel.toString() + '.group.' + this._group_key + '.' + this._group_id;
29198 };
29199
29200 // MixpanelGroup Exports
29201 MixpanelGroup.prototype['remove'] = MixpanelGroup.prototype.remove;
29202 MixpanelGroup.prototype['set'] = MixpanelGroup.prototype.set;
29203 MixpanelGroup.prototype['set_once'] = MixpanelGroup.prototype.set_once;
29204 MixpanelGroup.prototype['union'] = MixpanelGroup.prototype.union;
29205 MixpanelGroup.prototype['unset'] = MixpanelGroup.prototype.unset;
29206 MixpanelGroup.prototype['toString'] = MixpanelGroup.prototype.toString;
29207
29208 /* eslint camelcase: "off" */
29209
29210 /**
29211 * Mixpanel People Object
29212 * @constructor
29213 */
29214 var MixpanelPeople = function() {};
29215
29216 _.extend(MixpanelPeople.prototype, apiActions);
29217
29218 MixpanelPeople.prototype._init = function(mixpanel_instance) {
29219 this._mixpanel = mixpanel_instance;
29220 };
29221
29222 /*
29223 * Set properties on a user record.
29224 *
29225 * ### Usage:
29226 *
29227 * mixpanel.people.set('gender', 'm');
29228 *
29229 * // or set multiple properties at once
29230 * mixpanel.people.set({
29231 * 'Company': 'Acme',
29232 * 'Plan': 'Premium',
29233 * 'Upgrade date': new Date()
29234 * });
29235 * // properties can be strings, integers, dates, or lists
29236 *
29237 * @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.
29238 * @param {*} [to] A value to set on the given property name
29239 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29240 */
29241 MixpanelPeople.prototype.set = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
29242 var data = this.set_action(prop, to);
29243 if (_.isObject(prop)) {
29244 callback = to;
29245 }
29246 // make sure that the referrer info has been updated and saved
29247 if (this._get_config('save_referrer')) {
29248 this._mixpanel['persistence'].update_referrer_info(document.referrer);
29249 }
29250
29251 // update $set object with default people properties
29252 data[SET_ACTION] = _.extend(
29253 {},
29254 _.info.people_properties(),
29255 data[SET_ACTION]
29256 );
29257 return this._send_request(data, callback);
29258 });
29259
29260 /*
29261 * Set properties on a user record, only if they do not yet exist.
29262 * This will not overwrite previous people property values, unlike
29263 * people.set().
29264 *
29265 * ### Usage:
29266 *
29267 * mixpanel.people.set_once('First Login Date', new Date());
29268 *
29269 * // or set multiple properties at once
29270 * mixpanel.people.set_once({
29271 * 'First Login Date': new Date(),
29272 * 'Starting Plan': 'Premium'
29273 * });
29274 *
29275 * // properties can be strings, integers or dates
29276 *
29277 * @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.
29278 * @param {*} [to] A value to set on the given property name
29279 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29280 */
29281 MixpanelPeople.prototype.set_once = addOptOutCheckMixpanelPeople(function(prop, to, callback) {
29282 var data = this.set_once_action(prop, to);
29283 if (_.isObject(prop)) {
29284 callback = to;
29285 }
29286 return this._send_request(data, callback);
29287 });
29288
29289 /*
29290 * Unset properties on a user record (permanently removes the properties and their values from a profile).
29291 *
29292 * ### Usage:
29293 *
29294 * mixpanel.people.unset('gender');
29295 *
29296 * // or unset multiple properties at once
29297 * mixpanel.people.unset(['gender', 'Company']);
29298 *
29299 * @param {Array|String} prop If a string, this is the name of the property. If an array, this is a list of property names.
29300 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29301 */
29302 MixpanelPeople.prototype.unset = addOptOutCheckMixpanelPeople(function(prop, callback) {
29303 var data = this.unset_action(prop);
29304 return this._send_request(data, callback);
29305 });
29306
29307 /*
29308 * Increment/decrement numeric people analytics properties.
29309 *
29310 * ### Usage:
29311 *
29312 * mixpanel.people.increment('page_views', 1);
29313 *
29314 * // or, for convenience, if you're just incrementing a counter by
29315 * // 1, you can simply do
29316 * mixpanel.people.increment('page_views');
29317 *
29318 * // to decrement a counter, pass a negative number
29319 * mixpanel.people.increment('credits_left', -1);
29320 *
29321 * // like mixpanel.people.set(), you can increment multiple
29322 * // properties at once:
29323 * mixpanel.people.increment({
29324 * counter1: 1,
29325 * counter2: 6
29326 * });
29327 *
29328 * @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.
29329 * @param {Number} [by] An amount to increment the given property
29330 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29331 */
29332 MixpanelPeople.prototype.increment = addOptOutCheckMixpanelPeople(function(prop, by, callback) {
29333 var data = {};
29334 var $add = {};
29335 if (_.isObject(prop)) {
29336 _.each(prop, function(v, k) {
29337 if (!this._is_reserved_property(k)) {
29338 if (isNaN(parseFloat(v))) {
29339 console$1.error('Invalid increment value passed to mixpanel.people.increment - must be a number');
29340 return;
29341 } else {
29342 $add[k] = v;
29343 }
29344 }
29345 }, this);
29346 callback = by;
29347 } else {
29348 // convenience: mixpanel.people.increment('property'); will
29349 // increment 'property' by 1
29350 if (_.isUndefined(by)) {
29351 by = 1;
29352 }
29353 $add[prop] = by;
29354 }
29355 data[ADD_ACTION] = $add;
29356
29357 return this._send_request(data, callback);
29358 });
29359
29360 /*
29361 * Append a value to a list-valued people analytics property.
29362 *
29363 * ### Usage:
29364 *
29365 * // append a value to a list, creating it if needed
29366 * mixpanel.people.append('pages_visited', 'homepage');
29367 *
29368 * // like mixpanel.people.set(), you can append multiple
29369 * // properties at once:
29370 * mixpanel.people.append({
29371 * list1: 'bob',
29372 * list2: 123
29373 * });
29374 *
29375 * @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.
29376 * @param {*} [value] value An item to append to the list
29377 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29378 */
29379 MixpanelPeople.prototype.append = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
29380 if (_.isObject(list_name)) {
29381 callback = value;
29382 }
29383 var data = this.append_action(list_name, value);
29384 return this._send_request(data, callback);
29385 });
29386
29387 /*
29388 * Remove a value from a list-valued people analytics property.
29389 *
29390 * ### Usage:
29391 *
29392 * mixpanel.people.remove('School', 'UCB');
29393 *
29394 * @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.
29395 * @param {*} [value] value Item to remove from the list
29396 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29397 */
29398 MixpanelPeople.prototype.remove = addOptOutCheckMixpanelPeople(function(list_name, value, callback) {
29399 if (_.isObject(list_name)) {
29400 callback = value;
29401 }
29402 var data = this.remove_action(list_name, value);
29403 return this._send_request(data, callback);
29404 });
29405
29406 /*
29407 * Merge a given list with a list-valued people analytics property,
29408 * excluding duplicate values.
29409 *
29410 * ### Usage:
29411 *
29412 * // merge a value to a list, creating it if needed
29413 * mixpanel.people.union('pages_visited', 'homepage');
29414 *
29415 * // like mixpanel.people.set(), you can append multiple
29416 * // properties at once:
29417 * mixpanel.people.union({
29418 * list1: 'bob',
29419 * list2: 123
29420 * });
29421 *
29422 * // like mixpanel.people.append(), you can append multiple
29423 * // values to the same list:
29424 * mixpanel.people.union({
29425 * list1: ['bob', 'billy']
29426 * });
29427 *
29428 * @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.
29429 * @param {*} [value] Value / values to merge with the given property
29430 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29431 */
29432 MixpanelPeople.prototype.union = addOptOutCheckMixpanelPeople(function(list_name, values, callback) {
29433 if (_.isObject(list_name)) {
29434 callback = values;
29435 }
29436 var data = this.union_action(list_name, values);
29437 return this._send_request(data, callback);
29438 });
29439
29440 /*
29441 * Record that you have charged the current user a certain amount
29442 * of money. Charges recorded with track_charge() will appear in the
29443 * Mixpanel revenue report.
29444 *
29445 * ### Usage:
29446 *
29447 * // charge a user $50
29448 * mixpanel.people.track_charge(50);
29449 *
29450 * // charge a user $30.50 on the 2nd of january
29451 * mixpanel.people.track_charge(30.50, {
29452 * '$time': new Date('jan 1 2012')
29453 * });
29454 *
29455 * @param {Number} amount The amount of money charged to the current user
29456 * @param {Object} [properties] An associative array of properties associated with the charge
29457 * @param {Function} [callback] If provided, the callback will be called when the server responds
29458 * @deprecated
29459 */
29460 MixpanelPeople.prototype.track_charge = addOptOutCheckMixpanelPeople(function() {
29461 console$1.error('mixpanel.people.track_charge() is deprecated and no longer has any effect.');
29462 });
29463
29464 /*
29465 * Permanently clear all revenue report transactions from the
29466 * current user's people analytics profile.
29467 *
29468 * ### Usage:
29469 *
29470 * mixpanel.people.clear_charges();
29471 *
29472 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
29473 * @deprecated
29474 */
29475 MixpanelPeople.prototype.clear_charges = function(callback) {
29476 return this.set('$transactions', [], callback);
29477 };
29478
29479 /*
29480 * Permanently deletes the current people analytics profile from
29481 * Mixpanel (using the current distinct_id).
29482 *
29483 * ### Usage:
29484 *
29485 * // remove the all data you have stored about the current user
29486 * mixpanel.people.delete_user();
29487 *
29488 */
29489 MixpanelPeople.prototype.delete_user = function() {
29490 if (!this._identify_called()) {
29491 console$1.error('mixpanel.people.delete_user() requires you to call identify() first');
29492 return;
29493 }
29494 var data = {'$delete': this._mixpanel.get_distinct_id()};
29495 return this._send_request(data);
29496 };
29497
29498 MixpanelPeople.prototype.toString = function() {
29499 return this._mixpanel.toString() + '.people';
29500 };
29501
29502 MixpanelPeople.prototype._send_request = function(data, callback) {
29503 data['$token'] = this._get_config('token');
29504 data['$distinct_id'] = this._mixpanel.get_distinct_id();
29505 var device_id = this._mixpanel.get_property('$device_id');
29506 var user_id = this._mixpanel.get_property('$user_id');
29507 var had_persisted_distinct_id = this._mixpanel.get_property('$had_persisted_distinct_id');
29508 if (device_id) {
29509 data['$device_id'] = device_id;
29510 }
29511 if (user_id) {
29512 data['$user_id'] = user_id;
29513 }
29514 if (had_persisted_distinct_id) {
29515 data['$had_persisted_distinct_id'] = had_persisted_distinct_id;
29516 }
29517
29518 var date_encoded_data = _.encodeDates(data);
29519
29520 if (!this._identify_called()) {
29521 this._enqueue(data);
29522 if (!_.isUndefined(callback)) {
29523 if (this._get_config('verbose')) {
29524 callback({status: -1, error: null});
29525 } else {
29526 callback(-1);
29527 }
29528 }
29529 return _.truncate(date_encoded_data, 255);
29530 }
29531
29532 return this._mixpanel._track_or_batch({
29533 type: 'people',
29534 data: date_encoded_data,
29535 endpoint: this._mixpanel.get_api_host('people') + '/' + this._get_config('api_routes')['engage'],
29536 batcher: this._mixpanel.request_batchers.people
29537 }, callback);
29538 };
29539
29540 MixpanelPeople.prototype._get_config = function(conf_var) {
29541 return this._mixpanel.get_config(conf_var);
29542 };
29543
29544 MixpanelPeople.prototype._identify_called = function() {
29545 return this._mixpanel._flags.identify_called === true;
29546 };
29547
29548 // Queue up engage operations if identify hasn't been called yet.
29549 MixpanelPeople.prototype._enqueue = function(data) {
29550 if (SET_ACTION in data) {
29551 this._mixpanel['persistence']._add_to_people_queue(SET_ACTION, data);
29552 } else if (SET_ONCE_ACTION in data) {
29553 this._mixpanel['persistence']._add_to_people_queue(SET_ONCE_ACTION, data);
29554 } else if (UNSET_ACTION in data) {
29555 this._mixpanel['persistence']._add_to_people_queue(UNSET_ACTION, data);
29556 } else if (ADD_ACTION in data) {
29557 this._mixpanel['persistence']._add_to_people_queue(ADD_ACTION, data);
29558 } else if (APPEND_ACTION in data) {
29559 this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, data);
29560 } else if (REMOVE_ACTION in data) {
29561 this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, data);
29562 } else if (UNION_ACTION in data) {
29563 this._mixpanel['persistence']._add_to_people_queue(UNION_ACTION, data);
29564 } else {
29565 console$1.error('Invalid call to _enqueue():', data);
29566 }
29567 };
29568
29569 MixpanelPeople.prototype._flush_one_queue = function(action, action_method, callback, queue_to_params_fn) {
29570 var _this = this;
29571 var queued_data = _.extend({}, this._mixpanel['persistence'].load_queue(action));
29572 var action_params = queued_data;
29573
29574 if (!_.isUndefined(queued_data) && _.isObject(queued_data) && !_.isEmptyObject(queued_data)) {
29575 _this._mixpanel['persistence']._pop_from_people_queue(action, queued_data);
29576 _this._mixpanel['persistence'].save();
29577 if (queue_to_params_fn) {
29578 action_params = queue_to_params_fn(queued_data);
29579 }
29580 action_method.call(_this, action_params, function(response, data) {
29581 // on bad response, we want to add it back to the queue
29582 if (response === 0) {
29583 _this._mixpanel['persistence']._add_to_people_queue(action, queued_data);
29584 }
29585 if (!_.isUndefined(callback)) {
29586 callback(response, data);
29587 }
29588 });
29589 }
29590 };
29591
29592 // Flush queued engage operations - order does not matter,
29593 // and there are network level race conditions anyway
29594 MixpanelPeople.prototype._flush = function(
29595 _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback
29596 ) {
29597 var _this = this;
29598
29599 this._flush_one_queue(SET_ACTION, this.set, _set_callback);
29600 this._flush_one_queue(SET_ONCE_ACTION, this.set_once, _set_once_callback);
29601 this._flush_one_queue(UNSET_ACTION, this.unset, _unset_callback, function(queue) { return _.keys(queue); });
29602 this._flush_one_queue(ADD_ACTION, this.increment, _add_callback);
29603 this._flush_one_queue(UNION_ACTION, this.union, _union_callback);
29604
29605 // we have to fire off each $append individually since there is
29606 // no concat method server side
29607 var $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);
29608 if (!_.isUndefined($append_queue) && _.isArray($append_queue) && $append_queue.length) {
29609 var $append_item;
29610 var append_callback = function(response, data) {
29611 if (response === 0) {
29612 _this._mixpanel['persistence']._add_to_people_queue(APPEND_ACTION, $append_item);
29613 }
29614 if (!_.isUndefined(_append_callback)) {
29615 _append_callback(response, data);
29616 }
29617 };
29618 for (var i = $append_queue.length - 1; i >= 0; i--) {
29619 $append_queue = this._mixpanel['persistence'].load_queue(APPEND_ACTION);
29620 $append_item = $append_queue.pop();
29621 _this._mixpanel['persistence'].save();
29622 if (!_.isEmptyObject($append_item)) {
29623 _this.append($append_item, append_callback);
29624 }
29625 }
29626 }
29627
29628 // same for $remove
29629 var $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);
29630 if (!_.isUndefined($remove_queue) && _.isArray($remove_queue) && $remove_queue.length) {
29631 var $remove_item;
29632 var remove_callback = function(response, data) {
29633 if (response === 0) {
29634 _this._mixpanel['persistence']._add_to_people_queue(REMOVE_ACTION, $remove_item);
29635 }
29636 if (!_.isUndefined(_remove_callback)) {
29637 _remove_callback(response, data);
29638 }
29639 };
29640 for (var j = $remove_queue.length - 1; j >= 0; j--) {
29641 $remove_queue = this._mixpanel['persistence'].load_queue(REMOVE_ACTION);
29642 $remove_item = $remove_queue.pop();
29643 _this._mixpanel['persistence'].save();
29644 if (!_.isEmptyObject($remove_item)) {
29645 _this.remove($remove_item, remove_callback);
29646 }
29647 }
29648 }
29649 };
29650
29651 MixpanelPeople.prototype._is_reserved_property = function(prop) {
29652 return prop === '$distinct_id' || prop === '$token' || prop === '$device_id' || prop === '$user_id' || prop === '$had_persisted_distinct_id';
29653 };
29654
29655 // MixpanelPeople Exports
29656 MixpanelPeople.prototype['set'] = MixpanelPeople.prototype.set;
29657 MixpanelPeople.prototype['set_once'] = MixpanelPeople.prototype.set_once;
29658 MixpanelPeople.prototype['unset'] = MixpanelPeople.prototype.unset;
29659 MixpanelPeople.prototype['increment'] = MixpanelPeople.prototype.increment;
29660 MixpanelPeople.prototype['append'] = MixpanelPeople.prototype.append;
29661 MixpanelPeople.prototype['remove'] = MixpanelPeople.prototype.remove;
29662 MixpanelPeople.prototype['union'] = MixpanelPeople.prototype.union;
29663 MixpanelPeople.prototype['track_charge'] = MixpanelPeople.prototype.track_charge;
29664 MixpanelPeople.prototype['clear_charges'] = MixpanelPeople.prototype.clear_charges;
29665 MixpanelPeople.prototype['delete_user'] = MixpanelPeople.prototype.delete_user;
29666 MixpanelPeople.prototype['toString'] = MixpanelPeople.prototype.toString;
29667
29668 /* eslint camelcase: "off" */
29669
29670
29671 /*
29672 * Constants
29673 */
29674 /** @const */ var SET_QUEUE_KEY = '__mps';
29675 /** @const */ var SET_ONCE_QUEUE_KEY = '__mpso';
29676 /** @const */ var UNSET_QUEUE_KEY = '__mpus';
29677 /** @const */ var ADD_QUEUE_KEY = '__mpa';
29678 /** @const */ var APPEND_QUEUE_KEY = '__mpap';
29679 /** @const */ var REMOVE_QUEUE_KEY = '__mpr';
29680 /** @const */ var UNION_QUEUE_KEY = '__mpu';
29681 // This key is deprecated, but we want to check for it to see whether aliasing is allowed.
29682 /** @const */ var PEOPLE_DISTINCT_ID_KEY = '$people_distinct_id';
29683 /** @const */ var ALIAS_ID_KEY = '__alias';
29684 /** @const */ var EVENT_TIMERS_KEY = '__timers';
29685 /** @const */ var RESERVED_PROPERTIES = [
29686 SET_QUEUE_KEY,
29687 SET_ONCE_QUEUE_KEY,
29688 UNSET_QUEUE_KEY,
29689 ADD_QUEUE_KEY,
29690 APPEND_QUEUE_KEY,
29691 REMOVE_QUEUE_KEY,
29692 UNION_QUEUE_KEY,
29693 PEOPLE_DISTINCT_ID_KEY,
29694 ALIAS_ID_KEY,
29695 EVENT_TIMERS_KEY
29696 ];
29697
29698 /**
29699 * Mixpanel Persistence Object
29700 * @constructor
29701 */
29702 var MixpanelPersistence = function(config) {
29703 this['props'] = {};
29704 this.campaign_params_saved = false;
29705
29706 if (config['persistence_name']) {
29707 this.name = 'mp_' + config['persistence_name'];
29708 } else {
29709 this.name = 'mp_' + config['token'] + '_mixpanel';
29710 }
29711
29712 var storage_type = config['persistence'];
29713 if (storage_type !== 'cookie' && storage_type !== 'localStorage') {
29714 console$1.critical('Unknown persistence type ' + storage_type + '; falling back to cookie');
29715 storage_type = config['persistence'] = 'cookie';
29716 }
29717
29718 if (storage_type === 'localStorage' && _.localStorage.is_supported()) {
29719 this.storage = _.localStorage;
29720 } else {
29721 this.storage = _.cookie;
29722 }
29723
29724 this.load();
29725 this.update_config(config);
29726 this.upgrade();
29727 this.save();
29728 };
29729
29730 MixpanelPersistence.prototype.properties = function() {
29731 var p = {};
29732
29733 this.load();
29734
29735 // Filter out reserved properties
29736 _.each(this['props'], function(v, k) {
29737 if (!_.include(RESERVED_PROPERTIES, k)) {
29738 p[k] = v;
29739 }
29740 });
29741 return p;
29742 };
29743
29744 MixpanelPersistence.prototype.load = function() {
29745 if (this.disabled) { return; }
29746
29747 var entry = this.storage.parse(this.name);
29748
29749 if (entry) {
29750 this['props'] = _.extend({}, entry);
29751 }
29752 };
29753
29754 MixpanelPersistence.prototype.upgrade = function() {
29755 var old_cookie,
29756 old_localstorage;
29757
29758 // if transferring from cookie to localStorage or vice-versa, copy existing
29759 // super properties over to new storage mode
29760 if (this.storage === _.localStorage) {
29761 old_cookie = _.cookie.parse(this.name);
29762
29763 _.cookie.remove(this.name);
29764 _.cookie.remove(this.name, true);
29765
29766 if (old_cookie) {
29767 this.register_once(old_cookie);
29768 }
29769 } else if (this.storage === _.cookie) {
29770 old_localstorage = _.localStorage.parse(this.name);
29771
29772 _.localStorage.remove(this.name);
29773
29774 if (old_localstorage) {
29775 this.register_once(old_localstorage);
29776 }
29777 }
29778 };
29779
29780 MixpanelPersistence.prototype.save = function() {
29781 if (this.disabled) { return; }
29782
29783 this.storage.set(
29784 this.name,
29785 JSONStringify(this['props']),
29786 this.expire_days,
29787 this.cross_subdomain,
29788 this.secure,
29789 this.cross_site,
29790 this.cookie_domain
29791 );
29792 };
29793
29794 MixpanelPersistence.prototype.load_prop = function(key) {
29795 this.load();
29796 return this['props'][key];
29797 };
29798
29799 MixpanelPersistence.prototype.remove = function() {
29800 // remove both domain and subdomain cookies
29801 this.storage.remove(this.name, false, this.cookie_domain);
29802 this.storage.remove(this.name, true, this.cookie_domain);
29803 };
29804
29805 // removes the storage entry and deletes all loaded data
29806 // forced name for tests
29807 MixpanelPersistence.prototype.clear = function() {
29808 this.remove();
29809 this['props'] = {};
29810 };
29811
29812 /**
29813 * @param {Object} props
29814 * @param {*=} default_value
29815 * @param {number=} days
29816 */
29817 MixpanelPersistence.prototype.register_once = function(props, default_value, days) {
29818 if (_.isObject(props)) {
29819 if (typeof(default_value) === 'undefined') { default_value = 'None'; }
29820 this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
29821
29822 this.load();
29823
29824 _.each(props, function(val, prop) {
29825 if (!this['props'].hasOwnProperty(prop) || this['props'][prop] === default_value) {
29826 this['props'][prop] = val;
29827 }
29828 }, this);
29829
29830 this.save();
29831
29832 return true;
29833 }
29834 return false;
29835 };
29836
29837 /**
29838 * @param {Object} props
29839 * @param {number=} days
29840 */
29841 MixpanelPersistence.prototype.register = function(props, days) {
29842 if (_.isObject(props)) {
29843 this.expire_days = (typeof(days) === 'undefined') ? this.default_expiry : days;
29844
29845 this.load();
29846 _.extend(this['props'], props);
29847 this.save();
29848
29849 return true;
29850 }
29851 return false;
29852 };
29853
29854 MixpanelPersistence.prototype.unregister = function(prop) {
29855 this.load();
29856 if (prop in this['props']) {
29857 delete this['props'][prop];
29858 this.save();
29859 }
29860 };
29861
29862 MixpanelPersistence.prototype.update_search_keyword = function(referrer) {
29863 this.register(_.info.searchInfo(referrer));
29864 };
29865
29866 // EXPORTED METHOD, we test this directly.
29867 MixpanelPersistence.prototype.update_referrer_info = function(referrer) {
29868 // If referrer doesn't exist, we want to note the fact that it was type-in traffic.
29869 this.register_once({
29870 '$initial_referrer': referrer || '$direct',
29871 '$initial_referring_domain': _.info.referringDomain(referrer) || '$direct'
29872 }, '');
29873 };
29874
29875 MixpanelPersistence.prototype.get_referrer_info = function() {
29876 return _.strip_empty_properties({
29877 '$initial_referrer': this['props']['$initial_referrer'],
29878 '$initial_referring_domain': this['props']['$initial_referring_domain']
29879 });
29880 };
29881
29882 MixpanelPersistence.prototype.update_config = function(config) {
29883 this.default_expiry = this.expire_days = config['cookie_expiration'];
29884 this.set_disabled(config['disable_persistence']);
29885 this.set_cookie_domain(config['cookie_domain']);
29886 this.set_cross_site(config['cross_site_cookie']);
29887 this.set_cross_subdomain(config['cross_subdomain_cookie']);
29888 this.set_secure(config['secure_cookie']);
29889 };
29890
29891 MixpanelPersistence.prototype.set_disabled = function(disabled) {
29892 this.disabled = disabled;
29893 if (this.disabled) {
29894 this.remove();
29895 } else {
29896 this.save();
29897 }
29898 };
29899
29900 MixpanelPersistence.prototype.set_cookie_domain = function(cookie_domain) {
29901 if (cookie_domain !== this.cookie_domain) {
29902 this.remove();
29903 this.cookie_domain = cookie_domain;
29904 this.save();
29905 }
29906 };
29907
29908 MixpanelPersistence.prototype.set_cross_site = function(cross_site) {
29909 if (cross_site !== this.cross_site) {
29910 this.cross_site = cross_site;
29911 this.remove();
29912 this.save();
29913 }
29914 };
29915
29916 MixpanelPersistence.prototype.set_cross_subdomain = function(cross_subdomain) {
29917 if (cross_subdomain !== this.cross_subdomain) {
29918 this.cross_subdomain = cross_subdomain;
29919 this.remove();
29920 this.save();
29921 }
29922 };
29923
29924 MixpanelPersistence.prototype.get_cross_subdomain = function() {
29925 return this.cross_subdomain;
29926 };
29927
29928 MixpanelPersistence.prototype.set_secure = function(secure) {
29929 if (secure !== this.secure) {
29930 this.secure = secure ? true : false;
29931 this.remove();
29932 this.save();
29933 }
29934 };
29935
29936 MixpanelPersistence.prototype._add_to_people_queue = function(queue, data) {
29937 var q_key = this._get_queue_key(queue),
29938 q_data = data[queue],
29939 set_q = this._get_or_create_queue(SET_ACTION),
29940 set_once_q = this._get_or_create_queue(SET_ONCE_ACTION),
29941 unset_q = this._get_or_create_queue(UNSET_ACTION),
29942 add_q = this._get_or_create_queue(ADD_ACTION),
29943 union_q = this._get_or_create_queue(UNION_ACTION),
29944 remove_q = this._get_or_create_queue(REMOVE_ACTION, []),
29945 append_q = this._get_or_create_queue(APPEND_ACTION, []);
29946
29947 if (q_key === SET_QUEUE_KEY) {
29948 // Update the set queue - we can override any existing values
29949 _.extend(set_q, q_data);
29950 // if there was a pending increment, override it
29951 // with the set.
29952 this._pop_from_people_queue(ADD_ACTION, q_data);
29953 // if there was a pending union, override it
29954 // with the set.
29955 this._pop_from_people_queue(UNION_ACTION, q_data);
29956 this._pop_from_people_queue(UNSET_ACTION, q_data);
29957 } else if (q_key === SET_ONCE_QUEUE_KEY) {
29958 // only queue the data if there is not already a set_once call for it.
29959 _.each(q_data, function(v, k) {
29960 if (!(k in set_once_q)) {
29961 set_once_q[k] = v;
29962 }
29963 });
29964 this._pop_from_people_queue(UNSET_ACTION, q_data);
29965 } else if (q_key === UNSET_QUEUE_KEY) {
29966 _.each(q_data, function(prop) {
29967
29968 // undo previously-queued actions on this key
29969 _.each([set_q, set_once_q, add_q, union_q], function(enqueued_obj) {
29970 if (prop in enqueued_obj) {
29971 delete enqueued_obj[prop];
29972 }
29973 });
29974 _.each(append_q, function(append_obj) {
29975 if (prop in append_obj) {
29976 delete append_obj[prop];
29977 }
29978 });
29979
29980 unset_q[prop] = true;
29981
29982 });
29983 } else if (q_key === ADD_QUEUE_KEY) {
29984 _.each(q_data, function(v, k) {
29985 // If it exists in the set queue, increment
29986 // the value
29987 if (k in set_q) {
29988 set_q[k] += v;
29989 } else {
29990 // If it doesn't exist, update the add
29991 // queue
29992 if (!(k in add_q)) {
29993 add_q[k] = 0;
29994 }
29995 add_q[k] += v;
29996 }
29997 }, this);
29998 this._pop_from_people_queue(UNSET_ACTION, q_data);
29999 } else if (q_key === UNION_QUEUE_KEY) {
30000 _.each(q_data, function(v, k) {
30001 if (_.isArray(v)) {
30002 if (!(k in union_q)) {
30003 union_q[k] = [];
30004 }
30005 // Prevent duplicate values
30006 _.each(v, function(item) {
30007 if (!_.include(union_q[k], item)) {
30008 union_q[k].push(item);
30009 }
30010 });
30011 }
30012 });
30013 this._pop_from_people_queue(UNSET_ACTION, q_data);
30014 } else if (q_key === REMOVE_QUEUE_KEY) {
30015 remove_q.push(q_data);
30016 this._pop_from_people_queue(APPEND_ACTION, q_data);
30017 } else if (q_key === APPEND_QUEUE_KEY) {
30018 append_q.push(q_data);
30019 this._pop_from_people_queue(UNSET_ACTION, q_data);
30020 }
30021
30022 console$1.log('MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):');
30023 console$1.log(data);
30024
30025 this.save();
30026 };
30027
30028 MixpanelPersistence.prototype._pop_from_people_queue = function(queue, data) {
30029 var q = this['props'][this._get_queue_key(queue)];
30030 if (!_.isUndefined(q)) {
30031 _.each(data, function(v, k) {
30032 if (queue === APPEND_ACTION || queue === REMOVE_ACTION) {
30033 // list actions: only remove if both k+v match
30034 // e.g. remove should not override append in a case like
30035 // append({foo: 'bar'}); remove({foo: 'qux'})
30036 _.each(q, function(queued_action) {
30037 if (queued_action[k] === v) {
30038 delete queued_action[k];
30039 }
30040 });
30041 } else {
30042 delete q[k];
30043 }
30044 }, this);
30045 }
30046 };
30047
30048 MixpanelPersistence.prototype.load_queue = function(queue) {
30049 return this.load_prop(this._get_queue_key(queue));
30050 };
30051
30052 MixpanelPersistence.prototype._get_queue_key = function(queue) {
30053 if (queue === SET_ACTION) {
30054 return SET_QUEUE_KEY;
30055 } else if (queue === SET_ONCE_ACTION) {
30056 return SET_ONCE_QUEUE_KEY;
30057 } else if (queue === UNSET_ACTION) {
30058 return UNSET_QUEUE_KEY;
30059 } else if (queue === ADD_ACTION) {
30060 return ADD_QUEUE_KEY;
30061 } else if (queue === APPEND_ACTION) {
30062 return APPEND_QUEUE_KEY;
30063 } else if (queue === REMOVE_ACTION) {
30064 return REMOVE_QUEUE_KEY;
30065 } else if (queue === UNION_ACTION) {
30066 return UNION_QUEUE_KEY;
30067 } else {
30068 console$1.error('Invalid queue:', queue);
30069 }
30070 };
30071
30072 MixpanelPersistence.prototype._get_or_create_queue = function(queue, default_val) {
30073 var key = this._get_queue_key(queue);
30074 default_val = _.isUndefined(default_val) ? {} : default_val;
30075 return this['props'][key] || (this['props'][key] = default_val);
30076 };
30077
30078 MixpanelPersistence.prototype.set_event_timer = function(event_name, timestamp) {
30079 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
30080 timers[event_name] = timestamp;
30081 this['props'][EVENT_TIMERS_KEY] = timers;
30082 this.save();
30083 };
30084
30085 MixpanelPersistence.prototype.remove_event_timer = function(event_name) {
30086 var timers = this.load_prop(EVENT_TIMERS_KEY) || {};
30087 var timestamp = timers[event_name];
30088 if (!_.isUndefined(timestamp)) {
30089 delete this['props'][EVENT_TIMERS_KEY][event_name];
30090 this.save();
30091 }
30092 return timestamp;
30093 };
30094
30095 /* eslint camelcase: "off" */
30096
30097 /*
30098 * Mixpanel JS Library
30099 *
30100 * Copyright 2012, Mixpanel, Inc. All Rights Reserved
30101 * http://mixpanel.com/
30102 *
30103 * Includes portions of Underscore.js
30104 * http://documentcloud.github.com/underscore/
30105 * (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
30106 * Released under the MIT License.
30107 */
30108
30109 /*
30110 SIMPLE STYLE GUIDE:
30111
30112 this.x === public function
30113 this._x === internal - only use within this file
30114 this.__x === private - only use within the class
30115
30116 Globals should be all caps
30117 */
30118
30119 var init_type; // MODULE or SNIPPET loader
30120 // allow bundlers to specify how extra code (recorder bundle) should be loaded
30121 // eslint-disable-next-line no-unused-vars
30122 var load_extra_bundle = function(src, _onload) {
30123 throw new Error(src + ' not available in this build.');
30124 };
30125
30126 var mixpanel_master; // main mixpanel instance / object
30127 var INIT_MODULE = 0;
30128 var INIT_SNIPPET = 1;
30129
30130 var IDENTITY_FUNC = function(x) {return x;};
30131
30132 /** @const */ var PRIMARY_INSTANCE_NAME = 'mixpanel';
30133 /** @const */ var PAYLOAD_TYPE_BASE64 = 'base64';
30134 /** @const */ var PAYLOAD_TYPE_JSON = 'json';
30135 /** @const */ var DEVICE_ID_PREFIX = '$device:';
30136
30137
30138 /*
30139 * Dynamic... constants? Is that an oxymoron?
30140 */
30141 // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
30142 // https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
30143 var USE_XHR = (win.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest());
30144
30145 // IE<10 does not support cross-origin XHR's but script tags
30146 // with defer won't block window.onload; ENQUEUE_REQUESTS
30147 // should only be true for Opera<12
30148 var ENQUEUE_REQUESTS = !USE_XHR && (userAgent.indexOf('MSIE') === -1) && (userAgent.indexOf('Mozilla') === -1);
30149
30150 // save reference to navigator.sendBeacon so it can be minified
30151 var sendBeacon = null;
30152 if (navigator['sendBeacon']) {
30153 sendBeacon = function() {
30154 // late reference to navigator.sendBeacon to allow patching/spying
30155 return navigator['sendBeacon'].apply(navigator, arguments);
30156 };
30157 }
30158
30159 var DEFAULT_API_ROUTES = {
30160 'track': 'track/',
30161 'engage': 'engage/',
30162 'groups': 'groups/',
30163 'record': 'record/',
30164 'flags': 'flags/'
30165 };
30166
30167 /*
30168 * Module-level globals
30169 */
30170 var DEFAULT_CONFIG = {
30171 'api_host': 'https://api-js.mixpanel.com',
30172 'api_hosts': {},
30173 'api_routes': DEFAULT_API_ROUTES,
30174 'api_extra_query_params': {},
30175 'api_method': 'POST',
30176 'api_transport': 'XHR',
30177 'api_payload_format': PAYLOAD_TYPE_BASE64,
30178 'app_host': 'https://mixpanel.com',
30179 'autocapture': false,
30180 'cdn': 'https://cdn.mxpnl.com',
30181 'cross_site_cookie': false,
30182 'cross_subdomain_cookie': true,
30183 'error_reporter': NOOP_FUNC,
30184 'flags': false,
30185 'persistence': 'cookie',
30186 'persistence_name': '',
30187 'cookie_domain': '',
30188 'cookie_name': '',
30189 'loaded': NOOP_FUNC,
30190 'mp_loader': null,
30191 'track_marketing': true,
30192 'track_pageview': false,
30193 'skip_first_touch_marketing': false,
30194 'store_google': true,
30195 'stop_utm_persistence': false,
30196 'save_referrer': true,
30197 'test': false,
30198 'verbose': false,
30199 'img': false,
30200 'debug': false,
30201 'track_links_timeout': 300,
30202 'cookie_expiration': 365,
30203 'upgrade': false,
30204 'disable_persistence': false,
30205 'disable_cookie': false,
30206 'secure_cookie': false,
30207 'ip': true,
30208 'opt_out_tracking_by_default': false,
30209 'opt_out_persistence_by_default': false,
30210 'opt_out_tracking_persistence_type': 'localStorage',
30211 'opt_out_tracking_cookie_prefix': null,
30212 'property_blacklist': [],
30213 'xhr_headers': {}, // { header: value, header2: value }
30214 'ignore_dnt': false,
30215 'batch_requests': true,
30216 'batch_size': 50,
30217 'batch_flush_interval_ms': 5000,
30218 'batch_request_timeout_ms': 90000,
30219 'batch_autostart': true,
30220 'hooks': {},
30221 'record_block_class': new RegExp('^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$'),
30222 'record_block_selector': 'img, video, audio',
30223 'record_canvas': false,
30224 'record_collect_fonts': false,
30225 'record_heatmap_data': false,
30226 'record_idle_timeout_ms': 30 * 60 * 1000, // 30 minutes
30227 'record_mask_text_class': new RegExp('^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$'),
30228 'record_mask_text_selector': '*',
30229 'record_max_ms': MAX_RECORDING_MS,
30230 'record_min_ms': 0,
30231 'record_sessions_percent': 0,
30232 'recorder_src': 'https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js'
30233 };
30234
30235 var DOM_LOADED = false;
30236
30237 /**
30238 * Mixpanel Library Object
30239 * @constructor
30240 */
30241 var MixpanelLib = function() {};
30242
30243
30244 /**
30245 * create_mplib(token:string, config:object, name:string)
30246 *
30247 * This function is used by the init method of MixpanelLib objects
30248 * as well as the main initializer at the end of the JSLib (that
30249 * initializes document.mixpanel as well as any additional instances
30250 * declared before this file has loaded).
30251 */
30252 var create_mplib = function(token, config, name) {
30253 var instance,
30254 target = (name === PRIMARY_INSTANCE_NAME) ? mixpanel_master : mixpanel_master[name];
30255
30256 if (target && init_type === INIT_MODULE) {
30257 instance = target;
30258 } else {
30259 if (target && !_.isArray(target)) {
30260 console$1.error('You have already initialized ' + name);
30261 return;
30262 }
30263 instance = new MixpanelLib();
30264 }
30265
30266 instance._cached_groups = {}; // cache groups in a pool
30267
30268 instance._init(token, config, name);
30269
30270 instance['people'] = new MixpanelPeople();
30271 instance['people']._init(instance);
30272
30273 if (!instance.get_config('skip_first_touch_marketing')) {
30274 // We need null UTM params in the object because
30275 // UTM parameters act as a tuple. If any UTM param
30276 // is present, then we set all UTM params including
30277 // empty ones together
30278 var utm_params = _.info.campaignParams(null);
30279 var initial_utm_params = {};
30280 var has_utm = false;
30281 _.each(utm_params, function(utm_value, utm_key) {
30282 initial_utm_params['initial_' + utm_key] = utm_value;
30283 if (utm_value) {
30284 has_utm = true;
30285 }
30286 });
30287 if (has_utm) {
30288 instance['people'].set_once(initial_utm_params);
30289 }
30290 }
30291
30292 // if any instance on the page has debug = true, we set the
30293 // global debug to be true
30294 Config.DEBUG = Config.DEBUG || instance.get_config('debug');
30295
30296 // if target is not defined, we called init after the lib already
30297 // loaded, so there won't be an array of things to execute
30298 if (!_.isUndefined(target) && _.isArray(target)) {
30299 // Crunch through the people queue first - we queue this data up &
30300 // flush on identify, so it's better to do all these operations first
30301 instance._execute_array.call(instance['people'], target['people']);
30302 instance._execute_array(target);
30303 }
30304
30305 return instance;
30306 };
30307
30308 // Initialization methods
30309
30310 /**
30311 * This function initializes a new instance of the Mixpanel tracking object.
30312 * All new instances are added to the main mixpanel object as sub properties (such as
30313 * mixpanel.library_name) and also returned by this function. To define a
30314 * second instance on the page, you would call:
30315 *
30316 * mixpanel.init('new token', { your: 'config' }, 'library_name');
30317 *
30318 * and use it like so:
30319 *
30320 * mixpanel.library_name.track(...);
30321 *
30322 * @param {String} token Your Mixpanel API token
30323 * @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>.
30324 * @param {String} [name] The name for the new mixpanel instance that you want created
30325 */
30326 MixpanelLib.prototype.init = function (token, config, name) {
30327 if (_.isUndefined(name)) {
30328 this.report_error('You must name your new library: init(token, config, name)');
30329 return;
30330 }
30331 if (name === PRIMARY_INSTANCE_NAME) {
30332 this.report_error('You must initialize the main mixpanel object right after you include the Mixpanel js snippet');
30333 return;
30334 }
30335
30336 var instance = create_mplib(token, config, name);
30337 mixpanel_master[name] = instance;
30338 instance._loaded();
30339
30340 return instance;
30341 };
30342
30343 // mixpanel._init(token:string, config:object, name:string)
30344 //
30345 // This function sets up the current instance of the mixpanel
30346 // library. The difference between this method and the init(...)
30347 // method is this one initializes the actual instance, whereas the
30348 // init(...) method sets up a new library and calls _init on it.
30349 //
30350 MixpanelLib.prototype._init = function(token, config, name) {
30351 config = config || {};
30352
30353 this['__loaded'] = true;
30354 this['config'] = {};
30355
30356 var variable_features = {};
30357
30358 // default to JSON payload for standard mixpanel.com API hosts
30359 if (!('api_payload_format' in config)) {
30360 var api_host = config['api_host'] || DEFAULT_CONFIG['api_host'];
30361 if (api_host.match(/\.mixpanel\.com/)) {
30362 variable_features['api_payload_format'] = PAYLOAD_TYPE_JSON;
30363 }
30364 }
30365
30366 this.set_config(_.extend({}, DEFAULT_CONFIG, variable_features, config, {
30367 'name': name,
30368 'token': token,
30369 'callback_fn': ((name === PRIMARY_INSTANCE_NAME) ? name : PRIMARY_INSTANCE_NAME + '.' + name) + '._jsc'
30370 }));
30371
30372 this['_jsc'] = NOOP_FUNC;
30373
30374 this.__dom_loaded_queue = [];
30375 this.__request_queue = [];
30376 this.__disabled_events = [];
30377 this._flags = {
30378 'disable_all_events': false,
30379 'identify_called': false
30380 };
30381
30382 // set up request queueing/batching
30383 this.request_batchers = {};
30384 this._batch_requests = this.get_config('batch_requests');
30385 if (this._batch_requests) {
30386 if (!_.localStorage.is_supported(true) || !USE_XHR) {
30387 this._batch_requests = false;
30388 console$1.log('Turning off Mixpanel request-queueing; needs XHR and localStorage support');
30389 _.each(this.get_batcher_configs(), function(batcher_config) {
30390 console$1.log('Clearing batch queue ' + batcher_config.queue_key);
30391 _.localStorage.remove(batcher_config.queue_key);
30392 });
30393 } else {
30394 this.init_batchers();
30395 if (sendBeacon && win.addEventListener) {
30396 // Before page closes or hides (user tabs away etc), attempt to flush any events
30397 // queued up via navigator.sendBeacon. Since sendBeacon doesn't report success/failure,
30398 // events will not be removed from the persistent store; if the site is loaded again,
30399 // the events will be flushed again on startup and deduplicated on the Mixpanel server
30400 // side.
30401 // There is no reliable way to capture only page close events, so we lean on the
30402 // visibilitychange and pagehide events as recommended at
30403 // https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event#usage_notes.
30404 // These events fire when the user clicks away from the current page/tab, so will occur
30405 // more frequently than page unload, but are the only mechanism currently for capturing
30406 // this scenario somewhat reliably.
30407 var flush_on_unload = _.bind(function() {
30408 if (!this.request_batchers.events.stopped) {
30409 this.request_batchers.events.flush({unloading: true});
30410 }
30411 }, this);
30412 win.addEventListener('pagehide', function(ev) {
30413 if (ev['persisted']) {
30414 flush_on_unload();
30415 }
30416 });
30417 win.addEventListener('visibilitychange', function() {
30418 if (document$1['visibilityState'] === 'hidden') {
30419 flush_on_unload();
30420 }
30421 });
30422 }
30423 }
30424 }
30425
30426 this['persistence'] = this['cookie'] = new MixpanelPersistence(this['config']);
30427 this.unpersisted_superprops = {};
30428 this._gdpr_init();
30429
30430 var uuid = _.UUID();
30431 if (!this.get_distinct_id()) {
30432 // There is no need to set the distinct id
30433 // or the device id if something was already stored
30434 // in the persitence
30435 this.register_once({
30436 'distinct_id': DEVICE_ID_PREFIX + uuid,
30437 '$device_id': uuid
30438 }, '');
30439 }
30440
30441 this.flags = new FeatureFlagManager({
30442 getFullApiRoute: _.bind(function() {
30443 return this.get_api_host('flags') + '/' + this.get_config('api_routes')['flags'];
30444 }, this),
30445 getConfigFunc: _.bind(this.get_config, this),
30446 setConfigFunc: _.bind(this.set_config, this),
30447 getPropertyFunc: _.bind(this.get_property, this),
30448 trackingFunc: _.bind(this.track, this)
30449 });
30450 this.flags.init();
30451 this['flags'] = this.flags;
30452
30453 this.autocapture = new Autocapture(this);
30454 this.autocapture.init();
30455
30456 this._init_tab_id();
30457 this._check_and_start_session_recording();
30458 };
30459
30460 /**
30461 * Assigns a unique UUID to this tab / window by leveraging sessionStorage.
30462 * This is primarily used for session recording, where data must be isolated to the current tab.
30463 */
30464 MixpanelLib.prototype._init_tab_id = function() {
30465 if (this.get_config('disable_persistence')) {
30466 console$1.log('Tab ID initialization skipped due to disable_persistence config');
30467 } else if (_.sessionStorage.is_supported()) {
30468 try {
30469 var key_suffix = this.get_config('name') + '_' + this.get_config('token');
30470 var tab_id_key = 'mp_tab_id_' + key_suffix;
30471
30472 // A flag is used to determine if sessionStorage is copied over and we need to generate a new tab ID.
30473 // This enforces a unique ID in the cases like duplicated tab, window.open(...)
30474 var should_generate_new_tab_id_key = 'mp_gen_new_tab_id_' + key_suffix;
30475 if (_.sessionStorage.get(should_generate_new_tab_id_key) || !_.sessionStorage.get(tab_id_key)) {
30476 _.sessionStorage.set(tab_id_key, '$tab-' + _.UUID());
30477 }
30478
30479 _.sessionStorage.set(should_generate_new_tab_id_key, '1');
30480 this.tab_id = _.sessionStorage.get(tab_id_key);
30481
30482 // 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,
30483 // but reliable in cases where the user remains in the tab e.g. a refresh or href navigation.
30484 // If the flag is absent, this indicates to the next SDK instance that we can reuse the stored tab_id.
30485 win.addEventListener('beforeunload', function () {
30486 _.sessionStorage.remove(should_generate_new_tab_id_key);
30487 });
30488 } catch(err) {
30489 this.report_error('Error initializing tab id', err);
30490 }
30491 } else {
30492 this.report_error('Session storage is not supported, cannot keep track of unique tab ID.');
30493 }
30494 };
30495
30496 MixpanelLib.prototype.get_tab_id = function () {
30497 return this.tab_id || null;
30498 };
30499
30500 MixpanelLib.prototype._should_load_recorder = function () {
30501 if (this.get_config('disable_persistence')) {
30502 console$1.log('Load recorder check skipped due to disable_persistence config');
30503 return Promise.resolve(false);
30504 }
30505
30506 var recording_registry_idb = new IDBStorageWrapper(RECORDING_REGISTRY_STORE_NAME);
30507 var tab_id = this.get_tab_id();
30508 return recording_registry_idb.init()
30509 .then(function () {
30510 return recording_registry_idb.getAll();
30511 })
30512 .then(function (recordings) {
30513 for (var i = 0; i < recordings.length; i++) {
30514 // if there are expired recordings in the registry, we should load the recorder to flush them
30515 // if there's a recording for this tab id, we should load the recorder to continue the recording
30516 if (isRecordingExpired(recordings[i]) || recordings[i]['tabId'] === tab_id) {
30517 return true;
30518 }
30519 }
30520 return false;
30521 })
30522 .catch(_.bind(function (err) {
30523 this.report_error('Error checking recording registry', err);
30524 }, this));
30525 };
30526
30527 MixpanelLib.prototype._check_and_start_session_recording = addOptOutCheckMixpanelLib(function(force_start) {
30528 if (!win['MutationObserver']) {
30529 console$1.critical('Browser does not support MutationObserver; skipping session recording');
30530 return;
30531 }
30532
30533 var loadRecorder = _.bind(function(startNewIfInactive) {
30534 var handleLoadedRecorder = _.bind(function() {
30535 this._recorder = this._recorder || new win['__mp_recorder'](this);
30536 this._recorder['resumeRecording'](startNewIfInactive);
30537 }, this);
30538
30539 if (_.isUndefined(win['__mp_recorder'])) {
30540 load_extra_bundle(this.get_config('recorder_src'), handleLoadedRecorder);
30541 } else {
30542 handleLoadedRecorder();
30543 }
30544 }, this);
30545
30546 /**
30547 * If the user is sampled or start_session_recording is called, we always load the recorder since it's guaranteed a recording should start.
30548 * 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.
30549 */
30550 var is_sampled = this.get_config('record_sessions_percent') > 0 && Math.random() * 100 <= this.get_config('record_sessions_percent');
30551 if (force_start || is_sampled) {
30552 loadRecorder(true);
30553 } else {
30554 this._should_load_recorder()
30555 .then(function (shouldLoad) {
30556 if (shouldLoad) {
30557 loadRecorder(false);
30558 }
30559 });
30560 }
30561 });
30562
30563 MixpanelLib.prototype.start_session_recording = function () {
30564 this._check_and_start_session_recording(true);
30565 };
30566
30567 MixpanelLib.prototype.stop_session_recording = function () {
30568 if (this._recorder) {
30569 return this._recorder['stopRecording']();
30570 }
30571 return Promise.resolve();
30572 };
30573
30574 MixpanelLib.prototype.pause_session_recording = function () {
30575 if (this._recorder) {
30576 return this._recorder['pauseRecording']();
30577 }
30578 return Promise.resolve();
30579 };
30580
30581 MixpanelLib.prototype.resume_session_recording = function () {
30582 if (this._recorder) {
30583 return this._recorder['resumeRecording']();
30584 }
30585 return Promise.resolve();
30586 };
30587
30588 MixpanelLib.prototype.is_recording_heatmap_data = function () {
30589 return this._get_session_replay_id() && this.get_config('record_heatmap_data');
30590 };
30591
30592 MixpanelLib.prototype.get_session_recording_properties = function () {
30593 var props = {};
30594 var replay_id = this._get_session_replay_id();
30595 if (replay_id) {
30596 props['$mp_replay_id'] = replay_id;
30597 }
30598 return props;
30599 };
30600
30601 MixpanelLib.prototype.get_session_replay_url = function () {
30602 var replay_url = null;
30603 var replay_id = this._get_session_replay_id();
30604 if (replay_id) {
30605 var query_params = _.HTTPBuildQuery({
30606 'replay_id': replay_id,
30607 'distinct_id': this.get_distinct_id(),
30608 'token': this.get_config('token')
30609 });
30610 replay_url = 'https://mixpanel.com/projects/replay-redirect?' + query_params;
30611 }
30612 return replay_url;
30613 };
30614
30615 MixpanelLib.prototype._get_session_replay_id = function () {
30616 var replay_id = null;
30617 if (this._recorder) {
30618 replay_id = this._recorder['replayId'];
30619 }
30620 return replay_id || null;
30621 };
30622
30623 // "private" public method to reach into the recorder in test cases
30624 MixpanelLib.prototype.__get_recorder = function () {
30625 return this._recorder;
30626 };
30627
30628 // Private methods
30629
30630 MixpanelLib.prototype._loaded = function() {
30631 this.get_config('loaded')(this);
30632 this._set_default_superprops();
30633 this['people'].set_once(this['persistence'].get_referrer_info());
30634
30635 // `store_google` is now deprecated and previously stored UTM parameters are cleared
30636 // from persistence by default.
30637 if (this.get_config('store_google') && this.get_config('stop_utm_persistence')) {
30638 var utm_params = _.info.campaignParams(null);
30639 _.each(utm_params, function(_utm_value, utm_key) {
30640 // We need to unregister persisted UTM parameters so old values
30641 // are not mixed with the new UTM parameters
30642 this.unregister(utm_key);
30643 }.bind(this));
30644 }
30645 };
30646
30647 // update persistence with info on referrer, UTM params, etc
30648 MixpanelLib.prototype._set_default_superprops = function() {
30649 this['persistence'].update_search_keyword(document$1.referrer);
30650 // Registering super properties for UTM persistence by 'store_google' is deprecated.
30651 if (this.get_config('store_google') && !this.get_config('stop_utm_persistence')) {
30652 this.register(_.info.campaignParams());
30653 }
30654 if (this.get_config('save_referrer')) {
30655 this['persistence'].update_referrer_info(document$1.referrer);
30656 }
30657 };
30658
30659 MixpanelLib.prototype._dom_loaded = function() {
30660 _.each(this.__dom_loaded_queue, function(item) {
30661 this._track_dom.apply(this, item);
30662 }, this);
30663
30664 if (!this.has_opted_out_tracking()) {
30665 _.each(this.__request_queue, function(item) {
30666 this._send_request.apply(this, item);
30667 }, this);
30668 }
30669
30670 delete this.__dom_loaded_queue;
30671 delete this.__request_queue;
30672 };
30673
30674 MixpanelLib.prototype._track_dom = function(DomClass, args) {
30675 if (this.get_config('img')) {
30676 this.report_error('You can\'t use DOM tracking functions with img = true.');
30677 return false;
30678 }
30679
30680 if (!DOM_LOADED) {
30681 this.__dom_loaded_queue.push([DomClass, args]);
30682 return false;
30683 }
30684
30685 var dt = new DomClass().init(this);
30686 return dt.track.apply(dt, args);
30687 };
30688
30689 /**
30690 * _prepare_callback() should be called by callers of _send_request for use
30691 * as the callback argument.
30692 *
30693 * If there is no callback, this returns null.
30694 * If we are going to make XHR/XDR requests, this returns a function.
30695 * If we are going to use script tags, this returns a string to use as the
30696 * callback GET param.
30697 */
30698 MixpanelLib.prototype._prepare_callback = function(callback, data) {
30699 if (_.isUndefined(callback)) {
30700 return null;
30701 }
30702
30703 if (USE_XHR) {
30704 var callback_function = function(response) {
30705 callback(response, data);
30706 };
30707 return callback_function;
30708 } else {
30709 // if the user gives us a callback, we store as a random
30710 // property on this instances jsc function and update our
30711 // callback string to reflect that.
30712 var jsc = this['_jsc'];
30713 var randomized_cb = '' + Math.floor(Math.random() * 100000000);
30714 var callback_string = this.get_config('callback_fn') + '[' + randomized_cb + ']';
30715 jsc[randomized_cb] = function(response) {
30716 delete jsc[randomized_cb];
30717 callback(response, data);
30718 };
30719 return callback_string;
30720 }
30721 };
30722
30723 MixpanelLib.prototype._send_request = function(url, data, options, callback) {
30724 var succeeded = true;
30725
30726 if (ENQUEUE_REQUESTS) {
30727 this.__request_queue.push(arguments);
30728 return succeeded;
30729 }
30730
30731 var DEFAULT_OPTIONS = {
30732 method: this.get_config('api_method'),
30733 transport: this.get_config('api_transport'),
30734 verbose: this.get_config('verbose')
30735 };
30736 var body_data = null;
30737
30738 if (!callback && (_.isFunction(options) || typeof options === 'string')) {
30739 callback = options;
30740 options = null;
30741 }
30742 options = _.extend(DEFAULT_OPTIONS, options || {});
30743 if (!USE_XHR) {
30744 options.method = 'GET';
30745 }
30746 var use_post = options.method === 'POST';
30747 var use_sendBeacon = sendBeacon && use_post && options.transport.toLowerCase() === 'sendbeacon';
30748
30749 // needed to correctly format responses
30750 var verbose_mode = options.verbose;
30751 if (data['verbose']) { verbose_mode = true; }
30752
30753 if (this.get_config('test')) { data['test'] = 1; }
30754 if (verbose_mode) { data['verbose'] = 1; }
30755 if (this.get_config('img')) { data['img'] = 1; }
30756 if (!USE_XHR) {
30757 if (callback) {
30758 data['callback'] = callback;
30759 } else if (verbose_mode || this.get_config('test')) {
30760 // Verbose output (from verbose mode, or an error in test mode) is a json blob,
30761 // which by itself is not valid javascript. Without a callback, this verbose output will
30762 // cause an error when returned via jsonp, so we force a no-op callback param.
30763 // See the ECMA script spec: http://www.ecma-international.org/ecma-262/5.1/#sec-12.4
30764 data['callback'] = '(function(){})';
30765 }
30766 }
30767
30768 data['ip'] = this.get_config('ip')?1:0;
30769 data['_'] = new Date().getTime().toString();
30770
30771 if (use_post) {
30772 body_data = 'data=' + encodeURIComponent(data['data']);
30773 delete data['data'];
30774 }
30775
30776 _.extend(data, this.get_config('api_extra_query_params'));
30777
30778 url += '?' + _.HTTPBuildQuery(data);
30779
30780 var lib = this;
30781 if ('img' in data) {
30782 var img = document$1.createElement('img');
30783 img.src = url;
30784 document$1.body.appendChild(img);
30785 } else if (use_sendBeacon) {
30786 try {
30787 succeeded = sendBeacon(url, body_data);
30788 } catch (e) {
30789 lib.report_error(e);
30790 succeeded = false;
30791 }
30792 try {
30793 if (callback) {
30794 callback(succeeded ? 1 : 0);
30795 }
30796 } catch (e) {
30797 lib.report_error(e);
30798 }
30799 } else if (USE_XHR) {
30800 try {
30801 var req = new XMLHttpRequest();
30802 req.open(options.method, url, true);
30803
30804 var headers = this.get_config('xhr_headers');
30805 if (use_post) {
30806 headers['Content-Type'] = 'application/x-www-form-urlencoded';
30807 }
30808 _.each(headers, function(headerValue, headerName) {
30809 req.setRequestHeader(headerName, headerValue);
30810 });
30811
30812 if (options.timeout_ms && typeof req.timeout !== 'undefined') {
30813 req.timeout = options.timeout_ms;
30814 var start_time = new Date().getTime();
30815 }
30816
30817 // send the mp_optout cookie
30818 // withCredentials cannot be modified until after calling .open on Android and Mobile Safari
30819 req.withCredentials = true;
30820 req.onreadystatechange = function () {
30821 if (req.readyState === 4) { // XMLHttpRequest.DONE == 4, except in safari 4
30822 if (req.status === 200) {
30823 if (callback) {
30824 if (verbose_mode) {
30825 var response;
30826 try {
30827 response = _.JSONDecode(req.responseText);
30828 } catch (e) {
30829 lib.report_error(e);
30830 if (options.ignore_json_errors) {
30831 response = req.responseText;
30832 } else {
30833 return;
30834 }
30835 }
30836 callback(response);
30837 } else {
30838 callback(Number(req.responseText));
30839 }
30840 }
30841 } else {
30842 var error;
30843 if (
30844 req.timeout &&
30845 !req.status &&
30846 new Date().getTime() - start_time >= req.timeout
30847 ) {
30848 error = 'timeout';
30849 } else {
30850 error = 'Bad HTTP status: ' + req.status + ' ' + req.statusText;
30851 }
30852 lib.report_error(error);
30853 if (callback) {
30854 if (verbose_mode) {
30855 var response_headers = req['responseHeaders'] || {};
30856 callback({status: 0, httpStatusCode: req['status'], error: error, retryAfter: response_headers['Retry-After']});
30857 } else {
30858 callback(0);
30859 }
30860 }
30861 }
30862 }
30863 };
30864 req.send(body_data);
30865 } catch (e) {
30866 lib.report_error(e);
30867 succeeded = false;
30868 }
30869 } else {
30870 var script = document$1.createElement('script');
30871 script.type = 'text/javascript';
30872 script.async = true;
30873 script.defer = true;
30874 script.src = url;
30875 var s = document$1.getElementsByTagName('script')[0];
30876 s.parentNode.insertBefore(script, s);
30877 }
30878
30879 return succeeded;
30880 };
30881
30882 /**
30883 * _execute_array() deals with processing any mixpanel function
30884 * calls that were called before the Mixpanel library were loaded
30885 * (and are thus stored in an array so they can be called later)
30886 *
30887 * Note: we fire off all the mixpanel function calls && user defined
30888 * functions BEFORE we fire off mixpanel tracking calls. This is so
30889 * identify/register/set_config calls can properly modify early
30890 * tracking calls.
30891 *
30892 * @param {Array} array
30893 */
30894 MixpanelLib.prototype._execute_array = function(array) {
30895 var fn_name, alias_calls = [], other_calls = [], tracking_calls = [];
30896 _.each(array, function(item) {
30897 if (item) {
30898 fn_name = item[0];
30899 if (_.isArray(fn_name)) {
30900 tracking_calls.push(item); // chained call e.g. mixpanel.get_group().set()
30901 } else if (typeof(item) === 'function') {
30902 item.call(this);
30903 } else if (_.isArray(item) && fn_name === 'alias') {
30904 alias_calls.push(item);
30905 } else if (_.isArray(item) && fn_name.indexOf('track') !== -1 && typeof(this[fn_name]) === 'function') {
30906 tracking_calls.push(item);
30907 } else {
30908 other_calls.push(item);
30909 }
30910 }
30911 }, this);
30912
30913 var execute = function(calls, context) {
30914 _.each(calls, function(item) {
30915 if (_.isArray(item[0])) {
30916 // chained call
30917 var caller = context;
30918 _.each(item, function(call) {
30919 caller = caller[call[0]].apply(caller, call.slice(1));
30920 });
30921 } else {
30922 this[item[0]].apply(this, item.slice(1));
30923 }
30924 }, context);
30925 };
30926
30927 execute(alias_calls, this);
30928 execute(other_calls, this);
30929 execute(tracking_calls, this);
30930 };
30931
30932 // request queueing utils
30933
30934 MixpanelLib.prototype.are_batchers_initialized = function() {
30935 return !!this.request_batchers.events;
30936 };
30937
30938 MixpanelLib.prototype.get_batcher_configs = function() {
30939 var queue_prefix = '__mpq_' + this.get_config('token');
30940 this._batcher_configs = this._batcher_configs || {
30941 events: {type: 'events', api_name: 'track', queue_key: queue_prefix + '_ev'},
30942 people: {type: 'people', api_name: 'engage', queue_key: queue_prefix + '_pp'},
30943 groups: {type: 'groups', api_name: 'groups', queue_key: queue_prefix + '_gr'}
30944 };
30945 return this._batcher_configs;
30946 };
30947
30948 MixpanelLib.prototype.init_batchers = function() {
30949 if (!this.are_batchers_initialized()) {
30950 var batcher_for = _.bind(function(attrs) {
30951 return new RequestBatcher(
30952 attrs.queue_key,
30953 {
30954 libConfig: this['config'],
30955 errorReporter: this.get_config('error_reporter'),
30956 sendRequestFunc: _.bind(function(data, options, cb) {
30957 var api_routes = this.get_config('api_routes');
30958 this._send_request(
30959 this.get_api_host(attrs.api_name) + '/' + api_routes[attrs.api_name],
30960 this._encode_data_for_request(data),
30961 options,
30962 this._prepare_callback(cb, data)
30963 );
30964 }, this),
30965 beforeSendHook: _.bind(function(item) {
30966 return this._run_hook('before_send_' + attrs.type, item);
30967 }, this),
30968 stopAllBatchingFunc: _.bind(this.stop_batch_senders, this),
30969 usePersistence: true,
30970 }
30971 );
30972 }, this);
30973 var batcher_configs = this.get_batcher_configs();
30974 this.request_batchers = {
30975 events: batcher_for(batcher_configs.events),
30976 people: batcher_for(batcher_configs.people),
30977 groups: batcher_for(batcher_configs.groups)
30978 };
30979 }
30980 if (this.get_config('batch_autostart')) {
30981 this.start_batch_senders();
30982 }
30983 };
30984
30985 MixpanelLib.prototype.start_batch_senders = function() {
30986 this._batchers_were_started = true;
30987 if (this.are_batchers_initialized()) {
30988 this._batch_requests = true;
30989 _.each(this.request_batchers, function(batcher) {
30990 batcher.start();
30991 });
30992 }
30993 };
30994
30995 MixpanelLib.prototype.stop_batch_senders = function() {
30996 this._batch_requests = false;
30997 _.each(this.request_batchers, function(batcher) {
30998 batcher.stop();
30999 batcher.clear();
31000 });
31001 };
31002
31003 /**
31004 * push() keeps the standard async-array-push
31005 * behavior around after the lib is loaded.
31006 * This is only useful for external integrations that
31007 * do not wish to rely on our convenience methods
31008 * (created in the snippet).
31009 *
31010 * ### Usage:
31011 * mixpanel.push(['register', { a: 'b' }]);
31012 *
31013 * @param {Array} item A [function_name, args...] array to be executed
31014 */
31015 MixpanelLib.prototype.push = function(item) {
31016 this._execute_array([item]);
31017 };
31018
31019 /**
31020 * Disable events on the Mixpanel object. If passed no arguments,
31021 * this function disables tracking of any event. If passed an
31022 * array of event names, those events will be disabled, but other
31023 * events will continue to be tracked.
31024 *
31025 * Note: this function does not stop other mixpanel functions from
31026 * firing, such as register() or people.set().
31027 *
31028 * @param {Array} [events] An array of event names to disable
31029 */
31030 MixpanelLib.prototype.disable = function(events) {
31031 if (typeof(events) === 'undefined') {
31032 this._flags.disable_all_events = true;
31033 } else {
31034 this.__disabled_events = this.__disabled_events.concat(events);
31035 }
31036 };
31037
31038 MixpanelLib.prototype._encode_data_for_request = function(data) {
31039 var encoded_data = JSONStringify(data);
31040 if (this.get_config('api_payload_format') === PAYLOAD_TYPE_BASE64) {
31041 encoded_data = _.base64Encode(encoded_data);
31042 }
31043 return {'data': encoded_data};
31044 };
31045
31046 // internal method for handling track vs batch-enqueue logic
31047 MixpanelLib.prototype._track_or_batch = function(options, callback) {
31048 var truncated_data = _.truncate(options.data, 255);
31049 var endpoint = options.endpoint;
31050 var batcher = options.batcher;
31051 var should_send_immediately = options.should_send_immediately;
31052 var send_request_options = options.send_request_options || {};
31053 callback = callback || NOOP_FUNC;
31054
31055 var request_enqueued_or_initiated = true;
31056 var send_request_immediately = _.bind(function() {
31057 if (!send_request_options.skip_hooks) {
31058 truncated_data = this._run_hook('before_send_' + options.type, truncated_data);
31059 }
31060 if (truncated_data) {
31061 console$1.log('MIXPANEL REQUEST:');
31062 console$1.log(truncated_data);
31063 return this._send_request(
31064 endpoint,
31065 this._encode_data_for_request(truncated_data),
31066 send_request_options,
31067 this._prepare_callback(callback, truncated_data)
31068 );
31069 } else {
31070 return null;
31071 }
31072 }, this);
31073
31074 if (this._batch_requests && !should_send_immediately) {
31075 batcher.enqueue(truncated_data).then(function(succeeded) {
31076 if (succeeded) {
31077 callback(1, truncated_data);
31078 } else {
31079 send_request_immediately();
31080 }
31081 });
31082 } else {
31083 request_enqueued_or_initiated = send_request_immediately();
31084 }
31085
31086 return request_enqueued_or_initiated && truncated_data;
31087 };
31088
31089 /**
31090 * Track an event. This is the most important and
31091 * frequently used Mixpanel function.
31092 *
31093 * ### Usage:
31094 *
31095 * // track an event named 'Registered'
31096 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
31097 *
31098 * // track an event using navigator.sendBeacon
31099 * mixpanel.track('Left page', {'duration_seconds': 35}, {transport: 'sendBeacon'});
31100 *
31101 * To track link clicks or form submissions, see track_links() or track_forms().
31102 *
31103 * @param {String} event_name The name of the event. This can be anything the user does - 'Button Click', 'Sign Up', 'Item Purchased', etc.
31104 * @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.
31105 * @param {Object} [options] Optional configuration for this track request.
31106 * @param {String} [options.transport] Transport method for network request ('xhr' or 'sendBeacon').
31107 * @param {Boolean} [options.send_immediately] Whether to bypass batching/queueing and send track request immediately.
31108 * @param {Function} [callback] If provided, the callback function will be called after tracking the event.
31109 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
31110 * with the tracking payload sent to the API server is returned; otherwise false.
31111 */
31112 MixpanelLib.prototype.track = addOptOutCheckMixpanelLib(function(event_name, properties, options, callback) {
31113 if (!callback && typeof options === 'function') {
31114 callback = options;
31115 options = null;
31116 }
31117 options = options || {};
31118 var transport = options['transport']; // external API, don't minify 'transport' prop
31119 if (transport) {
31120 options.transport = transport; // 'transport' prop name can be minified internally
31121 }
31122 var should_send_immediately = options['send_immediately'];
31123 if (typeof callback !== 'function') {
31124 callback = NOOP_FUNC;
31125 }
31126
31127 if (_.isUndefined(event_name)) {
31128 this.report_error('No event name provided to mixpanel.track');
31129 return;
31130 }
31131
31132 if (this._event_is_disabled(event_name)) {
31133 callback(0);
31134 return;
31135 }
31136
31137 // set defaults
31138 properties = _.extend({}, properties);
31139 properties['token'] = this.get_config('token');
31140
31141 // set $duration if time_event was previously called for this event
31142 var start_timestamp = this['persistence'].remove_event_timer(event_name);
31143 if (!_.isUndefined(start_timestamp)) {
31144 var duration_in_ms = new Date().getTime() - start_timestamp;
31145 properties['$duration'] = parseFloat((duration_in_ms / 1000).toFixed(3));
31146 }
31147
31148 this._set_default_superprops();
31149
31150 var marketing_properties = this.get_config('track_marketing')
31151 ? _.info.marketingParams()
31152 : {};
31153
31154 // note: extend writes to the first object, so lets make sure we
31155 // don't write to the persistence properties object and info
31156 // properties object by passing in a new object
31157
31158 // update properties with pageview info and super-properties
31159 properties = _.extend(
31160 {},
31161 _.info.properties({'mp_loader': this.get_config('mp_loader')}),
31162 marketing_properties,
31163 this['persistence'].properties(),
31164 this.unpersisted_superprops,
31165 this.get_session_recording_properties(),
31166 properties
31167 );
31168
31169 var property_blacklist = this.get_config('property_blacklist');
31170 if (_.isArray(property_blacklist)) {
31171 _.each(property_blacklist, function(blacklisted_prop) {
31172 delete properties[blacklisted_prop];
31173 });
31174 } else {
31175 this.report_error('Invalid value for property_blacklist config: ' + property_blacklist);
31176 }
31177
31178 var data = {
31179 'event': event_name,
31180 'properties': properties
31181 };
31182 var ret = this._track_or_batch({
31183 type: 'events',
31184 data: data,
31185 endpoint: this.get_api_host('events') + '/' + this.get_config('api_routes')['track'],
31186 batcher: this.request_batchers.events,
31187 should_send_immediately: should_send_immediately,
31188 send_request_options: options
31189 }, callback);
31190
31191 return ret;
31192 });
31193
31194 /**
31195 * Register the current user into one/many groups.
31196 *
31197 * ### Usage:
31198 *
31199 * mixpanel.set_group('company', ['mixpanel', 'google']) // an array of IDs
31200 * mixpanel.set_group('company', 'mixpanel')
31201 * mixpanel.set_group('company', 128746312)
31202 *
31203 * @param {String} group_key Group key
31204 * @param {Array|String|Number} group_ids An array of group IDs, or a singular group ID
31205 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
31206 *
31207 */
31208 MixpanelLib.prototype.set_group = addOptOutCheckMixpanelLib(function(group_key, group_ids, callback) {
31209 if (!_.isArray(group_ids)) {
31210 group_ids = [group_ids];
31211 }
31212 var prop = {};
31213 prop[group_key] = group_ids;
31214 this.register(prop);
31215 return this['people'].set(group_key, group_ids, callback);
31216 });
31217
31218 /**
31219 * Add a new group for this user.
31220 *
31221 * ### Usage:
31222 *
31223 * mixpanel.add_group('company', 'mixpanel')
31224 *
31225 * @param {String} group_key Group key
31226 * @param {*} group_id A valid Mixpanel property type
31227 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
31228 */
31229 MixpanelLib.prototype.add_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
31230 var old_values = this.get_property(group_key);
31231 var prop = {};
31232 if (old_values === undefined) {
31233 prop[group_key] = [group_id];
31234 this.register(prop);
31235 } else {
31236 if (old_values.indexOf(group_id) === -1) {
31237 old_values.push(group_id);
31238 prop[group_key] = old_values;
31239 this.register(prop);
31240 }
31241 }
31242 return this['people'].union(group_key, group_id, callback);
31243 });
31244
31245 /**
31246 * Remove a group from this user.
31247 *
31248 * ### Usage:
31249 *
31250 * mixpanel.remove_group('company', 'mixpanel')
31251 *
31252 * @param {String} group_key Group key
31253 * @param {*} group_id A valid Mixpanel property type
31254 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
31255 */
31256 MixpanelLib.prototype.remove_group = addOptOutCheckMixpanelLib(function(group_key, group_id, callback) {
31257 var old_value = this.get_property(group_key);
31258 // if the value doesn't exist, the persistent store is unchanged
31259 if (old_value !== undefined) {
31260 var idx = old_value.indexOf(group_id);
31261 if (idx > -1) {
31262 old_value.splice(idx, 1);
31263 this.register({group_key: old_value});
31264 }
31265 if (old_value.length === 0) {
31266 this.unregister(group_key);
31267 }
31268 }
31269 return this['people'].remove(group_key, group_id, callback);
31270 });
31271
31272 /**
31273 * Track an event with specific groups.
31274 *
31275 * ### Usage:
31276 *
31277 * mixpanel.track_with_groups('purchase', {'product': 'iphone'}, {'University': ['UCB', 'UCLA']})
31278 *
31279 * @param {String} event_name The name of the event (see `mixpanel.track()`)
31280 * @param {Object=} properties A set of properties to include with the event you're sending (see `mixpanel.track()`)
31281 * @param {Object=} groups An object mapping group name keys to one or more values
31282 * @param {Function} [callback] If provided, the callback will be called after tracking the event.
31283 */
31284 MixpanelLib.prototype.track_with_groups = addOptOutCheckMixpanelLib(function(event_name, properties, groups, callback) {
31285 var tracking_props = _.extend({}, properties || {});
31286 _.each(groups, function(v, k) {
31287 if (v !== null && v !== undefined) {
31288 tracking_props[k] = v;
31289 }
31290 });
31291 return this.track(event_name, tracking_props, callback);
31292 });
31293
31294 MixpanelLib.prototype._create_map_key = function (group_key, group_id) {
31295 return group_key + '_' + JSON.stringify(group_id);
31296 };
31297
31298 MixpanelLib.prototype._remove_group_from_cache = function (group_key, group_id) {
31299 delete this._cached_groups[this._create_map_key(group_key, group_id)];
31300 };
31301
31302 /**
31303 * Look up reference to a Mixpanel group
31304 *
31305 * ### Usage:
31306 *
31307 * mixpanel.get_group(group_key, group_id)
31308 *
31309 * @param {String} group_key Group key
31310 * @param {Object} group_id A valid Mixpanel property type
31311 * @returns {Object} A MixpanelGroup identifier
31312 */
31313 MixpanelLib.prototype.get_group = function (group_key, group_id) {
31314 var map_key = this._create_map_key(group_key, group_id);
31315 var group = this._cached_groups[map_key];
31316 if (group === undefined || group._group_key !== group_key || group._group_id !== group_id) {
31317 group = new MixpanelGroup();
31318 group._init(this, group_key, group_id);
31319 this._cached_groups[map_key] = group;
31320 }
31321 return group;
31322 };
31323
31324 /**
31325 * Track a default Mixpanel page view event, which includes extra default event properties to
31326 * improve page view data.
31327 *
31328 * ### Usage:
31329 *
31330 * // track a default $mp_web_page_view event
31331 * mixpanel.track_pageview();
31332 *
31333 * // track a page view event with additional event properties
31334 * mixpanel.track_pageview({'ab_test_variant': 'card-layout-b'});
31335 *
31336 * // example approach to track page views on different page types as event properties
31337 * mixpanel.track_pageview({'page': 'pricing'});
31338 * mixpanel.track_pageview({'page': 'homepage'});
31339 *
31340 * // UNCOMMON: Tracking a page view event with a custom event_name option. NOT expected to be used for
31341 * // individual pages on the same site or product. Use cases for custom event_name may be page
31342 * // views on different products or internal applications that are considered completely separate
31343 * mixpanel.track_pageview({'page': 'customer-search'}, {'event_name': '[internal] Admin Page View'});
31344 *
31345 * ### Notes:
31346 *
31347 * The `config.track_pageview` option for <a href="#mixpanelinit">mixpanel.init()</a>
31348 * may be turned on for tracking page loads automatically.
31349 *
31350 * // track only page loads
31351 * mixpanel.init(PROJECT_TOKEN, {track_pageview: true});
31352 *
31353 * // track when the URL changes in any manner
31354 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'full-url'});
31355 *
31356 * // track when the URL changes, ignoring any changes in the hash part
31357 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path-and-query-string'});
31358 *
31359 * // track when the path changes, ignoring any query parameter or hash changes
31360 * mixpanel.init(PROJECT_TOKEN, {track_pageview: 'url-with-path'});
31361 *
31362 * @param {Object} [properties] An optional set of additional properties to send with the page view event
31363 * @param {Object} [options] Page view tracking options
31364 * @param {String} [options.event_name] - Alternate name for the tracking event
31365 * @returns {Boolean|Object} If the tracking request was successfully initiated/queued, an object
31366 * with the tracking payload sent to the API server is returned; otherwise false.
31367 */
31368 MixpanelLib.prototype.track_pageview = addOptOutCheckMixpanelLib(function(properties, options) {
31369 if (typeof properties !== 'object') {
31370 properties = {};
31371 }
31372 options = options || {};
31373 var event_name = options['event_name'] || '$mp_web_page_view';
31374
31375 var default_page_properties = _.extend(
31376 _.info.mpPageViewProperties(),
31377 _.info.campaignParams(),
31378 _.info.clickParams()
31379 );
31380
31381 var event_properties = _.extend(
31382 {},
31383 default_page_properties,
31384 properties
31385 );
31386
31387 return this.track(event_name, event_properties);
31388 });
31389
31390 /**
31391 * Track clicks on a set of document elements. Selector must be a
31392 * valid query. Elements must exist on the page at the time track_links is called.
31393 *
31394 * ### Usage:
31395 *
31396 * // track click for link id #nav
31397 * mixpanel.track_links('#nav', 'Clicked Nav Link');
31398 *
31399 * ### Notes:
31400 *
31401 * This function will wait up to 300 ms for the Mixpanel
31402 * servers to respond. If they have not responded by that time
31403 * it will head to the link without ensuring that your event
31404 * has been tracked. To configure this timeout please see the
31405 * set_config() documentation below.
31406 *
31407 * If you pass a function in as the properties argument, the
31408 * function will receive the DOMElement that triggered the
31409 * event as an argument. You are expected to return an object
31410 * from the function; any properties defined on this object
31411 * will be sent to mixpanel as event properties.
31412 *
31413 * @type {Function}
31414 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
31415 * @param {String} event_name The name of the event to track
31416 * @param {Object|Function} [properties] A properties object or function that returns a dictionary of properties when passed a DOMElement
31417 */
31418 MixpanelLib.prototype.track_links = function() {
31419 return this._track_dom.call(this, LinkTracker, arguments);
31420 };
31421
31422 /**
31423 * Track form submissions. Selector must be a valid query.
31424 *
31425 * ### Usage:
31426 *
31427 * // track submission for form id 'register'
31428 * mixpanel.track_forms('#register', 'Created Account');
31429 *
31430 * ### Notes:
31431 *
31432 * This function will wait up to 300 ms for the mixpanel
31433 * servers to respond, if they have not responded by that time
31434 * it will head to the link without ensuring that your event
31435 * has been tracked. To configure this timeout please see the
31436 * set_config() documentation below.
31437 *
31438 * If you pass a function in as the properties argument, the
31439 * function will receive the DOMElement that triggered the
31440 * event as an argument. You are expected to return an object
31441 * from the function; any properties defined on this object
31442 * will be sent to mixpanel as event properties.
31443 *
31444 * @type {Function}
31445 * @param {Object|String} query A valid DOM query, element or jQuery-esque list
31446 * @param {String} event_name The name of the event to track
31447 * @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
31448 */
31449 MixpanelLib.prototype.track_forms = function() {
31450 return this._track_dom.call(this, FormTracker, arguments);
31451 };
31452
31453 /**
31454 * Time an event by including the time between this call and a
31455 * later 'track' call for the same event in the properties sent
31456 * with the event.
31457 *
31458 * ### Usage:
31459 *
31460 * // time an event named 'Registered'
31461 * mixpanel.time_event('Registered');
31462 * mixpanel.track('Registered', {'Gender': 'Male', 'Age': 21});
31463 *
31464 * When called for a particular event name, the next track call for that event
31465 * name will include the elapsed time between the 'time_event' and 'track'
31466 * calls. This value is stored as seconds in the '$duration' property.
31467 *
31468 * @param {String} event_name The name of the event.
31469 */
31470 MixpanelLib.prototype.time_event = function(event_name) {
31471 if (_.isUndefined(event_name)) {
31472 this.report_error('No event name provided to mixpanel.time_event');
31473 return;
31474 }
31475
31476 if (this._event_is_disabled(event_name)) {
31477 return;
31478 }
31479
31480 this['persistence'].set_event_timer(event_name, new Date().getTime());
31481 };
31482
31483 var REGISTER_DEFAULTS = {
31484 'persistent': true
31485 };
31486 /**
31487 * Helper to parse options param for register methods, maintaining
31488 * legacy support for plain "days" param instead of options object
31489 * @param {Number|Object} [days_or_options] 'days' option (Number), or Options object for register methods
31490 * @returns {Object} options object
31491 */
31492 var options_for_register = function(days_or_options) {
31493 var options;
31494 if (_.isObject(days_or_options)) {
31495 options = days_or_options;
31496 } else if (!_.isUndefined(days_or_options)) {
31497 options = {'days': days_or_options};
31498 } else {
31499 options = {};
31500 }
31501 return _.extend({}, REGISTER_DEFAULTS, options);
31502 };
31503
31504 /**
31505 * Register a set of super properties, which are included with all
31506 * events. This will overwrite previous super property values.
31507 *
31508 * ### Usage:
31509 *
31510 * // register 'Gender' as a super property
31511 * mixpanel.register({'Gender': 'Female'});
31512 *
31513 * // register several super properties when a user signs up
31514 * mixpanel.register({
31515 * 'Email': 'jdoe@example.com',
31516 * 'Account Type': 'Free'
31517 * });
31518 *
31519 * // register only for the current pageload
31520 * mixpanel.register({'Name': 'Pat'}, {persistent: false});
31521 *
31522 * @param {Object} properties An associative array of properties to store about the user
31523 * @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)
31524 * @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)
31525 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
31526 */
31527 MixpanelLib.prototype.register = function(props, days_or_options) {
31528 var options = options_for_register(days_or_options);
31529 if (options['persistent']) {
31530 this['persistence'].register(props, options['days']);
31531 } else {
31532 _.extend(this.unpersisted_superprops, props);
31533 }
31534 };
31535
31536 /**
31537 * Register a set of super properties only once. This will not
31538 * overwrite previous super property values, unlike register().
31539 *
31540 * ### Usage:
31541 *
31542 * // register a super property for the first time only
31543 * mixpanel.register_once({
31544 * 'First Login Date': new Date().toISOString()
31545 * });
31546 *
31547 * // register once, only for the current pageload
31548 * mixpanel.register_once({
31549 * 'First interaction time': new Date().toISOString()
31550 * }, 'None', {persistent: false});
31551 *
31552 * ### Notes:
31553 *
31554 * If default_value is specified, current super properties
31555 * with that value will be overwritten.
31556 *
31557 * @param {Object} properties An associative array of properties to store about the user
31558 * @param {*} [default_value] Value to override if already set in super properties (ex: 'False') Default: 'None'
31559 * @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)
31560 * @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)
31561 * @param {boolean} [days_or_options.persistent=true] - whether to put in persistent storage (cookie/localStorage)
31562 */
31563 MixpanelLib.prototype.register_once = function(props, default_value, days_or_options) {
31564 var options = options_for_register(days_or_options);
31565 if (options['persistent']) {
31566 this['persistence'].register_once(props, default_value, options['days']);
31567 } else {
31568 if (typeof(default_value) === 'undefined') {
31569 default_value = 'None';
31570 }
31571 _.each(props, function(val, prop) {
31572 if (!this.unpersisted_superprops.hasOwnProperty(prop) || this.unpersisted_superprops[prop] === default_value) {
31573 this.unpersisted_superprops[prop] = val;
31574 }
31575 }, this);
31576 }
31577 };
31578
31579 /**
31580 * Delete a super property stored with the current user.
31581 *
31582 * @param {String} property The name of the super property to remove
31583 * @param {Object} [options]
31584 * @param {boolean} [options.persistent=true] - whether to look in persistent storage (cookie/localStorage)
31585 */
31586 MixpanelLib.prototype.unregister = function(property, options) {
31587 options = options_for_register(options);
31588 if (options['persistent']) {
31589 this['persistence'].unregister(property);
31590 } else {
31591 delete this.unpersisted_superprops[property];
31592 }
31593 };
31594
31595 MixpanelLib.prototype._register_single = function(prop, value) {
31596 var props = {};
31597 props[prop] = value;
31598 this.register(props);
31599 };
31600
31601 /**
31602 * Identify a user with a unique ID to track user activity across
31603 * devices, tie a user to their events, and create a user profile.
31604 * If you never call this method, unique visitors are tracked using
31605 * a UUID generated the first time they visit the site.
31606 *
31607 * Call identify when you know the identity of the current user,
31608 * typically after login or signup. We recommend against using
31609 * identify for anonymous visitors to your site.
31610 *
31611 * ### Notes:
31612 * If your project has
31613 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
31614 * enabled, the identify method will connect pre- and
31615 * post-authentication events when appropriate.
31616 *
31617 * If your project does not have ID Merge enabled, identify will
31618 * change the user's local distinct_id to the unique ID you pass.
31619 * Events tracked prior to authentication will not be connected
31620 * to the same user identity. If ID Merge is disabled, alias can
31621 * be used to connect pre- and post-registration events.
31622 *
31623 * @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.
31624 */
31625 MixpanelLib.prototype.identify = function(
31626 new_distinct_id, _set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback
31627 ) {
31628 // Optional Parameters
31629 // _set_callback:function A callback to be run if and when the People set queue is flushed
31630 // _add_callback:function A callback to be run if and when the People add queue is flushed
31631 // _append_callback:function A callback to be run if and when the People append queue is flushed
31632 // _set_once_callback:function A callback to be run if and when the People set_once queue is flushed
31633 // _union_callback:function A callback to be run if and when the People union queue is flushed
31634 // _unset_callback:function A callback to be run if and when the People unset queue is flushed
31635
31636 var previous_distinct_id = this.get_distinct_id();
31637 if (new_distinct_id && previous_distinct_id !== new_distinct_id) {
31638 // we allow the following condition if previous distinct_id is same as new_distinct_id
31639 // so that you can force flush people updates for anonymous profiles.
31640 if (typeof new_distinct_id === 'string' && new_distinct_id.indexOf(DEVICE_ID_PREFIX) === 0) {
31641 this.report_error('distinct_id cannot have $device: prefix');
31642 return -1;
31643 }
31644 this.register({'$user_id': new_distinct_id});
31645 }
31646
31647 if (!this.get_property('$device_id')) {
31648 // The persisted distinct id might not actually be a device id at all
31649 // it might be a distinct id of the user from before
31650 var device_id = previous_distinct_id;
31651 this.register_once({
31652 '$had_persisted_distinct_id': true,
31653 '$device_id': device_id
31654 }, '');
31655 }
31656
31657 // identify only changes the distinct id if it doesn't match either the existing or the alias;
31658 // if it's new, blow away the alias as well.
31659 if (new_distinct_id !== previous_distinct_id && new_distinct_id !== this.get_property(ALIAS_ID_KEY)) {
31660 this.unregister(ALIAS_ID_KEY);
31661 this.register({'distinct_id': new_distinct_id});
31662 }
31663 this._flags.identify_called = true;
31664 // Flush any queued up people requests
31665 this['people']._flush(_set_callback, _add_callback, _append_callback, _set_once_callback, _union_callback, _unset_callback, _remove_callback);
31666
31667 // send an $identify event any time the distinct_id is changing - logic on the server
31668 // will determine whether or not to do anything with it.
31669 if (new_distinct_id !== previous_distinct_id) {
31670 this.track('$identify', {
31671 'distinct_id': new_distinct_id,
31672 '$anon_distinct_id': previous_distinct_id
31673 }, {skip_hooks: true});
31674 }
31675
31676 // check feature flags again if distinct id has changed
31677 if (new_distinct_id !== previous_distinct_id) {
31678 this.flags.fetchFlags();
31679 }
31680 };
31681
31682 /**
31683 * Clears super properties and generates a new random distinct_id for this instance.
31684 * Useful for clearing data when a user logs out.
31685 */
31686 MixpanelLib.prototype.reset = function() {
31687 this.stop_session_recording();
31688 this['persistence'].clear();
31689 this._flags.identify_called = false;
31690 var uuid = _.UUID();
31691 this.register_once({
31692 'distinct_id': DEVICE_ID_PREFIX + uuid,
31693 '$device_id': uuid
31694 }, '');
31695 this._check_and_start_session_recording();
31696 };
31697
31698 /**
31699 * Returns the current distinct id of the user. This is either the id automatically
31700 * generated by the library or the id that has been passed by a call to identify().
31701 *
31702 * ### Notes:
31703 *
31704 * get_distinct_id() can only be called after the Mixpanel library has finished loading.
31705 * init() has a loaded function available to handle this automatically. For example:
31706 *
31707 * // set distinct_id after the mixpanel library has loaded
31708 * mixpanel.init('YOUR PROJECT TOKEN', {
31709 * loaded: function(mixpanel) {
31710 * distinct_id = mixpanel.get_distinct_id();
31711 * }
31712 * });
31713 */
31714 MixpanelLib.prototype.get_distinct_id = function() {
31715 return this.get_property('distinct_id');
31716 };
31717
31718 /**
31719 * The alias method creates an alias which Mixpanel will use to
31720 * remap one id to another. Multiple aliases can point to the
31721 * same identifier.
31722 *
31723 * The following is a valid use of alias:
31724 *
31725 * mixpanel.alias('new_id', 'existing_id');
31726 * // You can add multiple id aliases to the existing ID
31727 * mixpanel.alias('newer_id', 'existing_id');
31728 *
31729 * Aliases can also be chained - the following is a valid example:
31730 *
31731 * mixpanel.alias('new_id', 'existing_id');
31732 * // chain newer_id - new_id - existing_id
31733 * mixpanel.alias('newer_id', 'new_id');
31734 *
31735 * Aliases cannot point to multiple identifiers - the following
31736 * example will not work:
31737 *
31738 * mixpanel.alias('new_id', 'existing_id');
31739 * // this is invalid as 'new_id' already points to 'existing_id'
31740 * mixpanel.alias('new_id', 'newer_id');
31741 *
31742 * ### Notes:
31743 *
31744 * If your project does not have
31745 * <a href="https://help.mixpanel.com/hc/en-us/articles/360039133851">ID Merge</a>
31746 * enabled, the best practice is to call alias once when a unique
31747 * ID is first created for a user (e.g., when a user first registers
31748 * for an account). Do not use alias multiple times for a single
31749 * user without ID Merge enabled.
31750 *
31751 * @param {String} alias A unique identifier that you want to use for this user in the future.
31752 * @param {String} [original] The current identifier being used for this user.
31753 */
31754 MixpanelLib.prototype.alias = function(alias, original) {
31755 // If the $people_distinct_id key exists in persistence, there has been a previous
31756 // mixpanel.people.identify() call made for this user. It is VERY BAD to make an alias with
31757 // this ID, as it will duplicate users.
31758 if (alias === this.get_property(PEOPLE_DISTINCT_ID_KEY)) {
31759 this.report_error('Attempting to create alias for existing People user - aborting.');
31760 return -2;
31761 }
31762
31763 var _this = this;
31764 if (_.isUndefined(original)) {
31765 original = this.get_distinct_id();
31766 }
31767 if (alias !== original) {
31768 this._register_single(ALIAS_ID_KEY, alias);
31769 return this.track('$create_alias', {
31770 'alias': alias,
31771 'distinct_id': original
31772 }, {
31773 skip_hooks: true
31774 }, function() {
31775 // Flush the people queue
31776 _this.identify(alias);
31777 });
31778 } else {
31779 this.report_error('alias matches current distinct_id - skipping api call.');
31780 this.identify(alias);
31781 return -1;
31782 }
31783 };
31784
31785 /**
31786 * Provide a string to recognize the user by. The string passed to
31787 * this method will appear in the Mixpanel Streams product rather
31788 * than an automatically generated name. Name tags do not have to
31789 * be unique.
31790 *
31791 * This value will only be included in Streams data.
31792 *
31793 * @param {String} name_tag A human readable name for the user
31794 * @deprecated
31795 */
31796 MixpanelLib.prototype.name_tag = function(name_tag) {
31797 this._register_single('mp_name_tag', name_tag);
31798 };
31799
31800 /**
31801 * Update the configuration of a mixpanel library instance.
31802 *
31803 * The default config is:
31804 *
31805 * {
31806 * // host for requests (customizable for e.g. a local proxy)
31807 * api_host: 'https://api-js.mixpanel.com',
31808 *
31809 * // endpoints for different types of requests
31810 * api_routes: {
31811 * track: 'track/',
31812 * engage: 'engage/',
31813 * groups: 'groups/',
31814 * }
31815 *
31816 * // HTTP method for tracking requests
31817 * api_method: 'POST'
31818 *
31819 * // transport for sending requests ('XHR' or 'sendBeacon')
31820 * // NB: sendBeacon should only be used for scenarios such as
31821 * // page unload where a "best-effort" attempt to send is
31822 * // acceptable; the sendBeacon API does not support callbacks
31823 * // or any way to know the result of the request. Mixpanel
31824 * // tracking via sendBeacon will not support any event-
31825 * // batching or retry mechanisms.
31826 * api_transport: 'XHR'
31827 *
31828 * // request-batching/queueing/retry
31829 * batch_requests: true,
31830 *
31831 * // maximum number of events/updates to send in a single
31832 * // network request
31833 * batch_size: 50,
31834 *
31835 * // milliseconds to wait between sending batch requests
31836 * batch_flush_interval_ms: 5000,
31837 *
31838 * // milliseconds to wait for network responses to batch requests
31839 * // before they are considered timed-out and retried
31840 * batch_request_timeout_ms: 90000,
31841 *
31842 * // override value for cookie domain, only useful for ensuring
31843 * // correct cross-subdomain cookies on unusual domains like
31844 * // subdomain.mainsite.avocat.fr; NB this cannot be used to
31845 * // set cookies on a different domain than the current origin
31846 * cookie_domain: ''
31847 *
31848 * // super properties cookie expiration (in days)
31849 * cookie_expiration: 365
31850 *
31851 * // if true, cookie will be set with SameSite=None; Secure
31852 * // this is only useful in special situations, like embedded
31853 * // 3rd-party iframes that set up a Mixpanel instance
31854 * cross_site_cookie: false
31855 *
31856 * // super properties span subdomains
31857 * cross_subdomain_cookie: true
31858 *
31859 * // debug mode
31860 * debug: false
31861 *
31862 * // if this is true, the mixpanel cookie or localStorage entry
31863 * // will be deleted, and no user persistence will take place
31864 * disable_persistence: false
31865 *
31866 * // if this is true, Mixpanel will automatically determine
31867 * // City, Region and Country data using the IP address of
31868 * //the client
31869 * ip: true
31870 *
31871 * // opt users out of tracking by this Mixpanel instance by default
31872 * opt_out_tracking_by_default: false
31873 *
31874 * // opt users out of browser data storage by this Mixpanel instance by default
31875 * opt_out_persistence_by_default: false
31876 *
31877 * // persistence mechanism used by opt-in/opt-out methods - cookie
31878 * // or localStorage - falls back to cookie if localStorage is unavailable
31879 * opt_out_tracking_persistence_type: 'localStorage'
31880 *
31881 * // customize the name of cookie/localStorage set by opt-in/opt-out methods
31882 * opt_out_tracking_cookie_prefix: null
31883 *
31884 * // type of persistent store for super properties (cookie/
31885 * // localStorage) if set to 'localStorage', any existing
31886 * // mixpanel cookie value with the same persistence_name
31887 * // will be transferred to localStorage and deleted
31888 * persistence: 'cookie'
31889 *
31890 * // name for super properties persistent store
31891 * persistence_name: ''
31892 *
31893 * // names of properties/superproperties which should never
31894 * // be sent with track() calls
31895 * property_blacklist: []
31896 *
31897 * // if this is true, mixpanel cookies will be marked as
31898 * // secure, meaning they will only be transmitted over https
31899 * secure_cookie: false
31900 *
31901 * // disables enriching user profiles with first touch marketing data
31902 * skip_first_touch_marketing: false
31903 *
31904 * // the amount of time track_links will
31905 * // wait for Mixpanel's servers to respond
31906 * track_links_timeout: 300
31907 *
31908 * // adds any UTM parameters and click IDs present on the page to any events fired
31909 * track_marketing: true
31910 *
31911 * // enables automatic page view tracking using default page view events through
31912 * // the track_pageview() method
31913 * track_pageview: false
31914 *
31915 * // if you set upgrade to be true, the library will check for
31916 * // a cookie from our old js library and import super
31917 * // properties from it, then the old cookie is deleted
31918 * // The upgrade config option only works in the initialization,
31919 * // so make sure you set it when you create the library.
31920 * upgrade: false
31921 *
31922 * // extra HTTP request headers to set for each API request, in
31923 * // the format {'Header-Name': value}
31924 * xhr_headers: {}
31925 *
31926 * // whether to ignore or respect the web browser's Do Not Track setting
31927 * ignore_dnt: false
31928 * }
31929 *
31930 *
31931 * @param {Object} config A dictionary of new configuration values to update
31932 */
31933 MixpanelLib.prototype.set_config = function(config) {
31934 if (_.isObject(config)) {
31935 _.extend(this['config'], config);
31936
31937 var new_batch_size = config['batch_size'];
31938 if (new_batch_size) {
31939 _.each(this.request_batchers, function(batcher) {
31940 batcher.resetBatchSize();
31941 });
31942 }
31943
31944 if (!this.get_config('persistence_name')) {
31945 this['config']['persistence_name'] = this['config']['cookie_name'];
31946 }
31947 if (!this.get_config('disable_persistence')) {
31948 this['config']['disable_persistence'] = this['config']['disable_cookie'];
31949 }
31950
31951 if (this['persistence']) {
31952 this['persistence'].update_config(this['config']);
31953 }
31954 Config.DEBUG = Config.DEBUG || this.get_config('debug');
31955
31956 if (('autocapture' in config || 'record_heatmap_data' in config) && this.autocapture) {
31957 this.autocapture.init();
31958 }
31959 }
31960 };
31961
31962 /**
31963 * returns the current config object for the library.
31964 */
31965 MixpanelLib.prototype.get_config = function(prop_name) {
31966 return this['config'][prop_name];
31967 };
31968
31969 /**
31970 * Fetch a hook function from config, with safe default, and run it
31971 * against the given arguments
31972 * @param {string} hook_name which hook to retrieve
31973 * @returns {any|null} return value of user-provided hook, or null if nothing was returned
31974 */
31975 MixpanelLib.prototype._run_hook = function(hook_name) {
31976 var ret = (this['config']['hooks'][hook_name] || IDENTITY_FUNC).apply(this, slice.call(arguments, 1));
31977 if (typeof ret === 'undefined') {
31978 this.report_error(hook_name + ' hook did not return a value');
31979 ret = null;
31980 }
31981 return ret;
31982 };
31983
31984 /**
31985 * Returns the value of the super property named property_name. If no such
31986 * property is set, get_property() will return the undefined value.
31987 *
31988 * ### Notes:
31989 *
31990 * get_property() can only be called after the Mixpanel library has finished loading.
31991 * init() has a loaded function available to handle this automatically. For example:
31992 *
31993 * // grab value for 'user_id' after the mixpanel library has loaded
31994 * mixpanel.init('YOUR PROJECT TOKEN', {
31995 * loaded: function(mixpanel) {
31996 * user_id = mixpanel.get_property('user_id');
31997 * }
31998 * });
31999 *
32000 * @param {String} property_name The name of the super property you want to retrieve
32001 */
32002 MixpanelLib.prototype.get_property = function(property_name) {
32003 return this['persistence'].load_prop([property_name]);
32004 };
32005
32006 /**
32007 * Get the API host for a specific endpoint type, falling back to the default api_host if not specified
32008 *
32009 * @param {String} endpoint_type The type of endpoint (e.g., "events", "people", "groups")
32010 * @returns {String} The API host to use for this endpoint
32011 */
32012 MixpanelLib.prototype.get_api_host = function(endpoint_type) {
32013 return this.get_config('api_hosts')[endpoint_type] || this.get_config('api_host');
32014 };
32015
32016 MixpanelLib.prototype.toString = function() {
32017 var name = this.get_config('name');
32018 if (name !== PRIMARY_INSTANCE_NAME) {
32019 name = PRIMARY_INSTANCE_NAME + '.' + name;
32020 }
32021 return name;
32022 };
32023
32024 MixpanelLib.prototype._event_is_disabled = function(event_name) {
32025 return _.isBlockedUA(userAgent) ||
32026 this._flags.disable_all_events ||
32027 _.include(this.__disabled_events, event_name);
32028 };
32029
32030 // perform some housekeeping around GDPR opt-in/out state
32031 MixpanelLib.prototype._gdpr_init = function() {
32032 var is_localStorage_requested = this.get_config('opt_out_tracking_persistence_type') === 'localStorage';
32033
32034 // try to convert opt-in/out cookies to localStorage if possible
32035 if (is_localStorage_requested && _.localStorage.is_supported()) {
32036 if (!this.has_opted_in_tracking() && this.has_opted_in_tracking({'persistence_type': 'cookie'})) {
32037 this.opt_in_tracking({'enable_persistence': false});
32038 }
32039 if (!this.has_opted_out_tracking() && this.has_opted_out_tracking({'persistence_type': 'cookie'})) {
32040 this.opt_out_tracking({'clear_persistence': false});
32041 }
32042 this.clear_opt_in_out_tracking({
32043 'persistence_type': 'cookie',
32044 'enable_persistence': false
32045 });
32046 }
32047
32048 // check whether the user has already opted out - if so, clear & disable persistence
32049 if (this.has_opted_out_tracking()) {
32050 this._gdpr_update_persistence({'clear_persistence': true});
32051
32052 // check whether we should opt out by default
32053 // note: we don't clear persistence here by default since opt-out default state is often
32054 // used as an initial state while GDPR information is being collected
32055 } else if (!this.has_opted_in_tracking() && (
32056 this.get_config('opt_out_tracking_by_default') || _.cookie.get('mp_optout')
32057 )) {
32058 _.cookie.remove('mp_optout');
32059 this.opt_out_tracking({
32060 'clear_persistence': this.get_config('opt_out_persistence_by_default')
32061 });
32062 }
32063 };
32064
32065 /**
32066 * Enable or disable persistence based on options
32067 * only enable/disable if persistence is not already in this state
32068 * @param {boolean} [options.clear_persistence] If true, will delete all data stored by the sdk in persistence and disable it
32069 * @param {boolean} [options.enable_persistence] If true, will re-enable sdk persistence
32070 */
32071 MixpanelLib.prototype._gdpr_update_persistence = function(options) {
32072 var disabled;
32073 if (options && options['clear_persistence']) {
32074 disabled = true;
32075 } else if (options && options['enable_persistence']) {
32076 disabled = false;
32077 } else {
32078 return;
32079 }
32080
32081 if (!this.get_config('disable_persistence') && this['persistence'].disabled !== disabled) {
32082 this['persistence'].set_disabled(disabled);
32083 }
32084
32085 if (disabled) {
32086 this.stop_batch_senders();
32087 this.stop_session_recording();
32088 } else {
32089 // only start batchers after opt-in if they have previously been started
32090 // in order to avoid unintentionally starting up batching for the first time
32091 if (this._batchers_were_started) {
32092 this.start_batch_senders();
32093 }
32094 }
32095 };
32096
32097 // call a base gdpr function after constructing the appropriate token and options args
32098 MixpanelLib.prototype._gdpr_call_func = function(func, options) {
32099 options = _.extend({
32100 'track': _.bind(this.track, this),
32101 'persistence_type': this.get_config('opt_out_tracking_persistence_type'),
32102 'cookie_prefix': this.get_config('opt_out_tracking_cookie_prefix'),
32103 'cookie_expiration': this.get_config('cookie_expiration'),
32104 'cross_site_cookie': this.get_config('cross_site_cookie'),
32105 'cross_subdomain_cookie': this.get_config('cross_subdomain_cookie'),
32106 'cookie_domain': this.get_config('cookie_domain'),
32107 'secure_cookie': this.get_config('secure_cookie'),
32108 'ignore_dnt': this.get_config('ignore_dnt')
32109 }, options);
32110
32111 // check if localStorage can be used for recording opt out status, fall back to cookie if not
32112 if (!_.localStorage.is_supported()) {
32113 options['persistence_type'] = 'cookie';
32114 }
32115
32116 return func(this.get_config('token'), {
32117 track: options['track'],
32118 trackEventName: options['track_event_name'],
32119 trackProperties: options['track_properties'],
32120 persistenceType: options['persistence_type'],
32121 persistencePrefix: options['cookie_prefix'],
32122 cookieDomain: options['cookie_domain'],
32123 cookieExpiration: options['cookie_expiration'],
32124 crossSiteCookie: options['cross_site_cookie'],
32125 crossSubdomainCookie: options['cross_subdomain_cookie'],
32126 secureCookie: options['secure_cookie'],
32127 ignoreDnt: options['ignore_dnt']
32128 });
32129 };
32130
32131 /**
32132 * Opt the user in to data tracking and cookies/localstorage for this Mixpanel instance
32133 *
32134 * ### Usage:
32135 *
32136 * // opt user in
32137 * mixpanel.opt_in_tracking();
32138 *
32139 * // opt user in with specific event name, properties, cookie configuration
32140 * mixpanel.opt_in_tracking({
32141 * track_event_name: 'User opted in',
32142 * track_event_properties: {
32143 * 'Email': 'jdoe@example.com'
32144 * },
32145 * cookie_expiration: 30,
32146 * secure_cookie: true
32147 * });
32148 *
32149 * @param {Object} [options] A dictionary of config options to override
32150 * @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)
32151 * @param {string} [options.track_event_name=$opt_in] Event name to be used for tracking the opt-in action
32152 * @param {Object} [options.track_properties] Set of properties to be tracked along with the opt-in action
32153 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
32154 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32155 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32156 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
32157 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
32158 * @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)
32159 * @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)
32160 * @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)
32161 */
32162 MixpanelLib.prototype.opt_in_tracking = function(options) {
32163 options = _.extend({
32164 'enable_persistence': true
32165 }, options);
32166
32167 this._gdpr_call_func(optIn, options);
32168 this._gdpr_update_persistence(options);
32169 };
32170
32171 /**
32172 * Opt the user out of data tracking and cookies/localstorage for this Mixpanel instance
32173 *
32174 * ### Usage:
32175 *
32176 * // opt user out
32177 * mixpanel.opt_out_tracking();
32178 *
32179 * // opt user out with different cookie configuration from Mixpanel instance
32180 * mixpanel.opt_out_tracking({
32181 * cookie_expiration: 30,
32182 * secure_cookie: true
32183 * });
32184 *
32185 * @param {Object} [options] A dictionary of config options to override
32186 * @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
32187 * @param {boolean} [options.clear_persistence=true] If true, will delete all data stored by the sdk in persistence
32188 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32189 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32190 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
32191 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
32192 * @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)
32193 * @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)
32194 * @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)
32195 */
32196 MixpanelLib.prototype.opt_out_tracking = function(options) {
32197 options = _.extend({
32198 'clear_persistence': true,
32199 'delete_user': true
32200 }, options);
32201
32202 // delete user and clear charges since these methods may be disabled by opt-out
32203 if (options['delete_user'] && this['people'] && this['people']._identify_called()) {
32204 this['people'].delete_user();
32205 this['people'].clear_charges();
32206 }
32207
32208 this._gdpr_call_func(optOut, options);
32209 this._gdpr_update_persistence(options);
32210 };
32211
32212 /**
32213 * Check whether the user has opted in to data tracking and cookies/localstorage for this Mixpanel instance
32214 *
32215 * ### Usage:
32216 *
32217 * var has_opted_in = mixpanel.has_opted_in_tracking();
32218 * // use has_opted_in value
32219 *
32220 * @param {Object} [options] A dictionary of config options to override
32221 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32222 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32223 * @returns {boolean} current opt-in status
32224 */
32225 MixpanelLib.prototype.has_opted_in_tracking = function(options) {
32226 return this._gdpr_call_func(hasOptedIn, options);
32227 };
32228
32229 /**
32230 * Check whether the user has opted out of data tracking and cookies/localstorage for this Mixpanel instance
32231 *
32232 * ### Usage:
32233 *
32234 * var has_opted_out = mixpanel.has_opted_out_tracking();
32235 * // use has_opted_out value
32236 *
32237 * @param {Object} [options] A dictionary of config options to override
32238 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32239 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32240 * @returns {boolean} current opt-out status
32241 */
32242 MixpanelLib.prototype.has_opted_out_tracking = function(options) {
32243 return this._gdpr_call_func(hasOptedOut, options);
32244 };
32245
32246 /**
32247 * Clear the user's opt in/out status of data tracking and cookies/localstorage for this Mixpanel instance
32248 *
32249 * ### Usage:
32250 *
32251 * // clear user's opt-in/out status
32252 * mixpanel.clear_opt_in_out_tracking();
32253 *
32254 * // clear user's opt-in/out status with specific cookie configuration - should match
32255 * // configuration used when opt_in_tracking/opt_out_tracking methods were called.
32256 * mixpanel.clear_opt_in_out_tracking({
32257 * cookie_expiration: 30,
32258 * secure_cookie: true
32259 * });
32260 *
32261 * @param {Object} [options] A dictionary of config options to override
32262 * @param {boolean} [options.enable_persistence=true] If true, will re-enable sdk persistence
32263 * @param {string} [options.persistence_type=localStorage] Persistence mechanism used - cookie or localStorage - falls back to cookie if localStorage is unavailable
32264 * @param {string} [options.cookie_prefix=__mp_opt_in_out] Custom prefix to be used in the cookie/localstorage name
32265 * @param {Number} [options.cookie_expiration] Number of days until the opt-in cookie expires (overrides value specified in this Mixpanel instance's config)
32266 * @param {string} [options.cookie_domain] Custom cookie domain (overrides value specified in this Mixpanel instance's config)
32267 * @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)
32268 * @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)
32269 * @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)
32270 */
32271 MixpanelLib.prototype.clear_opt_in_out_tracking = function(options) {
32272 options = _.extend({
32273 'enable_persistence': true
32274 }, options);
32275
32276 this._gdpr_call_func(clearOptInOut, options);
32277 this._gdpr_update_persistence(options);
32278 };
32279
32280 MixpanelLib.prototype.report_error = function(msg, err) {
32281 console$1.error.apply(console$1.error, arguments);
32282 try {
32283 if (!err && !(msg instanceof Error)) {
32284 msg = new Error(msg);
32285 }
32286 this.get_config('error_reporter')(msg, err);
32287 } catch(err) {
32288 console$1.error(err);
32289 }
32290 };
32291
32292 // EXPORTS (for closure compiler)
32293
32294 // MixpanelLib Exports
32295 MixpanelLib.prototype['init'] = MixpanelLib.prototype.init;
32296 MixpanelLib.prototype['reset'] = MixpanelLib.prototype.reset;
32297 MixpanelLib.prototype['disable'] = MixpanelLib.prototype.disable;
32298 MixpanelLib.prototype['time_event'] = MixpanelLib.prototype.time_event;
32299 MixpanelLib.prototype['track'] = MixpanelLib.prototype.track;
32300 MixpanelLib.prototype['track_links'] = MixpanelLib.prototype.track_links;
32301 MixpanelLib.prototype['track_forms'] = MixpanelLib.prototype.track_forms;
32302 MixpanelLib.prototype['track_pageview'] = MixpanelLib.prototype.track_pageview;
32303 MixpanelLib.prototype['register'] = MixpanelLib.prototype.register;
32304 MixpanelLib.prototype['register_once'] = MixpanelLib.prototype.register_once;
32305 MixpanelLib.prototype['unregister'] = MixpanelLib.prototype.unregister;
32306 MixpanelLib.prototype['identify'] = MixpanelLib.prototype.identify;
32307 MixpanelLib.prototype['alias'] = MixpanelLib.prototype.alias;
32308 MixpanelLib.prototype['name_tag'] = MixpanelLib.prototype.name_tag;
32309 MixpanelLib.prototype['set_config'] = MixpanelLib.prototype.set_config;
32310 MixpanelLib.prototype['get_config'] = MixpanelLib.prototype.get_config;
32311 MixpanelLib.prototype['get_api_host'] = MixpanelLib.prototype.get_api_host;
32312 MixpanelLib.prototype['get_property'] = MixpanelLib.prototype.get_property;
32313 MixpanelLib.prototype['get_distinct_id'] = MixpanelLib.prototype.get_distinct_id;
32314 MixpanelLib.prototype['toString'] = MixpanelLib.prototype.toString;
32315 MixpanelLib.prototype['opt_out_tracking'] = MixpanelLib.prototype.opt_out_tracking;
32316 MixpanelLib.prototype['opt_in_tracking'] = MixpanelLib.prototype.opt_in_tracking;
32317 MixpanelLib.prototype['has_opted_out_tracking'] = MixpanelLib.prototype.has_opted_out_tracking;
32318 MixpanelLib.prototype['has_opted_in_tracking'] = MixpanelLib.prototype.has_opted_in_tracking;
32319 MixpanelLib.prototype['clear_opt_in_out_tracking'] = MixpanelLib.prototype.clear_opt_in_out_tracking;
32320 MixpanelLib.prototype['get_group'] = MixpanelLib.prototype.get_group;
32321 MixpanelLib.prototype['set_group'] = MixpanelLib.prototype.set_group;
32322 MixpanelLib.prototype['add_group'] = MixpanelLib.prototype.add_group;
32323 MixpanelLib.prototype['remove_group'] = MixpanelLib.prototype.remove_group;
32324 MixpanelLib.prototype['track_with_groups'] = MixpanelLib.prototype.track_with_groups;
32325 MixpanelLib.prototype['start_batch_senders'] = MixpanelLib.prototype.start_batch_senders;
32326 MixpanelLib.prototype['stop_batch_senders'] = MixpanelLib.prototype.stop_batch_senders;
32327 MixpanelLib.prototype['start_session_recording'] = MixpanelLib.prototype.start_session_recording;
32328 MixpanelLib.prototype['stop_session_recording'] = MixpanelLib.prototype.stop_session_recording;
32329 MixpanelLib.prototype['pause_session_recording'] = MixpanelLib.prototype.pause_session_recording;
32330 MixpanelLib.prototype['resume_session_recording'] = MixpanelLib.prototype.resume_session_recording;
32331 MixpanelLib.prototype['get_session_recording_properties'] = MixpanelLib.prototype.get_session_recording_properties;
32332 MixpanelLib.prototype['get_session_replay_url'] = MixpanelLib.prototype.get_session_replay_url;
32333 MixpanelLib.prototype['get_tab_id'] = MixpanelLib.prototype.get_tab_id;
32334 MixpanelLib.prototype['DEFAULT_API_ROUTES'] = DEFAULT_API_ROUTES;
32335
32336 // Exports intended only for testing
32337 MixpanelLib.prototype['__get_recorder'] = MixpanelLib.prototype.__get_recorder;
32338
32339 // MixpanelPersistence Exports
32340 MixpanelPersistence.prototype['properties'] = MixpanelPersistence.prototype.properties;
32341 MixpanelPersistence.prototype['update_search_keyword'] = MixpanelPersistence.prototype.update_search_keyword;
32342 MixpanelPersistence.prototype['update_referrer_info'] = MixpanelPersistence.prototype.update_referrer_info;
32343 MixpanelPersistence.prototype['get_cross_subdomain'] = MixpanelPersistence.prototype.get_cross_subdomain;
32344 MixpanelPersistence.prototype['clear'] = MixpanelPersistence.prototype.clear;
32345
32346
32347 var instances = {};
32348 var extend_mp = function() {
32349 // add all the sub mixpanel instances
32350 _.each(instances, function(instance, name) {
32351 if (name !== PRIMARY_INSTANCE_NAME) { mixpanel_master[name] = instance; }
32352 });
32353
32354 // add private functions as _
32355 mixpanel_master['_'] = _;
32356 };
32357
32358 var override_mp_init_func = function() {
32359 // we override the snippets init function to handle the case where a
32360 // user initializes the mixpanel library after the script loads & runs
32361 mixpanel_master['init'] = function(token, config, name) {
32362 if (name) {
32363 // initialize a sub library
32364 if (!mixpanel_master[name]) {
32365 mixpanel_master[name] = instances[name] = create_mplib(token, config, name);
32366 mixpanel_master[name]._loaded();
32367 }
32368 return mixpanel_master[name];
32369 } else {
32370 var instance = mixpanel_master;
32371
32372 if (instances[PRIMARY_INSTANCE_NAME]) {
32373 // main mixpanel lib already initialized
32374 instance = instances[PRIMARY_INSTANCE_NAME];
32375 } else if (token) {
32376 // intialize the main mixpanel lib
32377 instance = create_mplib(token, config, PRIMARY_INSTANCE_NAME);
32378 instance._loaded();
32379 instances[PRIMARY_INSTANCE_NAME] = instance;
32380 }
32381
32382 mixpanel_master = instance;
32383 if (init_type === INIT_SNIPPET) {
32384 win[PRIMARY_INSTANCE_NAME] = mixpanel_master;
32385 }
32386 extend_mp();
32387 }
32388 };
32389 };
32390
32391 var add_dom_loaded_handler = function() {
32392 // Cross browser DOM Loaded support
32393 function dom_loaded_handler() {
32394 // function flag since we only want to execute this once
32395 if (dom_loaded_handler.done) { return; }
32396 dom_loaded_handler.done = true;
32397
32398 DOM_LOADED = true;
32399 ENQUEUE_REQUESTS = false;
32400
32401 _.each(instances, function(inst) {
32402 inst._dom_loaded();
32403 });
32404 }
32405
32406 function do_scroll_check() {
32407 try {
32408 document$1.documentElement.doScroll('left');
32409 } catch(e) {
32410 setTimeout(do_scroll_check, 1);
32411 return;
32412 }
32413
32414 dom_loaded_handler();
32415 }
32416
32417 if (document$1.addEventListener) {
32418 if (document$1.readyState === 'complete') {
32419 // safari 4 can fire the DOMContentLoaded event before loading all
32420 // external JS (including this file). you will see some copypasta
32421 // on the internet that checks for 'complete' and 'loaded', but
32422 // 'loaded' is an IE thing
32423 dom_loaded_handler();
32424 } else {
32425 document$1.addEventListener('DOMContentLoaded', dom_loaded_handler, false);
32426 }
32427 } else if (document$1.attachEvent) {
32428 // IE
32429 document$1.attachEvent('onreadystatechange', dom_loaded_handler);
32430
32431 // check to make sure we arn't in a frame
32432 var toplevel = false;
32433 try {
32434 toplevel = win.frameElement === null;
32435 } catch(e) {
32436 // noop
32437 }
32438
32439 if (document$1.documentElement.doScroll && toplevel) {
32440 do_scroll_check();
32441 }
32442 }
32443
32444 // fallback handler, always will work
32445 _.register_event(win, 'load', dom_loaded_handler, true);
32446 };
32447
32448 function init_as_module(bundle_loader) {
32449 load_extra_bundle = bundle_loader;
32450 init_type = INIT_MODULE;
32451 mixpanel_master = new MixpanelLib();
32452
32453 override_mp_init_func();
32454 mixpanel_master['init']();
32455 add_dom_loaded_handler();
32456
32457 return mixpanel_master;
32458 }
32459
32460 // For loading separate bundles asynchronously via script tag
32461 // so that we don't load them until they are needed at runtime.
32462
32463 // For builds that have everything in one bundle, no extra work.
32464 function loadNoop (_src, onload) {
32465 onload();
32466 }
32467
32468 /* eslint camelcase: "off" */
32469
32470 var mixpanel = init_as_module(loadNoop);
32471
32472
32473
32474
32475 /***/ }),
32476
32477 /***/ "../node_modules/redux-thunk/es/index.js":
32478 /*!***********************************************!*\
32479 !*** ../node_modules/redux-thunk/es/index.js ***!
32480 \***********************************************/
32481 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
32482
32483 "use strict";
32484 __webpack_require__.r(__webpack_exports__);
32485 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
32486 /* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
32487 /* harmony export */ });
32488 /** A function that accepts a potential "extra argument" value to be injected later,
32489 * and returns an instance of the thunk middleware that uses that value
32490 */
32491 function createThunkMiddleware(extraArgument) {
32492 // Standard Redux middleware definition pattern:
32493 // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
32494 var middleware = function middleware(_ref) {
32495 var dispatch = _ref.dispatch,
32496 getState = _ref.getState;
32497 return function (next) {
32498 return function (action) {
32499 // The thunk middleware looks for any functions that were passed to `store.dispatch`.
32500 // If this "action" is really a function, call it and return the result.
32501 if (typeof action === 'function') {
32502 // Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
32503 return action(dispatch, getState, extraArgument);
32504 } // Otherwise, pass the action down the middleware chain as usual
32505
32506
32507 return next(action);
32508 };
32509 };
32510 };
32511
32512 return middleware;
32513 }
32514
32515 var thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version
32516 // with whatever "extra arg" they want to inject into their thunks
32517
32518 thunk.withExtraArgument = createThunkMiddleware;
32519 /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (thunk);
32520
32521 /***/ }),
32522
32523 /***/ "../node_modules/redux/es/redux.js":
32524 /*!*****************************************!*\
32525 !*** ../node_modules/redux/es/redux.js ***!
32526 \*****************************************/
32527 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
32528
32529 "use strict";
32530 __webpack_require__.r(__webpack_exports__);
32531 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
32532 /* harmony export */ __DO_NOT_USE__ActionTypes: () => (/* binding */ ActionTypes),
32533 /* harmony export */ applyMiddleware: () => (/* binding */ applyMiddleware),
32534 /* harmony export */ bindActionCreators: () => (/* binding */ bindActionCreators),
32535 /* harmony export */ combineReducers: () => (/* binding */ combineReducers),
32536 /* harmony export */ compose: () => (/* binding */ compose),
32537 /* harmony export */ createStore: () => (/* binding */ createStore),
32538 /* harmony export */ legacy_createStore: () => (/* binding */ legacy_createStore)
32539 /* harmony export */ });
32540 /* harmony import */ var _babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectSpread2 */ "../node_modules/@babel/runtime/helpers/esm/objectSpread2.js");
32541
32542
32543 /**
32544 * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
32545 *
32546 * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
32547 * during build.
32548 * @param {number} code
32549 */
32550 function formatProdErrorMessage(code) {
32551 return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. ';
32552 }
32553
32554 // Inlined version of the `symbol-observable` polyfill
32555 var $$observable = (function () {
32556 return typeof Symbol === 'function' && Symbol.observable || '@@observable';
32557 })();
32558
32559 /**
32560 * These are private action types reserved by Redux.
32561 * For any unknown actions, you must return the current state.
32562 * If the current state is undefined, you must return the initial state.
32563 * Do not reference these action types directly in your code.
32564 */
32565 var randomString = function randomString() {
32566 return Math.random().toString(36).substring(7).split('').join('.');
32567 };
32568
32569 var ActionTypes = {
32570 INIT: "@@redux/INIT" + randomString(),
32571 REPLACE: "@@redux/REPLACE" + randomString(),
32572 PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
32573 return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
32574 }
32575 };
32576
32577 /**
32578 * @param {any} obj The object to inspect.
32579 * @returns {boolean} True if the argument appears to be a plain object.
32580 */
32581 function isPlainObject(obj) {
32582 if (typeof obj !== 'object' || obj === null) return false;
32583 var proto = obj;
32584
32585 while (Object.getPrototypeOf(proto) !== null) {
32586 proto = Object.getPrototypeOf(proto);
32587 }
32588
32589 return Object.getPrototypeOf(obj) === proto;
32590 }
32591
32592 // Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of
32593 function miniKindOf(val) {
32594 if (val === void 0) return 'undefined';
32595 if (val === null) return 'null';
32596 var type = typeof val;
32597
32598 switch (type) {
32599 case 'boolean':
32600 case 'string':
32601 case 'number':
32602 case 'symbol':
32603 case 'function':
32604 {
32605 return type;
32606 }
32607 }
32608
32609 if (Array.isArray(val)) return 'array';
32610 if (isDate(val)) return 'date';
32611 if (isError(val)) return 'error';
32612 var constructorName = ctorName(val);
32613
32614 switch (constructorName) {
32615 case 'Symbol':
32616 case 'Promise':
32617 case 'WeakMap':
32618 case 'WeakSet':
32619 case 'Map':
32620 case 'Set':
32621 return constructorName;
32622 } // other
32623
32624
32625 return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
32626 }
32627
32628 function ctorName(val) {
32629 return typeof val.constructor === 'function' ? val.constructor.name : null;
32630 }
32631
32632 function isError(val) {
32633 return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';
32634 }
32635
32636 function isDate(val) {
32637 if (val instanceof Date) return true;
32638 return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';
32639 }
32640
32641 function kindOf(val) {
32642 var typeOfVal = typeof val;
32643
32644 if (true) {
32645 typeOfVal = miniKindOf(val);
32646 }
32647
32648 return typeOfVal;
32649 }
32650
32651 /**
32652 * @deprecated
32653 *
32654 * **We recommend using the `configureStore` method
32655 * of the `@reduxjs/toolkit` package**, which replaces `createStore`.
32656 *
32657 * Redux Toolkit is our recommended approach for writing Redux logic today,
32658 * including store setup, reducers, data fetching, and more.
32659 *
32660 * **For more details, please read this Redux docs page:**
32661 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
32662 *
32663 * `configureStore` from Redux Toolkit is an improved version of `createStore` that
32664 * simplifies setup and helps avoid common bugs.
32665 *
32666 * You should not be using the `redux` core package by itself today, except for learning purposes.
32667 * The `createStore` method from the core `redux` package will not be removed, but we encourage
32668 * all users to migrate to using Redux Toolkit for all Redux code.
32669 *
32670 * If you want to use `createStore` without this visual deprecation warning, use
32671 * the `legacy_createStore` import instead:
32672 *
32673 * `import { legacy_createStore as createStore} from 'redux'`
32674 *
32675 */
32676
32677 function createStore(reducer, preloadedState, enhancer) {
32678 var _ref2;
32679
32680 if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
32681 throw new Error( false ? 0 : 'It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.');
32682 }
32683
32684 if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
32685 enhancer = preloadedState;
32686 preloadedState = undefined;
32687 }
32688
32689 if (typeof enhancer !== 'undefined') {
32690 if (typeof enhancer !== 'function') {
32691 throw new Error( false ? 0 : "Expected the enhancer to be a function. Instead, received: '" + kindOf(enhancer) + "'");
32692 }
32693
32694 return enhancer(createStore)(reducer, preloadedState);
32695 }
32696
32697 if (typeof reducer !== 'function') {
32698 throw new Error( false ? 0 : "Expected the root reducer to be a function. Instead, received: '" + kindOf(reducer) + "'");
32699 }
32700
32701 var currentReducer = reducer;
32702 var currentState = preloadedState;
32703 var currentListeners = [];
32704 var nextListeners = currentListeners;
32705 var isDispatching = false;
32706 /**
32707 * This makes a shallow copy of currentListeners so we can use
32708 * nextListeners as a temporary list while dispatching.
32709 *
32710 * This prevents any bugs around consumers calling
32711 * subscribe/unsubscribe in the middle of a dispatch.
32712 */
32713
32714 function ensureCanMutateNextListeners() {
32715 if (nextListeners === currentListeners) {
32716 nextListeners = currentListeners.slice();
32717 }
32718 }
32719 /**
32720 * Reads the state tree managed by the store.
32721 *
32722 * @returns {any} The current state tree of your application.
32723 */
32724
32725
32726 function getState() {
32727 if (isDispatching) {
32728 throw new Error( false ? 0 : 'You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
32729 }
32730
32731 return currentState;
32732 }
32733 /**
32734 * Adds a change listener. It will be called any time an action is dispatched,
32735 * and some part of the state tree may potentially have changed. You may then
32736 * call `getState()` to read the current state tree inside the callback.
32737 *
32738 * You may call `dispatch()` from a change listener, with the following
32739 * caveats:
32740 *
32741 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
32742 * If you subscribe or unsubscribe while the listeners are being invoked, this
32743 * will not have any effect on the `dispatch()` that is currently in progress.
32744 * However, the next `dispatch()` call, whether nested or not, will use a more
32745 * recent snapshot of the subscription list.
32746 *
32747 * 2. The listener should not expect to see all state changes, as the state
32748 * might have been updated multiple times during a nested `dispatch()` before
32749 * the listener is called. It is, however, guaranteed that all subscribers
32750 * registered before the `dispatch()` started will be called with the latest
32751 * state by the time it exits.
32752 *
32753 * @param {Function} listener A callback to be invoked on every dispatch.
32754 * @returns {Function} A function to remove this change listener.
32755 */
32756
32757
32758 function subscribe(listener) {
32759 if (typeof listener !== 'function') {
32760 throw new Error( false ? 0 : "Expected the listener to be a function. Instead, received: '" + kindOf(listener) + "'");
32761 }
32762
32763 if (isDispatching) {
32764 throw new Error( false ? 0 : 'You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
32765 }
32766
32767 var isSubscribed = true;
32768 ensureCanMutateNextListeners();
32769 nextListeners.push(listener);
32770 return function unsubscribe() {
32771 if (!isSubscribed) {
32772 return;
32773 }
32774
32775 if (isDispatching) {
32776 throw new Error( false ? 0 : 'You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');
32777 }
32778
32779 isSubscribed = false;
32780 ensureCanMutateNextListeners();
32781 var index = nextListeners.indexOf(listener);
32782 nextListeners.splice(index, 1);
32783 currentListeners = null;
32784 };
32785 }
32786 /**
32787 * Dispatches an action. It is the only way to trigger a state change.
32788 *
32789 * The `reducer` function, used to create the store, will be called with the
32790 * current state tree and the given `action`. Its return value will
32791 * be considered the **next** state of the tree, and the change listeners
32792 * will be notified.
32793 *
32794 * The base implementation only supports plain object actions. If you want to
32795 * dispatch a Promise, an Observable, a thunk, or something else, you need to
32796 * wrap your store creating function into the corresponding middleware. For
32797 * example, see the documentation for the `redux-thunk` package. Even the
32798 * middleware will eventually dispatch plain object actions using this method.
32799 *
32800 * @param {Object} action A plain object representing “what changed”. It is
32801 * a good idea to keep actions serializable so you can record and replay user
32802 * sessions, or use the time travelling `redux-devtools`. An action must have
32803 * a `type` property which may not be `undefined`. It is a good idea to use
32804 * string constants for action types.
32805 *
32806 * @returns {Object} For convenience, the same action object you dispatched.
32807 *
32808 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
32809 * return something else (for example, a Promise you can await).
32810 */
32811
32812
32813 function dispatch(action) {
32814 if (!isPlainObject(action)) {
32815 throw new Error( false ? 0 : "Actions must be plain objects. Instead, the actual type was: '" + kindOf(action) + "'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.");
32816 }
32817
32818 if (typeof action.type === 'undefined') {
32819 throw new Error( false ? 0 : 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
32820 }
32821
32822 if (isDispatching) {
32823 throw new Error( false ? 0 : 'Reducers may not dispatch actions.');
32824 }
32825
32826 try {
32827 isDispatching = true;
32828 currentState = currentReducer(currentState, action);
32829 } finally {
32830 isDispatching = false;
32831 }
32832
32833 var listeners = currentListeners = nextListeners;
32834
32835 for (var i = 0; i < listeners.length; i++) {
32836 var listener = listeners[i];
32837 listener();
32838 }
32839
32840 return action;
32841 }
32842 /**
32843 * Replaces the reducer currently used by the store to calculate the state.
32844 *
32845 * You might need this if your app implements code splitting and you want to
32846 * load some of the reducers dynamically. You might also need this if you
32847 * implement a hot reloading mechanism for Redux.
32848 *
32849 * @param {Function} nextReducer The reducer for the store to use instead.
32850 * @returns {void}
32851 */
32852
32853
32854 function replaceReducer(nextReducer) {
32855 if (typeof nextReducer !== 'function') {
32856 throw new Error( false ? 0 : "Expected the nextReducer to be a function. Instead, received: '" + kindOf(nextReducer));
32857 }
32858
32859 currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
32860 // Any reducers that existed in both the new and old rootReducer
32861 // will receive the previous state. This effectively populates
32862 // the new state tree with any relevant data from the old one.
32863
32864 dispatch({
32865 type: ActionTypes.REPLACE
32866 });
32867 }
32868 /**
32869 * Interoperability point for observable/reactive libraries.
32870 * @returns {observable} A minimal observable of state changes.
32871 * For more information, see the observable proposal:
32872 * https://github.com/tc39/proposal-observable
32873 */
32874
32875
32876 function observable() {
32877 var _ref;
32878
32879 var outerSubscribe = subscribe;
32880 return _ref = {
32881 /**
32882 * The minimal observable subscription method.
32883 * @param {Object} observer Any object that can be used as an observer.
32884 * The observer object should have a `next` method.
32885 * @returns {subscription} An object with an `unsubscribe` method that can
32886 * be used to unsubscribe the observable from the store, and prevent further
32887 * emission of values from the observable.
32888 */
32889 subscribe: function subscribe(observer) {
32890 if (typeof observer !== 'object' || observer === null) {
32891 throw new Error( false ? 0 : "Expected the observer to be an object. Instead, received: '" + kindOf(observer) + "'");
32892 }
32893
32894 function observeState() {
32895 if (observer.next) {
32896 observer.next(getState());
32897 }
32898 }
32899
32900 observeState();
32901 var unsubscribe = outerSubscribe(observeState);
32902 return {
32903 unsubscribe: unsubscribe
32904 };
32905 }
32906 }, _ref[$$observable] = function () {
32907 return this;
32908 }, _ref;
32909 } // When a store is created, an "INIT" action is dispatched so that every
32910 // reducer returns their initial state. This effectively populates
32911 // the initial state tree.
32912
32913
32914 dispatch({
32915 type: ActionTypes.INIT
32916 });
32917 return _ref2 = {
32918 dispatch: dispatch,
32919 subscribe: subscribe,
32920 getState: getState,
32921 replaceReducer: replaceReducer
32922 }, _ref2[$$observable] = observable, _ref2;
32923 }
32924 /**
32925 * Creates a Redux store that holds the state tree.
32926 *
32927 * **We recommend using `configureStore` from the
32928 * `@reduxjs/toolkit` package**, which replaces `createStore`:
32929 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
32930 *
32931 * The only way to change the data in the store is to call `dispatch()` on it.
32932 *
32933 * There should only be a single store in your app. To specify how different
32934 * parts of the state tree respond to actions, you may combine several reducers
32935 * into a single reducer function by using `combineReducers`.
32936 *
32937 * @param {Function} reducer A function that returns the next state tree, given
32938 * the current state tree and the action to handle.
32939 *
32940 * @param {any} [preloadedState] The initial state. You may optionally specify it
32941 * to hydrate the state from the server in universal apps, or to restore a
32942 * previously serialized user session.
32943 * If you use `combineReducers` to produce the root reducer function, this must be
32944 * an object with the same shape as `combineReducers` keys.
32945 *
32946 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
32947 * to enhance the store with third-party capabilities such as middleware,
32948 * time travel, persistence, etc. The only store enhancer that ships with Redux
32949 * is `applyMiddleware()`.
32950 *
32951 * @returns {Store} A Redux store that lets you read the state, dispatch actions
32952 * and subscribe to changes.
32953 */
32954
32955 var legacy_createStore = createStore;
32956
32957 /**
32958 * Prints a warning in the console if it exists.
32959 *
32960 * @param {String} message The warning message.
32961 * @returns {void}
32962 */
32963 function warning(message) {
32964 /* eslint-disable no-console */
32965 if (typeof console !== 'undefined' && typeof console.error === 'function') {
32966 console.error(message);
32967 }
32968 /* eslint-enable no-console */
32969
32970
32971 try {
32972 // This error was thrown as a convenience so that if you enable
32973 // "break on all exceptions" in your console,
32974 // it would pause the execution at this line.
32975 throw new Error(message);
32976 } catch (e) {} // eslint-disable-line no-empty
32977
32978 }
32979
32980 function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
32981 var reducerKeys = Object.keys(reducers);
32982 var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
32983
32984 if (reducerKeys.length === 0) {
32985 return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
32986 }
32987
32988 if (!isPlainObject(inputState)) {
32989 return "The " + argumentName + " has unexpected type of \"" + kindOf(inputState) + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
32990 }
32991
32992 var unexpectedKeys = Object.keys(inputState).filter(function (key) {
32993 return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
32994 });
32995 unexpectedKeys.forEach(function (key) {
32996 unexpectedKeyCache[key] = true;
32997 });
32998 if (action && action.type === ActionTypes.REPLACE) return;
32999
33000 if (unexpectedKeys.length > 0) {
33001 return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored.");
33002 }
33003 }
33004
33005 function assertReducerShape(reducers) {
33006 Object.keys(reducers).forEach(function (key) {
33007 var reducer = reducers[key];
33008 var initialState = reducer(undefined, {
33009 type: ActionTypes.INIT
33010 });
33011
33012 if (typeof initialState === 'undefined') {
33013 throw new Error( false ? 0 : "The slice reducer for key \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
33014 }
33015
33016 if (typeof reducer(undefined, {
33017 type: ActionTypes.PROBE_UNKNOWN_ACTION()
33018 }) === 'undefined') {
33019 throw new Error( false ? 0 : "The slice reducer for key \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle '" + ActionTypes.INIT + "' or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
33020 }
33021 });
33022 }
33023 /**
33024 * Turns an object whose values are different reducer functions, into a single
33025 * reducer function. It will call every child reducer, and gather their results
33026 * into a single state object, whose keys correspond to the keys of the passed
33027 * reducer functions.
33028 *
33029 * @param {Object} reducers An object whose values correspond to different
33030 * reducer functions that need to be combined into one. One handy way to obtain
33031 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
33032 * undefined for any action. Instead, they should return their initial state
33033 * if the state passed to them was undefined, and the current state for any
33034 * unrecognized action.
33035 *
33036 * @returns {Function} A reducer function that invokes every reducer inside the
33037 * passed object, and builds a state object with the same shape.
33038 */
33039
33040
33041 function combineReducers(reducers) {
33042 var reducerKeys = Object.keys(reducers);
33043 var finalReducers = {};
33044
33045 for (var i = 0; i < reducerKeys.length; i++) {
33046 var key = reducerKeys[i];
33047
33048 if (true) {
33049 if (typeof reducers[key] === 'undefined') {
33050 warning("No reducer provided for key \"" + key + "\"");
33051 }
33052 }
33053
33054 if (typeof reducers[key] === 'function') {
33055 finalReducers[key] = reducers[key];
33056 }
33057 }
33058
33059 var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same
33060 // keys multiple times.
33061
33062 var unexpectedKeyCache;
33063
33064 if (true) {
33065 unexpectedKeyCache = {};
33066 }
33067
33068 var shapeAssertionError;
33069
33070 try {
33071 assertReducerShape(finalReducers);
33072 } catch (e) {
33073 shapeAssertionError = e;
33074 }
33075
33076 return function combination(state, action) {
33077 if (state === void 0) {
33078 state = {};
33079 }
33080
33081 if (shapeAssertionError) {
33082 throw shapeAssertionError;
33083 }
33084
33085 if (true) {
33086 var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
33087
33088 if (warningMessage) {
33089 warning(warningMessage);
33090 }
33091 }
33092
33093 var hasChanged = false;
33094 var nextState = {};
33095
33096 for (var _i = 0; _i < finalReducerKeys.length; _i++) {
33097 var _key = finalReducerKeys[_i];
33098 var reducer = finalReducers[_key];
33099 var previousStateForKey = state[_key];
33100 var nextStateForKey = reducer(previousStateForKey, action);
33101
33102 if (typeof nextStateForKey === 'undefined') {
33103 var actionType = action && action.type;
33104 throw new Error( false ? 0 : "When called with an action of type " + (actionType ? "\"" + String(actionType) + "\"" : '(unknown type)') + ", the slice reducer for key \"" + _key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined.");
33105 }
33106
33107 nextState[_key] = nextStateForKey;
33108 hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
33109 }
33110
33111 hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
33112 return hasChanged ? nextState : state;
33113 };
33114 }
33115
33116 function bindActionCreator(actionCreator, dispatch) {
33117 return function () {
33118 return dispatch(actionCreator.apply(this, arguments));
33119 };
33120 }
33121 /**
33122 * Turns an object whose values are action creators, into an object with the
33123 * same keys, but with every function wrapped into a `dispatch` call so they
33124 * may be invoked directly. This is just a convenience method, as you can call
33125 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
33126 *
33127 * For convenience, you can also pass an action creator as the first argument,
33128 * and get a dispatch wrapped function in return.
33129 *
33130 * @param {Function|Object} actionCreators An object whose values are action
33131 * creator functions. One handy way to obtain it is to use ES6 `import * as`
33132 * syntax. You may also pass a single function.
33133 *
33134 * @param {Function} dispatch The `dispatch` function available on your Redux
33135 * store.
33136 *
33137 * @returns {Function|Object} The object mimicking the original object, but with
33138 * every action creator wrapped into the `dispatch` call. If you passed a
33139 * function as `actionCreators`, the return value will also be a single
33140 * function.
33141 */
33142
33143
33144 function bindActionCreators(actionCreators, dispatch) {
33145 if (typeof actionCreators === 'function') {
33146 return bindActionCreator(actionCreators, dispatch);
33147 }
33148
33149 if (typeof actionCreators !== 'object' || actionCreators === null) {
33150 throw new Error( false ? 0 : "bindActionCreators expected an object or a function, but instead received: '" + kindOf(actionCreators) + "'. " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?");
33151 }
33152
33153 var boundActionCreators = {};
33154
33155 for (var key in actionCreators) {
33156 var actionCreator = actionCreators[key];
33157
33158 if (typeof actionCreator === 'function') {
33159 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
33160 }
33161 }
33162
33163 return boundActionCreators;
33164 }
33165
33166 /**
33167 * Composes single-argument functions from right to left. The rightmost
33168 * function can take multiple arguments as it provides the signature for
33169 * the resulting composite function.
33170 *
33171 * @param {...Function} funcs The functions to compose.
33172 * @returns {Function} A function obtained by composing the argument functions
33173 * from right to left. For example, compose(f, g, h) is identical to doing
33174 * (...args) => f(g(h(...args))).
33175 */
33176 function compose() {
33177 for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
33178 funcs[_key] = arguments[_key];
33179 }
33180
33181 if (funcs.length === 0) {
33182 return function (arg) {
33183 return arg;
33184 };
33185 }
33186
33187 if (funcs.length === 1) {
33188 return funcs[0];
33189 }
33190
33191 return funcs.reduce(function (a, b) {
33192 return function () {
33193 return a(b.apply(void 0, arguments));
33194 };
33195 });
33196 }
33197
33198 /**
33199 * Creates a store enhancer that applies middleware to the dispatch method
33200 * of the Redux store. This is handy for a variety of tasks, such as expressing
33201 * asynchronous actions in a concise manner, or logging every action payload.
33202 *
33203 * See `redux-thunk` package as an example of the Redux middleware.
33204 *
33205 * Because middleware is potentially asynchronous, this should be the first
33206 * store enhancer in the composition chain.
33207 *
33208 * Note that each middleware will be given the `dispatch` and `getState` functions
33209 * as named arguments.
33210 *
33211 * @param {...Function} middlewares The middleware chain to be applied.
33212 * @returns {Function} A store enhancer applying the middleware.
33213 */
33214
33215 function applyMiddleware() {
33216 for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
33217 middlewares[_key] = arguments[_key];
33218 }
33219
33220 return function (createStore) {
33221 return function () {
33222 var store = createStore.apply(void 0, arguments);
33223
33224 var _dispatch = function dispatch() {
33225 throw new Error( false ? 0 : 'Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');
33226 };
33227
33228 var middlewareAPI = {
33229 getState: store.getState,
33230 dispatch: function dispatch() {
33231 return _dispatch.apply(void 0, arguments);
33232 }
33233 };
33234 var chain = middlewares.map(function (middleware) {
33235 return middleware(middlewareAPI);
33236 });
33237 _dispatch = compose.apply(void 0, chain)(store.dispatch);
33238 return (0,_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__["default"])((0,_babel_runtime_helpers_esm_objectSpread2__WEBPACK_IMPORTED_MODULE_0__["default"])({}, store), {}, {
33239 dispatch: _dispatch
33240 });
33241 };
33242 };
33243 }
33244
33245
33246
33247
33248 /***/ }),
33249
33250 /***/ "../node_modules/reselect/es/defaultMemoize.js":
33251 /*!*****************************************************!*\
33252 !*** ../node_modules/reselect/es/defaultMemoize.js ***!
33253 \*****************************************************/
33254 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
33255
33256 "use strict";
33257 __webpack_require__.r(__webpack_exports__);
33258 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
33259 /* harmony export */ createCacheKeyComparator: () => (/* binding */ createCacheKeyComparator),
33260 /* harmony export */ defaultEqualityCheck: () => (/* binding */ defaultEqualityCheck),
33261 /* harmony export */ defaultMemoize: () => (/* binding */ defaultMemoize)
33262 /* harmony export */ });
33263 // Cache implementation based on Erik Rasmussen's `lru-memoize`:
33264 // https://github.com/erikras/lru-memoize
33265 var NOT_FOUND = 'NOT_FOUND';
33266
33267 function createSingletonCache(equals) {
33268 var entry;
33269 return {
33270 get: function get(key) {
33271 if (entry && equals(entry.key, key)) {
33272 return entry.value;
33273 }
33274
33275 return NOT_FOUND;
33276 },
33277 put: function put(key, value) {
33278 entry = {
33279 key: key,
33280 value: value
33281 };
33282 },
33283 getEntries: function getEntries() {
33284 return entry ? [entry] : [];
33285 },
33286 clear: function clear() {
33287 entry = undefined;
33288 }
33289 };
33290 }
33291
33292 function createLruCache(maxSize, equals) {
33293 var entries = [];
33294
33295 function get(key) {
33296 var cacheIndex = entries.findIndex(function (entry) {
33297 return equals(key, entry.key);
33298 }); // We found a cached entry
33299
33300 if (cacheIndex > -1) {
33301 var entry = entries[cacheIndex]; // Cached entry not at top of cache, move it to the top
33302
33303 if (cacheIndex > 0) {
33304 entries.splice(cacheIndex, 1);
33305 entries.unshift(entry);
33306 }
33307
33308 return entry.value;
33309 } // No entry found in cache, return sentinel
33310
33311
33312 return NOT_FOUND;
33313 }
33314
33315 function put(key, value) {
33316 if (get(key) === NOT_FOUND) {
33317 // TODO Is unshift slow?
33318 entries.unshift({
33319 key: key,
33320 value: value
33321 });
33322
33323 if (entries.length > maxSize) {
33324 entries.pop();
33325 }
33326 }
33327 }
33328
33329 function getEntries() {
33330 return entries;
33331 }
33332
33333 function clear() {
33334 entries = [];
33335 }
33336
33337 return {
33338 get: get,
33339 put: put,
33340 getEntries: getEntries,
33341 clear: clear
33342 };
33343 }
33344
33345 var defaultEqualityCheck = function defaultEqualityCheck(a, b) {
33346 return a === b;
33347 };
33348 function createCacheKeyComparator(equalityCheck) {
33349 return function areArgumentsShallowlyEqual(prev, next) {
33350 if (prev === null || next === null || prev.length !== next.length) {
33351 return false;
33352 } // Do this in a for loop (and not a `forEach` or an `every`) so we can determine equality as fast as possible.
33353
33354
33355 var length = prev.length;
33356
33357 for (var i = 0; i < length; i++) {
33358 if (!equalityCheck(prev[i], next[i])) {
33359 return false;
33360 }
33361 }
33362
33363 return true;
33364 };
33365 }
33366 // defaultMemoize now supports a configurable cache size with LRU behavior,
33367 // and optional comparison of the result value with existing values
33368 function defaultMemoize(func, equalityCheckOrOptions) {
33369 var providedOptions = typeof equalityCheckOrOptions === 'object' ? equalityCheckOrOptions : {
33370 equalityCheck: equalityCheckOrOptions
33371 };
33372 var _providedOptions$equa = providedOptions.equalityCheck,
33373 equalityCheck = _providedOptions$equa === void 0 ? defaultEqualityCheck : _providedOptions$equa,
33374 _providedOptions$maxS = providedOptions.maxSize,
33375 maxSize = _providedOptions$maxS === void 0 ? 1 : _providedOptions$maxS,
33376 resultEqualityCheck = providedOptions.resultEqualityCheck;
33377 var comparator = createCacheKeyComparator(equalityCheck);
33378 var cache = maxSize === 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator); // we reference arguments instead of spreading them for performance reasons
33379
33380 function memoized() {
33381 var value = cache.get(arguments);
33382
33383 if (value === NOT_FOUND) {
33384 // @ts-ignore
33385 value = func.apply(null, arguments);
33386
33387 if (resultEqualityCheck) {
33388 var entries = cache.getEntries();
33389 var matchingEntry = entries.find(function (entry) {
33390 return resultEqualityCheck(entry.value, value);
33391 });
33392
33393 if (matchingEntry) {
33394 value = matchingEntry.value;
33395 }
33396 }
33397
33398 cache.put(arguments, value);
33399 }
33400
33401 return value;
33402 }
33403
33404 memoized.clearCache = function () {
33405 return cache.clear();
33406 };
33407
33408 return memoized;
33409 }
33410
33411 /***/ }),
33412
33413 /***/ "../node_modules/reselect/es/index.js":
33414 /*!********************************************!*\
33415 !*** ../node_modules/reselect/es/index.js ***!
33416 \********************************************/
33417 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
33418
33419 "use strict";
33420 __webpack_require__.r(__webpack_exports__);
33421 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
33422 /* harmony export */ createSelector: () => (/* binding */ createSelector),
33423 /* harmony export */ createSelectorCreator: () => (/* binding */ createSelectorCreator),
33424 /* harmony export */ createStructuredSelector: () => (/* binding */ createStructuredSelector),
33425 /* harmony export */ defaultEqualityCheck: () => (/* reexport safe */ _defaultMemoize__WEBPACK_IMPORTED_MODULE_0__.defaultEqualityCheck),
33426 /* harmony export */ defaultMemoize: () => (/* reexport safe */ _defaultMemoize__WEBPACK_IMPORTED_MODULE_0__.defaultMemoize)
33427 /* harmony export */ });
33428 /* harmony import */ var _defaultMemoize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./defaultMemoize */ "../node_modules/reselect/es/defaultMemoize.js");
33429
33430
33431
33432 function getDependencies(funcs) {
33433 var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs;
33434
33435 if (!dependencies.every(function (dep) {
33436 return typeof dep === 'function';
33437 })) {
33438 var dependencyTypes = dependencies.map(function (dep) {
33439 return typeof dep === 'function' ? "function " + (dep.name || 'unnamed') + "()" : typeof dep;
33440 }).join(', ');
33441 throw new Error("createSelector expects all input-selectors to be functions, but received the following types: [" + dependencyTypes + "]");
33442 }
33443
33444 return dependencies;
33445 }
33446
33447 function createSelectorCreator(memoize) {
33448 for (var _len = arguments.length, memoizeOptionsFromArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
33449 memoizeOptionsFromArgs[_key - 1] = arguments[_key];
33450 }
33451
33452 var createSelector = function createSelector() {
33453 for (var _len2 = arguments.length, funcs = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
33454 funcs[_key2] = arguments[_key2];
33455 }
33456
33457 var _recomputations = 0;
33458
33459 var _lastResult; // Due to the intricacies of rest params, we can't do an optional arg after `...funcs`.
33460 // So, start by declaring the default value here.
33461 // (And yes, the words 'memoize' and 'options' appear too many times in this next sequence.)
33462
33463
33464 var directlyPassedOptions = {
33465 memoizeOptions: undefined
33466 }; // Normally, the result func or "output selector" is the last arg
33467
33468 var resultFunc = funcs.pop(); // If the result func is actually an _object_, assume it's our options object
33469
33470 if (typeof resultFunc === 'object') {
33471 directlyPassedOptions = resultFunc; // and pop the real result func off
33472
33473 resultFunc = funcs.pop();
33474 }
33475
33476 if (typeof resultFunc !== 'function') {
33477 throw new Error("createSelector expects an output function after the inputs, but received: [" + typeof resultFunc + "]");
33478 } // Determine which set of options we're using. Prefer options passed directly,
33479 // but fall back to options given to createSelectorCreator.
33480
33481
33482 var _directlyPassedOption = directlyPassedOptions,
33483 _directlyPassedOption2 = _directlyPassedOption.memoizeOptions,
33484 memoizeOptions = _directlyPassedOption2 === void 0 ? memoizeOptionsFromArgs : _directlyPassedOption2; // Simplifying assumption: it's unlikely that the first options arg of the provided memoizer
33485 // is an array. In most libs I've looked at, it's an equality function or options object.
33486 // Based on that, if `memoizeOptions` _is_ an array, we assume it's a full
33487 // user-provided array of options. Otherwise, it must be just the _first_ arg, and so
33488 // we wrap it in an array so we can apply it.
33489
33490 var finalMemoizeOptions = Array.isArray(memoizeOptions) ? memoizeOptions : [memoizeOptions];
33491 var dependencies = getDependencies(funcs);
33492 var memoizedResultFunc = memoize.apply(void 0, [function recomputationWrapper() {
33493 _recomputations++; // apply arguments instead of spreading for performance.
33494
33495 return resultFunc.apply(null, arguments);
33496 }].concat(finalMemoizeOptions)); // If a selector is called with the exact same arguments we don't need to traverse our dependencies again.
33497
33498 var selector = memoize(function dependenciesChecker() {
33499 var params = [];
33500 var length = dependencies.length;
33501
33502 for (var i = 0; i < length; i++) {
33503 // apply arguments instead of spreading and mutate a local list of params for performance.
33504 // @ts-ignore
33505 params.push(dependencies[i].apply(null, arguments));
33506 } // apply arguments instead of spreading for performance.
33507
33508
33509 _lastResult = memoizedResultFunc.apply(null, params);
33510 return _lastResult;
33511 });
33512 Object.assign(selector, {
33513 resultFunc: resultFunc,
33514 memoizedResultFunc: memoizedResultFunc,
33515 dependencies: dependencies,
33516 lastResult: function lastResult() {
33517 return _lastResult;
33518 },
33519 recomputations: function recomputations() {
33520 return _recomputations;
33521 },
33522 resetRecomputations: function resetRecomputations() {
33523 return _recomputations = 0;
33524 }
33525 });
33526 return selector;
33527 }; // @ts-ignore
33528
33529
33530 return createSelector;
33531 }
33532 var createSelector = /* #__PURE__ */createSelectorCreator(_defaultMemoize__WEBPACK_IMPORTED_MODULE_0__.defaultMemoize);
33533 // Manual definition of state and output arguments
33534 var createStructuredSelector = function createStructuredSelector(selectors, selectorCreator) {
33535 if (selectorCreator === void 0) {
33536 selectorCreator = createSelector;
33537 }
33538
33539 if (typeof selectors !== 'object') {
33540 throw new Error('createStructuredSelector expects first argument to be an object ' + ("where each property is a selector, instead received a " + typeof selectors));
33541 }
33542
33543 var objectKeys = Object.keys(selectors);
33544 var resultSelector = selectorCreator( // @ts-ignore
33545 objectKeys.map(function (key) {
33546 return selectors[key];
33547 }), function () {
33548 for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
33549 values[_key3] = arguments[_key3];
33550 }
33551
33552 return values.reduce(function (composition, value, index) {
33553 composition[objectKeys[index]] = value;
33554 return composition;
33555 }, {});
33556 });
33557 return resultSelector;
33558 };
33559
33560 /***/ }),
33561
33562 /***/ "@wordpress/i18n":
33563 /*!**************************!*\
33564 !*** external "wp.i18n" ***!
33565 \**************************/
33566 /***/ ((module) => {
33567
33568 "use strict";
33569 module.exports = wp.i18n;
33570
33571 /***/ })
33572
33573 /******/ });
33574 /************************************************************************/
33575 /******/ // The module cache
33576 /******/ var __webpack_module_cache__ = {};
33577 /******/
33578 /******/ // The require function
33579 /******/ function __webpack_require__(moduleId) {
33580 /******/ // Check if module is in cache
33581 /******/ var cachedModule = __webpack_module_cache__[moduleId];
33582 /******/ if (cachedModule !== undefined) {
33583 /******/ return cachedModule.exports;
33584 /******/ }
33585 /******/ // Create a new module (and put it into the cache)
33586 /******/ var module = __webpack_module_cache__[moduleId] = {
33587 /******/ // no module.id needed
33588 /******/ // no module.loaded needed
33589 /******/ exports: {}
33590 /******/ };
33591 /******/
33592 /******/ // Execute the module function
33593 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
33594 /******/
33595 /******/ // Return the exports of the module
33596 /******/ return module.exports;
33597 /******/ }
33598 /******/
33599 /************************************************************************/
33600 /******/ /* webpack/runtime/define property getters */
33601 /******/ (() => {
33602 /******/ // define getter functions for harmony exports
33603 /******/ __webpack_require__.d = (exports, definition) => {
33604 /******/ for(var key in definition) {
33605 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
33606 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
33607 /******/ }
33608 /******/ }
33609 /******/ };
33610 /******/ })();
33611 /******/
33612 /******/ /* webpack/runtime/global */
33613 /******/ (() => {
33614 /******/ __webpack_require__.g = (function() {
33615 /******/ if (typeof globalThis === 'object') return globalThis;
33616 /******/ try {
33617 /******/ return this || new Function('return this')();
33618 /******/ } catch (e) {
33619 /******/ if (typeof window === 'object') return window;
33620 /******/ }
33621 /******/ })();
33622 /******/ })();
33623 /******/
33624 /******/ /* webpack/runtime/hasOwnProperty shorthand */
33625 /******/ (() => {
33626 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
33627 /******/ })();
33628 /******/
33629 /******/ /* webpack/runtime/make namespace object */
33630 /******/ (() => {
33631 /******/ // define __esModule on exports
33632 /******/ __webpack_require__.r = (exports) => {
33633 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
33634 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
33635 /******/ }
33636 /******/ Object.defineProperty(exports, '__esModule', { value: true });
33637 /******/ };
33638 /******/ })();
33639 /******/
33640 /************************************************************************/
33641 var __webpack_exports__ = {};
33642 // This entry needs to be wrapped in an IIFE because it needs to be in strict mode.
33643 (() => {
33644 "use strict";
33645 /*!******************************************!*\
33646 !*** ../core/common/assets/js/common.js ***!
33647 \******************************************/
33648
33649
33650 var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "../node_modules/@babel/runtime/helpers/interopRequireDefault.js");
33651 var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../node_modules/@babel/runtime/helpers/classCallCheck.js"));
33652 var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "../node_modules/@babel/runtime/helpers/createClass.js"));
33653 var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"));
33654 var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../node_modules/@babel/runtime/helpers/getPrototypeOf.js"));
33655 var _get2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/get */ "../node_modules/@babel/runtime/helpers/get.js"));
33656 var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "../node_modules/@babel/runtime/helpers/inherits.js"));
33657 var _helpers = _interopRequireDefault(__webpack_require__(/*! ./utils/helpers */ "../core/common/assets/js/utils/helpers.js"));
33658 var _storage = _interopRequireDefault(__webpack_require__(/*! ./utils/storage */ "../core/common/assets/js/utils/storage.js"));
33659 var _debug = _interopRequireDefault(__webpack_require__(/*! ./utils/debug */ "../core/common/assets/js/utils/debug.js"));
33660 var _ajax = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/ajax/assets/js/ajax */ "../core/common/modules/ajax/assets/js/ajax.js"));
33661 var _finder = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/finder/assets/js/finder */ "../core/common/modules/finder/assets/js/finder.js"));
33662 var _connect = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/connect/assets/js/connect */ "../core/common/modules/connect/assets/js/connect.js"));
33663 var _component = _interopRequireDefault(__webpack_require__(/*! ./components/wordpress/component */ "../core/common/assets/js/components/wordpress/component.js"));
33664 var _component2 = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/event-tracker/assets/js/data/component */ "../core/common/modules/event-tracker/assets/js/data/component.js"));
33665 var _events = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/event-tracker/assets/js/events */ "../core/common/modules/event-tracker/assets/js/events.js"));
33666 var _module = _interopRequireDefault(__webpack_require__(/*! elementor-common-modules/events-manager/assets/js/module */ "../core/common/modules/events-manager/assets/js/module.js"));
33667 var _notifications = _interopRequireDefault(__webpack_require__(/*! elementor-utils/notifications */ "../assets/dev/js/utils/notifications.js"));
33668 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)); }
33669 function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
33670 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; }
33671 var ElementorCommonApp = /*#__PURE__*/function (_elementorModules$Vie) {
33672 function ElementorCommonApp() {
33673 (0, _classCallCheck2.default)(this, ElementorCommonApp);
33674 return _callSuper(this, ElementorCommonApp, arguments);
33675 }
33676 (0, _inherits2.default)(ElementorCommonApp, _elementorModules$Vie);
33677 return (0, _createClass2.default)(ElementorCommonApp, [{
33678 key: "setMarionetteTemplateCompiler",
33679 value: function setMarionetteTemplateCompiler() {
33680 Marionette.TemplateCache.prototype.compileTemplate = function (rawTemplate, options) {
33681 options = {
33682 evaluate: /<#([\s\S]+?)#>/g,
33683 interpolate: /{{{([\s\S]+?)}}}/g,
33684 escape: /{{([^}]+?)}}(?!})/g
33685 };
33686 return _.template(rawTemplate, options);
33687 };
33688 }
33689 }, {
33690 key: "getDefaultElements",
33691 value: function getDefaultElements() {
33692 return {
33693 $window: jQuery(window),
33694 $document: jQuery(document),
33695 $body: jQuery(document.body)
33696 };
33697 }
33698 }, {
33699 key: "initComponents",
33700 value: function initComponents() {
33701 this.events = new _events.default();
33702 this.eventsManager = new _module.default();
33703 this.debug = new _debug.default();
33704 this.helpers = new _helpers.default();
33705 this.storage = new _storage.default();
33706 this.dialogsManager = new DialogsManager.Instance();
33707 this.notifications = new _notifications.default();
33708 this.api = window.$e;
33709 $e.components.register(new _component2.default());
33710 elementorCommon.elements.$window.on('elementor:init-components', function () {
33711 $e.components.register(new _component.default());
33712 });
33713 this.initModules();
33714 }
33715 }, {
33716 key: "initModules",
33717 value: function initModules() {
33718 var _this = this;
33719 var activeModules = this.config.activeModules;
33720 var modules = {
33721 ajax: _ajax.default,
33722 finder: _finder.default,
33723 connect: _connect.default
33724 };
33725 activeModules.forEach(function (name) {
33726 if (modules[name]) {
33727 _this[name] = new modules[name](_this.config[name]);
33728 }
33729 });
33730 }
33731 }, {
33732 key: "compileArrayTemplateArgs",
33733 value: function compileArrayTemplateArgs(template, templateArgs) {
33734 return template.replace(/%(?:(\d+)\$)?s/g, function (match, number) {
33735 if (!number) {
33736 number = 1;
33737 }
33738 number--;
33739 return undefined !== templateArgs[number] ? templateArgs[number] : match;
33740 });
33741 }
33742 }, {
33743 key: "compileObjectTemplateArgs",
33744 value: function compileObjectTemplateArgs(template, templateArgs) {
33745 return template.replace(/{{(?:([ \w]+))}}/g, function (match, name) {
33746 return templateArgs[name] ? templateArgs[name] : match;
33747 });
33748 }
33749 }, {
33750 key: "compileTemplate",
33751 value: function compileTemplate(template, templateArgs) {
33752 return jQuery.isPlainObject(templateArgs) ? this.compileObjectTemplateArgs(template, templateArgs) : this.compileArrayTemplateArgs(template, templateArgs);
33753 }
33754 }, {
33755 key: "translate",
33756 value: function translate(stringKey, context, templateArgs, i18nStack) {
33757 if (context) {
33758 i18nStack = this.config[context].i18n;
33759 }
33760 if (!i18nStack) {
33761 i18nStack = this.config.i18n;
33762 }
33763 var string = i18nStack[stringKey];
33764 if (undefined === string) {
33765 string = stringKey;
33766 }
33767 if (templateArgs) {
33768 string = this.compileTemplate(string, templateArgs);
33769 }
33770 return string;
33771 }
33772 }, {
33773 key: "onInit",
33774 value: function onInit() {
33775 _superPropGet(ElementorCommonApp, "onInit", this, 3)([]);
33776 this.config = elementorCommonConfig;
33777 this.setMarionetteTemplateCompiler();
33778 }
33779 }]);
33780 }(elementorModules.ViewModule);
33781 window.elementorCommon = new ElementorCommonApp();
33782 elementorCommon.initComponents();
33783 })();
33784
33785 /******/ })()
33786 ;
33787 //# sourceMappingURL=common.js.map