1(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["firebase-analytics"],{ 2 3/***/ "3Kre": 4/*!************************************************************!*\ 5 !*** ./node_modules/@firebase/analytics/dist/index.esm.js ***! 6 \************************************************************/ 7/*! exports provided: factory, getGlobalVars, registerAnalytics, resetGlobalVars, settings */ 8/***/ (function(module, __webpack_exports__, __webpack_require__) { 9 10"use strict"; 11__webpack_require__.r(__webpack_exports__); 12/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "factory", function() { return factory; }); 13/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getGlobalVars", function() { return getGlobalVars; }); 14/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerAnalytics", function() { return registerAnalytics; }); 15/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "resetGlobalVars", function() { return resetGlobalVars; }); 16/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "settings", function() { return settings; }); 17/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "30Go"); 18/* harmony import */ var _firebase_app__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @firebase/app */ "zIRd"); 19/* harmony import */ var _firebase_installations__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @firebase/installations */ "fSjL"); 20/* harmony import */ var _firebase_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @firebase/logger */ "q/0M"); 21/* harmony import */ var _firebase_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @firebase/util */ "qOnz"); 22/* harmony import */ var _firebase_component__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @firebase/component */ "/6Yf"); 23 24 25 26 27 28 29 30/** 31 * @license 32 * Copyright 2019 Google LLC 33 * 34 * Licensed under the Apache License, Version 2.0 (the "License"); 35 * you may not use this file except in compliance with the License. 36 * You may obtain a copy of the License at 37 * 38 * http://www.apache.org/licenses/LICENSE-2.0 39 * 40 * Unless required by applicable law or agreed to in writing, software 41 * distributed under the License is distributed on an "AS IS" BASIS, 42 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 43 * See the License for the specific language governing permissions and 44 * limitations under the License. 45 */ 46// Key to attach FID to in gtag params. 47var GA_FID_KEY = 'firebase_id'; 48var ORIGIN_KEY = 'origin'; 49var FETCH_TIMEOUT_MILLIS = 60 * 1000; 50var DYNAMIC_CONFIG_URL = 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig'; 51var GTAG_URL = 'https://www.googletagmanager.com/gtag/js'; 52var GtagCommand; 53(function (GtagCommand) { 54 GtagCommand["EVENT"] = "event"; 55 GtagCommand["SET"] = "set"; 56 GtagCommand["CONFIG"] = "config"; 57})(GtagCommand || (GtagCommand = {})); 58/** 59 * Officially recommended event names for gtag.js 60 * Any other string is also allowed. 61 * 62 * @public 63 */ 64var EventName; 65(function (EventName) { 66 EventName["ADD_SHIPPING_INFO"] = "add_shipping_info"; 67 EventName["ADD_PAYMENT_INFO"] = "add_payment_info"; 68 EventName["ADD_TO_CART"] = "add_to_cart"; 69 EventName["ADD_TO_WISHLIST"] = "add_to_wishlist"; 70 EventName["BEGIN_CHECKOUT"] = "begin_checkout"; 71 /** 72 * @deprecated 73 * This event name is deprecated and is unsupported in updated 74 * Enhanced Ecommerce reports. 75 */ 76 EventName["CHECKOUT_PROGRESS"] = "checkout_progress"; 77 EventName["EXCEPTION"] = "exception"; 78 EventName["GENERATE_LEAD"] = "generate_lead"; 79 EventName["LOGIN"] = "login"; 80 EventName["PAGE_VIEW"] = "page_view"; 81 EventName["PURCHASE"] = "purchase"; 82 EventName["REFUND"] = "refund"; 83 EventName["REMOVE_FROM_CART"] = "remove_from_cart"; 84 EventName["SCREEN_VIEW"] = "screen_view"; 85 EventName["SEARCH"] = "search"; 86 EventName["SELECT_CONTENT"] = "select_content"; 87 EventName["SELECT_ITEM"] = "select_item"; 88 EventName["SELECT_PROMOTION"] = "select_promotion"; 89 /** @deprecated */ 90 EventName["SET_CHECKOUT_OPTION"] = "set_checkout_option"; 91 EventName["SHARE"] = "share"; 92 EventName["SIGN_UP"] = "sign_up"; 93 EventName["TIMING_COMPLETE"] = "timing_complete"; 94 EventName["VIEW_CART"] = "view_cart"; 95 EventName["VIEW_ITEM"] = "view_item"; 96 EventName["VIEW_ITEM_LIST"] = "view_item_list"; 97 EventName["VIEW_PROMOTION"] = "view_promotion"; 98 EventName["VIEW_SEARCH_RESULTS"] = "view_search_results"; 99})(EventName || (EventName = {})); 100 101/** 102 * @license 103 * Copyright 2019 Google LLC 104 * 105 * Licensed under the Apache License, Version 2.0 (the "License");
106 * you may not use this file except in compliance with the License. 107 * You may obtain a copy of the License at 108 * 109 * http://www.apache.org/licenses/LICENSE-2.0 110 * 111 * Unless required by applicable law or agreed to in writing, software 112 * distributed under the License is distributed on an "AS IS" BASIS, 113 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 114 * See the License for the specific language governing permissions and 115 * limitations under the License. 116 */ 117/** 118 * Logs an analytics event through the Firebase SDK. 119 * 120 * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event 121 * @param eventName Google Analytics event name, choose from standard list or use a custom string. 122 * @param eventParams Analytics event parameters. 123 */ 124function logEvent(gtagFunction, initializationPromise, eventName, eventParams, options) { 125 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 126 var measurementId, params; 127 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 128 switch (_a.label) { 129 case 0: 130 if (!(options && options.global)) return [3 /*break*/, 1]; 131 gtagFunction(GtagCommand.EVENT, eventName, eventParams); 132 return [2 /*return*/]; 133 case 1: return [4 /*yield*/, initializationPromise]; 134 case 2: 135 measurementId = _a.sent(); 136 params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, eventParams), { 'send_to': measurementId }); 137 gtagFunction(GtagCommand.EVENT, eventName, params); 138 _a.label = 3; 139 case 3: return [2 /*return*/]; 140 } 141 }); 142 }); 143} 144/** 145 * Set screen_name parameter for this Google Analytics ID. 146 * 147 * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event 148 * @param screenName Screen name string to set. 149 */ 150function setCurrentScreen(gtagFunction, initializationPromise, screenName, options) { 151 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 152 var measurementId; 153 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 154 switch (_a.label) { 155 case 0: 156 if (!(options && options.global)) return [3 /*break*/, 1]; 157 gtagFunction(GtagCommand.SET, { 'screen_name': screenName }); 158 return [2 /*return*/, Promise.resolve()]; 159 case 1: return [4 /*yield*/, initializationPromise]; 160 case 2: 161 measurementId = _a.sent(); 162 gtagFunction(GtagCommand.CONFIG, measurementId, { 163 update: true, 164 'screen_name': screenName 165 }); 166 _a.label = 3; 167 case 3: return [2 /*return*/]; 168 } 169 }); 170 }); 171} 172/** 173 * Set user_id parameter for this Google Analytics ID. 174 * 175 * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event 176 * @param id User ID string to set 177 */ 178function setUserId(gtagFunction, initializationPromise, id, options) { 179 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 180 var measurementId; 181 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 182 switch (_a.label) { 183 case 0: 184 if (!(options && options.global)) return [3 /*break*/, 1]; 185 gtagFunction(GtagCommand.SET, { 'user_id': id }); 186 return [2 /*return*/, Promise.resolve()]; 187 case 1: return [4 /*yield*/, initializationPromise]; 188 case 2: 189 measurementId = _a.sent(); 190 gtagFunction(GtagCommand.CONFIG, measurementId, { 191 update: true, 192 'user_id': id 193 }); 194 _a.label = 3; 195 case 3: return [2 /*return*/]; 196 } 197 }); 198 });
199} 200/** 201 * Set all other user properties other than user_id and screen_name. 202 * 203 * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event 204 * @param properties Map of user properties to set 205 */ 206function setUserProperties(gtagFunction, initializationPromise, properties, options) { 207 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 208 var flatProperties, _i, _a, key, measurementId; 209 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) { 210 switch (_b.label) { 211 case 0: 212 if (!(options && options.global)) return [3 /*break*/, 1]; 213 flatProperties = {}; 214 for (_i = 0, _a = Object.keys(properties); _i < _a.length; _i++) { 215 key = _a[_i]; 216 // use dot notation for merge behavior in gtag.js 217 flatProperties["user_properties." + key] = properties[key]; 218 } 219 gtagFunction(GtagCommand.SET, flatProperties); 220 return [2 /*return*/, Promise.resolve()]; 221 case 1: return [4 /*yield*/, initializationPromise]; 222 case 2: 223 measurementId = _b.sent(); 224 gtagFunction(GtagCommand.CONFIG, measurementId, { 225 update: true, 226 'user_properties': properties 227 }); 228 _b.label = 3; 229 case 3: return [2 /*return*/]; 230 } 231 }); 232 }); 233} 234/** 235 * Set whether collection is enabled for this ID. 236 * 237 * @param enabled If true, collection is enabled for this ID. 238 */ 239function setAnalyticsCollectionEnabled(initializationPromise, enabled) { 240 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 241 var measurementId; 242 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 243 switch (_a.label) { 244 case 0: return [4 /*yield*/, initializationPromise]; 245 case 1: 246 measurementId = _a.sent(); 247 window["ga-disable-" + measurementId] = !enabled; 248 return [2 /*return*/]; 249 } 250 }); 251 }); 252} 253 254/** 255 * @license 256 * Copyright 2019 Google LLC 257 * 258 * Licensed under the Apache License, Version 2.0 (the "License"); 259 * you may not use this file except in compliance with the License. 260 * You may obtain a copy of the License at 261 * 262 * http://www.apache.org/licenses/LICENSE-2.0 263 * 264 * Unless required by applicable law or agreed to in writing, software 265 * distributed under the License is distributed on an "AS IS" BASIS, 266 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 267 * See the License for the specific language governing permissions and 268 * limitations under the License. 269 */ 270var logger = new _firebase_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"]('@firebase/analytics'); 271 272/** 273 * @license 274 * Copyright 2019 Google LLC 275 * 276 * Licensed under the Apache License, Version 2.0 (the "License"); 277 * you may not use this file except in compliance with the License. 278 * You may obtain a copy of the License at 279 * 280 * http://www.apache.org/licenses/LICENSE-2.0 281 * 282 * Unless required by applicable law or agreed to in writing, software 283 * distributed under the License is distributed on an "AS IS" BASIS, 284 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 285 * See the License for the specific language governing permissions and 286 * limitations under the License. 287 */ 288/** 289 * Inserts gtag script tag into the page to asynchronously download gtag. 290 * @param dataLayerName Name of datalayer (most often the default, "_dataLayer"). 291 */ 292function insertScriptTag(dataLayerName, measurementId) { 293 var script = document.createElement('script'); 294 script.src = GTAG_URL + "?l=" + dataLayerName + "&id=" + measurementId; 295 script.async = true; 296 document.head.appendChild(script); 297} 298/** 299 * Get reference to, or create, global datalayer. 300 * @param dataLayerName Name of datalayer (most often the default, "_dataLayer"). 301 */ 302function getOrCreateDataLayer(dataLayerName) { 303 // Check for existing dataLayer and create if needed. 304 var dataLayer = []; 305 if (Array.isArray(window[dataLayerName])) { 306 dataLayer = window[dataLayerName]; 307 } 308 else { 309 window[dataLayerName] = dataLayer; 310 } 311 return dataLayer; 312} 313/** 314 * Wrapped gtag logic when gtag is called with 'config' command. 315 * 316 * @param gtagCore Basic gtag function that just appends to dataLayer. 317 * @param initializationPromisesMap Map of appIds to their initialization promises. 318 * @param dynamicConfigPromisesList Array of dynamic config fetch promises. 319 * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appI
319d. 320 * @param measurementId GA Measurement ID to set config for. 321 * @param gtagParams Gtag config params to set. 322 */ 323function gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams) { 324 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 325 var correspondingAppId, dynamicConfigResults, foundConfig, e_1; 326 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 327 switch (_a.label) { 328 case 0: 329 correspondingAppId = measurementIdToAppId[measurementId]; 330 _a.label = 1; 331 case 1: 332 _a.trys.push([1, 7, , 8]); 333 if (!correspondingAppId) return [3 /*break*/, 3]; 334 return [4 /*yield*/, initializationPromisesMap[correspondingAppId]]; 335 case 2: 336 _a.sent(); 337 return [3 /*break*/, 6]; 338 case 3: return [4 /*yield*/, Promise.all(dynamicConfigPromisesList)]; 339 case 4: 340 dynamicConfigResults = _a.sent(); 341 foundConfig = dynamicConfigResults.find(function (config) { return config.measurementId === measurementId; }); 342 if (!foundConfig) return [3 /*break*/, 6]; 343 return [4 /*yield*/, initializationPromisesMap[foundConfig.appId]]; 344 case 5: 345 _a.sent(); 346 _a.label = 6; 347 case 6: return [3 /*break*/, 8]; 348 case 7: 349 e_1 = _a.sent(); 350 logger.error(e_1); 351 return [3 /*break*/, 8]; 352 case 8: 353 gtagCore(GtagCommand.CONFIG, measurementId, gtagParams); 354 return [2 /*return*/]; 355 } 356 }); 357 }); 358} 359/** 360 * Wrapped gtag logic when gtag is called with 'event' command. 361 * 362 * @param gtagCore Basic gtag function that just appends to dataLayer. 363 * @param initializationPromisesMap Map of appIds to their initialization promises. 364 * @param dynamicConfigPromisesList Array of dynamic config fetch promises. 365 * @param measurementId GA Measurement ID to log event to. 366 * @param gtagParams Params to log with this event. 367 */ 368function gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams) { 369 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 370 var initializationPromisesToWaitFor, gaSendToList, dynamicConfigResults, _loop_1, _i, gaSendToList_1, sendToId, state_1, e_2; 371 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 372 switch (_a.label) { 373 case 0: 374 _a.trys.push([0, 4, , 5]); 375 initializationPromisesToWaitFor = []; 376 if (!(gtagParams && gtagParams['send_to'])) return [3 /*break*/, 2]; 377 gaSendToList = gtagParams['send_to']; 378 // Make it an array if is isn't, so it can be dealt with the same way. 379 if (!Array.isArray(gaSendToList)) { 380 gaSendToList = [gaSendToList]; 381 } 382 return [4 /*yield*/, Promise.all(dynamicConfigPromisesList)]; 383 case 1: 384 dynamicConfigResults = _a.sent(); 385 _loop_1 = function (sendToId) { 386 // Any fetched dynamic measurement ID that matches this 'send_to' ID 387 var foundConfig = dynamicConfigResults.find(function (config) { return config.measurementId === sendToId; }); 388 var initializationPromise = foundConfig && initializationPromisesMap[foundConfig.appId]; 389 if (initializationPromise) { 390 initializationPromisesToWaitFor.push(initializationPromise); 391 } 392 else { 393 // Found an item in 'send_to' that is not associated 394 // directly with an FID, possibly a group. Empty this array, 395 // exit the loop early, and let it get populated below. 396 initializationPromisesToWaitFor = []; 397 return "break"; 398 } 399 }; 400 for (_i = 0, gaSendToList_1 = gaSendToList; _i < gaSendToList_1.length; _i++) { 401 sendToId = gaSendToList_1[_i]; 402 state_1 = _loop_1(sendToId); 403 if (state_1 === "break") 404 break; 405 } 406 _a.label = 2; 407 case 2: 408 // This will be unpopulated if there was no 'send_to' field , or 409 // if not all entries in the 'send_to' field could be mapped to 410 // a FID. In these cases, wait on all pending initialization promises. 411 if (initializationPromisesToWaitFor.length === 0) { 412 initializationPromisesToWaitFor = Object.values(initializationPromisesMap); 413 } 414 // Run core gtag function with args after all relevant initialization 415 // promises have been resolved. 416 return [4 /*yield*/, Promise.all(initializationPromisesToWaitFor)]; 417 case 3: 418 // Run core gtag function with args after all relevant initialization 419 // promises have been resolved. 420 _a.sent(); 421 // Workaround for http://b/141370449 - third argument cannot be undefined. 422 gtagCore(GtagCommand.EVENT, measurementId, gtagParams || {}); 423 return [3 /*break*/, 5]; 424 case 4: 425 e_2 = _a.sent(); 426 logger.error(e_2); 427 return [3 /*break*/, 5]; 428 case 5: return [2 /*return*/]; 429 } 430 }); 431 });
432} 433/** 434 * Wraps a standard gtag function with extra code to wait for completion of 435 * relevant initialization promises before sending requests. 436 * 437 * @param gtagCore Basic gtag function that just appends to dataLayer. 438 * @param initializationPromisesMap Map of appIds to their initialization promises. 439 * @param dynamicConfigPromisesList Array of dynamic config fetch promises. 440 * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId. 441 */ 442function wrapGtag(gtagCore, 443/** 444 * Allows wrapped gtag calls to wait on whichever intialization promises are required, 445 * depending on the contents of the gtag params' `send_to` field, if any. 446 */ 447initializationPromisesMap, 448/** 449 * Wrapped gtag calls sometimes require all dynamic config fetches to have returned 450 * before determining what initialization promises (which include FIDs) to wait for. 451 */ 452dynamicConfigPromisesList, 453/** 454 * Wrapped gtag config calls can narrow down which initialization promise (with FID) 455 * to wait for if the measurementId is already fetched, by getting the corresponding appId, 456 * which is the key for the initialization promises map. 457 */ 458measurementIdToAppId) { 459 /** 460 * Wrapper around gtag that ensures FID is sent with gtag calls. 461 * @param command Gtag command type. 462 * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET. 463 * @param gtagParams Params if event is EVENT/CONFIG. 464 */ 465 function gtagWrapper(command, idOrNameOrParams, gtagParams) { 466 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 467 var e_3; 468 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 469 switch (_a.label) { 470 case 0: 471 _a.trys.push([0, 6, , 7]); 472 if (!(command === GtagCommand.EVENT)) return [3 /*break*/, 2]; 473 // If EVENT, second arg must be measurementId. 474 return [4 /*yield*/, gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams)]; 475 case 1: 476 // If EVENT, second arg must be measurementId. 477 _a.sent(); 478 return [3 /*break*/, 5]; 479 case 2: 480 if (!(command === GtagCommand.CONFIG)) return [3 /*break*/, 4]; 481 // If CONFIG, second arg must be measurementId. 482 return [4 /*yield*/, gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams)]; 483 case 3: 484 // If CONFIG, second arg must be measurementId. 485 _a.sent(); 486 return [3 /*break*/, 5]; 487 case 4: 488 // If SET, second arg must be params. 489 gtagCore(GtagCommand.SET, idOrNameOrParams); 490 _a.label = 5; 491 case 5: return [3 /*break*/, 7]; 492 case 6: 493 e_3 = _a.sent(); 494 logger.error(e_3); 495 return [3 /*break*/, 7]; 496 case 7: return [2 /*return*/]; 497 } 498 }); 499 }); 500 } 501 return gtagWrapper; 502} 503/** 504 * Creates global gtag function or wraps existing one if found. 505 * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and 506 * 'event' calls that belong to the GAID associated with this Firebase instance. 507 * 508 * @param initializationPromisesMap Map of appIds to their initialization promises. 509 * @param dynamicConfigPromisesList Array of dynamic config fetch promises. 510 * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appI
510d. 511 * @param dataLayerName Name of global GA datalayer array. 512 * @param gtagFunctionName Name of global gtag function ("gtag" if not user-specified). 513 */ 514function wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagFunctionName) { 515 // Create a basic core gtag function 516 var gtagCore = function () { 517 var _args = []; 518 for (var _i = 0; _i < arguments.length; _i++) { 519 _args[_i] = arguments[_i]; 520 } 521 // Must push IArguments object, not an array. 522 window[dataLayerName].push(arguments); 523 }; 524 // Replace it with existing one if found 525 if (window[gtagFunctionName] && 526 typeof window[gtagFunctionName] === 'function') { 527 // @ts-ignore 528 gtagCore = window[gtagFunctionName]; 529 } 530 window[gtagFunctionName] = wrapGtag(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId); 531 return { 532 gtagCore: gtagCore, 533 wrappedGtag: window[gtagFunctionName] 534 }; 535} 536/** 537 * Returns first script tag in DOM matching our gtag url pattern. 538 */ 539function findGtagScriptOnPage() { 540 var scriptTags = window.document.getElementsByTagName('script'); 541 for (var _i = 0, _a = Object.values(scriptTags); _i < _a.length; _i++) { 542 var tag = _a[_i]; 543 if (tag.src && tag.src.includes(GTAG_URL)) { 544 return tag; 545 } 546 } 547 return null; 548} 549 550/** 551 * @license 552 * Copyright 2019 Google LLC 553 * 554 * Licensed under the Apache License, Version 2.0 (the "License"); 555 * you may not use this file except in compliance with the License. 556 * You may obtain a copy of the License at 557 * 558 * http://www.apache.org/licenses/LICENSE-2.0 559 * 560 * Unless required by applicable law or agreed to in writing, software 561 * distributed under the License is distributed on an "AS IS" BASIS, 562 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 563 * See the License for the specific language governing permissions and 564 * limitations under the License. 565 */ 566var _a; 567var ERRORS = (_a = {}, 568 _a["already-exists" /* ALREADY_EXISTS */] = 'A Firebase Analytics instance with the appId {$id} ' + 569 ' already exists. ' + 570 'Only one Firebase Analytics instance can be created for each appId.', 571 _a["already-initialized" /* ALREADY_INITIALIZED */] = 'Firebase Analytics has already been initialized.' + 572 'settings() must be called before initializing any Analytics instance' + 573 'or it will have no effect.', 574 _a["interop-component-reg-failed" /* INTEROP_COMPONENT_REG_FAILED */] = 'Firebase Analytics Interop Component failed to instantiate: {$reason}', 575 _a["invalid-analytics-context" /* INVALID_ANALYTICS_CONTEXT */] = 'Firebase Analytics is not supported in this environment. ' + 576 'Wrap initialization of analytics in analytics.isSupported() ' + 577 'to prevent initialization in unsupported environments. Details: {$errorInfo}', 578 _a["indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */] = 'IndexedDB unavailable or restricted in this environment. ' + 579 'Wrap initialization of analytics in analytics.isSupported() ' + 580 'to prevent initialization in unsupported environments. Details: {$errorInfo}', 581 _a["fetch-throttle" /* FETCH_THROTTLE */] = 'The config fetch request timed out while in an exponential backoff state.' + 582 ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.', 583 _a["config-fetch-failed" /* CONFIG_FETCH_FAILED */] = 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}', 584 _a["no-api-key" /* NO_API_KEY */] = 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' + 585 'contain a valid API key.', 586 _a["no-app-id" /* NO_APP_ID */] = 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' + 587 'contain a valid app ID.', 588 _a); 589var ERROR_FACTORY = new _firebase_util__WEBPACK_IMPORTED_MODULE_4__["ErrorFactory"]('analytics', 'Analytics', ERRORS); 590 591/** 592 * @license 593 * Copyright 2020 Google LLC 594 * 595 * Licensed under the Apache License, Version 2.0 (the "License");
596 * you may not use this file except in compliance with the License. 597 * You may obtain a copy of the License at 598 * 599 * http://www.apache.org/licenses/LICENSE-2.0 600 * 601 * Unless required by applicable law or agreed to in writing, software 602 * distributed under the License is distributed on an "AS IS" BASIS, 603 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 604 * See the License for the specific language governing permissions and 605 * limitations under the License. 606 */ 607/** 608 * Backoff factor for 503 errors, which we want to be conservative about 609 * to avoid overloading servers. Each retry interval will be 610 * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one 611 * will be ~30 seconds (with fuzzing). 612 */ 613var LONG_RETRY_FACTOR = 30; 614/** 615 * Base wait interval to multiplied by backoffFactor^backoffCount. 616 */ 617var BASE_INTERVAL_MILLIS = 1000; 618/** 619 * Stubbable retry data storage class. 620 */ 621var RetryData = /** @class */ (function () { 622 function RetryData(throttleMetadata, intervalMillis) { 623 if (throttleMetadata === void 0) { throttleMetadata = {}; } 624 if (intervalMillis === void 0) { intervalMillis = BASE_INTERVAL_MILLIS; } 625 this.throttleMetadata = throttleMetadata; 626 this.intervalMillis = intervalMillis; 627 } 628 RetryData.prototype.getThrottleMetadata = function (appId) { 629 return this.throttleMetadata[appId]; 630 }; 631 RetryData.prototype.setThrottleMetadata = function (appId, metadata) { 632 this.throttleMetadata[appId] = metadata; 633 }; 634 RetryData.prototype.deleteThrottleMetadata = function (appId) { 635 delete this.throttleMetadata[appId]; 636 }; 637 return RetryData; 638}()); 639var defaultRetryData = new RetryData(); 640/** 641 * Set GET request headers. 642 * @param apiKey App API key. 643 */ 644function getHeaders(apiKey) { 645 return new Headers({ 646 Accept: 'application/json', 647 'x-goog-api-key': apiKey 648 }); 649} 650/** 651 * Fetches dynamic config from backend. 652 * @param app Firebase app to fetch config for. 653 */ 654function fetchDynamicConfig(appFields) { 655 var _a; 656 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 657 var appId, apiKey, request, appUrl, response, errorMessage, jsonResponse, _ignored_1;
658 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) { 659 switch (_b.label) { 660 case 0: 661 appId = appFields.appId, apiKey = appFields.apiKey; 662 request = { 663 method: 'GET', 664 headers: getHeaders(apiKey) 665 }; 666 appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId); 667 return [4 /*yield*/, fetch(appUrl, request)]; 668 case 1: 669 response = _b.sent(); 670 if (!(response.status !== 200 && response.status !== 304)) return [3 /*break*/, 6]; 671 errorMessage = ''; 672 _b.label = 2; 673 case 2: 674 _b.trys.push([2, 4, , 5]); 675 return [4 /*yield*/, response.json()]; 676 case 3: 677 jsonResponse = (_b.sent()); 678 if ((_a = jsonResponse.error) === null || _a === void 0 ? void 0 : _a.message) { 679 errorMessage = jsonResponse.error.message; 680 } 681 return [3 /*break*/, 5]; 682 case 4: 683 _ignored_1 = _b.sent(); 684 return [3 /*break*/, 5]; 685 case 5: throw ERROR_FACTORY.create("config-fetch-failed" /* CONFIG_FETCH_FAILED */, { 686 httpStatus: response.status, 687 responseMessage: errorMessage 688 }); 689 case 6: return [2 /*return*/, response.json()]; 690 } 691 }); 692 }); 693} 694/** 695 * Fetches dynamic config from backend, retrying if failed. 696 * @param app Firebase app to fetch config for. 697 */ 698function fetchDynamicConfigWithRetry(app, 699// retryData and timeoutMillis are parameterized to allow passing a different value for testing. 700retryData, timeoutMillis) { 701 if (retryData === void 0) { retryData = defaultRetryData; } 702 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 703 var _a, appId, apiKey, measurementId, throttleMetadata, signal; 704 var _this = this; 705 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) { 706 _a = app.options, appId = _a.appId, apiKey = _a.apiKey, measurementId = _a.measurementId; 707 if (!appId) { 708 throw ERROR_FACTORY.create("no-app-id" /* NO_APP_ID */); 709 } 710 if (!apiKey) { 711 if (measurementId) { 712 return [2 /*return*/, { 713 measurementId: measurementId, 714 appId: appId 715 }]; 716 } 717 throw ERROR_FACTORY.create("no-api-key" /* NO_API_KEY */); 718 } 719 throttleMetadata = retryData.getThrottleMetadata(appId) || { 720 backoffCount: 0, 721 throttleEndTimeMillis: Date.now() 722 }; 723 signal = new AnalyticsAbortSignal(); 724 setTimeout(function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () { 725 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 726 // Note a very low delay, eg < 10ms, can elapse before listeners are initialized. 727 signal.abort(); 728 return [2 /*return*/]; 729 }); 730 }); }, timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS); 731 return [2 /*return*/, attemptFetchDynamicConfigWithRetry({ appId: appId, apiKey: apiKey, measurementId: measurementId }, throttleMetadata, signal, retryData)]; 732 }); 733 }); 734} 735/** 736 * Runs one retry attempt. 737 * @param appFields Necessary app config fields. 738 * @param throttleMetadata Ongoing metadata to determine throttling times. 739 * @param signal Abort signal. 740 */ 741function attemptFetchDynamicConfigWithRetry(appFields, _a, signal, retryData // for testing 742) { 743 var throttleEndTimeMillis = _a.throttleEndTimeMillis, backoffCount = _a.backoffCount; 744 if (retryData === void 0) { retryData = defaultRetryData; } 745 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 746 var appId, measurementId, e_1, response, e_2, backoffMillis, throttleMetadata; 747 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) { 748 switch (_b.label) { 749 case 0: 750 appId = appFields.appId, measurementId = appFields.measurementId; 751 _b.label = 1; 752 case 1: 753 _b.trys.push([1, 3, , 4]); 754 return [4 /*yield*/, setAbortableTimeout(signal, throttleEndTimeMillis)]; 755 case 2: 756 _b.sent(); 757 return [3 /*break*/, 4]; 758 case 3: 759 e_1 = _b.sent(); 760 if (measurementId) { 761 logger.warn("Timed out fetching this Firebase app's measurement ID from the server." + 762 (" Falling back to the measurement ID " + measurementId) + 763 (" provided in the \"measurementId\" field in the local Firebase config. [" + e_1.message + "]")); 764 return [2 /*return*/, { appId: appId, measurementId: measurementId }]; 765 } 766 throw e_1; 767 case 4: 768 _b.trys.push([4, 6, , 7]); 769 return [4 /*yield*/, fetchDynamicConfig(appFields)]; 770 case 5: 771 response = _b.sent(); 772 // Note the SDK only clears throttle state if response is success or non-retriable. 773 retryData.deleteThrottleMetadata(appId); 774 return [2 /*return*/, response]; 775 case 6: 776 e_2 = _b.sent(); 777 if (!isRetriableError(e_2)) { 778 retryData.deleteThrottleMetadata(appId); 779 if (measurementId) { 780 logger.warn("Failed to fetch this Firebase app's measurement ID from the server." + 781 (" Falling back to the measurement ID " + measurementId) + 782 (" provided in the \"measurementId\" field in the local Firebase config. [" + e_2.message + "]")); 783 return [2 /*return*/, { appId: appId, measurementId: measurementId }]; 784 } 785 else { 786 throw e_2; 787 } 788 } 789 backoffMillis = Number(e_2.customData.httpStatus) === 503 790 ? Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["calculateBackoffMillis"])(backoffCount, retryData.intervalMillis, LONG_RETRY_FACTOR) 791 : Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["calculateBackoffMillis"])(backoffCount, retryData.intervalMillis); 792 throttleMetadata = { 793 throttleEndTimeMillis: Date.now() + backoffMillis, 794 backoffCount: backoffCount + 1 795 }; 796 // Persists state. 797 retryData.setThrottleMetadata(appId, throttleMetadata); 798 logger.debug("Calling attemptFetch again in " + backoffMillis + " millis"); 799 return [2 /*return*/, attemptFetchDynamicConfigWithRetry(appFields, throttleMetadata, signal, retryData)]; 800 case 7: return [2 /*return*/]; 801 } 802 }); 803 });
804} 805/** 806 * Supports waiting on a backoff by: 807 * 808 * <ul> 809 * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li> 810 * <li>Listening on a signal bus for abort events, just like the Fetch API</li> 811 * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled 812 * request appear the same.</li> 813 * </ul> 814 * 815 * <p>Visible for testing. 816 */ 817function setAbortableTimeout(signal, throttleEndTimeMillis) { 818 return new Promise(function (resolve, reject) { 819 // Derives backoff from given end time, normalizing negative numbers to zero. 820 var backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0); 821 var timeout = setTimeout(resolve, backoffMillis); 822 // Adds listener, rather than sets onabort, because signal is a shared object. 823 signal.addEventListener(function () { 824 clearTimeout(timeout); 825 // If the request completes before this timeout, the rejection has no effect. 826 reject(ERROR_FACTORY.create("fetch-throttle" /* FETCH_THROTTLE */, { 827 throttleEndTimeMillis: throttleEndTimeMillis 828 })); 829 }); 830 }); 831} 832/** 833 * Returns true if the {@link Error} indicates a fetch request may succeed later. 834 */ 835function isRetriableError(e) { 836 if (!(e instanceof _firebase_util__WEBPACK_IMPORTED_MODULE_4__["FirebaseError"]) || !e.customData) { 837 return false; 838 } 839 // Uses string index defined by ErrorData, which FirebaseError implements. 840 var httpStatus = Number(e.customData['httpStatus']); 841 return (httpStatus === 429 || 842 httpStatus === 500 || 843 httpStatus === 503 || 844 httpStatus === 504); 845} 846/** 847 * Shims a minimal AbortSignal (copied from Remote Config). 848 * 849 * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects 850 * of networking, such as retries. Firebase doesn't use AbortController enough to justify a 851 * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be 852 * swapped out if/when we do. 853 */ 854var AnalyticsAbortSignal = /** @class */ (function () { 855 function AnalyticsAbortSignal() { 856 this.listeners = []; 857 } 858 AnalyticsAbortSignal.prototype.addEventListener = function (listener) { 859 this.listeners.push(listener); 860 }; 861 AnalyticsAbortSignal.prototype.abort = function () { 862 this.listeners.forEach(function (listener) { return listener(); }); 863 }; 864 return AnalyticsAbortSignal; 865}()); 866 867/** 868 * @license 869 * Copyright 2020 Google LLC 870 * 871 * Licensed under the Apache License, Version 2.0 (the "License"); 872 * you may not use this file except in compliance with the License. 873 * You may obtain a copy of the License at 874 * 875 * http://www.apache.org/licenses/LICENSE-2.0 876 * 877 * Unless required by applicable law or agreed to in writing, software 878 * distributed under the License is distributed on an "AS IS" BASIS, 879 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 880 * See the License for the specific language governing permissions and 881 * limitations under the License. 882 */ 883function validateIndexedDB() { 884 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 885 var e_1; 886 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 887 switch (_a.label) { 888 case 0: 889 if (!!Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["isIndexedDBAvailable"])()) return [3 /*break*/, 1]; 890 logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */, { 891 errorInfo: 'IndexedDB is not available in this environment.' 892 }).message); 893 return [2 /*return*/, false]; 894 case 1: 895 _a.trys.push([1, 3, , 4]); 896 return [4 /*yield*/, Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["validateIndexedDBOpenable"])()]; 897 case 2: 898 _a.sent(); 899 return [3 /*break*/, 4]; 900 case 3: 901 e_1 = _a.sent(); 902 logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */, { 903 errorInfo: e_1 904 }).message); 905 return [2 /*return*/, false]; 906 case 4: return [2 /*return*/, true]; 907 } 908 }); 909 });
910} 911/** 912 * Initialize the analytics instance in gtag.js by calling config command with fid. 913 * 914 * NOTE: We combine analytics initialization and setting fid together because we want fid to be 915 * part of the `page_view` event that's sent during the initialization 916 * @param app Firebase app 917 * @param gtagCore The gtag function that's not wrapped. 918 * @param dynamicConfigPromisesList Array of all dynamic config promises. 919 * @param measurementIdToAppId Maps measurementID to appID. 920 * @param installations FirebaseInstallations instance. 921 * 922 * @returns Measurement ID. 923 */ 924function initializeIds(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName) { 925 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 926 var dynamicConfigPromise, fidPromise, _a, dynamicConfig, fid, configProperties; 927 var _b; 928 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_c) { 929 switch (_c.label) { 930 case 0: 931 dynamicConfigPromise = fetchDynamicConfigWithRetry(app); 932 // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function. 933 dynamicConfigPromise 934 .then(function (config) { 935 measurementIdToAppId[config.measurementId] = config.appId; 936 if (app.options.measurementId && 937 config.measurementId !== app.options.measurementId) { 938 logger.warn("The measurement ID in the local Firebase config (" + app.options.measurementId + ")" + 939 (" does not match the measurement ID fetched from the server (" + config.measurementId + ").") + 940 " To ensure analytics events are always sent to the correct Analytics property," + 941 " update the" + 942 " measurement ID field in the local config or remove it from the local config."); 943 } 944 }) 945 .catch(function (e) { return logger.error(e); }); 946 // Add to list to track state of all dynamic config promises. 947 dynamicConfigPromisesList.push(dynamicConfigPromise); 948 fidPromise = validateIndexedDB().then(function (envIsValid) { 949 if (envIsValid) { 950 return installations.getId(); 951 } 952 else { 953 return undefined; 954 } 955 }); 956 return [4 /*yield*/, Promise.all([ 957 dynamicConfigPromise, 958 fidPromise 959 ])]; 960 case 1: 961 _a = _c.sent(), dynamicConfig = _a[0], fid = _a[1]; 962 // Detect if user has already put the gtag <script> tag on this page. 963 if (!findGtagScriptOnPage()) { 964 insertScriptTag(dataLayerName, dynamicConfig.measurementId); 965 } 966 // This command initializes gtag.js and only needs to be called once for the entire web app, 967 // but since it is idempotent, we can call it multiple times. 968 // We keep it together with other initialization logic for better code structure. 969 // eslint-disable-next-line @typescript-eslint/no-explicit-any 970 gtagCore('js', new Date()); 971 configProperties = (_b = {}, 972 // guard against developers accidentally setting properties with prefix `firebase_` 973 _b[ORIGIN_KEY] = 'firebase', 974 _b.update = true, 975 _b); 976 if (fid != null) { 977 configProperties[GA_FID_KEY] = fid; 978 } 979 // It should be the first config command called on this GA-ID 980 // Initialize this GA-ID and set FID on it using the gtag config API. 981 // Note: This will trigger a page_view event unless 'send_page_view' is set to false in 982 // `configProperties`. 983 gtagCore(GtagCommand.CONFIG, dynamicConfig.measurementId, configProperties); 984 return [2 /*return*/, dynamicConfig.measurementId]; 985 } 986 }); 987 });
988} 989 990/** 991 * @license 992 * Copyright 2019 Google LLC 993 * 994 * Licensed under the Apache License, Version 2.0 (the "License"); 995 * you may not use this file except in compliance with the License. 996 * You may obtain a copy of the License at 997 * 998 * http://www.apache.org/licenses/LICENSE-2.0 999 * 1000 * Unless required by applicable law or agreed to in writing, software 1001 * distributed under the License is distributed on an "AS IS" BASIS, 1002 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1003 * See the License for the specific language governing permissions and 1004 * limitations under the License. 1005 */ 1006/** 1007 * Maps appId to full initialization promise. Wrapped gtag calls must wait on 1008 * all or some of these, depending on the call's `send_to` param and the status 1009 * of the dynamic config fetches (see below). 1010 */ 1011var initializationPromisesMap = {}; 1012/** 1013 * List of dynamic config fetch promises. In certain cases, wrapped gtag calls 1014 * wait on all these to be complete in order to determine if it can selectively 1015 * wait for only certain initialization (FID) promises or if it must wait for all. 1016 */ 1017var dynamicConfigPromisesList = []; 1018/** 1019 * Maps fetched measurementIds to appId. Populated when the app's dynamic config 1020 * fetch completes. If already populated, gtag config calls can use this to 1021 * selectively wait for only this app's initialization promise (FID) instead of all 1022 * initialization promises. 1023 */ 1024var measurementIdToAppId = {}; 1025/** 1026 * Name for window global data layer array used by GA: defaults to 'dataLayer'. 1027 */ 1028var dataLayerName = 'dataLayer'; 1029/** 1030 * Name for window global gtag function used by GA: defaults to 'gtag'. 1031 */ 1032var gtagName = 'gtag'; 1033/** 1034 * Reproduction of standard gtag function or reference to existing 1035 * gtag function on window object. 1036 */ 1037var gtagCoreFunction; 1038/** 1039 * Wrapper around gtag function that ensures FID is sent with all 1040 * relevant event and config calls. 1041 */ 1042var wrappedGtagFunction; 1043/** 1044 * Flag to ensure page initialization steps (creation or wrapping of 1045 * dataLayer and gtag script) are only run once per page load. 1046 */ 1047var globalInitDone = false; 1048/** 1049 * For testing 1050 */ 1051function resetGlobalVars(newGlobalInitDone, newInitializationPromisesMap, newDynamicPromises) { 1052 if (newGlobalInitDone === void 0) { newGlobalInitDone = false; } 1053 if (newInitializationPromisesMap === void 0) { newInitializationPromisesMap = {}; } 1054 if (newDynamicPromises === void 0) { newDynamicPromises = []; } 1055 globalInitDone = newGlobalInitDone; 1056 initializationPromisesMap = newInitializationPromisesMap; 1057 dynamicConfigPromisesList = newDynamicPromises; 1058 dataLayerName = 'dataLayer'; 1059 gtagName = 'gtag'; 1060} 1061/** 1062 * For testing 1063 */ 1064function getGlobalVars() { 1065 return { 1066 initializationPromisesMap: initializationPromisesMap, 1067 dynamicConfigPromisesList: dynamicConfigPromisesList 1068 }; 1069} 1070/** 1071 * This must be run before calling firebase.analytics() or it won't 1072 * have any effect. 1073 * @param options Custom gtag and dataLayer names. 1074 */ 1075function settings(options) { 1076 if (globalInitDone) { 1077 throw ERROR_FACTORY.create("already-initialized" /* ALREADY_INITIALIZED */); 1078 } 1079 if (options.dataLayerName) { 1080 dataLayerName = options.dataLayerName; 1081 } 1082 if (options.gtagName) { 1083 gtagName = options.gtagName; 1084 } 1085} 1086/** 1087 * Returns true if no environment mismatch is found. 1088 * If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT 1089 * error that also lists details for each mismatch found. 1090 */ 1091function warnOnBrowserContextMismatch() { 1092 var mismatchedEnvMessages = []; 1093 if (Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["isBrowserExtension"])()) { 1094 mismatchedEnvMessages.push('This is a browser extension environment.'); 1095 } 1096 if (!Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["areCookiesEnabled"])()) { 1097 mismatchedEnvMessages.push('Cookies are not available.'); 1098 } 1099 if (mismatchedEnvMessages.length > 0) { 1100 var details = mismatchedEnvMessages 1101 .map(function (message, index) { return "(" + (index + 1) + ") " + message; }) 1102 .join(' '); 1103 var err = ERROR_FACTORY.create("invalid-analytics-context" /* INVA
1103LID_ANALYTICS_CONTEXT */, { 1104 errorInfo: details 1105 }); 1106 logger.warn(err.message); 1107 } 1108} 1109function factory(app, installations) { 1110 warnOnBrowserContextMismatch(); 1111 var appId = app.options.appId; 1112 if (!appId) { 1113 throw ERROR_FACTORY.create("no-app-id" /* NO_APP_ID */); 1114 } 1115 if (!app.options.apiKey) { 1116 if (app.options.measurementId) { 1117 logger.warn("The \"apiKey\" field is empty in the local Firebase config. This is needed to fetch the latest" + 1118 (" measurement ID for this Firebase app. Falling back to the measurement ID " + app.options.measurementId) + 1119 " provided in the \"measurementId\" field in the local Firebase config."); 1120 } 1121 else { 1122 throw ERROR_FACTORY.create("no-api-key" /* NO_API_KEY */); 1123 } 1124 } 1125 if (initializationPromisesMap[appId] != null) { 1126 throw ERROR_FACTORY.create("already-exists" /* ALREADY_EXISTS */, { 1127 id: appId 1128 }); 1129 } 1130 if (!globalInitDone) { 1131 // Steps here should only be done once per page: creation or wrapping 1132 // of dataLayer and global gtag function. 1133 getOrCreateDataLayer(dataLayerName); 1134 var _a = wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagName), wrappedGtag = _a.wrappedGtag, gtagCore = _a.gtagCore; 1135 wrappedGtagFunction = wrappedGtag; 1136 gtagCoreFunction = gtagCore; 1137 globalInitDone = true; 1138 } 1139 // Async but non-blocking. 1140 // This map reflects the completion state of all promises for each appId. 1141 initializationPromisesMap[appId] = initializeIds(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCoreFunction, dataLayerName); 1142 var analyticsInstance = { 1143 app: app, 1144 // Public methods return void for API simplicity and to better match gtag, 1145 // while internal implementations return promises. 1146 logEvent: function (eventName, eventParams, options) { 1147 logEvent(wrappedGtagFunction, initializationPromisesMap[appId], eventName, eventParams, options).catch(function (e) { return logger.error(e); }); 1148 }, 1149 setCurrentScreen: function (screenName, options) { 1150 setCurrentScreen(wrappedGtagFunction, initializationPromisesMap[appId], screenName, options).catch(function (e) { return logger.error(e); }); 1151 }, 1152 setUserId: function (id, options) { 1153 setUserId(wrappedGtagFunction, initializationPromisesMap[appId], id, options).catch(function (e) { return logger.error(e); }); 1154 }, 1155 setUserProperties: function (properties, options) { 1156 setUserProperties(wrappedGtagFunction, initializationPromisesMap[appId], properties, options).catch(function (e) { return logger.error(e); }); 1157 }, 1158 setAnalyticsCollectionEnabled: function (enabled) { 1159 setAnalyticsCollectionEnabled(initializationPromisesMap[appId], enabled).catch(function (e) { return logger.error(e); }); 1160 }, 1161 INTERNAL: { 1162 delete: function () { 1163 delete initializationPromisesMap[appId]; 1164 return Promise.resolve(); 1165 } 1166 } 1167 }; 1168 return analyticsInstance; 1169} 1170 1171var name = "@firebase/analytics"; 1172var version = "0.6.4"; 1173 1174/** 1175 * Type constant for Firebase Analytics. 1176 */ 1177var ANALYTICS_TYPE = 'analytics'; 1178function registerAnalytics(instance) { 1179 instance.INTERNAL.registerComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_5__["Component"](ANALYTICS_TYPE, function (container) { 1180 // getImmediate for FirebaseApp will always succeed 1181 var app = container.getProvider('app').getImmediate(); 1182 var installations = container 1183 .getProvider('installations') 1184 .getImmediate(); 1185 return factory(app, installations); 1186 }, "PUBLIC" /* PUBLIC */).setServiceProps({ 1187 settings: settings, 1188 EventName: EventName, 1189 isSupported: isSupported 1190 })); 1191 instance.INTERNAL.registerComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_5__["Component"]('analytics-internal', internalFactory, "PRIVATE" /* PRIVATE */)); 1192 instance.registerVersion(name, version); 1193 function internalFactory(container) { 1194 try { 1195 var analytics = container.getProvider(ANALYTICS_TYPE).getImmediate(); 1196 return { 1197 logEvent: analytics.logEvent 1198 }; 1199 } 1200 catch (e) { 1201 throw ERROR_FACTORY.create("interop-component-reg-failed" /* INTEROP_COMPONENT_REG_FAILED */, { 1202 reason: e 1203 }); 1204 } 1205 } 1206} 1207registerAnalytics(_firebase_app__WEBPACK_IMPORTED_MODULE_1__["default"]);
1208/** 1209 * this is a public static method provided to users that wraps four different checks: 1210 * 1211 * 1. check if it's not a browser extension environment. 1212 * 1. check if cookie is enabled in current browser. 1213 * 3. check if IndexedDB is supported by the browser environment. 1214 * 4. check if the current browser context is valid for using IndexedDB. 1215 * 1216 */ 1217function isSupported() { 1218 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () { 1219 var isDBOpenable, error_1; 1220 return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) { 1221 switch (_a.label) { 1222 case 0: 1223 if (Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["isBrowserExtension"])()) { 1224 return [2 /*return*/, false]; 1225 } 1226 if (!Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["areCookiesEnabled"])()) { 1227 return [2 /*return*/, false]; 1228 } 1229 if (!Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["isIndexedDBAvailable"])()) { 1230 return [2 /*return*/, false]; 1231 } 1232 _a.label = 1; 1233 case 1: 1234 _a.trys.push([1, 3, , 4]); 1235 return [4 /*yield*/, Object(_firebase_util__WEBPACK_IMPORTED_MODULE_4__["validateIndexedDBOpenable"])()]; 1236 case 2: 1237 isDBOpenable = _a.sent(); 1238 return [2 /*return*/, isDBOpenable]; 1239 case 3: 1240 error_1 = _a.sent(); 1241 return [2 /*return*/, false]; 1242 case 4: return [2 /*return*/]; 1243 } 1244 }); 1245 }); 1246} 1247 1248 1249//# sourceMappingURL=index.esm.js.map 1250 1251 1252/***/ }), 1253 1254/***/ "AAub": 1255/*!***********************************************************!*\ 1256 !*** ./node_modules/firebase/analytics/dist/index.esm.js ***! 1257 \***********************************************************/ 1258/*! no exports provided */ 1259/***/ (function(module, __webpack_exports__, __webpack_require__) { 1260 1261"use strict"; 1262__webpack_require__.r(__webpack_exports__); 1263/* harmony import */ var _firebase_analytics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @firebase/analytics */ "3Kre"); 1264 1265//# sourceMappingURL=index.esm.js.map 1266 1267 1268/***/ }), 1269 1270/***/ "fSjL": 1271/*!****************************************************************!*\ 1272 !*** ./node_modules/@firebase/installations/dist/index.esm.js ***! 1273 \****************************************************************/ 1274/*! exports provided: registerInstallations */ 1275/***/ (function(module, __webpack_exports__, __webpack_require__) { 1276 1277"use strict"; 1278__webpack_require__.r(__webpack_exports__); 1279/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerInstallations", function() { return registerInstallations; }); 1280/* harmony import */ var _firebase_app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @firebase/app */ "zIRd"); 1281/* harmony import */ var _firebase_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @firebase/component */ "/6Yf"); 1282/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! tslib */ "30Go"); 1283/* harmony import */ var _firebase_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @firebase/util */ "qOnz"); 1284/* harmony import */ var idb__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! idb */ "nbvr"); 1285/* harmony import */ var idb__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(idb__WEBPACK_IMPORTED_MODULE_4__); 1286 1287 1288 1289 1290 1291 1292var name = "@firebase/installations"; 1293var version = "0.4.20"; 1294 1295/** 1296 * @license 1297 * Copyright 2019 Google LLC 1298 * 1299 * Licensed under the Apache License, Version 2.0 (the "License"); 1300 * you may not use this file except in compliance with the License. 1301 * You may obtain a copy of the License at 1302 * 1303 * http://www.apache.org/licenses/LICENSE-2.0 1304 * 1305 * Unless required by applicable law or agreed to in writing, software 1306 * distributed under the License is distributed on an "AS IS" BASIS, 1307 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1308 * See the License for the specific language governing permissions and 1309 * limitations under the License. 1310 */
1311var PENDING_TIMEOUT_MS = 10000; 1312var PACKAGE_VERSION = "w:" + version; 1313var INTERNAL_AUTH_VERSION = 'FIS_v2'; 1314var INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1'; 1315var TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour 1316var SERVICE = 'installations'; 1317var SERVICE_NAME = 'Installations'; 1318 1319/** 1320 * @license 1321 * Copyright 2019 Google LLC 1322 * 1323 * Licensed under the Apache License, Version 2.0 (the "License"); 1324 * you may not use this file except in compliance with the License. 1325 * You may obtain a copy of the License at 1326 * 1327 * http://www.apache.org/licenses/LICENSE-2.0 1328 * 1329 * Unless required by applicable law or agreed to in writing, software 1330 * distributed under the License is distributed on an "AS IS" BASIS, 1331 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1332 * See the License for the specific language governing permissions and 1333 * limitations under the License. 1334 */ 1335var _a; 1336var ERROR_DESCRIPTION_MAP = (_a = {}, 1337 _a["missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration value: "{$valueName}"', 1338 _a["not-registered" /* NOT_REGISTERED */] = 'Firebase Installation is not registered.', 1339 _a["installation-not-found" /* INSTALLATION_NOT_FOUND */] = 'Firebase Installation not found.', 1340 _a["request-failed" /* REQUEST_FAILED */] = '{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"', 1341 _a["app-offline" /* APP_OFFLINE */] = 'Could not process request. Application offline.', 1342 _a["delete-pending-registration" /* DELETE_PENDING_REGISTRATION */] = "Can't delete installation while there is a pending registration request.", 1343 _a); 1344var ERROR_FACTORY = new _firebase_util__WEBPACK_IMPORTED_MODULE_3__["ErrorFactory"](SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP); 1345/** Returns true if error is a FirebaseError that is based on an error from the server. */ 1346function isServerError(error) { 1347 return (error instanceof _firebase_util__WEBPACK_IMPORTED_MODULE_3__["FirebaseError"] && 1348 error.code.includes("request-failed" /* REQUEST_FAILED */)); 1349} 1350 1351/** 1352 * @license 1353 * Copyright 2019 Google LLC 1354 * 1355 * Licensed under the Apache License, Version 2.0 (the "License"); 1356 * you may not use this file except in compliance with the License. 1357 * You may obtain a copy of the License at 1358 * 1359 * http://www.apache.org/licenses/LICENSE-2.0 1360 * 1361 * Unless required by applicable law or agreed to in writing, software 1362 * distributed under the License is distributed on an "AS IS" BASIS, 1363 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1364 * See the License for the specific language governing permissions and 1365 * limitations under the License. 1366 */ 1367function getInstallationsEndpoint(_a) { 1368 var projectId = _a.projectId; 1369 return INSTALLATIONS_API_URL + "/projects/" + projectId + "/installations"; 1370}
1371function extractAuthTokenInfoFromResponse(response) { 1372 return { 1373 token: response.token, 1374 requestStatus: 2 /* COMPLETED */, 1375 expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn), 1376 creationTime: Date.now() 1377 }; 1378} 1379function getErrorFromResponse(requestName, response) { 1380 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1381 var responseJson, errorData; 1382 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 1383 switch (_a.label) { 1384 case 0: return [4 /*yield*/, response.json()]; 1385 case 1: 1386 responseJson = _a.sent(); 1387 errorData = responseJson.error; 1388 return [2 /*return*/, ERROR_FACTORY.create("request-failed" /* REQUEST_FAILED */, { 1389 requestName: requestName, 1390 serverCode: errorData.code, 1391 serverMessage: errorData.message, 1392 serverStatus: errorData.status 1393 })]; 1394 } 1395 }); 1396 }); 1397} 1398function getHeaders(_a) { 1399 var apiKey = _a.apiKey; 1400 return new Headers({ 1401 'Content-Type': 'application/json', 1402 Accept: 'application/json', 1403 'x-goog-api-key': apiKey 1404 }); 1405} 1406function getHeadersWithAuth(appConfig, _a) { 1407 var refreshToken = _a.refreshToken; 1408 var headers = getHeaders(appConfig); 1409 headers.append('Authorization', getAuthorizationHeader(refreshToken)); 1410 return headers; 1411} 1412/** 1413 * Calls the passed in fetch wrapper and returns the response. 1414 * If the returned response has a status of 5xx, re-runs the function once and 1415 * returns the response. 1416 */ 1417function retryIfServerError(fn) { 1418 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1419 var result; 1420 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 1421 switch (_a.label) { 1422 case 0: return [4 /*yield*/, fn()]; 1423 case 1: 1424 result = _a.sent(); 1425 if (result.status >= 500 && result.status < 600) { 1426 // Internal Server Error. Retry request. 1427 return [2 /*return*/, fn()]; 1428 } 1429 return [2 /*return*/, result]; 1430 } 1431 }); 1432 }); 1433} 1434function getExpiresInFromResponseExpiresIn(responseExpiresIn) { 1435 // This works because the server will never respond with fractions of a second. 1436 return Number(responseExpiresIn.replace('s', '000')); 1437} 1438function getAuthorizationHeader(refreshToken) { 1439 return INTERNAL_AUTH_VERSION + " " + refreshToken; 1440} 1441 1442/** 1443 * @license 1444 * Copyright 2019 Google LLC 1445 * 1446 * Licensed under the Apache License, Version 2.0 (the "License"); 1447 * you may not use this file except in compliance with the License. 1448 * You may obtain a copy of the License at 1449 * 1450 * http://www.apache.org/licenses/LICENSE-2.0 1451 * 1452 * Unless required by applicable law or agreed to in writing, software 1453 * distributed under the License is distributed on an "AS IS" BASIS, 1454 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1455 * See the License for the specific language governing permissions and 1456 * limitations under the License. 1457 */ 1458function createInstallationRequest(appConfig, _a) { 1459 var fid = _a.fid; 1460 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1461 var endpoint, headers, body, request, response, responseValue, registeredInstallationEntry; 1462 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_b) { 1463 switch (_b.label) { 1464 case 0: 1465 endpoint = getInstallationsEndpoint(appConfig); 1466 headers = getHeaders(appConfig); 1467 body = { 1468 fid: fid, 1469 authVersion: INTERNAL_AUTH_VERSION, 1470 appId: appConfig.appId, 1471 sdkVersion: PACKAGE_VERSION 1472 }; 1473 request = { 1474 method: 'POST', 1475 headers: headers, 1476 body: JSON.stringify(body) 1477 }; 1478 return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })]; 1479 case 1: 1480 response = _b.sent(); 1481 if (!response.ok) return [3 /*break*/, 3]; 1482 return [4 /*yield*/, response.json()]; 1483 case 2: 1484 responseValue = _b.sent(); 1485 registeredInstallationEntry = { 1486 fid: responseValue.fid || fid, 1487 registrationStatus: 2 /* COMPLETED */, 1488 refreshToken: responseValue.refreshToken,
1489 authToken: extractAuthTokenInfoFromResponse(responseValue.authToken) 1490 }; 1491 return [2 /*return*/, registeredInstallationEntry]; 1492 case 3: return [4 /*yield*/, getErrorFromResponse('Create Installation', response)]; 1493 case 4: throw _b.sent(); 1494 } 1495 }); 1496 }); 1497} 1498 1499/** 1500 * @license 1501 * Copyright 2019 Google LLC 1502 * 1503 * Licensed under the Apache License, Version 2.0 (the "License"); 1504 * you may not use this file except in compliance with the License. 1505 * You may obtain a copy of the License at 1506 * 1507 * http://www.apache.org/licenses/LICENSE-2.0 1508 * 1509 * Unless required by applicable law or agreed to in writing, software 1510 * distributed under the License is distributed on an "AS IS" BASIS, 1511 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1512 * See the License for the specific language governing permissions and 1513 * limitations under the License. 1514 */ 1515/** Returns a promise that resolves after given time passes. */ 1516function sleep(ms) { 1517 return new Promise(function (resolve) { 1518 setTimeout(resolve, ms); 1519 }); 1520} 1521 1522/** 1523 * @license 1524 * Copyright 2019 Google LLC 1525 * 1526 * Licensed under the Apache License, Version 2.0 (the "License"); 1527 * you may not use this file except in compliance with the License. 1528 * You may obtain a copy of the License at 1529 * 1530 * http://www.apache.org/licenses/LICENSE-2.0 1531 * 1532 * Unless required by applicable law or agreed to in writing, software 1533 * distributed under the License is distributed on an "AS IS" BASIS, 1534 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1535 * See the License for the specific language governing permissions and 1536 * limitations under the License. 1537 */ 1538function bufferToBase64UrlSafe(array) { 1539 var b64 = btoa(String.fromCharCode.apply(String, Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__spread"])(array))); 1540 return b64.replace(/\+/g, '-').replace(/\//g, '_'); 1541} 1542 1543/** 1544 * @license 1545 * Copyright 2019 Google LLC 1546 * 1547 * Licensed under the Apache License, Version 2.0 (the "License"); 1548 * you may not use this file except in compliance with the License. 1549 * You may obtain a copy of the License at 1550 * 1551 * http://www.apache.org/licenses/LICENSE-2.0 1552 * 1553 * Unless required by applicable law or agreed to in writing, software 1554 * distributed under the License is distributed on an "AS IS" BASIS, 1555 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1556 * See the License for the specific language governing permissions and 1557 * limitations under the License. 1558 */ 1559var VALID_FID_PATTERN = /^[cdef][\w-]{21}$/; 1560var INVALID_FID = ''; 1561/** 1562 * Generates a new FID using random values from Web Crypto API. 1563 * Returns an empty string if FID generation fails for any reason. 1564 */ 1565function generateFid() { 1566 try { 1567 // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5 1568 // bytes. our implementation generates a 17 byte array instead. 1569 var fidByteArray = new Uint8Array(17); 1570 var crypto_1 = self.crypto || self.msCrypto; 1571 crypto_1.getRandomValues(fidByteArray); 1572 // Replace the first 4 random bits with the constant FID header of 0b0111. 1573 fidByteArray[0] = 112 + (fidByteArray[0] % 16); 1574 var fid = encode(fidByteArray); 1575 return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID; 1576 } 1577 catch (_a) { 1578 // FID generation errored 1579 return INVALID_FID; 1580 } 1581} 1582/** Converts a FID Uint8Array to a base64 string representation. */ 1583function encode(fidByteArray) { 1584 var b64String = bufferToBase64UrlSafe(fidByteArray); 1585 // Remove the 23rd character that was added because of the extra 4 bits at the 1586 // end of our 17 byte array, and the '=' padding. 1587 return b64String.substr(0, 22); 1588} 1589 1590/** 1591 * @license 1592 * Copyright 2019 Google LLC 1593 * 1594 * Licensed under the Apache License, Version 2.0 (the "License"); 1595 * you may not use this file except in compliance with the License. 1596 * You may obtain a copy of the License at 1597 * 1598 * http://www.apache.org/licenses/LICENSE-2.0 1599 * 1600 * Unless required by applicable law or agreed to in writing, softw
1600are 1601 * distributed under the License is distributed on an "AS IS" BASIS, 1602 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1603 * See the License for the specific language governing permissions and 1604 * limitations under the License. 1605 */ 1606/** Returns a string key that can be used to identify the app. */ 1607function getKey(appConfig) { 1608 return appConfig.appName + "!" + appConfig.appId; 1609} 1610 1611/** 1612 * @license 1613 * Copyright 2019 Google LLC 1614 * 1615 * Licensed under the Apache License, Version 2.0 (the "License"); 1616 * you may not use this file except in compliance with the License. 1617 * You may obtain a copy of the License at 1618 * 1619 * http://www.apache.org/licenses/LICENSE-2.0 1620 * 1621 * Unless required by applicable law or agreed to in writing, software 1622 * distributed under the License is distributed on an "AS IS" BASIS, 1623 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1624 * See the License for the specific language governing permissions and 1625 * limitations under the License. 1626 */ 1627var fidChangeCallbacks = new Map(); 1628/** 1629 * Calls the onIdChange callbacks with the new FID value, and broadcasts the 1630 * change to other tabs. 1631 */ 1632function fidChanged(appConfig, fid) { 1633 var key = getKey(appConfig); 1634 callFidChangeCallbacks(key, fid); 1635 broadcastFidChange(key, fid); 1636} 1637function addCallback(appConfig, callback) { 1638 // Open the broadcast channel if it's not already open, 1639 // to be able to listen to change events from other tabs. 1640 getBroadcastChannel(); 1641 var key = getKey(appConfig); 1642 var callbackSet = fidChangeCallbacks.get(key); 1643 if (!callbackSet) { 1644 callbackSet = new Set(); 1645 fidChangeCallbacks.set(key, callbackSet); 1646 } 1647 callbackSet.add(callback); 1648} 1649function removeCallback(appConfig, callback) { 1650 var key = getKey(appConfig); 1651 var callbackSet = fidChangeCallbacks.get(key); 1652 if (!callbackSet) { 1653 return; 1654 } 1655 callbackSet.delete(callback); 1656 if (callbackSet.size === 0) { 1657 fidChangeCallbacks.delete(key); 1658 } 1659 // Close broadcast channel if there are no more callbacks. 1660 closeBroadcastChannel(); 1661} 1662function callFidChangeCallbacks(key, fid) { 1663 var e_1, _a; 1664 var callbacks = fidChangeCallbacks.get(key); 1665 if (!callbacks) { 1666 return; 1667 } 1668 try { 1669 for (var callbacks_1 = Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__values"])(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) { 1670 var callback = callbacks_1_1.value; 1671 callback(fid); 1672 } 1673 } 1674 catch (e_1_1) { e_1 = { error: e_1_1 }; } 1675 finally { 1676 try { 1677 if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1); 1678 } 1679 finally { if (e_1) throw e_1.error; } 1680 } 1681} 1682function broadcastFidChange(key, fid) { 1683 var channel = getBroadcastChannel(); 1684 if (channel) { 1685 channel.postMessage({ key: key, fid: fid }); 1686 } 1687 closeBroadcastChannel(); 1688} 1689var broadcastChannel = null; 1690/** Opens and returns a BroadcastChannel if it is supported by the browser. */ 1691function getBroadcastChannel() { 1692 if (!broadcastChannel && 'BroadcastChannel' in self) { 1693 broadcastChannel = new BroadcastChannel('[Firebase] FID Change'); 1694 broadcastChannel.onmessage = function (e) { 1695 callFidChangeCallbacks(e.data.key, e.data.fid); 1696 }; 1697 } 1698 return broadcastChannel; 1699} 1700function closeBroadcastChannel() { 1701 if (fidChangeCallbacks.size === 0 && broadcastChannel) { 1702 broadcastChannel.close(); 1703 broadcastChannel = null; 1704 } 1705} 1706 1707/** 1708 * @license 1709 * Copyright 2019 Google LLC 1710 * 1711 * Licensed under the Apache License, Version 2.0 (the "License"); 1712 * you may not use this file except in compliance with the License. 1713 * You may obtain a copy of the License at 1714 * 1715 * http://www.apache.org/licenses/LICENSE-2.0 1716 * 1717 * Unless required by applicable law or agreed to in writing, software 1718 * distributed under the License is distributed on an "AS IS" BASIS, 1719 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1720 * See the License for the specific language governing permissions and 1721 * limitations under the License. 1722 */ 1723var DATABASE_NAME = 'firebase-installations-database'; 1724var DATABASE_VERSION = 1;
1725var OBJECT_STORE_NAME = 'firebase-installations-store'; 1726var dbPromise = null; 1727function getDbPromise() { 1728 if (!dbPromise) { 1729 dbPromise = Object(idb__WEBPACK_IMPORTED_MODULE_4__["openDb"])(DATABASE_NAME, DATABASE_VERSION, function (upgradeDB) { 1730 // We don't use 'break' in this switch statement, the fall-through 1731 // behavior is what we want, because if there are multiple versions between 1732 // the old version and the current version, we want ALL the migrations 1733 // that correspond to those versions to run, not only the last one. 1734 // eslint-disable-next-line default-case 1735 switch (upgradeDB.oldVersion) { 1736 case 0: 1737 upgradeDB.createObjectStore(OBJECT_STORE_NAME); 1738 } 1739 }); 1740 } 1741 return dbPromise; 1742} 1743/** Assigns or overwrites the record for the given key with the given value. */ 1744function set(appConfig, value) { 1745 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1746 var key, db, tx, objectStore, oldValue; 1747 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 1748 switch (_a.label) { 1749 case 0: 1750 key = getKey(appConfig); 1751 return [4 /*yield*/, getDbPromise()]; 1752 case 1: 1753 db = _a.sent(); 1754 tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); 1755 objectStore = tx.objectStore(OBJECT_STORE_NAME); 1756 return [4 /*yield*/, objectStore.get(key)]; 1757 case 2: 1758 oldValue = _a.sent(); 1759 return [4 /*yield*/, objectStore.put(value, key)]; 1760 case 3: 1761 _a.sent(); 1762 return [4 /*yield*/, tx.complete]; 1763 case 4: 1764 _a.sent(); 1765 if (!oldValue || oldValue.fid !== value.fid) { 1766 fidChanged(appConfig, value.fid); 1767 } 1768 return [2 /*return*/, value]; 1769 } 1770 }); 1771 }); 1772} 1773/** Removes record(s) from the objectStore that match the given key. */ 1774function remove(appConfig) { 1775 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1776 var key, db, tx; 1777 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 1778 switch (_a.label) { 1779 case 0: 1780 key = getKey(appConfig); 1781 return [4 /*yield*/, getDbPromise()]; 1782 case 1: 1783 db = _a.sent(); 1784 tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); 1785 return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).delete(key)]; 1786 case 2: 1787 _a.sent(); 1788 return [4 /*yield*/, tx.complete]; 1789 case 3: 1790 _a.sent(); 1791 return [2 /*return*/]; 1792 } 1793 }); 1794 }); 1795} 1796/** 1797 * Atomically updates a record with the result of updateFn, which gets 1798 * called with the current value. If newValue is undefined, the record is 1799 * deleted instead. 1800 * @return Updated value 1801 */ 1802function update(appConfig, updateFn) { 1803 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1804 var key, db, tx, store, oldValue, newValue; 1805 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 1806 switch (_a.label) { 1807 case 0: 1808 key = getKey(appConfig); 1809 return [4 /*yield*/, getDbPromise()]; 1810 case 1: 1811 db = _a.sent(); 1812 tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); 1813 store = tx.objectStore(OBJECT_STORE_NAME); 1814 return [4 /*yield*/, store.get(key)]; 1815 case 2: 1816 oldValue = _a.sent(); 1817 newValue = updateFn(oldValue); 1818 if (!(newValue === undefined)) return [3 /*break*/, 4]; 1819 return [4 /*yield*/, store.delete(key)]; 1820 case 3: 1821 _a.sent(); 1822 return [3 /*break*/, 6]; 1823 case 4: return [4 /*yield*/, store.put(newValue, key)]; 1824 case 5: 1825 _a.sent(); 1826 _a.label = 6; 1827 case 6: return [4 /*yield*/, tx.complete]; 1828 case 7: 1829 _a.sent(); 1830 if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) { 1831 fidChanged(appConfig, newValue.fid); 1832 } 1833 return [2 /*return*/, newValue]; 1834 } 1835 }); 1836 });
1837} 1838 1839/** 1840 * @license 1841 * Copyright 2019 Google LLC 1842 * 1843 * Licensed under the Apache License, Version 2.0 (the "License"); 1844 * you may not use this file except in compliance with the License. 1845 * You may obtain a copy of the License at 1846 * 1847 * http://www.apache.org/licenses/LICENSE-2.0 1848 * 1849 * Unless required by applicable law or agreed to in writing, software 1850 * distributed under the License is distributed on an "AS IS" BASIS, 1851 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1852 * See the License for the specific language governing permissions and 1853 * limitations under the License. 1854 */ 1855/** 1856 * Updates and returns the InstallationEntry from the database. 1857 * Also triggers a registration request if it is necessary and possible. 1858 */ 1859function getInstallationEntry(appConfig) { 1860 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1861 var registrationPromise, installationEntry; 1862 var _a; 1863 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_b) { 1864 switch (_b.label) { 1865 case 0: return [4 /*yield*/, update(appConfig, function (oldEntry) { 1866 var installationEntry = updateOrCreateInstallationEntry(oldEntry); 1867 var entryWithPromise = triggerRegistrationIfNecessary(appConfig, installationEntry); 1868 registrationPromise = entryWithPromise.registrationPromise; 1869 return entryWithPromise.installationEntry; 1870 })]; 1871 case 1: 1872 installationEntry = _b.sent(); 1873 if (!(installationEntry.fid === INVALID_FID)) return [3 /*break*/, 3]; 1874 _a = {}; 1875 return [4 /*yield*/, registrationPromise]; 1876 case 2: 1877 // FID generation failed. Waiting for the FID from the server. 1878 return [2 /*return*/, (_a.installationEntry = _b.sent(), _a)]; 1879 case 3: return [2 /*return*/, { 1880 installationEntry: installationEntry, 1881 registrationPromise: registrationPromise 1882 }]; 1883 } 1884 }); 1885 }); 1886} 1887/** 1888 * Creates a new Installation Entry if one does not exist. 1889 * Also clears timed out pending requests. 1890 */ 1891function updateOrCreateInstallationEntry(oldEntry) { 1892 var entry = oldEntry || { 1893 fid: generateFid(), 1894 registrationStatus: 0 /* NOT_STARTED */ 1895 }; 1896 return clearTimedOutRequest(entry); 1897} 1898/** 1899 * If the Firebase Installation is not registered yet, this will trigger the 1900 * registration and return an InProgressInstallationEntry. 1901 * 1902 * If registrationPromise does not exist, the installationEntry is guaranteed 1903 * to be registered. 1904 */ 1905function triggerRegistrationIfNecessary(appConfig, installationEntry) { 1906 if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) { 1907 if (!navigator.onLine) { 1908 // Registration required but app is offline. 1909 var registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */)); 1910 return { 1911 installationEntry: installationEntry, 1912 registrationPromise: registrationPromiseWithError 1913 }; 1914 } 1915 // Try registering. Change status to IN_PROGRESS. 1916 var inProgressEntry = { 1917 fid: installationEntry.fid, 1918 registrationStatus: 1 /* IN_PROGRESS */, 1919 registrationTime: Date.now() 1920 }; 1921 var registrationPromise = registerInstallation(appConfig, inProgressEntry); 1922 return { installationEntry: inProgressEntry, registrationPromise: registrationPromise }; 1923 } 1924 else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) { 1925 return { 1926 installationEntry: installationEntry, 1927 registrationPromise: waitUntilFidRegistration(appConfig) 1928 }; 1929 } 1930 else { 1931 return { installationEntry: installationEntry }; 1932 } 1933} 1934/** This will be executed only once for each new Firebase Installation. */ 1935function registerInstallation(appConfig, installationEntry) { 1936 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1937 var registeredInstallationEntry, e_1; 1938 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 1939 switch (_a.label) { 1940 case 0: 1941 _a.trys.push([0, 2, , 7]); 1942 return [4 /*yield*/, createInstallationRequest(appConfig, installationEntry)]; 1943 case 1: 1944 registeredInstallationEntry = _a.sent(); 1945 return [2 /*return*/, set(appConfig, registeredInstallationEntry)]; 1946 case 2: 1947 e_1 = _a.sent(); 1948 if (!(isServerError(e_1) && e_1.customData.serverCode === 409)) return [3 /*break*/, 4]; 1949 // Server returned a "FID can not be used" error. 1950 // Generate a new ID next time. 1951 return [4 /*yield*/, remove(appConfig)]; 1952 case 3: 1953 // Server returned a "FID can not be used" error. 1954 // Generate a new ID next time. 1955 _a.sent(); 1956 return [3 /*break*/, 6]; 1957 case 4: 1958 // Registration failed. Set FID as not registered. 1959 return [4 /*yield*/, set(appConfig, { 1960 fid: installationEntry.fid, 1961 registrationStatus: 0 /* NOT_STARTED */ 1962 })]; 1963 case 5: 1964 // Registration failed. Set FID as not registered. 1965 _a.sent(); 1966 _a.label = 6; 1967 case 6: throw e_1; 1968 case 7: return [2 /*return*/]; 1969 } 1970 }); 1971 });
1972} 1973/** Call if FID registration is pending in another request. */ 1974function waitUntilFidRegistration(appConfig) { 1975 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 1976 var entry, _a, installationEntry, registrationPromise; 1977 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_b) { 1978 switch (_b.label) { 1979 case 0: return [4 /*yield*/, updateInstallationRequest(appConfig)]; 1980 case 1: 1981 entry = _b.sent(); 1982 _b.label = 2; 1983 case 2: 1984 if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5]; 1985 // createInstallation request still in progress. 1986 return [4 /*yield*/, sleep(100)]; 1987 case 3: 1988 // createInstallation request still in progress. 1989 _b.sent(); 1990 return [4 /*yield*/, updateInstallationRequest(appConfig)]; 1991 case 4: 1992 entry = _b.sent(); 1993 return [3 /*break*/, 2]; 1994 case 5: 1995 if (!(entry.registrationStatus === 0 /* NOT_STARTED */)) return [3 /*break*/, 7]; 1996 return [4 /*yield*/, getInstallationEntry(appConfig)]; 1997 case 6: 1998 _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise; 1999 if (registrationPromise) { 2000 return [2 /*return*/, registrationPromise]; 2001 } 2002 else { 2003 // if there is no registrationPromise, entry is registered. 2004 return [2 /*return*/, installationEntry]; 2005 } 2006 case 7: return [2 /*return*/, entry]; 2007 } 2008 }); 2009 }); 2010} 2011/** 2012 * Called only if there is a CreateInstallation request in progress. 2013 * 2014 * Updates the InstallationEntry in the DB based on the status of the 2015 * CreateInstallation request. 2016 * 2017 * Returns the updated InstallationEntry. 2018 */ 2019function updateInstallationRequest(appConfig) { 2020 return update(appConfig, function (oldEntry) { 2021 if (!oldEntry) { 2022 throw ERROR_FACTORY.create("installation-not-found" /* INSTALLATION_NOT_FOUND */); 2023 } 2024 return clearTimedOutRequest(oldEntry); 2025 }); 2026} 2027function clearTimedOutRequest(entry) { 2028 if (hasInstallationRequestTimedOut(entry)) { 2029 return { 2030 fid: entry.fid, 2031 registrationStatus: 0 /* NOT_STARTED */ 2032 }; 2033 } 2034 return entry; 2035} 2036function hasInstallationRequestTimedOut(installationEntry) { 2037 return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ && 2038 installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()); 2039} 2040 2041/** 2042 * @license 2043 * Copyright 2019 Google LLC 2044 * 2045 * Licensed under the Apache License, Version 2.0 (the "License"); 2046 * you may not use this file except in compliance with the License. 2047 * You may obtain a copy of the License at 2048 * 2049 * http://www.apache.org/licenses/LICENSE-2.0 2050 * 2051 * Unless required by applicable law or agreed to in writing, software 2052 * distributed under the License is distributed on an "AS IS" BASIS, 2053 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2054 * See the License for the specific language governing permissions and 2055 * limitations under the License. 2056 */ 2057function generateAuthTokenRequest(_a, installationEntry) { 2058 var appConfig = _a.appConfig, platformLoggerProvider = _a.platformLoggerProvider; 2059 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2060 var endpoint, headers, platformLogger, body, request, response, responseValue, completedAuthToken; 2061 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_b) { 2062 switch (_b.label) { 2063 case 0: 2064 endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry); 2065 headers = getHeadersWithAuth(appConfig, installationEntry); 2066 platformLogger = platformLoggerProvider.getImmediate({ 2067 optional: true 2068 }); 2069 if (platformLogger) { 2070 headers.append('x-firebase-client', platformLogger.getPlatformInfoString()); 2071 } 2072 body = { 2073 installation: { 2074 sdkVersion: PACKAGE_VERSION 2075 } 2076 }; 2077 request = { 2078 method: 'POST', 2079 headers: headers, 2080 body: JSON.stringify(body) 2081 }; 2082 return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })]; 2083 case 1: 2084 response = _b.sent(); 2085 if (!response.ok) return [3 /*break*/, 3]; 2086 return [4 /*yield*/, response.json()]; 2087 case 2: 2088 responseValue = _b.sent(); 2089 completedAuthToken = extractAuthTokenInfoFromRe
2089sponse(responseValue); 2090 return [2 /*return*/, completedAuthToken]; 2091 case 3: return [4 /*yield*/, getErrorFromResponse('Generate Auth Token', response)]; 2092 case 4: throw _b.sent(); 2093 } 2094 }); 2095 }); 2096} 2097function getGenerateAuthTokenEndpoint(appConfig, _a) { 2098 var fid = _a.fid; 2099 return getInstallationsEndpoint(appConfig) + "/" + fid + "/authTokens:generate"; 2100} 2101 2102/** 2103 * @license 2104 * Copyright 2019 Google LLC 2105 * 2106 * Licensed under the Apache License, Version 2.0 (the "License"); 2107 * you may not use this file except in compliance with the License. 2108 * You may obtain a copy of the License at 2109 * 2110 * http://www.apache.org/licenses/LICENSE-2.0 2111 * 2112 * Unless required by applicable law or agreed to in writing, software 2113 * distributed under the License is distributed on an "AS IS" BASIS, 2114 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2115 * See the License for the specific language governing permissions and 2116 * limitations under the License. 2117 */ 2118/** 2119 * Returns a valid authentication token for the installation. Generates a new 2120 * token if one doesn't exist, is expired or about to expire. 2121 * 2122 * Should only be called if the Firebase Installation is registered. 2123 */ 2124function refreshAuthToken(dependencies, forceRefresh) { 2125 if (forceRefresh === void 0) { forceRefresh = false; } 2126 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2127 var tokenPromise, entry, authToken, _a; 2128 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_b) { 2129 switch (_b.label) { 2130 case 0: return [4 /*yield*/, update(dependencies.appConfig, function (oldEntry) { 2131 if (!isEntryRegistered(oldEntry)) { 2132 throw ERROR_FACTORY.create("not-registered" /* NOT_REGISTERED */); 2133 } 2134 var oldAuthToken = oldEntry.authToken; 2135 if (!forceRefresh && isAuthTokenValid(oldAuthToken)) { 2136 // There is a valid token in the DB. 2137 return oldEntry; 2138 } 2139 else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) { 2140 // There already is a token request in progress. 2141 tokenPromise = waitUntilAuthTokenRequest(dependencies, forceRefresh); 2142 return oldEntry; 2143 } 2144 else { 2145 // No token or token expired. 2146 if (!navigator.onLine) { 2147 throw ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */); 2148 } 2149 var inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry); 2150 tokenPromise = fetchAuthTokenFromServer(dependencies, inProgressEntry); 2151 return inProgressEntry; 2152 } 2153 })]; 2154 case 1: 2155 entry = _b.sent(); 2156 if (!tokenPromise) return [3 /*break*/, 3]; 2157 return [4 /*yield*/, tokenPromise]; 2158 case 2: 2159 _a = _b.sent(); 2160 return [3 /*break*/, 4]; 2161 case 3: 2162 _a = entry.authToken; 2163 _b.label = 4; 2164 case 4: 2165 authToken = _a; 2166 return [2 /*return*/, authToken]; 2167 } 2168 }); 2169 }); 2170} 2171/** 2172 * Call only if FID is registered and Auth Token request is in progress. 2173 * 2174 * Waits until the current pending request finishes. If the request times out, 2175 * tries once in this thread as well. 2176 */ 2177function waitUntilAuthTokenRequest(dependencies, forceRefresh) { 2178 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2179 var entry, authToken; 2180 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 2181 switch (_a.label) { 2182 case 0: return [4 /*yield*/, updateAuthTokenRequest(dependencies.appConfig)]; 2183 case 1: 2184 entry = _a.sent(); 2185 _a.label = 2; 2186 case 2: 2187 if (!(entry.authToken.requestStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5]; 2188 // generateAuthToken still in progress. 2189 return [4 /*yield*/, sleep(100)]; 2190 case 3: 2191 // generateAuthToken still in progress. 2192 _a.sent(); 2193 return [4 /*yield*/, updateAuthTokenRequest(dependencies.appConfig)]; 2194 case 4: 2195 entry = _a.sent(); 2196 return [3 /*break*/, 2]; 2197 case 5: 2198 authToken = entry.authToken; 2199 if (authToken.requestStatus === 0 /* NOT_STARTED */) { 2200 // The request timed out or failed in a different call. Try again. 2201 return [2 /*return*/, refreshAuthToken(dependencies, forceRefresh)]; 2202 } 2203 else { 2204 return [2 /*return*/, authToken]; 2205 } 2206 } 2207 }); 2208 });
2209} 2210/** 2211 * Called only if there is a GenerateAuthToken request in progress. 2212 * 2213 * Updates the InstallationEntry in the DB based on the status of the 2214 * GenerateAuthToken request. 2215 * 2216 * Returns the updated InstallationEntry. 2217 */ 2218function updateAuthTokenRequest(appConfig) { 2219 return update(appConfig, function (oldEntry) { 2220 if (!isEntryRegistered(oldEntry)) { 2221 throw ERROR_FACTORY.create("not-registered" /* NOT_REGISTERED */); 2222 } 2223 var oldAuthToken = oldEntry.authToken; 2224 if (hasAuthTokenRequestTimedOut(oldAuthToken)) { 2225 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__assign"])({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } }); 2226 } 2227 return oldEntry; 2228 }); 2229} 2230function fetchAuthTokenFromServer(dependencies, installationEntry) { 2231 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2232 var authToken, updatedInstallationEntry, e_1, updatedInstallationEntry; 2233 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 2234 switch (_a.label) { 2235 case 0: 2236 _a.trys.push([0, 3, , 8]); 2237 return [4 /*yield*/, generateAuthTokenRequest(dependencies, installationEntry)]; 2238 case 1: 2239 authToken = _a.sent(); 2240 updatedInstallationEntry = Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__assign"])({}, installationEntry), { authToken: authToken }); 2241 return [4 /*yield*/, set(dependencies.appConfig, updatedInstallationEntry)]; 2242 case 2: 2243 _a.sent(); 2244 return [2 /*return*/, authToken]; 2245 case 3: 2246 e_1 = _a.sent(); 2247 if (!(isServerError(e_1) && 2248 (e_1.customData.serverCode === 401 || e_1.customData.serverCode === 404))) return [3 /*break*/, 5]; 2249 // Server returned a "FID not found" or a "Invalid authentication" error. 2250 // Generate a new ID next time. 2251 return [4 /*yield*/, remove(dependencies.appConfig)]; 2252 case 4: 2253 // Server returned a "FID not found" or a "Invalid authentication" error. 2254 // Generate a new ID next time. 2255 _a.sent(); 2256 return [3 /*break*/, 7]; 2257 case 5: 2258 updatedInstallationEntry = Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__assign"])({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } }); 2259 return [4 /*yield*/, set(dependencies.appConfig, updatedInstallationEntry)]; 2260 case 6: 2261 _a.sent(); 2262 _a.label = 7; 2263 case 7: throw e_1; 2264 case 8: return [2 /*return*/]; 2265 } 2266 }); 2267 }); 2268} 2269function isEntryRegistered(installationEntry) { 2270 return (installationEntry !== undefined && 2271 installationEntry.registrationStatus === 2 /* COMPLETED */); 2272} 2273function isAuthTokenValid(authToken) { 2274 return (authToken.requestStatus === 2 /* COMPLETED */ && 2275 !isAuthTokenExpired(authToken)); 2276} 2277function isAuthTokenExpired(authToken) { 2278 var now = Date.now(); 2279 return (now < authToken.creationTime || 2280 authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER); 2281} 2282/** Returns an updated InstallationEntry with an InProgressAuthToken. */ 2283function makeAuthTokenRequestInProgressEntry(oldEntry) { 2284 var inProgressAuthToken = { 2285 requestStatus: 1 /* IN_PROGRESS */, 2286 requestTime: Date.now() 2287 }; 2288 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__assign"])({}, oldEntry), { authToken: inProgressAuthToken }); 2289} 2290function hasAuthTokenRequestTimedOut(authToken) { 2291 return (authToken.requestStatus === 1 /* IN_PROGRESS */ && 2292 authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()); 2293} 2294 2295/** 2296 * @license 2297 * Copyright 2019 Google LLC 2298 * 2299 * Licensed under the Apache License, Version 2.0 (the "License");
2300 * you may not use this file except in compliance with the License. 2301 * You may obtain a copy of the License at 2302 * 2303 * http://www.apache.org/licenses/LICENSE-2.0 2304 * 2305 * Unless required by applicable law or agreed to in writing, software 2306 * distributed under the License is distributed on an "AS IS" BASIS, 2307 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2308 * See the License for the specific language governing permissions and 2309 * limitations under the License. 2310 */ 2311function getId(dependencies) { 2312 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2313 var _a, installationEntry, registrationPromise; 2314 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_b) { 2315 switch (_b.label) { 2316 case 0: return [4 /*yield*/, getInstallationEntry(dependencies.appConfig)]; 2317 case 1: 2318 _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise; 2319 if (registrationPromise) { 2320 registrationPromise.catch(console.error); 2321 } 2322 else { 2323 // If the installation is already registered, update the authentication 2324 // token if needed. 2325 refreshAuthToken(dependencies).catch(console.error); 2326 } 2327 return [2 /*return*/, installationEntry.fid]; 2328 } 2329 }); 2330 }); 2331} 2332 2333/** 2334 * @license 2335 * Copyright 2019 Google LLC 2336 * 2337 * Licensed under the Apache License, Version 2.0 (the "License"); 2338 * you may not use this file except in compliance with the License. 2339 * You may obtain a copy of the License at 2340 * 2341 * http://www.apache.org/licenses/LICENSE-2.0 2342 * 2343 * Unless required by applicable law or agreed to in writing, software 2344 * distributed under the License is distributed on an "AS IS" BASIS, 2345 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2346 * See the License for the specific language governing permissions and 2347 * limitations under the License. 2348 */ 2349function getToken(dependencies, forceRefresh) { 2350 if (forceRefresh === void 0) { forceRefresh = false; } 2351 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2352 var authToken; 2353 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 2354 switch (_a.label) { 2355 case 0: return [4 /*yield*/, completeInstallationRegistration(dependencies.appConfig)]; 2356 case 1: 2357 _a.sent(); 2358 return [4 /*yield*/, refreshAuthToken(dependencies, forceRefresh)]; 2359 case 2: 2360 authToken = _a.sent(); 2361 return [2 /*return*/, authToken.token]; 2362 } 2363 }); 2364 }); 2365} 2366function completeInstallationRegistration(appConfig) { 2367 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2368 var registrationPromise; 2369 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 2370 switch (_a.label) { 2371 case 0: return [4 /*yield*/, getInstallationEntry(appConfig)]; 2372 case 1: 2373 registrationPromise = (_a.sent()).registrationPromise; 2374 if (!registrationPromise) return [3 /*break*/, 3]; 2375 // A createInstallation request is in progress. Wait until it finishes. 2376 return [4 /*yield*/, registrationPromise]; 2377 case 2: 2378 // A createInstallation request is in progress. Wait until it finishes. 2379 _a.sent(); 2380 _a.label = 3; 2381 case 3: return [2 /*return*/]; 2382 } 2383 }); 2384 }); 2385} 2386 2387/** 2388 * @license 2389 * Copyright 2019 Google LLC 2390 * 2391 * Licensed under the Apache License, Version 2.0 (the "License");
2392 * you may not use this file except in compliance with the License. 2393 * You may obtain a copy of the License at 2394 * 2395 * http://www.apache.org/licenses/LICENSE-2.0 2396 * 2397 * Unless required by applicable law or agreed to in writing, software 2398 * distributed under the License is distributed on an "AS IS" BASIS, 2399 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2400 * See the License for the specific language governing permissions and 2401 * limitations under the License. 2402 */ 2403function deleteInstallationRequest(appConfig, installationEntry) { 2404 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2405 var endpoint, headers, request, response; 2406 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 2407 switch (_a.label) { 2408 case 0: 2409 endpoint = getDeleteEndpoint(appConfig, installationEntry); 2410 headers = getHeadersWithAuth(appConfig, installationEntry); 2411 request = { 2412 method: 'DELETE', 2413 headers: headers 2414 }; 2415 return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })]; 2416 case 1: 2417 response = _a.sent(); 2418 if (!!response.ok) return [3 /*break*/, 3]; 2419 return [4 /*yield*/, getErrorFromResponse('Delete Installation', response)]; 2420 case 2: throw _a.sent(); 2421 case 3: return [2 /*return*/]; 2422 } 2423 }); 2424 }); 2425} 2426function getDeleteEndpoint(appConfig, _a) { 2427 var fid = _a.fid; 2428 return getInstallationsEndpoint(appConfig) + "/" + fid; 2429} 2430 2431/** 2432 * @license 2433 * Copyright 2019 Google LLC 2434 * 2435 * Licensed under the Apache License, Version 2.0 (the "License"); 2436 * you may not use this file except in compliance with the License. 2437 * You may obtain a copy of the License at 2438 * 2439 * http://www.apache.org/licenses/LICENSE-2.0 2440 * 2441 * Unless required by applicable law or agreed to in writing, software 2442 * distributed under the License is distributed on an "AS IS" BASIS, 2443 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2444 * See the License for the specific language governing permissions and 2445 * limitations under the License. 2446 */ 2447function deleteInstallation(dependencies) { 2448 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__awaiter"])(this, void 0, void 0, function () { 2449 var appConfig, entry; 2450 return Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__generator"])(this, function (_a) { 2451 switch (_a.label) { 2452 case 0: 2453 appConfig = dependencies.appConfig; 2454 return [4 /*yield*/, update(appConfig, function (oldEntry) { 2455 if (oldEntry && oldEntry.registrationStatus === 0 /* NOT_STARTED */) { 2456 // Delete the unregistered entry without sending a deleteInstallation request. 2457 return undefined; 2458 } 2459 return oldEntry; 2460 })]; 2461 case 1: 2462 entry = _a.sent(); 2463 if (!entry) return [3 /*break*/, 6]; 2464 if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 2]; 2465 // Can't delete while trying to register. 2466 throw ERROR_FACTORY.create("delete-pending-registration" /* DELETE_PENDING_REGISTRATION */); 2467 case 2: 2468 if (!(entry.registrationStatus === 2 /* COMPLETED */)) return [3 /*break*/, 6]; 2469 if (!!navigator.onLine) return [3 /*break*/, 3]; 2470 throw ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */); 2471 case 3: return [4 /*yield*/, deleteInstallationRequest(appConfig, entry)]; 2472 case 4: 2473 _a.sent(); 2474 return [4 /*yield*/, remove(appConfig)]; 2475 case 5: 2476 _a.sent(); 2477 _a.label = 6; 2478 case 6: return [2 /*return*/]; 2479 } 2480 }); 2481 });
2482} 2483 2484/** 2485 * @license 2486 * Copyright 2019 Google LLC 2487 * 2488 * Licensed under the Apache License, Version 2.0 (the "License"); 2489 * you may not use this file except in compliance with the License. 2490 * You may obtain a copy of the License at 2491 * 2492 * http://www.apache.org/licenses/LICENSE-2.0 2493 * 2494 * Unless required by applicable law or agreed to in writing, software 2495 * distributed under the License is distributed on an "AS IS" BASIS, 2496 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2497 * See the License for the specific language governing permissions and 2498 * limitations under the License. 2499 */ 2500/** 2501 * Sets a new callback that will get called when Installation ID changes. 2502 * Returns an unsubscribe function that will remove the callback when called. 2503 */ 2504function onIdChange(_a, callback) { 2505 var appConfig = _a.appConfig; 2506 addCallback(appConfig, callback); 2507 return function () { 2508 removeCallback(appConfig, callback); 2509 }; 2510} 2511 2512/** 2513 * @license 2514 * Copyright 2019 Google LLC 2515 * 2516 * Licensed under the Apache License, Version 2.0 (the "License"); 2517 * you may not use this file except in compliance with the License. 2518 * You may obtain a copy of the License at 2519 * 2520 * http://www.apache.org/licenses/LICENSE-2.0 2521 * 2522 * Unless required by applicable law or agreed to in writing, software 2523 * distributed under the License is distributed on an "AS IS" BASIS, 2524 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2525 * See the License for the specific language governing permissions and 2526 * limitations under the License. 2527 */ 2528function extractAppConfig(app) { 2529 var e_1, _a; 2530 if (!app || !app.options) { 2531 throw getMissingValueError('App Configuration'); 2532 } 2533 if (!app.name) { 2534 throw getMissingValueError('App Name'); 2535 } 2536 // Required app config keys 2537 var configKeys = [ 2538 'projectId', 2539 'apiKey', 2540 'appId' 2541 ]; 2542 try { 2543 for (var configKeys_1 = Object(tslib__WEBPACK_IMPORTED_MODULE_2__["__values"])(configKeys), configKeys_1_1 = configKeys_1.next(); !configKeys_1_1.done; configKeys_1_1 = configKeys_1.next()) { 2544 var keyName = configKeys_1_1.value; 2545 if (!app.options[keyName]) { 2546 throw getMissingValueError(keyName); 2547 } 2548 } 2549 } 2550 catch (e_1_1) { e_1 = { error: e_1_1 }; } 2551 finally { 2552 try { 2553 if (configKeys_1_1 && !configKeys_1_1.done && (_a = configKeys_1.return)) _a.call(configKeys_1); 2554 } 2555 finally { if (e_1) throw e_1.error; } 2556 } 2557 return { 2558 appName: app.name, 2559 projectId: app.options.projectId, 2560 apiKey: app.options.apiKey, 2561 appId: app.options.appId 2562 }; 2563} 2564function getMissingValueError(valueName) { 2565 return ERROR_FACTORY.create("missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */, { 2566 valueName: valueName 2567 }); 2568} 2569 2570/** 2571 * @license 2572 * Copyright 2019 Google LLC 2573 * 2574 * Licensed under the Apache License, Version 2.0 (the "License"); 2575 * you may not use this file except in compliance with the License. 2576 * You may obtain a copy of the License at 2577 * 2578 * http://www.apache.org/licenses/LICENSE-2.0 2579 * 2580 * Unless required by applicable law or agreed to in writing, software 2581 * distributed under the License is distributed on an "AS IS" BASIS, 2582 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 2583 * See the License for the specific language governing permissions and 2584 * limitations under the License. 2585 */ 2586function registerInstallations(instance) { 2587 var installationsName = 'installations'; 2588 instance.INTERNAL.registerComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_1__["Component"](installationsName, function (container) { 2589 var app = container.getProvider('app').getImmediate(); 2590 // Throws if app isn't configured properly. 2591 var appConfig = extractAppConfig(app); 2592 var platformLoggerProvider = container.getProvider('platform-logger'); 2593 var dependencies = { 2594 appConfig: appConfig, 2595 platformLoggerProvider: platformLoggerProvider 2596 }; 2597 var installations = { 2598 app: app, 2599 getId: function () { return getId(dependencies); }, 2600 getToken: function (forceRefresh) { 2601 return getToken(dependencies, forceRefresh); 2602 }, 2603 delete: function () { return deleteInstallation(dependencies); }, 2604 onIdChange: function (callback) { 2605 return onIdChange(dependencies, callback); 2606 } 2607 }; 2608 return installations; 2609 }, "PUBLIC" /* PUBLIC */)); 2610 instance.registerVersion(name, version); 2611} 2612registerInstallations(_firebase_app__WEBPACK_IMPORTED_MODULE_0__["default"]); 2613 2614 2615//# sourceMappingURL=index.esm.js.map 2616 2617 2618/***/ }), 2619 2620/***/ "nbvr": 2621/*!***************************************!*\ 2622 !*** ./node_modules/idb/build/idb.js ***! 2623 \***************************************/ 2624/*! no static exports found */ 2625/***/ (function(module, exports, __webpack_require__) { 2626 2627(function (global, factory) { 2628 true ? factory(exports) : 2629 undefined; 2630}(this, function (exports) { 'use strict'; 2631 2632 function toArray(arr) { 2633 return Array.prototype.slice.call(arr); 2634 } 2635 2636 function promisifyRequest(request) { 2637 return new Promise(function(resolve, reject) { 2638 request.onsuccess = function() { 2639 resolve(request.result); 2640 }; 2641 2642 request.onerror = function() { 2643 reject(request.error); 2644 }; 2645 }); 2646 } 2647 2648 function promisifyRequestCall(obj, method, args) { 2649 var request; 2650 var p = new Promise(function(resolve, reject) { 2651 request = obj[method].apply(obj, args); 2652 promisifyRequest(request).then(resolve, reject); 2653 }); 2654 2655 p.request = request; 2656 return p; 2657 } 2658 2659 function promisifyCursorRequestCall(obj, method, args) { 2660 var p = promisifyRequestCall(obj, method, args); 2661 return p.then(function(value) { 2662 if (!value) return; 2663 return new Cursor(value, p.request); 2664 }); 2665 } 2666 2667 function proxyProperties(ProxyClass, targetProp, properties) {
vendor: 6,937 bytes, lines 2668-2947
2668 properties.forEach(function(prop) { 2669 Object.defineProperty(ProxyClass.prototype, prop, { 2670 get: function() { 2671 return this[targetProp][prop]; 2672 }, 2673 set: function(val) { 2674 this[targetProp][prop] = val; 2675 } 2676 }); 2677 }); 2678 } 2679 2680 function proxyRequestMethods(ProxyClass, targetProp, Constructor, properties) { 2681 properties.forEach(function(prop) { 2682 if (!(prop in Constructor.prototype)) return; 2683 ProxyClass.prototype[prop] = function() { 2684 return promisifyRequestCall(this[targetProp], prop, arguments); 2685 }; 2686 }); 2687 } 2688 2689 function proxyMethods(ProxyClass, targetProp, Constructor, properties) { 2690 properties.forEach(function(prop) { 2691 if (!(prop in Constructor.prototype)) return; 2692 ProxyClass.prototype[prop] = function() { 2693 return this[targetProp][prop].apply(this[targetProp], arguments); 2694 }; 2695 }); 2696 } 2697 2698 function proxyCursorRequestMethods(ProxyClass, targetProp, Constructor, properties) { 2699 properties.forEach(function(prop) { 2700 if (!(prop in Constructor.prototype)) return; 2701 ProxyClass.prototype[prop] = function() { 2702 return promisifyCursorRequestCall(this[targetProp], prop, arguments); 2703 }; 2704 }); 2705 } 2706 2707 function Index(index) { 2708 this._index = index; 2709 } 2710 2711 proxyProperties(Index, '_index', [ 2712 'name', 2713 'keyPath', 2714 'multiEntry', 2715 'unique' 2716 ]); 2717 2718 proxyRequestMethods(Index, '_index', IDBIndex, [ 2719 'get', 2720 'getKey', 2721 'getAll', 2722 'getAllKeys', 2723 'count' 2724 ]); 2725 2726 proxyCursorRequestMethods(Index, '_index', IDBIndex, [ 2727 'openCursor', 2728 'openKeyCursor' 2729 ]); 2730 2731 function Cursor(cursor, request) { 2732 this._cursor = cursor; 2733 this._request = request; 2734 } 2735 2736 proxyProperties(Cursor, '_cursor', [ 2737 'direction', 2738 'key', 2739 'primaryKey', 2740 'value' 2741 ]); 2742 2743 proxyRequestMethods(Cursor, '_cursor', IDBCursor, [ 2744 'update', 2745 'delete' 2746 ]); 2747 2748 // proxy 'next' methods 2749 ['advance', 'continue', 'continuePrimaryKey'].forEach(function(methodName) { 2750 if (!(methodName in IDBCursor.prototype)) return; 2751 Cursor.prototype[methodName] = function() { 2752 var cursor = this; 2753 var args = arguments; 2754 return Promise.resolve().then(function() { 2755 cursor._cursor[methodName].apply(cursor._cursor, args); 2756 return promisifyRequest(cursor._request).then(function(value) { 2757 if (!value) return; 2758 return new Cursor(value, cursor._request); 2759 }); 2760 }); 2761 }; 2762 }); 2763 2764 function ObjectStore(store) { 2765 this._store = store; 2766 } 2767 2768 ObjectStore.prototype.createIndex = function() { 2769 return new Index(this._store.createIndex.apply(this._store, arguments)); 2770 }; 2771 2772 ObjectStore.prototype.index = function() { 2773 return new Index(this._store.index.apply(this._store, arguments)); 2774 }; 2775 2776 proxyProperties(ObjectStore, '_store', [ 2777 'name', 2778 'keyPath', 2779 'indexNames', 2780 'autoIncrement' 2781 ]); 2782 2783 proxyRequestMethods(ObjectStore, '_store', IDBObjectStore, [ 2784 'put', 2785 'add', 2786 'delete', 2787 'clear', 2788 'get', 2789 'getAll', 2790 'getKey', 2791 'getAllKeys', 2792 'count' 2793 ]); 2794 2795 proxyCursorRequestMethods(ObjectStore, '_store', IDBObjectStore, [ 2796 'openCursor', 2797 'openKeyCursor' 2798 ]); 2799 2800 proxyMethods(ObjectStore, '_store', IDBObjectStore, [ 2801 'deleteIndex' 2802 ]); 2803 2804 function Transaction(idbTransaction) { 2805 this._tx = idbTransaction; 2806 this.complete = new Promise(function(resolve, reject) { 2807 idbTransaction.oncomplete = function() { 2808 resolve(); 2809 }; 2810 idbTransaction.onerror = function() { 2811 reject(idbTransaction.error); 2812 }; 2813 idbTransaction.onabort = function() { 2814 reject(idbTransaction.error); 2815 }; 2816 }); 2817 } 2818 2819 Transaction.prototype.objectStore = function() { 2820 return new ObjectStore(this._tx.objectStore.apply(this._tx, arguments)); 2821 }; 2822 2823 proxyProperties(Transaction, '_tx', [ 2824 'objectStoreNames', 2825 'mode' 2826 ]); 2827 2828 proxyMethods(Transaction, '_tx', IDBTransaction, [ 2829 'abort' 2830 ]); 2831 2832 function UpgradeDB(db, oldVersion, transaction) { 2833 this._db = db; 2834 this.oldVersion = oldVersion; 2835 this.transaction = new Transaction(transaction); 2836 } 2837 2838 UpgradeDB.prototype.createObjectStore = function() { 2839 return new ObjectStore(this._db.createObjectStore.apply(this._db, arguments)); 2840 }; 2841 2842 proxyProperties(UpgradeDB, '_db', [ 2843 'name', 2844 'version', 2845 'objectStoreNames' 2846 ]); 2847 2848 proxyMethods(UpgradeDB, '_db', IDBDatabase, [ 2849 'deleteObjectStore', 2850 'close' 2851 ]); 2852 2853 function DB(db) { 2854 this._db = db; 2855 } 2856 2857 DB.prototype.transaction = function() { 2858 return new Transaction(this._db.transaction.apply(this._db, arguments)); 2859 }; 2860 2861 proxyProperties(DB, '_db', [ 2862 'name', 2863 'version', 2864 'objectStoreNames' 2865 ]); 2866 2867 proxyMethods(DB, '_db', IDBDatabase, [ 2868 'close' 2869 ]); 2870 2871 // Add cursor iterators 2872 // TODO: remove this once browsers do the right thing with promises 2873 ['openCursor', 'openKeyCursor'].forEach(function(funcName) { 2874 [ObjectStore, Index].forEach(function(Constructor) { 2875 // Don't create iterateKeyCursor if openKeyCursor doesn't exist. 2876 if (!(funcName in Constructor.prototype)) return; 2877 2878 Constructor.prototype[funcName.replace('open', 'iterate')] = function() { 2879 var args = toArray(arguments); 2880 var callback = args[args.length - 1]; 2881 var nativeObject = this._store || this._index; 2882 var request = nativeObject[funcName].apply(nativeObject, args.slice(0, -1)); 2883 request.onsuccess = function() { 2884 callback(request.result); 2885 }; 2886 }; 2887 }); 2888 }); 2889 2890 // polyfill getAll 2891 [Index, ObjectStore].forEach(function(Constructor) { 2892 if (Constructor.prototype.getAll) return; 2893 Constructor.prototype.getAll = function(query, count) { 2894 var instance = this; 2895 var items = []; 2896 2897 return new Promise(function(resolve) { 2898 instance.iterateCursor(query, function(cursor) { 2899 if (!cursor) { 2900 resolve(items); 2901 return; 2902 } 2903 items.push(cursor.value); 2904 2905 if (count !== undefined && items.length == count) { 2906 resolve(items); 2907 return; 2908 } 2909 cursor.continue(); 2910 }); 2911 }); 2912 }; 2913 }); 2914 2915 function openDb(name, version, upgradeCallback) { 2916 var p = promisifyRequestCall(indexedDB, 'open', [name, version]); 2917 var request = p.request; 2918 2919 if (request) { 2920 request.onupgradeneeded = function(event) { 2921 if (upgradeCallback) { 2922 upgradeCallback(new UpgradeDB(request.result, event.oldVersion, request.transaction)); 2923 } 2924 }; 2925 } 2926 2927 return p.then(function(db) { 2928 return new DB(db); 2929 }); 2930 } 2931 2932 function deleteDb(name) { 2933 return promisifyRequestCall(indexedDB, 'deleteDatabase', [name]); 2934 } 2935 2936 exports.openDb = openDb; 2937 exports.deleteDb = deleteDb; 2938 2939 Object.defineProperty(exports, '__esModule', { value: true }); 2940 2941})); 2942 2943 2944/***/ }) 2945 2946}]); 2947//# sourceMappingURL=firebase-analytics.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.