GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

14422 lines
572 KiB

2 months ago
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var Websocket = require('faye-websocket');
  4. var util = require('@firebase/util');
  5. var tslib = require('tslib');
  6. var logger$1 = require('@firebase/logger');
  7. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  8. var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket);
  9. /**
  10. * @license
  11. * Copyright 2017 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. var PROTOCOL_VERSION = '5';
  26. var VERSION_PARAM = 'v';
  27. var TRANSPORT_SESSION_PARAM = 's';
  28. var REFERER_PARAM = 'r';
  29. var FORGE_REF = 'f';
  30. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  31. // firebase.corp.google.com
  32. var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  33. var LAST_SESSION_PARAM = 'ls';
  34. var APPLICATION_ID_PARAM = 'p';
  35. var APP_CHECK_TOKEN_PARAM = 'ac';
  36. var WEBSOCKET = 'websocket';
  37. var LONG_POLLING = 'long_polling';
  38. /**
  39. * @license
  40. * Copyright 2017 Google LLC
  41. *
  42. * Licensed under the Apache License, Version 2.0 (the "License");
  43. * you may not use this file except in compliance with the License.
  44. * You may obtain a copy of the License at
  45. *
  46. * http://www.apache.org/licenses/LICENSE-2.0
  47. *
  48. * Unless required by applicable law or agreed to in writing, software
  49. * distributed under the License is distributed on an "AS IS" BASIS,
  50. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  51. * See the License for the specific language governing permissions and
  52. * limitations under the License.
  53. */
  54. /**
  55. * Wraps a DOM Storage object and:
  56. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  57. * - prefixes names with "firebase:" to avoid collisions with app data.
  58. *
  59. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  60. * and one for localStorage.
  61. *
  62. */
  63. var DOMStorageWrapper = /** @class */ (function () {
  64. /**
  65. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  66. */
  67. function DOMStorageWrapper(domStorage_) {
  68. this.domStorage_ = domStorage_;
  69. // Use a prefix to avoid collisions with other stuff saved by the app.
  70. this.prefix_ = 'firebase:';
  71. }
  72. /**
  73. * @param key - The key to save the value under
  74. * @param value - The value being stored, or null to remove the key.
  75. */
  76. DOMStorageWrapper.prototype.set = function (key, value) {
  77. if (value == null) {
  78. this.domStorage_.removeItem(this.prefixedName_(key));
  79. }
  80. else {
  81. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  82. }
  83. };
  84. /**
  85. * @returns The value that was stored under this key, or null
  86. */
  87. DOMStorageWrapper.prototype.get = function (key) {
  88. var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  89. if (storedVal == null) {
  90. return null;
  91. }
  92. else {
  93. return util.jsonEval(storedVal);
  94. }
  95. };
  96. DOMStorageWrapper.prototype.remove = function (key) {
  97. this.domStorage_.removeItem(this.prefixedName_(key));
  98. };
  99. DOMStorageWrapper.prototype.prefixedName_ = function (name) {
  100. return this.prefix_ + name;
  101. };
  102. DOMStorageWrapper.prototype.toString = function () {
  103. return this.domStorage_.toString();
  104. };
  105. return DOMStorageWrapper;
  106. }());
  107. /**
  108. * @license
  109. * Copyright 2017 Google LLC
  110. *
  111. * Licensed under the Apache License, Version 2.0 (the "License");
  112. * you may not use this file except in compliance with the License.
  113. * You may obtain a copy of the License at
  114. *
  115. * http://www.apache.org/licenses/LICENSE-2.0
  116. *
  117. * Unless required by applicable law or agreed to in writing, software
  118. * distributed under the License is distributed on an "AS IS" BASIS,
  119. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  120. * See the License for the specific language governing permissions and
  121. * limitations under the License.
  122. */
  123. /**
  124. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  125. * (TODO: create interface for both to implement).
  126. */
  127. var MemoryStorage = /** @class */ (function () {
  128. function MemoryStorage() {
  129. this.cache_ = {};
  130. this.isInMemoryStorage = true;
  131. }
  132. MemoryStorage.prototype.set = function (key, value) {
  133. if (value == null) {
  134. delete this.cache_[key];
  135. }
  136. else {
  137. this.cache_[key] = value;
  138. }
  139. };
  140. MemoryStorage.prototype.get = function (key) {
  141. if (util.contains(this.cache_, key)) {
  142. return this.cache_[key];
  143. }
  144. return null;
  145. };
  146. MemoryStorage.prototype.remove = function (key) {
  147. delete this.cache_[key];
  148. };
  149. return MemoryStorage;
  150. }());
  151. /**
  152. * @license
  153. * Copyright 2017 Google LLC
  154. *
  155. * Licensed under the Apache License, Version 2.0 (the "License");
  156. * you may not use this file except in compliance with the License.
  157. * You may obtain a copy of the License at
  158. *
  159. * http://www.apache.org/licenses/LICENSE-2.0
  160. *
  161. * Unless required by applicable law or agreed to in writing, software
  162. * distributed under the License is distributed on an "AS IS" BASIS,
  163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  164. * See the License for the specific language governing permissions and
  165. * limitations under the License.
  166. */
  167. /**
  168. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  169. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  170. * to reflect this type
  171. *
  172. * @param domStorageName - Name of the underlying storage object
  173. * (e.g. 'localStorage' or 'sessionStorage').
  174. * @returns Turning off type information until a common interface is defined.
  175. */
  176. var createStoragefor = function (domStorageName) {
  177. try {
  178. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  179. // so it must be inside the try/catch.
  180. if (typeof window !== 'undefined' &&
  181. typeof window[domStorageName] !== 'undefined') {
  182. // Need to test cache. Just because it's here doesn't mean it works
  183. var domStorage = window[domStorageName];
  184. domStorage.setItem('firebase:sentinel', 'cache');
  185. domStorage.removeItem('firebase:sentinel');
  186. return new DOMStorageWrapper(domStorage);
  187. }
  188. }
  189. catch (e) { }
  190. // Failed to create wrapper. Just return in-memory storage.
  191. // TODO: log?
  192. return new MemoryStorage();
  193. };
  194. /** A storage object that lasts across sessions */
  195. var PersistentStorage = createStoragefor('localStorage');
  196. /** A storage object that only lasts one session */
  197. var SessionStorage = createStoragefor('sessionStorage');
  198. /**
  199. * @license
  200. * Copyright 2017 Google LLC
  201. *
  202. * Licensed under the Apache License, Version 2.0 (the "License");
  203. * you may not use this file except in compliance with the License.
  204. * You may obtain a copy of the License at
  205. *
  206. * http://www.apache.org/licenses/LICENSE-2.0
  207. *
  208. * Unless required by applicable law or agreed to in writing, software
  209. * distributed under the License is distributed on an "AS IS" BASIS,
  210. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  211. * See the License for the specific language governing permissions and
  212. * limitations under the License.
  213. */
  214. var logClient = new logger$1.Logger('@firebase/database');
  215. /**
  216. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  217. */
  218. var LUIDGenerator = (function () {
  219. var id = 1;
  220. return function () {
  221. return id++;
  222. };
  223. })();
  224. /**
  225. * Sha1 hash of the input string
  226. * @param str - The string to hash
  227. * @returns {!string} The resulting hash
  228. */
  229. var sha1 = function (str) {
  230. var utf8Bytes = util.stringToByteArray(str);
  231. var sha1 = new util.Sha1();
  232. sha1.update(utf8Bytes);
  233. var sha1Bytes = sha1.digest();
  234. return util.base64.encodeByteArray(sha1Bytes);
  235. };
  236. var buildLogMessage_ = function () {
  237. var varArgs = [];
  238. for (var _i = 0; _i < arguments.length; _i++) {
  239. varArgs[_i] = arguments[_i];
  240. }
  241. var message = '';
  242. for (var i = 0; i < varArgs.length; i++) {
  243. var arg = varArgs[i];
  244. if (Array.isArray(arg) ||
  245. (arg &&
  246. typeof arg === 'object' &&
  247. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  248. typeof arg.length === 'number')) {
  249. message += buildLogMessage_.apply(null, arg);
  250. }
  251. else if (typeof arg === 'object') {
  252. message += util.stringify(arg);
  253. }
  254. else {
  255. message += arg;
  256. }
  257. message += ' ';
  258. }
  259. return message;
  260. };
  261. /**
  262. * Use this for all debug messages in Firebase.
  263. */
  264. var logger = null;
  265. /**
  266. * Flag to check for log availability on first log message
  267. */
  268. var firstLog_ = true;
  269. /**
  270. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  271. * @param logger_ - A flag to turn on logging, or a custom logger
  272. * @param persistent - Whether or not to persist logging settings across refreshes
  273. */
  274. var enableLogging$1 = function (logger_, persistent) {
  275. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  276. if (logger_ === true) {
  277. logClient.logLevel = logger$1.LogLevel.VERBOSE;
  278. logger = logClient.log.bind(logClient);
  279. if (persistent) {
  280. SessionStorage.set('logging_enabled', true);
  281. }
  282. }
  283. else if (typeof logger_ === 'function') {
  284. logger = logger_;
  285. }
  286. else {
  287. logger = null;
  288. SessionStorage.remove('logging_enabled');
  289. }
  290. };
  291. var log = function () {
  292. var varArgs = [];
  293. for (var _i = 0; _i < arguments.length; _i++) {
  294. varArgs[_i] = arguments[_i];
  295. }
  296. if (firstLog_ === true) {
  297. firstLog_ = false;
  298. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  299. enableLogging$1(true);
  300. }
  301. }
  302. if (logger) {
  303. var message = buildLogMessage_.apply(null, varArgs);
  304. logger(message);
  305. }
  306. };
  307. var logWrapper = function (prefix) {
  308. return function () {
  309. var varArgs = [];
  310. for (var _i = 0; _i < arguments.length; _i++) {
  311. varArgs[_i] = arguments[_i];
  312. }
  313. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  314. };
  315. };
  316. var error = function () {
  317. var varArgs = [];
  318. for (var _i = 0; _i < arguments.length; _i++) {
  319. varArgs[_i] = arguments[_i];
  320. }
  321. var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  322. logClient.error(message);
  323. };
  324. var fatal = function () {
  325. var varArgs = [];
  326. for (var _i = 0; _i < arguments.length; _i++) {
  327. varArgs[_i] = arguments[_i];
  328. }
  329. var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false)));
  330. logClient.error(message);
  331. throw new Error(message);
  332. };
  333. var warn = function () {
  334. var varArgs = [];
  335. for (var _i = 0; _i < arguments.length; _i++) {
  336. varArgs[_i] = arguments[_i];
  337. }
  338. var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  339. logClient.warn(message);
  340. };
  341. /**
  342. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  343. * does not use https.
  344. */
  345. var warnIfPageIsSecure = function () {
  346. // Be very careful accessing browser globals. Who knows what may or may not exist.
  347. if (typeof window !== 'undefined' &&
  348. window.location &&
  349. window.location.protocol &&
  350. window.location.protocol.indexOf('https:') !== -1) {
  351. warn('Insecure Firebase access from a secure page. ' +
  352. 'Please use https in calls to new Firebase().');
  353. }
  354. };
  355. /**
  356. * Returns true if data is NaN, or +/- Infinity.
  357. */
  358. var isInvalidJSONNumber = function (data) {
  359. return (typeof data === 'number' &&
  360. (data !== data || // NaN
  361. data === Number.POSITIVE_INFINITY ||
  362. data === Number.NEGATIVE_INFINITY));
  363. };
  364. var executeWhenDOMReady = function (fn) {
  365. if (util.isNodeSdk() || document.readyState === 'complete') {
  366. fn();
  367. }
  368. else {
  369. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  370. // fire before onload), but fall back to onload.
  371. var called_1 = false;
  372. var wrappedFn_1 = function () {
  373. if (!document.body) {
  374. setTimeout(wrappedFn_1, Math.floor(10));
  375. return;
  376. }
  377. if (!called_1) {
  378. called_1 = true;
  379. fn();
  380. }
  381. };
  382. if (document.addEventListener) {
  383. document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
  384. // fallback to onload.
  385. window.addEventListener('load', wrappedFn_1, false);
  386. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  387. }
  388. else if (document.attachEvent) {
  389. // IE.
  390. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  391. document.attachEvent('onreadystatechange', function () {
  392. if (document.readyState === 'complete') {
  393. wrappedFn_1();
  394. }
  395. });
  396. // fallback to onload.
  397. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  398. window.attachEvent('onload', wrappedFn_1);
  399. // jQuery has an extra hack for IE that we could employ (based on
  400. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  401. // I'm hoping we don't need it.
  402. }
  403. }
  404. };
  405. /**
  406. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  407. */
  408. var MIN_NAME = '[MIN_NAME]';
  409. /**
  410. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  411. */
  412. var MAX_NAME = '[MAX_NAME]';
  413. /**
  414. * Compares valid Firebase key names, plus min and max name
  415. */
  416. var nameCompare = function (a, b) {
  417. if (a === b) {
  418. return 0;
  419. }
  420. else if (a === MIN_NAME || b === MAX_NAME) {
  421. return -1;
  422. }
  423. else if (b === MIN_NAME || a === MAX_NAME) {
  424. return 1;
  425. }
  426. else {
  427. var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  428. if (aAsInt !== null) {
  429. if (bAsInt !== null) {
  430. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  431. }
  432. else {
  433. return -1;
  434. }
  435. }
  436. else if (bAsInt !== null) {
  437. return 1;
  438. }
  439. else {
  440. return a < b ? -1 : 1;
  441. }
  442. }
  443. };
  444. /**
  445. * @returns {!number} comparison result.
  446. */
  447. var stringCompare = function (a, b) {
  448. if (a === b) {
  449. return 0;
  450. }
  451. else if (a < b) {
  452. return -1;
  453. }
  454. else {
  455. return 1;
  456. }
  457. };
  458. var requireKey = function (key, obj) {
  459. if (obj && key in obj) {
  460. return obj[key];
  461. }
  462. else {
  463. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  464. }
  465. };
  466. var ObjectToUniqueKey = function (obj) {
  467. if (typeof obj !== 'object' || obj === null) {
  468. return util.stringify(obj);
  469. }
  470. var keys = [];
  471. // eslint-disable-next-line guard-for-in
  472. for (var k in obj) {
  473. keys.push(k);
  474. }
  475. // Export as json, but with the keys sorted.
  476. keys.sort();
  477. var key = '{';
  478. for (var i = 0; i < keys.length; i++) {
  479. if (i !== 0) {
  480. key += ',';
  481. }
  482. key += util.stringify(keys[i]);
  483. key += ':';
  484. key += ObjectToUniqueKey(obj[keys[i]]);
  485. }
  486. key += '}';
  487. return key;
  488. };
  489. /**
  490. * Splits a string into a number of smaller segments of maximum size
  491. * @param str - The string
  492. * @param segsize - The maximum number of chars in the string.
  493. * @returns The string, split into appropriately-sized chunks
  494. */
  495. var splitStringBySize = function (str, segsize) {
  496. var len = str.length;
  497. if (len <= segsize) {
  498. return [str];
  499. }
  500. var dataSegs = [];
  501. for (var c = 0; c < len; c += segsize) {
  502. if (c + segsize > len) {
  503. dataSegs.push(str.substring(c, len));
  504. }
  505. else {
  506. dataSegs.push(str.substring(c, c + segsize));
  507. }
  508. }
  509. return dataSegs;
  510. };
  511. /**
  512. * Apply a function to each (key, value) pair in an object or
  513. * apply a function to each (index, value) pair in an array
  514. * @param obj - The object or array to iterate over
  515. * @param fn - The function to apply
  516. */
  517. function each(obj, fn) {
  518. for (var key in obj) {
  519. if (obj.hasOwnProperty(key)) {
  520. fn(key, obj[key]);
  521. }
  522. }
  523. }
  524. /**
  525. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  526. * I made one modification at the end and removed the NaN / Infinity
  527. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  528. * @param v - A double
  529. *
  530. */
  531. var doubleToIEEE754String = function (v) {
  532. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  533. var ebits = 11, fbits = 52;
  534. var bias = (1 << (ebits - 1)) - 1;
  535. var s, e, f, ln, i;
  536. // Compute sign, exponent, fraction
  537. // Skip NaN / Infinity handling --MJL.
  538. if (v === 0) {
  539. e = 0;
  540. f = 0;
  541. s = 1 / v === -Infinity ? 1 : 0;
  542. }
  543. else {
  544. s = v < 0;
  545. v = Math.abs(v);
  546. if (v >= Math.pow(2, 1 - bias)) {
  547. // Normalized
  548. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  549. e = ln + bias;
  550. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  551. }
  552. else {
  553. // Denormalized
  554. e = 0;
  555. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  556. }
  557. }
  558. // Pack sign, exponent, fraction
  559. var bits = [];
  560. for (i = fbits; i; i -= 1) {
  561. bits.push(f % 2 ? 1 : 0);
  562. f = Math.floor(f / 2);
  563. }
  564. for (i = ebits; i; i -= 1) {
  565. bits.push(e % 2 ? 1 : 0);
  566. e = Math.floor(e / 2);
  567. }
  568. bits.push(s ? 1 : 0);
  569. bits.reverse();
  570. var str = bits.join('');
  571. // Return the data as a hex string. --MJL
  572. var hexByteString = '';
  573. for (i = 0; i < 64; i += 8) {
  574. var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  575. if (hexByte.length === 1) {
  576. hexByte = '0' + hexByte;
  577. }
  578. hexByteString = hexByteString + hexByte;
  579. }
  580. return hexByteString.toLowerCase();
  581. };
  582. /**
  583. * Used to detect if we're in a Chrome content script (which executes in an
  584. * isolated environment where long-polling doesn't work).
  585. */
  586. var isChromeExtensionContentScript = function () {
  587. return !!(typeof window === 'object' &&
  588. window['chrome'] &&
  589. window['chrome']['extension'] &&
  590. !/^chrome/.test(window.location.href));
  591. };
  592. /**
  593. * Used to detect if we're in a Windows 8 Store app.
  594. */
  595. var isWindowsStoreApp = function () {
  596. // Check for the presence of a couple WinRT globals
  597. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  598. };
  599. /**
  600. * Converts a server error code to a Javascript Error
  601. */
  602. function errorForServerCode(code, query) {
  603. var reason = 'Unknown Error';
  604. if (code === 'too_big') {
  605. reason =
  606. 'The data requested exceeds the maximum size ' +
  607. 'that can be accessed with a single request.';
  608. }
  609. else if (code === 'permission_denied') {
  610. reason = "Client doesn't have permission to access the desired data.";
  611. }
  612. else if (code === 'unavailable') {
  613. reason = 'The service is unavailable';
  614. }
  615. var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  616. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  617. error.code = code.toUpperCase();
  618. return error;
  619. }
  620. /**
  621. * Used to test for integer-looking strings
  622. */
  623. var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  624. /**
  625. * For use in keys, the minimum possible 32-bit integer.
  626. */
  627. var INTEGER_32_MIN = -2147483648;
  628. /**
  629. * For use in kyes, the maximum possible 32-bit integer.
  630. */
  631. var INTEGER_32_MAX = 2147483647;
  632. /**
  633. * If the string contains a 32-bit integer, return it. Else return null.
  634. */
  635. var tryParseInt = function (str) {
  636. if (INTEGER_REGEXP_.test(str)) {
  637. var intVal = Number(str);
  638. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  639. return intVal;
  640. }
  641. }
  642. return null;
  643. };
  644. /**
  645. * Helper to run some code but catch any exceptions and re-throw them later.
  646. * Useful for preventing user callbacks from breaking internal code.
  647. *
  648. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  649. * convenient (we don't have to try to figure out when is a safe point to
  650. * re-throw it), and the behavior seems reasonable:
  651. *
  652. * * If you aren't pausing on exceptions, you get an error in the console with
  653. * the correct stack trace.
  654. * * If you're pausing on all exceptions, the debugger will pause on your
  655. * exception and then again when we rethrow it.
  656. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  657. * on us re-throwing it.
  658. *
  659. * @param fn - The code to guard.
  660. */
  661. var exceptionGuard = function (fn) {
  662. try {
  663. fn();
  664. }
  665. catch (e) {
  666. // Re-throw exception when it's safe.
  667. setTimeout(function () {
  668. // It used to be that "throw e" would result in a good console error with
  669. // relevant context, but as of Chrome 39, you just get the firebase.js
  670. // file/line number where we re-throw it, which is useless. So we log
  671. // e.stack explicitly.
  672. var stack = e.stack || '';
  673. warn('Exception was thrown by user callback.', stack);
  674. throw e;
  675. }, Math.floor(0));
  676. }
  677. };
  678. /**
  679. * @returns {boolean} true if we think we're currently being crawled.
  680. */
  681. var beingCrawled = function () {
  682. var userAgent = (typeof window === 'object' &&
  683. window['navigator'] &&
  684. window['navigator']['userAgent']) ||
  685. '';
  686. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  687. // believe to support JavaScript/AJAX rendering.
  688. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  689. // would have seen the page" is flaky if we don't treat it as a crawler.
  690. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  691. };
  692. /**
  693. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  694. *
  695. * It is removed with clearTimeout() as normal.
  696. *
  697. * @param fn - Function to run.
  698. * @param time - Milliseconds to wait before running.
  699. * @returns The setTimeout() return value.
  700. */
  701. var setTimeoutNonBlocking = function (fn, time) {
  702. var timeout = setTimeout(fn, time);
  703. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  704. if (typeof timeout === 'number' &&
  705. // @ts-ignore Is only defined in Deno environments.
  706. typeof Deno !== 'undefined' &&
  707. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  708. Deno['unrefTimer']) {
  709. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  710. Deno.unrefTimer(timeout);
  711. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  712. }
  713. else if (typeof timeout === 'object' && timeout['unref']) {
  714. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  715. timeout['unref']();
  716. }
  717. return timeout;
  718. };
  719. /**
  720. * @license
  721. * Copyright 2017 Google LLC
  722. *
  723. * Licensed under the Apache License, Version 2.0 (the "License");
  724. * you may not use this file except in compliance with the License.
  725. * You may obtain a copy of the License at
  726. *
  727. * http://www.apache.org/licenses/LICENSE-2.0
  728. *
  729. * Unless required by applicable law or agreed to in writing, software
  730. * distributed under the License is distributed on an "AS IS" BASIS,
  731. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  732. * See the License for the specific language governing permissions and
  733. * limitations under the License.
  734. */
  735. /**
  736. * A class that holds metadata about a Repo object
  737. */
  738. var RepoInfo = /** @class */ (function () {
  739. /**
  740. * @param host - Hostname portion of the url for the repo
  741. * @param secure - Whether or not this repo is accessed over ssl
  742. * @param namespace - The namespace represented by the repo
  743. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  744. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  745. * @param persistenceKey - Override the default session persistence storage key
  746. */
  747. function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams) {
  748. if (nodeAdmin === void 0) { nodeAdmin = false; }
  749. if (persistenceKey === void 0) { persistenceKey = ''; }
  750. if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
  751. this.secure = secure;
  752. this.namespace = namespace;
  753. this.webSocketOnly = webSocketOnly;
  754. this.nodeAdmin = nodeAdmin;
  755. this.persistenceKey = persistenceKey;
  756. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  757. this._host = host.toLowerCase();
  758. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  759. this.internalHost =
  760. PersistentStorage.get('host:' + host) || this._host;
  761. }
  762. RepoInfo.prototype.isCacheableHost = function () {
  763. return this.internalHost.substr(0, 2) === 's-';
  764. };
  765. RepoInfo.prototype.isCustomHost = function () {
  766. return (this._domain !== 'firebaseio.com' &&
  767. this._domain !== 'firebaseio-demo.com');
  768. };
  769. Object.defineProperty(RepoInfo.prototype, "host", {
  770. get: function () {
  771. return this._host;
  772. },
  773. set: function (newHost) {
  774. if (newHost !== this.internalHost) {
  775. this.internalHost = newHost;
  776. if (this.isCacheableHost()) {
  777. PersistentStorage.set('host:' + this._host, this.internalHost);
  778. }
  779. }
  780. },
  781. enumerable: false,
  782. configurable: true
  783. });
  784. RepoInfo.prototype.toString = function () {
  785. var str = this.toURLString();
  786. if (this.persistenceKey) {
  787. str += '<' + this.persistenceKey + '>';
  788. }
  789. return str;
  790. };
  791. RepoInfo.prototype.toURLString = function () {
  792. var protocol = this.secure ? 'https://' : 'http://';
  793. var query = this.includeNamespaceInQueryParams
  794. ? "?ns=".concat(this.namespace)
  795. : '';
  796. return "".concat(protocol).concat(this.host, "/").concat(query);
  797. };
  798. return RepoInfo;
  799. }());
  800. function repoInfoNeedsQueryParam(repoInfo) {
  801. return (repoInfo.host !== repoInfo.internalHost ||
  802. repoInfo.isCustomHost() ||
  803. repoInfo.includeNamespaceInQueryParams);
  804. }
  805. /**
  806. * Returns the websocket URL for this repo
  807. * @param repoInfo - RepoInfo object
  808. * @param type - of connection
  809. * @param params - list
  810. * @returns The URL for this repo
  811. */
  812. function repoInfoConnectionURL(repoInfo, type, params) {
  813. util.assert(typeof type === 'string', 'typeof type must == string');
  814. util.assert(typeof params === 'object', 'typeof params must == object');
  815. var connURL;
  816. if (type === WEBSOCKET) {
  817. connURL =
  818. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  819. }
  820. else if (type === LONG_POLLING) {
  821. connURL =
  822. (repoInfo.secure ? 'https://' : 'http://') +
  823. repoInfo.internalHost +
  824. '/.lp?';
  825. }
  826. else {
  827. throw new Error('Unknown connection type: ' + type);
  828. }
  829. if (repoInfoNeedsQueryParam(repoInfo)) {
  830. params['ns'] = repoInfo.namespace;
  831. }
  832. var pairs = [];
  833. each(params, function (key, value) {
  834. pairs.push(key + '=' + value);
  835. });
  836. return connURL + pairs.join('&');
  837. }
  838. /**
  839. * @license
  840. * Copyright 2017 Google LLC
  841. *
  842. * Licensed under the Apache License, Version 2.0 (the "License");
  843. * you may not use this file except in compliance with the License.
  844. * You may obtain a copy of the License at
  845. *
  846. * http://www.apache.org/licenses/LICENSE-2.0
  847. *
  848. * Unless required by applicable law or agreed to in writing, software
  849. * distributed under the License is distributed on an "AS IS" BASIS,
  850. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  851. * See the License for the specific language governing permissions and
  852. * limitations under the License.
  853. */
  854. /**
  855. * Tracks a collection of stats.
  856. */
  857. var StatsCollection = /** @class */ (function () {
  858. function StatsCollection() {
  859. this.counters_ = {};
  860. }
  861. StatsCollection.prototype.incrementCounter = function (name, amount) {
  862. if (amount === void 0) { amount = 1; }
  863. if (!util.contains(this.counters_, name)) {
  864. this.counters_[name] = 0;
  865. }
  866. this.counters_[name] += amount;
  867. };
  868. StatsCollection.prototype.get = function () {
  869. return util.deepCopy(this.counters_);
  870. };
  871. return StatsCollection;
  872. }());
  873. /**
  874. * @license
  875. * Copyright 2017 Google LLC
  876. *
  877. * Licensed under the Apache License, Version 2.0 (the "License");
  878. * you may not use this file except in compliance with the License.
  879. * You may obtain a copy of the License at
  880. *
  881. * http://www.apache.org/licenses/LICENSE-2.0
  882. *
  883. * Unless required by applicable law or agreed to in writing, software
  884. * distributed under the License is distributed on an "AS IS" BASIS,
  885. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  886. * See the License for the specific language governing permissions and
  887. * limitations under the License.
  888. */
  889. var collections = {};
  890. var reporters = {};
  891. function statsManagerGetCollection(repoInfo) {
  892. var hashString = repoInfo.toString();
  893. if (!collections[hashString]) {
  894. collections[hashString] = new StatsCollection();
  895. }
  896. return collections[hashString];
  897. }
  898. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  899. var hashString = repoInfo.toString();
  900. if (!reporters[hashString]) {
  901. reporters[hashString] = creatorFunction();
  902. }
  903. return reporters[hashString];
  904. }
  905. /**
  906. * @license
  907. * Copyright 2019 Google LLC
  908. *
  909. * Licensed under the Apache License, Version 2.0 (the "License");
  910. * you may not use this file except in compliance with the License.
  911. * You may obtain a copy of the License at
  912. *
  913. * http://www.apache.org/licenses/LICENSE-2.0
  914. *
  915. * Unless required by applicable law or agreed to in writing, software
  916. * distributed under the License is distributed on an "AS IS" BASIS,
  917. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  918. * See the License for the specific language governing permissions and
  919. * limitations under the License.
  920. */
  921. /** The semver (www.semver.org) version of the SDK. */
  922. var SDK_VERSION = '';
  923. /**
  924. * SDK_VERSION should be set before any database instance is created
  925. * @internal
  926. */
  927. function setSDKVersion(version) {
  928. SDK_VERSION = version;
  929. }
  930. /**
  931. * @license
  932. * Copyright 2017 Google LLC
  933. *
  934. * Licensed under the Apache License, Version 2.0 (the "License");
  935. * you may not use this file except in compliance with the License.
  936. * You may obtain a copy of the License at
  937. *
  938. * http://www.apache.org/licenses/LICENSE-2.0
  939. *
  940. * Unless required by applicable law or agreed to in writing, software
  941. * distributed under the License is distributed on an "AS IS" BASIS,
  942. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  943. * See the License for the specific language governing permissions and
  944. * limitations under the License.
  945. */
  946. var WEBSOCKET_MAX_FRAME_SIZE = 16384;
  947. var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  948. var WebSocketImpl = null;
  949. if (typeof MozWebSocket !== 'undefined') {
  950. WebSocketImpl = MozWebSocket;
  951. }
  952. else if (typeof WebSocket !== 'undefined') {
  953. WebSocketImpl = WebSocket;
  954. }
  955. function setWebSocketImpl(impl) {
  956. WebSocketImpl = impl;
  957. }
  958. /**
  959. * Create a new websocket connection with the given callbacks.
  960. */
  961. var WebSocketConnection = /** @class */ (function () {
  962. /**
  963. * @param connId identifier for this transport
  964. * @param repoInfo The info for the websocket endpoint.
  965. * @param applicationId The Firebase App ID for this project.
  966. * @param appCheckToken The App Check Token for this client.
  967. * @param authToken The Auth Token for this client.
  968. * @param transportSessionId Optional transportSessionId if this is connecting
  969. * to an existing transport session
  970. * @param lastSessionId Optional lastSessionId if there was a previous
  971. * connection
  972. */
  973. function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  974. this.connId = connId;
  975. this.applicationId = applicationId;
  976. this.appCheckToken = appCheckToken;
  977. this.authToken = authToken;
  978. this.keepaliveTimer = null;
  979. this.frames = null;
  980. this.totalFrames = 0;
  981. this.bytesSent = 0;
  982. this.bytesReceived = 0;
  983. this.log_ = logWrapper(this.connId);
  984. this.stats_ = statsManagerGetCollection(repoInfo);
  985. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  986. this.nodeAdmin = repoInfo.nodeAdmin;
  987. }
  988. /**
  989. * @param repoInfo - The info for the websocket endpoint.
  990. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  991. * session
  992. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  993. * @returns connection url
  994. */
  995. WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  996. var urlParams = {};
  997. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  998. if (!util.isNodeSdk() &&
  999. typeof location !== 'undefined' &&
  1000. location.hostname &&
  1001. FORGE_DOMAIN_RE.test(location.hostname)) {
  1002. urlParams[REFERER_PARAM] = FORGE_REF;
  1003. }
  1004. if (transportSessionId) {
  1005. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1006. }
  1007. if (lastSessionId) {
  1008. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1009. }
  1010. if (appCheckToken) {
  1011. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1012. }
  1013. if (applicationId) {
  1014. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1015. }
  1016. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1017. };
  1018. /**
  1019. * @param onMessage - Callback when messages arrive
  1020. * @param onDisconnect - Callback with connection lost.
  1021. */
  1022. WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
  1023. var _this = this;
  1024. this.onDisconnect = onDisconnect;
  1025. this.onMessage = onMessage;
  1026. this.log_('Websocket connecting to ' + this.connURL);
  1027. this.everConnected_ = false;
  1028. // Assume failure until proven otherwise.
  1029. PersistentStorage.set('previous_websocket_failure', true);
  1030. try {
  1031. var options = void 0;
  1032. if (util.isNodeSdk()) {
  1033. var device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1034. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1035. options = {
  1036. headers: {
  1037. 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
  1038. 'X-Firebase-GMPID': this.applicationId || ''
  1039. }
  1040. };
  1041. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1042. // Note that we send the credentials here even if they aren't admin credentials, which is
  1043. // not a problem.
  1044. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1045. // through the websocket connection once it is established.
  1046. if (this.authToken) {
  1047. options.headers['Authorization'] = "Bearer ".concat(this.authToken);
  1048. }
  1049. if (this.appCheckToken) {
  1050. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1051. }
  1052. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1053. var env = process['env'];
  1054. var proxy = this.connURL.indexOf('wss://') === 0
  1055. ? env['HTTPS_PROXY'] || env['https_proxy']
  1056. : env['HTTP_PROXY'] || env['http_proxy'];
  1057. if (proxy) {
  1058. options['proxy'] = { origin: proxy };
  1059. }
  1060. }
  1061. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1062. }
  1063. catch (e) {
  1064. this.log_('Error instantiating WebSocket.');
  1065. var error = e.message || e.data;
  1066. if (error) {
  1067. this.log_(error);
  1068. }
  1069. this.onClosed_();
  1070. return;
  1071. }
  1072. this.mySock.onopen = function () {
  1073. _this.log_('Websocket connected.');
  1074. _this.everConnected_ = true;
  1075. };
  1076. this.mySock.onclose = function () {
  1077. _this.log_('Websocket connection was disconnected.');
  1078. _this.mySock = null;
  1079. _this.onClosed_();
  1080. };
  1081. this.mySock.onmessage = function (m) {
  1082. _this.handleIncomingFrame(m);
  1083. };
  1084. this.mySock.onerror = function (e) {
  1085. _this.log_('WebSocket error. Closing connection.');
  1086. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1087. var error = e.message || e.data;
  1088. if (error) {
  1089. _this.log_(error);
  1090. }
  1091. _this.onClosed_();
  1092. };
  1093. };
  1094. /**
  1095. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1096. */
  1097. WebSocketConnection.prototype.start = function () { };
  1098. WebSocketConnection.forceDisallow = function () {
  1099. WebSocketConnection.forceDisallow_ = true;
  1100. };
  1101. WebSocketConnection.isAvailable = function () {
  1102. var isOldAndroid = false;
  1103. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1104. var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1105. var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1106. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1107. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1108. isOldAndroid = true;
  1109. }
  1110. }
  1111. }
  1112. return (!isOldAndroid &&
  1113. WebSocketImpl !== null &&
  1114. !WebSocketConnection.forceDisallow_);
  1115. };
  1116. /**
  1117. * Returns true if we previously failed to connect with this transport.
  1118. */
  1119. WebSocketConnection.previouslyFailed = function () {
  1120. // If our persistent storage is actually only in-memory storage,
  1121. // we default to assuming that it previously failed to be safe.
  1122. return (PersistentStorage.isInMemoryStorage ||
  1123. PersistentStorage.get('previous_websocket_failure') === true);
  1124. };
  1125. WebSocketConnection.prototype.markConnectionHealthy = function () {
  1126. PersistentStorage.remove('previous_websocket_failure');
  1127. };
  1128. WebSocketConnection.prototype.appendFrame_ = function (data) {
  1129. this.frames.push(data);
  1130. if (this.frames.length === this.totalFrames) {
  1131. var fullMess = this.frames.join('');
  1132. this.frames = null;
  1133. var jsonMess = util.jsonEval(fullMess);
  1134. //handle the message
  1135. this.onMessage(jsonMess);
  1136. }
  1137. };
  1138. /**
  1139. * @param frameCount - The number of frames we are expecting from the server
  1140. */
  1141. WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
  1142. this.totalFrames = frameCount;
  1143. this.frames = [];
  1144. };
  1145. /**
  1146. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1147. * @returns Any remaining data to be process, or null if there is none
  1148. */
  1149. WebSocketConnection.prototype.extractFrameCount_ = function (data) {
  1150. util.assert(this.frames === null, 'We already have a frame buffer');
  1151. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1152. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1153. if (data.length <= 6) {
  1154. var frameCount = Number(data);
  1155. if (!isNaN(frameCount)) {
  1156. this.handleNewFrameCount_(frameCount);
  1157. return null;
  1158. }
  1159. }
  1160. this.handleNewFrameCount_(1);
  1161. return data;
  1162. };
  1163. /**
  1164. * Process a websocket frame that has arrived from the server.
  1165. * @param mess - The frame data
  1166. */
  1167. WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
  1168. if (this.mySock === null) {
  1169. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1170. }
  1171. var data = mess['data'];
  1172. this.bytesReceived += data.length;
  1173. this.stats_.incrementCounter('bytes_received', data.length);
  1174. this.resetKeepAlive();
  1175. if (this.frames !== null) {
  1176. // we're buffering
  1177. this.appendFrame_(data);
  1178. }
  1179. else {
  1180. // try to parse out a frame count, otherwise, assume 1 and process it
  1181. var remainingData = this.extractFrameCount_(data);
  1182. if (remainingData !== null) {
  1183. this.appendFrame_(remainingData);
  1184. }
  1185. }
  1186. };
  1187. /**
  1188. * Send a message to the server
  1189. * @param data - The JSON object to transmit
  1190. */
  1191. WebSocketConnection.prototype.send = function (data) {
  1192. this.resetKeepAlive();
  1193. var dataStr = util.stringify(data);
  1194. this.bytesSent += dataStr.length;
  1195. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1196. //We can only fit a certain amount in each websocket frame, so we need to split this request
  1197. //up into multiple pieces if it doesn't fit in one request.
  1198. var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  1199. //Send the length header
  1200. if (dataSegs.length > 1) {
  1201. this.sendString_(String(dataSegs.length));
  1202. }
  1203. //Send the actual data in segments.
  1204. for (var i = 0; i < dataSegs.length; i++) {
  1205. this.sendString_(dataSegs[i]);
  1206. }
  1207. };
  1208. WebSocketConnection.prototype.shutdown_ = function () {
  1209. this.isClosed_ = true;
  1210. if (this.keepaliveTimer) {
  1211. clearInterval(this.keepaliveTimer);
  1212. this.keepaliveTimer = null;
  1213. }
  1214. if (this.mySock) {
  1215. this.mySock.close();
  1216. this.mySock = null;
  1217. }
  1218. };
  1219. WebSocketConnection.prototype.onClosed_ = function () {
  1220. if (!this.isClosed_) {
  1221. this.log_('WebSocket is closing itself');
  1222. this.shutdown_();
  1223. // since this is an internal close, trigger the close listener
  1224. if (this.onDisconnect) {
  1225. this.onDisconnect(this.everConnected_);
  1226. this.onDisconnect = null;
  1227. }
  1228. }
  1229. };
  1230. /**
  1231. * External-facing close handler.
  1232. * Close the websocket and kill the connection.
  1233. */
  1234. WebSocketConnection.prototype.close = function () {
  1235. if (!this.isClosed_) {
  1236. this.log_('WebSocket is being closed');
  1237. this.shutdown_();
  1238. }
  1239. };
  1240. /**
  1241. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  1242. * the last activity.
  1243. */
  1244. WebSocketConnection.prototype.resetKeepAlive = function () {
  1245. var _this = this;
  1246. clearInterval(this.keepaliveTimer);
  1247. this.keepaliveTimer = setInterval(function () {
  1248. //If there has been no websocket activity for a while, send a no-op
  1249. if (_this.mySock) {
  1250. _this.sendString_('0');
  1251. }
  1252. _this.resetKeepAlive();
  1253. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1254. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  1255. };
  1256. /**
  1257. * Send a string over the websocket.
  1258. *
  1259. * @param str - String to send.
  1260. */
  1261. WebSocketConnection.prototype.sendString_ = function (str) {
  1262. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  1263. // calls for some unknown reason. We treat these as an error and disconnect.
  1264. // See https://app.asana.com/0/58926111402292/68021340250410
  1265. try {
  1266. this.mySock.send(str);
  1267. }
  1268. catch (e) {
  1269. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  1270. setTimeout(this.onClosed_.bind(this), 0);
  1271. }
  1272. };
  1273. /**
  1274. * Number of response before we consider the connection "healthy."
  1275. */
  1276. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  1277. /**
  1278. * Time to wait for the connection te become healthy before giving up.
  1279. */
  1280. WebSocketConnection.healthyTimeout = 30000;
  1281. return WebSocketConnection;
  1282. }());
  1283. /**
  1284. * @license
  1285. * Copyright 2021 Google LLC
  1286. *
  1287. * Licensed under the Apache License, Version 2.0 (the "License");
  1288. * you may not use this file except in compliance with the License.
  1289. * You may obtain a copy of the License at
  1290. *
  1291. * http://www.apache.org/licenses/LICENSE-2.0
  1292. *
  1293. * Unless required by applicable law or agreed to in writing, software
  1294. * distributed under the License is distributed on an "AS IS" BASIS,
  1295. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1296. * See the License for the specific language governing permissions and
  1297. * limitations under the License.
  1298. */
  1299. /**
  1300. * Abstraction around AppCheck's token fetching capabilities.
  1301. */
  1302. var AppCheckTokenProvider = /** @class */ (function () {
  1303. function AppCheckTokenProvider(appName_, appCheckProvider) {
  1304. var _this = this;
  1305. this.appName_ = appName_;
  1306. this.appCheckProvider = appCheckProvider;
  1307. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  1308. if (!this.appCheck) {
  1309. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
  1310. }
  1311. }
  1312. AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
  1313. var _this = this;
  1314. if (!this.appCheck) {
  1315. return new Promise(function (resolve, reject) {
  1316. // Support delayed initialization of FirebaseAppCheck. This allows our
  1317. // customers to initialize the RTDB SDK before initializing Firebase
  1318. // AppCheck and ensures that all requests are authenticated if a token
  1319. // becomes available before the timoeout below expires.
  1320. setTimeout(function () {
  1321. if (_this.appCheck) {
  1322. _this.getToken(forceRefresh).then(resolve, reject);
  1323. }
  1324. else {
  1325. resolve(null);
  1326. }
  1327. }, 0);
  1328. });
  1329. }
  1330. return this.appCheck.getToken(forceRefresh);
  1331. };
  1332. AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1333. var _a;
  1334. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
  1335. };
  1336. AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
  1337. warn("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
  1338. 'are invalid. This usually indicates your app was not initialized correctly.');
  1339. };
  1340. return AppCheckTokenProvider;
  1341. }());
  1342. /**
  1343. * @license
  1344. * Copyright 2017 Google LLC
  1345. *
  1346. * Licensed under the Apache License, Version 2.0 (the "License");
  1347. * you may not use this file except in compliance with the License.
  1348. * You may obtain a copy of the License at
  1349. *
  1350. * http://www.apache.org/licenses/LICENSE-2.0
  1351. *
  1352. * Unless required by applicable law or agreed to in writing, software
  1353. * distributed under the License is distributed on an "AS IS" BASIS,
  1354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1355. * See the License for the specific language governing permissions and
  1356. * limitations under the License.
  1357. */
  1358. /**
  1359. * Abstraction around FirebaseApp's token fetching capabilities.
  1360. */
  1361. var FirebaseAuthTokenProvider = /** @class */ (function () {
  1362. function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
  1363. var _this = this;
  1364. this.appName_ = appName_;
  1365. this.firebaseOptions_ = firebaseOptions_;
  1366. this.authProvider_ = authProvider_;
  1367. this.auth_ = null;
  1368. this.auth_ = authProvider_.getImmediate({ optional: true });
  1369. if (!this.auth_) {
  1370. authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
  1371. }
  1372. }
  1373. FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
  1374. var _this = this;
  1375. if (!this.auth_) {
  1376. return new Promise(function (resolve, reject) {
  1377. // Support delayed initialization of FirebaseAuth. This allows our
  1378. // customers to initialize the RTDB SDK before initializing Firebase
  1379. // Auth and ensures that all requests are authenticated if a token
  1380. // becomes available before the timoeout below expires.
  1381. setTimeout(function () {
  1382. if (_this.auth_) {
  1383. _this.getToken(forceRefresh).then(resolve, reject);
  1384. }
  1385. else {
  1386. resolve(null);
  1387. }
  1388. }, 0);
  1389. });
  1390. }
  1391. return this.auth_.getToken(forceRefresh).catch(function (error) {
  1392. // TODO: Need to figure out all the cases this is raised and whether
  1393. // this makes sense.
  1394. if (error && error.code === 'auth/token-not-initialized') {
  1395. log('Got auth/token-not-initialized error. Treating as null token.');
  1396. return null;
  1397. }
  1398. else {
  1399. return Promise.reject(error);
  1400. }
  1401. });
  1402. };
  1403. FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1404. // TODO: We might want to wrap the listener and call it with no args to
  1405. // avoid a leaky abstraction, but that makes removing the listener harder.
  1406. if (this.auth_) {
  1407. this.auth_.addAuthTokenListener(listener);
  1408. }
  1409. else {
  1410. this.authProvider_
  1411. .get()
  1412. .then(function (auth) { return auth.addAuthTokenListener(listener); });
  1413. }
  1414. };
  1415. FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
  1416. this.authProvider_
  1417. .get()
  1418. .then(function (auth) { return auth.removeAuthTokenListener(listener); });
  1419. };
  1420. FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
  1421. var errorMessage = 'Provided authentication credentials for the app named "' +
  1422. this.appName_ +
  1423. '" are invalid. This usually indicates your app was not ' +
  1424. 'initialized correctly. ';
  1425. if ('credential' in this.firebaseOptions_) {
  1426. errorMessage +=
  1427. 'Make sure the "credential" property provided to initializeApp() ' +
  1428. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1429. 'project.';
  1430. }
  1431. else if ('serviceAccount' in this.firebaseOptions_) {
  1432. errorMessage +=
  1433. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  1434. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1435. 'project.';
  1436. }
  1437. else {
  1438. errorMessage +=
  1439. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  1440. 'initializeApp() match the values provided for your app at ' +
  1441. 'https://console.firebase.google.com/.';
  1442. }
  1443. warn(errorMessage);
  1444. };
  1445. return FirebaseAuthTokenProvider;
  1446. }());
  1447. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  1448. var EmulatorTokenProvider = /** @class */ (function () {
  1449. function EmulatorTokenProvider(accessToken) {
  1450. this.accessToken = accessToken;
  1451. }
  1452. EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
  1453. return Promise.resolve({
  1454. accessToken: this.accessToken
  1455. });
  1456. };
  1457. EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1458. // Invoke the listener immediately to match the behavior in Firebase Auth
  1459. // (see packages/auth/src/auth.js#L1807)
  1460. listener(this.accessToken);
  1461. };
  1462. EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
  1463. EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
  1464. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  1465. EmulatorTokenProvider.OWNER = 'owner';
  1466. return EmulatorTokenProvider;
  1467. }());
  1468. /**
  1469. * @license
  1470. * Copyright 2017 Google LLC
  1471. *
  1472. * Licensed under the Apache License, Version 2.0 (the "License");
  1473. * you may not use this file except in compliance with the License.
  1474. * You may obtain a copy of the License at
  1475. *
  1476. * http://www.apache.org/licenses/LICENSE-2.0
  1477. *
  1478. * Unless required by applicable law or agreed to in writing, software
  1479. * distributed under the License is distributed on an "AS IS" BASIS,
  1480. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1481. * See the License for the specific language governing permissions and
  1482. * limitations under the License.
  1483. */
  1484. /**
  1485. * This class ensures the packets from the server arrive in order
  1486. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1487. */
  1488. var PacketReceiver = /** @class */ (function () {
  1489. /**
  1490. * @param onMessage_
  1491. */
  1492. function PacketReceiver(onMessage_) {
  1493. this.onMessage_ = onMessage_;
  1494. this.pendingResponses = [];
  1495. this.currentResponseNum = 0;
  1496. this.closeAfterResponse = -1;
  1497. this.onClose = null;
  1498. }
  1499. PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
  1500. this.closeAfterResponse = responseNum;
  1501. this.onClose = callback;
  1502. if (this.closeAfterResponse < this.currentResponseNum) {
  1503. this.onClose();
  1504. this.onClose = null;
  1505. }
  1506. };
  1507. /**
  1508. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1509. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1510. * browsers will respond in the same order as the requests we sent
  1511. */
  1512. PacketReceiver.prototype.handleResponse = function (requestNum, data) {
  1513. var _this = this;
  1514. this.pendingResponses[requestNum] = data;
  1515. var _loop_1 = function () {
  1516. var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
  1517. delete this_1.pendingResponses[this_1.currentResponseNum];
  1518. var _loop_2 = function (i) {
  1519. if (toProcess[i]) {
  1520. exceptionGuard(function () {
  1521. _this.onMessage_(toProcess[i]);
  1522. });
  1523. }
  1524. };
  1525. for (var i = 0; i < toProcess.length; ++i) {
  1526. _loop_2(i);
  1527. }
  1528. if (this_1.currentResponseNum === this_1.closeAfterResponse) {
  1529. if (this_1.onClose) {
  1530. this_1.onClose();
  1531. this_1.onClose = null;
  1532. }
  1533. return "break";
  1534. }
  1535. this_1.currentResponseNum++;
  1536. };
  1537. var this_1 = this;
  1538. while (this.pendingResponses[this.currentResponseNum]) {
  1539. var state_1 = _loop_1();
  1540. if (state_1 === "break")
  1541. break;
  1542. }
  1543. };
  1544. return PacketReceiver;
  1545. }());
  1546. /**
  1547. * @license
  1548. * Copyright 2017 Google LLC
  1549. *
  1550. * Licensed under the Apache License, Version 2.0 (the "License");
  1551. * you may not use this file except in compliance with the License.
  1552. * You may obtain a copy of the License at
  1553. *
  1554. * http://www.apache.org/licenses/LICENSE-2.0
  1555. *
  1556. * Unless required by applicable law or agreed to in writing, software
  1557. * distributed under the License is distributed on an "AS IS" BASIS,
  1558. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1559. * See the License for the specific language governing permissions and
  1560. * limitations under the License.
  1561. */
  1562. // URL query parameters associated with longpolling
  1563. var FIREBASE_LONGPOLL_START_PARAM = 'start';
  1564. var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1565. var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1566. var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1567. var FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1568. var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1569. var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1570. var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1571. var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1572. var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1573. var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1574. var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1575. //Data size constants.
  1576. //TODO: Perf: the maximum length actually differs from browser to browser.
  1577. // We should check what browser we're on and set accordingly.
  1578. var MAX_URL_DATA_SIZE = 1870;
  1579. var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1580. var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1581. /**
  1582. * Keepalive period
  1583. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1584. * length of 30 seconds that we can't exceed.
  1585. */
  1586. var KEEPALIVE_REQUEST_INTERVAL = 25000;
  1587. /**
  1588. * How long to wait before aborting a long-polling connection attempt.
  1589. */
  1590. var LP_CONNECT_TIMEOUT = 30000;
  1591. /**
  1592. * This class manages a single long-polling connection.
  1593. */
  1594. var BrowserPollConnection = /** @class */ (function () {
  1595. /**
  1596. * @param connId An identifier for this connection, used for logging
  1597. * @param repoInfo The info for the endpoint to send data to.
  1598. * @param applicationId The Firebase App ID for this project.
  1599. * @param appCheckToken The AppCheck token for this client.
  1600. * @param authToken The AuthToken to use for this connection.
  1601. * @param transportSessionId Optional transportSessionid if we are
  1602. * reconnecting for an existing transport session
  1603. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1604. * already created a connection previously
  1605. */
  1606. function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1607. var _this = this;
  1608. this.connId = connId;
  1609. this.repoInfo = repoInfo;
  1610. this.applicationId = applicationId;
  1611. this.appCheckToken = appCheckToken;
  1612. this.authToken = authToken;
  1613. this.transportSessionId = transportSessionId;
  1614. this.lastSessionId = lastSessionId;
  1615. this.bytesSent = 0;
  1616. this.bytesReceived = 0;
  1617. this.everConnected_ = false;
  1618. this.log_ = logWrapper(connId);
  1619. this.stats_ = statsManagerGetCollection(repoInfo);
  1620. this.urlFn = function (params) {
  1621. // Always add the token if we have one.
  1622. if (_this.appCheckToken) {
  1623. params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1624. }
  1625. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1626. };
  1627. }
  1628. /**
  1629. * @param onMessage - Callback when messages arrive
  1630. * @param onDisconnect - Callback with connection lost.
  1631. */
  1632. BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
  1633. var _this = this;
  1634. this.curSegmentNum = 0;
  1635. this.onDisconnect_ = onDisconnect;
  1636. this.myPacketOrderer = new PacketReceiver(onMessage);
  1637. this.isClosed_ = false;
  1638. this.connectTimeoutTimer_ = setTimeout(function () {
  1639. _this.log_('Timed out trying to connect.');
  1640. // Make sure we clear the host cache
  1641. _this.onClosed_();
  1642. _this.connectTimeoutTimer_ = null;
  1643. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1644. }, Math.floor(LP_CONNECT_TIMEOUT));
  1645. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1646. executeWhenDOMReady(function () {
  1647. if (_this.isClosed_) {
  1648. return;
  1649. }
  1650. //Set up a callback that gets triggered once a connection is set up.
  1651. _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
  1652. var args = [];
  1653. for (var _i = 0; _i < arguments.length; _i++) {
  1654. args[_i] = arguments[_i];
  1655. }
  1656. var _a = tslib.__read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
  1657. _this.incrementIncomingBytes_(args);
  1658. if (!_this.scriptTagHolder) {
  1659. return; // we closed the connection.
  1660. }
  1661. if (_this.connectTimeoutTimer_) {
  1662. clearTimeout(_this.connectTimeoutTimer_);
  1663. _this.connectTimeoutTimer_ = null;
  1664. }
  1665. _this.everConnected_ = true;
  1666. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1667. _this.id = arg1;
  1668. _this.password = arg2;
  1669. }
  1670. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1671. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1672. if (arg1) {
  1673. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1674. // through our already open polls), so don't send any more.
  1675. _this.scriptTagHolder.sendNewPolls = false;
  1676. // arg1 in this case is the last response number sent by the server. We should try to receive
  1677. // all of the responses up to this one before closing
  1678. _this.myPacketOrderer.closeAfter(arg1, function () {
  1679. _this.onClosed_();
  1680. });
  1681. }
  1682. else {
  1683. _this.onClosed_();
  1684. }
  1685. }
  1686. else {
  1687. throw new Error('Unrecognized command received: ' + command);
  1688. }
  1689. }, function () {
  1690. var args = [];
  1691. for (var _i = 0; _i < arguments.length; _i++) {
  1692. args[_i] = arguments[_i];
  1693. }
  1694. var _a = tslib.__read(args, 2), pN = _a[0], data = _a[1];
  1695. _this.incrementIncomingBytes_(args);
  1696. _this.myPacketOrderer.handleResponse(pN, data);
  1697. }, function () {
  1698. _this.onClosed_();
  1699. }, _this.urlFn);
  1700. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1701. //from cache.
  1702. var urlParams = {};
  1703. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1704. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1705. if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
  1706. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1707. _this.scriptTagHolder.uniqueCallbackIdentifier;
  1708. }
  1709. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1710. if (_this.transportSessionId) {
  1711. urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
  1712. }
  1713. if (_this.lastSessionId) {
  1714. urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
  1715. }
  1716. if (_this.applicationId) {
  1717. urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
  1718. }
  1719. if (_this.appCheckToken) {
  1720. urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1721. }
  1722. if (typeof location !== 'undefined' &&
  1723. location.hostname &&
  1724. FORGE_DOMAIN_RE.test(location.hostname)) {
  1725. urlParams[REFERER_PARAM] = FORGE_REF;
  1726. }
  1727. var connectURL = _this.urlFn(urlParams);
  1728. _this.log_('Connecting via long-poll to ' + connectURL);
  1729. _this.scriptTagHolder.addTag(connectURL, function () {
  1730. /* do nothing */
  1731. });
  1732. });
  1733. };
  1734. /**
  1735. * Call this when a handshake has completed successfully and we want to consider the connection established
  1736. */
  1737. BrowserPollConnection.prototype.start = function () {
  1738. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1739. this.addDisconnectPingFrame(this.id, this.password);
  1740. };
  1741. /**
  1742. * Forces long polling to be considered as a potential transport
  1743. */
  1744. BrowserPollConnection.forceAllow = function () {
  1745. BrowserPollConnection.forceAllow_ = true;
  1746. };
  1747. /**
  1748. * Forces longpolling to not be considered as a potential transport
  1749. */
  1750. BrowserPollConnection.forceDisallow = function () {
  1751. BrowserPollConnection.forceDisallow_ = true;
  1752. };
  1753. // Static method, use string literal so it can be accessed in a generic way
  1754. BrowserPollConnection.isAvailable = function () {
  1755. if (util.isNodeSdk()) {
  1756. return false;
  1757. }
  1758. else if (BrowserPollConnection.forceAllow_) {
  1759. return true;
  1760. }
  1761. else {
  1762. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1763. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1764. return (!BrowserPollConnection.forceDisallow_ &&
  1765. typeof document !== 'undefined' &&
  1766. document.createElement != null &&
  1767. !isChromeExtensionContentScript() &&
  1768. !isWindowsStoreApp());
  1769. }
  1770. };
  1771. /**
  1772. * No-op for polling
  1773. */
  1774. BrowserPollConnection.prototype.markConnectionHealthy = function () { };
  1775. /**
  1776. * Stops polling and cleans up the iframe
  1777. */
  1778. BrowserPollConnection.prototype.shutdown_ = function () {
  1779. this.isClosed_ = true;
  1780. if (this.scriptTagHolder) {
  1781. this.scriptTagHolder.close();
  1782. this.scriptTagHolder = null;
  1783. }
  1784. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1785. if (this.myDisconnFrame) {
  1786. document.body.removeChild(this.myDisconnFrame);
  1787. this.myDisconnFrame = null;
  1788. }
  1789. if (this.connectTimeoutTimer_) {
  1790. clearTimeout(this.connectTimeoutTimer_);
  1791. this.connectTimeoutTimer_ = null;
  1792. }
  1793. };
  1794. /**
  1795. * Triggered when this transport is closed
  1796. */
  1797. BrowserPollConnection.prototype.onClosed_ = function () {
  1798. if (!this.isClosed_) {
  1799. this.log_('Longpoll is closing itself');
  1800. this.shutdown_();
  1801. if (this.onDisconnect_) {
  1802. this.onDisconnect_(this.everConnected_);
  1803. this.onDisconnect_ = null;
  1804. }
  1805. }
  1806. };
  1807. /**
  1808. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1809. * that we've left.
  1810. */
  1811. BrowserPollConnection.prototype.close = function () {
  1812. if (!this.isClosed_) {
  1813. this.log_('Longpoll is being closed.');
  1814. this.shutdown_();
  1815. }
  1816. };
  1817. /**
  1818. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1819. * broken into chunks (since URLs have a small maximum length).
  1820. * @param data - The JSON data to transmit.
  1821. */
  1822. BrowserPollConnection.prototype.send = function (data) {
  1823. var dataStr = util.stringify(data);
  1824. this.bytesSent += dataStr.length;
  1825. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1826. //first, lets get the base64-encoded data
  1827. var base64data = util.base64Encode(dataStr);
  1828. //We can only fit a certain amount in each URL, so we need to split this request
  1829. //up into multiple pieces if it doesn't fit in one request.
  1830. var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1831. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1832. //of segments so that we can reassemble the packet on the server.
  1833. for (var i = 0; i < dataSegs.length; i++) {
  1834. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1835. this.curSegmentNum++;
  1836. }
  1837. };
  1838. /**
  1839. * This is how we notify the server that we're leaving.
  1840. * We aren't able to send requests with DHTML on a window close event, but we can
  1841. * trigger XHR requests in some browsers (everything but Opera basically).
  1842. */
  1843. BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
  1844. if (util.isNodeSdk()) {
  1845. return;
  1846. }
  1847. this.myDisconnFrame = document.createElement('iframe');
  1848. var urlParams = {};
  1849. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1850. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1851. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1852. this.myDisconnFrame.src = this.urlFn(urlParams);
  1853. this.myDisconnFrame.style.display = 'none';
  1854. document.body.appendChild(this.myDisconnFrame);
  1855. };
  1856. /**
  1857. * Used to track the bytes received by this client
  1858. */
  1859. BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
  1860. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1861. var bytesReceived = util.stringify(args).length;
  1862. this.bytesReceived += bytesReceived;
  1863. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1864. };
  1865. return BrowserPollConnection;
  1866. }());
  1867. /*********************************************************************************************
  1868. * A wrapper around an iframe that is used as a long-polling script holder.
  1869. *********************************************************************************************/
  1870. var FirebaseIFrameScriptHolder = /** @class */ (function () {
  1871. /**
  1872. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1873. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1874. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1875. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1876. */
  1877. function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
  1878. this.onDisconnect = onDisconnect;
  1879. this.urlFn = urlFn;
  1880. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1881. //problems in some browsers.
  1882. this.outstandingRequests = new Set();
  1883. //A queue of the pending segments waiting for transmission to the server.
  1884. this.pendingSegs = [];
  1885. //A serial number. We use this for two things:
  1886. // 1) A way to ensure the browser doesn't cache responses to polls
  1887. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1888. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1889. // JSONP code in the order it was added to the iframe.
  1890. this.currentSerial = Math.floor(Math.random() * 100000000);
  1891. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1892. // incoming data from the server that we're waiting for).
  1893. this.sendNewPolls = true;
  1894. if (!util.isNodeSdk()) {
  1895. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1896. //iframes where we put the long-polling script tags. We have two callbacks:
  1897. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1898. // 2) Message Callback - Triggered when new data arrives.
  1899. this.uniqueCallbackIdentifier = LUIDGenerator();
  1900. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1901. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1902. onMessageCB;
  1903. //Create an iframe for us to add script tags to.
  1904. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1905. // Set the iframe's contents.
  1906. var script = '';
  1907. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1908. // for ie9, but ie8 needs to do it again in the document itself.
  1909. if (this.myIFrame.src &&
  1910. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1911. var currentDomain = document.domain;
  1912. script = '<script>document.domain="' + currentDomain + '";</script>';
  1913. }
  1914. var iframeContents = '<html><body>' + script + '</body></html>';
  1915. try {
  1916. this.myIFrame.doc.open();
  1917. this.myIFrame.doc.write(iframeContents);
  1918. this.myIFrame.doc.close();
  1919. }
  1920. catch (e) {
  1921. log('frame writing exception');
  1922. if (e.stack) {
  1923. log(e.stack);
  1924. }
  1925. log(e);
  1926. }
  1927. }
  1928. else {
  1929. this.commandCB = commandCB;
  1930. this.onMessageCB = onMessageCB;
  1931. }
  1932. }
  1933. /**
  1934. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1935. * actually use.
  1936. */
  1937. FirebaseIFrameScriptHolder.createIFrame_ = function () {
  1938. var iframe = document.createElement('iframe');
  1939. iframe.style.display = 'none';
  1940. // This is necessary in order to initialize the document inside the iframe
  1941. if (document.body) {
  1942. document.body.appendChild(iframe);
  1943. try {
  1944. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1945. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1946. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1947. var a = iframe.contentWindow.document;
  1948. if (!a) {
  1949. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1950. log('No IE domain setting required');
  1951. }
  1952. }
  1953. catch (e) {
  1954. var domain = document.domain;
  1955. iframe.src =
  1956. "javascript:void((function(){document.open();document.domain='" +
  1957. domain +
  1958. "';document.close();})())";
  1959. }
  1960. }
  1961. else {
  1962. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1963. // never gets hit.
  1964. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1965. }
  1966. // Get the document of the iframe in a browser-specific way.
  1967. if (iframe.contentDocument) {
  1968. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1969. }
  1970. else if (iframe.contentWindow) {
  1971. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1972. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1973. }
  1974. else if (iframe.document) {
  1975. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1976. iframe.doc = iframe.document; //others?
  1977. }
  1978. return iframe;
  1979. };
  1980. /**
  1981. * Cancel all outstanding queries and remove the frame.
  1982. */
  1983. FirebaseIFrameScriptHolder.prototype.close = function () {
  1984. var _this = this;
  1985. //Mark this iframe as dead, so no new requests are sent.
  1986. this.alive = false;
  1987. if (this.myIFrame) {
  1988. //We have to actually remove all of the html inside this iframe before removing it from the
  1989. //window, or IE will continue loading and executing the script tags we've already added, which
  1990. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1991. this.myIFrame.doc.body.textContent = '';
  1992. setTimeout(function () {
  1993. if (_this.myIFrame !== null) {
  1994. document.body.removeChild(_this.myIFrame);
  1995. _this.myIFrame = null;
  1996. }
  1997. }, Math.floor(0));
  1998. }
  1999. // Protect from being called recursively.
  2000. var onDisconnect = this.onDisconnect;
  2001. if (onDisconnect) {
  2002. this.onDisconnect = null;
  2003. onDisconnect();
  2004. }
  2005. };
  2006. /**
  2007. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  2008. * @param id - The ID of this connection
  2009. * @param pw - The password for this connection
  2010. */
  2011. FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
  2012. this.myID = id;
  2013. this.myPW = pw;
  2014. this.alive = true;
  2015. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  2016. while (this.newRequest_()) { }
  2017. };
  2018. /**
  2019. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  2020. * too many outstanding requests and we are still alive.
  2021. *
  2022. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  2023. * needed.
  2024. */
  2025. FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
  2026. // We keep one outstanding request open all the time to receive data, but if we need to send data
  2027. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  2028. // close the old request.
  2029. if (this.alive &&
  2030. this.sendNewPolls &&
  2031. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  2032. //construct our url
  2033. this.currentSerial++;
  2034. var urlParams = {};
  2035. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  2036. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  2037. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  2038. var theURL = this.urlFn(urlParams);
  2039. //Now add as much data as we can.
  2040. var curDataString = '';
  2041. var i = 0;
  2042. while (this.pendingSegs.length > 0) {
  2043. //first, lets see if the next segment will fit.
  2044. var nextSeg = this.pendingSegs[0];
  2045. if (nextSeg.d.length +
  2046. SEG_HEADER_SIZE +
  2047. curDataString.length <=
  2048. MAX_URL_DATA_SIZE) {
  2049. //great, the segment will fit. Lets append it.
  2050. var theSeg = this.pendingSegs.shift();
  2051. curDataString =
  2052. curDataString +
  2053. '&' +
  2054. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  2055. i +
  2056. '=' +
  2057. theSeg.seg +
  2058. '&' +
  2059. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  2060. i +
  2061. '=' +
  2062. theSeg.ts +
  2063. '&' +
  2064. FIREBASE_LONGPOLL_DATA_PARAM +
  2065. i +
  2066. '=' +
  2067. theSeg.d;
  2068. i++;
  2069. }
  2070. else {
  2071. break;
  2072. }
  2073. }
  2074. theURL = theURL + curDataString;
  2075. this.addLongPollTag_(theURL, this.currentSerial);
  2076. return true;
  2077. }
  2078. else {
  2079. return false;
  2080. }
  2081. };
  2082. /**
  2083. * Queue a packet for transmission to the server.
  2084. * @param segnum - A sequential id for this packet segment used for reassembly
  2085. * @param totalsegs - The total number of segments in this packet
  2086. * @param data - The data for this segment.
  2087. */
  2088. FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
  2089. //add this to the queue of segments to send.
  2090. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  2091. //send the data immediately if there isn't already data being transmitted, unless
  2092. //startLongPoll hasn't been called yet.
  2093. if (this.alive) {
  2094. this.newRequest_();
  2095. }
  2096. };
  2097. /**
  2098. * Add a script tag for a regular long-poll request.
  2099. * @param url - The URL of the script tag.
  2100. * @param serial - The serial number of the request.
  2101. */
  2102. FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
  2103. var _this = this;
  2104. //remember that we sent this request.
  2105. this.outstandingRequests.add(serial);
  2106. var doNewRequest = function () {
  2107. _this.outstandingRequests.delete(serial);
  2108. _this.newRequest_();
  2109. };
  2110. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  2111. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  2112. var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  2113. var readyStateCB = function () {
  2114. // Request completed. Cancel the keepalive.
  2115. clearTimeout(keepaliveTimeout);
  2116. // Trigger a new request so we can continue receiving data.
  2117. doNewRequest();
  2118. };
  2119. this.addTag(url, readyStateCB);
  2120. };
  2121. /**
  2122. * Add an arbitrary script tag to the iframe.
  2123. * @param url - The URL for the script tag source.
  2124. * @param loadCB - A callback to be triggered once the script has loaded.
  2125. */
  2126. FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
  2127. var _this = this;
  2128. if (util.isNodeSdk()) {
  2129. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2130. this.doNodeLongPoll(url, loadCB);
  2131. }
  2132. else {
  2133. setTimeout(function () {
  2134. try {
  2135. // if we're already closed, don't add this poll
  2136. if (!_this.sendNewPolls) {
  2137. return;
  2138. }
  2139. var newScript_1 = _this.myIFrame.doc.createElement('script');
  2140. newScript_1.type = 'text/javascript';
  2141. newScript_1.async = true;
  2142. newScript_1.src = url;
  2143. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2144. newScript_1.onload = newScript_1.onreadystatechange =
  2145. function () {
  2146. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2147. var rstate = newScript_1.readyState;
  2148. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  2149. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2150. newScript_1.onload = newScript_1.onreadystatechange = null;
  2151. if (newScript_1.parentNode) {
  2152. newScript_1.parentNode.removeChild(newScript_1);
  2153. }
  2154. loadCB();
  2155. }
  2156. };
  2157. newScript_1.onerror = function () {
  2158. log('Long-poll script failed to load: ' + url);
  2159. _this.sendNewPolls = false;
  2160. _this.close();
  2161. };
  2162. _this.myIFrame.doc.body.appendChild(newScript_1);
  2163. }
  2164. catch (e) {
  2165. // TODO: we should make this error visible somehow
  2166. }
  2167. }, Math.floor(1));
  2168. }
  2169. };
  2170. return FirebaseIFrameScriptHolder;
  2171. }());
  2172. /**
  2173. * @license
  2174. * Copyright 2017 Google LLC
  2175. *
  2176. * Licensed under the Apache License, Version 2.0 (the "License");
  2177. * you may not use this file except in compliance with the License.
  2178. * You may obtain a copy of the License at
  2179. *
  2180. * http://www.apache.org/licenses/LICENSE-2.0
  2181. *
  2182. * Unless required by applicable law or agreed to in writing, software
  2183. * distributed under the License is distributed on an "AS IS" BASIS,
  2184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2185. * See the License for the specific language governing permissions and
  2186. * limitations under the License.
  2187. */
  2188. /**
  2189. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2190. * lifecycle.
  2191. *
  2192. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2193. * they are available.
  2194. */
  2195. var TransportManager = /** @class */ (function () {
  2196. /**
  2197. * @param repoInfo - Metadata around the namespace we're connecting to
  2198. */
  2199. function TransportManager(repoInfo) {
  2200. this.initTransports_(repoInfo);
  2201. }
  2202. Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
  2203. get: function () {
  2204. return [BrowserPollConnection, WebSocketConnection];
  2205. },
  2206. enumerable: false,
  2207. configurable: true
  2208. });
  2209. Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
  2210. /**
  2211. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2212. * TransportManager has already set up transports_
  2213. */
  2214. get: function () {
  2215. return this.globalTransportInitialized_;
  2216. },
  2217. enumerable: false,
  2218. configurable: true
  2219. });
  2220. TransportManager.prototype.initTransports_ = function (repoInfo) {
  2221. var e_1, _a;
  2222. var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2223. var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2224. if (repoInfo.webSocketOnly) {
  2225. if (!isWebSocketsAvailable) {
  2226. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2227. }
  2228. isSkipPollConnection = true;
  2229. }
  2230. if (isSkipPollConnection) {
  2231. this.transports_ = [WebSocketConnection];
  2232. }
  2233. else {
  2234. var transports = (this.transports_ = []);
  2235. try {
  2236. for (var _b = tslib.__values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
  2237. var transport = _c.value;
  2238. if (transport && transport['isAvailable']()) {
  2239. transports.push(transport);
  2240. }
  2241. }
  2242. }
  2243. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2244. finally {
  2245. try {
  2246. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  2247. }
  2248. finally { if (e_1) throw e_1.error; }
  2249. }
  2250. TransportManager.globalTransportInitialized_ = true;
  2251. }
  2252. };
  2253. /**
  2254. * @returns The constructor for the initial transport to use
  2255. */
  2256. TransportManager.prototype.initialTransport = function () {
  2257. if (this.transports_.length > 0) {
  2258. return this.transports_[0];
  2259. }
  2260. else {
  2261. throw new Error('No transports available');
  2262. }
  2263. };
  2264. /**
  2265. * @returns The constructor for the next transport, or null
  2266. */
  2267. TransportManager.prototype.upgradeTransport = function () {
  2268. if (this.transports_.length > 1) {
  2269. return this.transports_[1];
  2270. }
  2271. else {
  2272. return null;
  2273. }
  2274. };
  2275. // Keeps track of whether the TransportManager has already chosen a transport to use
  2276. TransportManager.globalTransportInitialized_ = false;
  2277. return TransportManager;
  2278. }());
  2279. /**
  2280. * @license
  2281. * Copyright 2017 Google LLC
  2282. *
  2283. * Licensed under the Apache License, Version 2.0 (the "License");
  2284. * you may not use this file except in compliance with the License.
  2285. * You may obtain a copy of the License at
  2286. *
  2287. * http://www.apache.org/licenses/LICENSE-2.0
  2288. *
  2289. * Unless required by applicable law or agreed to in writing, software
  2290. * distributed under the License is distributed on an "AS IS" BASIS,
  2291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2292. * See the License for the specific language governing permissions and
  2293. * limitations under the License.
  2294. */
  2295. // Abort upgrade attempt if it takes longer than 60s.
  2296. var UPGRADE_TIMEOUT = 60000;
  2297. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2298. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2299. var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2300. // If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)
  2301. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2302. // but we've sent/received enough bytes, we don't cancel the connection.
  2303. var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2304. var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2305. var MESSAGE_TYPE = 't';
  2306. var MESSAGE_DATA = 'd';
  2307. var CONTROL_SHUTDOWN = 's';
  2308. var CONTROL_RESET = 'r';
  2309. var CONTROL_ERROR = 'e';
  2310. var CONTROL_PONG = 'o';
  2311. var SWITCH_ACK = 'a';
  2312. var END_TRANSMISSION = 'n';
  2313. var PING = 'p';
  2314. var SERVER_HELLO = 'h';
  2315. /**
  2316. * Creates a new real-time connection to the server using whichever method works
  2317. * best in the current browser.
  2318. */
  2319. var Connection = /** @class */ (function () {
  2320. /**
  2321. * @param id - an id for this connection
  2322. * @param repoInfo_ - the info for the endpoint to connect to
  2323. * @param applicationId_ - the Firebase App ID for this project
  2324. * @param appCheckToken_ - The App Check Token for this device.
  2325. * @param authToken_ - The auth token for this session.
  2326. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2327. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2328. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2329. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2330. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2331. */
  2332. function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2333. this.id = id;
  2334. this.repoInfo_ = repoInfo_;
  2335. this.applicationId_ = applicationId_;
  2336. this.appCheckToken_ = appCheckToken_;
  2337. this.authToken_ = authToken_;
  2338. this.onMessage_ = onMessage_;
  2339. this.onReady_ = onReady_;
  2340. this.onDisconnect_ = onDisconnect_;
  2341. this.onKill_ = onKill_;
  2342. this.lastSessionId = lastSessionId;
  2343. this.connectionCount = 0;
  2344. this.pendingDataMessages = [];
  2345. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2346. this.log_ = logWrapper('c:' + this.id + ':');
  2347. this.transportManager_ = new TransportManager(repoInfo_);
  2348. this.log_('Connection created');
  2349. this.start_();
  2350. }
  2351. /**
  2352. * Starts a connection attempt
  2353. */
  2354. Connection.prototype.start_ = function () {
  2355. var _this = this;
  2356. var conn = this.transportManager_.initialTransport();
  2357. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2358. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2359. // can consider the transport healthy.
  2360. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2361. var onMessageReceived = this.connReceiver_(this.conn_);
  2362. var onConnectionLost = this.disconnReceiver_(this.conn_);
  2363. this.tx_ = this.conn_;
  2364. this.rx_ = this.conn_;
  2365. this.secondaryConn_ = null;
  2366. this.isHealthy_ = false;
  2367. /*
  2368. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2369. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2370. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2371. * still have the context of your originating frame.
  2372. */
  2373. setTimeout(function () {
  2374. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2375. _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
  2376. }, Math.floor(0));
  2377. var healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2378. if (healthyTimeoutMS > 0) {
  2379. this.healthyTimeout_ = setTimeoutNonBlocking(function () {
  2380. _this.healthyTimeout_ = null;
  2381. if (!_this.isHealthy_) {
  2382. if (_this.conn_ &&
  2383. _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2384. _this.log_('Connection exceeded healthy timeout but has received ' +
  2385. _this.conn_.bytesReceived +
  2386. ' bytes. Marking connection healthy.');
  2387. _this.isHealthy_ = true;
  2388. _this.conn_.markConnectionHealthy();
  2389. }
  2390. else if (_this.conn_ &&
  2391. _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2392. _this.log_('Connection exceeded healthy timeout but has sent ' +
  2393. _this.conn_.bytesSent +
  2394. ' bytes. Leaving connection alive.');
  2395. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2396. // the server.
  2397. }
  2398. else {
  2399. _this.log_('Closing unhealthy connection after timeout.');
  2400. _this.close();
  2401. }
  2402. }
  2403. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2404. }, Math.floor(healthyTimeoutMS));
  2405. }
  2406. };
  2407. Connection.prototype.nextTransportId_ = function () {
  2408. return 'c:' + this.id + ':' + this.connectionCount++;
  2409. };
  2410. Connection.prototype.disconnReceiver_ = function (conn) {
  2411. var _this = this;
  2412. return function (everConnected) {
  2413. if (conn === _this.conn_) {
  2414. _this.onConnectionLost_(everConnected);
  2415. }
  2416. else if (conn === _this.secondaryConn_) {
  2417. _this.log_('Secondary connection lost.');
  2418. _this.onSecondaryConnectionLost_();
  2419. }
  2420. else {
  2421. _this.log_('closing an old connection');
  2422. }
  2423. };
  2424. };
  2425. Connection.prototype.connReceiver_ = function (conn) {
  2426. var _this = this;
  2427. return function (message) {
  2428. if (_this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2429. if (conn === _this.rx_) {
  2430. _this.onPrimaryMessageReceived_(message);
  2431. }
  2432. else if (conn === _this.secondaryConn_) {
  2433. _this.onSecondaryMessageReceived_(message);
  2434. }
  2435. else {
  2436. _this.log_('message on old connection');
  2437. }
  2438. }
  2439. };
  2440. };
  2441. /**
  2442. * @param dataMsg - An arbitrary data message to be sent to the server
  2443. */
  2444. Connection.prototype.sendRequest = function (dataMsg) {
  2445. // wrap in a data message envelope and send it on
  2446. var msg = { t: 'd', d: dataMsg };
  2447. this.sendData_(msg);
  2448. };
  2449. Connection.prototype.tryCleanupConnection = function () {
  2450. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2451. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2452. this.conn_ = this.secondaryConn_;
  2453. this.secondaryConn_ = null;
  2454. // the server will shutdown the old connection
  2455. }
  2456. };
  2457. Connection.prototype.onSecondaryControl_ = function (controlData) {
  2458. if (MESSAGE_TYPE in controlData) {
  2459. var cmd = controlData[MESSAGE_TYPE];
  2460. if (cmd === SWITCH_ACK) {
  2461. this.upgradeIfSecondaryHealthy_();
  2462. }
  2463. else if (cmd === CONTROL_RESET) {
  2464. // Most likely the session wasn't valid. Abandon the switch attempt
  2465. this.log_('Got a reset on secondary, closing it');
  2466. this.secondaryConn_.close();
  2467. // If we were already using this connection for something, than we need to fully close
  2468. if (this.tx_ === this.secondaryConn_ ||
  2469. this.rx_ === this.secondaryConn_) {
  2470. this.close();
  2471. }
  2472. }
  2473. else if (cmd === CONTROL_PONG) {
  2474. this.log_('got pong on secondary.');
  2475. this.secondaryResponsesRequired_--;
  2476. this.upgradeIfSecondaryHealthy_();
  2477. }
  2478. }
  2479. };
  2480. Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
  2481. var layer = requireKey('t', parsedData);
  2482. var data = requireKey('d', parsedData);
  2483. if (layer === 'c') {
  2484. this.onSecondaryControl_(data);
  2485. }
  2486. else if (layer === 'd') {
  2487. // got a data message, but we're still second connection. Need to buffer it up
  2488. this.pendingDataMessages.push(data);
  2489. }
  2490. else {
  2491. throw new Error('Unknown protocol layer: ' + layer);
  2492. }
  2493. };
  2494. Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
  2495. if (this.secondaryResponsesRequired_ <= 0) {
  2496. this.log_('Secondary connection is healthy.');
  2497. this.isHealthy_ = true;
  2498. this.secondaryConn_.markConnectionHealthy();
  2499. this.proceedWithUpgrade_();
  2500. }
  2501. else {
  2502. // Send a ping to make sure the connection is healthy.
  2503. this.log_('sending ping on secondary.');
  2504. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2505. }
  2506. };
  2507. Connection.prototype.proceedWithUpgrade_ = function () {
  2508. // tell this connection to consider itself open
  2509. this.secondaryConn_.start();
  2510. // send ack
  2511. this.log_('sending client ack on secondary');
  2512. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2513. // send end packet on primary transport, switch to sending on this one
  2514. // can receive on this one, buffer responses until end received on primary transport
  2515. this.log_('Ending transmission on primary');
  2516. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2517. this.tx_ = this.secondaryConn_;
  2518. this.tryCleanupConnection();
  2519. };
  2520. Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
  2521. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2522. var layer = requireKey('t', parsedData);
  2523. var data = requireKey('d', parsedData);
  2524. if (layer === 'c') {
  2525. this.onControl_(data);
  2526. }
  2527. else if (layer === 'd') {
  2528. this.onDataMessage_(data);
  2529. }
  2530. };
  2531. Connection.prototype.onDataMessage_ = function (message) {
  2532. this.onPrimaryResponse_();
  2533. // We don't do anything with data messages, just kick them up a level
  2534. this.onMessage_(message);
  2535. };
  2536. Connection.prototype.onPrimaryResponse_ = function () {
  2537. if (!this.isHealthy_) {
  2538. this.primaryResponsesRequired_--;
  2539. if (this.primaryResponsesRequired_ <= 0) {
  2540. this.log_('Primary connection is healthy.');
  2541. this.isHealthy_ = true;
  2542. this.conn_.markConnectionHealthy();
  2543. }
  2544. }
  2545. };
  2546. Connection.prototype.onControl_ = function (controlData) {
  2547. var cmd = requireKey(MESSAGE_TYPE, controlData);
  2548. if (MESSAGE_DATA in controlData) {
  2549. var payload = controlData[MESSAGE_DATA];
  2550. if (cmd === SERVER_HELLO) {
  2551. this.onHandshake_(payload);
  2552. }
  2553. else if (cmd === END_TRANSMISSION) {
  2554. this.log_('recvd end transmission on primary');
  2555. this.rx_ = this.secondaryConn_;
  2556. for (var i = 0; i < this.pendingDataMessages.length; ++i) {
  2557. this.onDataMessage_(this.pendingDataMessages[i]);
  2558. }
  2559. this.pendingDataMessages = [];
  2560. this.tryCleanupConnection();
  2561. }
  2562. else if (cmd === CONTROL_SHUTDOWN) {
  2563. // This was previously the 'onKill' callback passed to the lower-level connection
  2564. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2565. this.onConnectionShutdown_(payload);
  2566. }
  2567. else if (cmd === CONTROL_RESET) {
  2568. // payload in this case is the host we should contact
  2569. this.onReset_(payload);
  2570. }
  2571. else if (cmd === CONTROL_ERROR) {
  2572. error('Server Error: ' + payload);
  2573. }
  2574. else if (cmd === CONTROL_PONG) {
  2575. this.log_('got pong on primary.');
  2576. this.onPrimaryResponse_();
  2577. this.sendPingOnPrimaryIfNecessary_();
  2578. }
  2579. else {
  2580. error('Unknown control packet command: ' + cmd);
  2581. }
  2582. }
  2583. };
  2584. /**
  2585. * @param handshake - The handshake data returned from the server
  2586. */
  2587. Connection.prototype.onHandshake_ = function (handshake) {
  2588. var timestamp = handshake.ts;
  2589. var version = handshake.v;
  2590. var host = handshake.h;
  2591. this.sessionId = handshake.s;
  2592. this.repoInfo_.host = host;
  2593. // if we've already closed the connection, then don't bother trying to progress further
  2594. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2595. this.conn_.start();
  2596. this.onConnectionEstablished_(this.conn_, timestamp);
  2597. if (PROTOCOL_VERSION !== version) {
  2598. warn('Protocol version mismatch detected');
  2599. }
  2600. // TODO: do we want to upgrade? when? maybe a delay?
  2601. this.tryStartUpgrade_();
  2602. }
  2603. };
  2604. Connection.prototype.tryStartUpgrade_ = function () {
  2605. var conn = this.transportManager_.upgradeTransport();
  2606. if (conn) {
  2607. this.startUpgrade_(conn);
  2608. }
  2609. };
  2610. Connection.prototype.startUpgrade_ = function (conn) {
  2611. var _this = this;
  2612. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2613. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2614. // can consider the transport healthy.
  2615. this.secondaryResponsesRequired_ =
  2616. conn['responsesRequiredToBeHealthy'] || 0;
  2617. var onMessage = this.connReceiver_(this.secondaryConn_);
  2618. var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2619. this.secondaryConn_.open(onMessage, onDisconnect);
  2620. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2621. setTimeoutNonBlocking(function () {
  2622. if (_this.secondaryConn_) {
  2623. _this.log_('Timed out trying to upgrade.');
  2624. _this.secondaryConn_.close();
  2625. }
  2626. }, Math.floor(UPGRADE_TIMEOUT));
  2627. };
  2628. Connection.prototype.onReset_ = function (host) {
  2629. this.log_('Reset packet received. New host: ' + host);
  2630. this.repoInfo_.host = host;
  2631. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2632. // We don't currently support resets after the connection has already been established
  2633. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2634. this.close();
  2635. }
  2636. else {
  2637. // Close whatever connections we have open and start again.
  2638. this.closeConnections_();
  2639. this.start_();
  2640. }
  2641. };
  2642. Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
  2643. var _this = this;
  2644. this.log_('Realtime connection established.');
  2645. this.conn_ = conn;
  2646. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2647. if (this.onReady_) {
  2648. this.onReady_(timestamp, this.sessionId);
  2649. this.onReady_ = null;
  2650. }
  2651. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2652. // send some pings.
  2653. if (this.primaryResponsesRequired_ === 0) {
  2654. this.log_('Primary connection is healthy.');
  2655. this.isHealthy_ = true;
  2656. }
  2657. else {
  2658. setTimeoutNonBlocking(function () {
  2659. _this.sendPingOnPrimaryIfNecessary_();
  2660. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2661. }
  2662. };
  2663. Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
  2664. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2665. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2666. this.log_('sending ping on primary.');
  2667. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2668. }
  2669. };
  2670. Connection.prototype.onSecondaryConnectionLost_ = function () {
  2671. var conn = this.secondaryConn_;
  2672. this.secondaryConn_ = null;
  2673. if (this.tx_ === conn || this.rx_ === conn) {
  2674. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2675. this.close();
  2676. }
  2677. };
  2678. /**
  2679. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2680. * we should flush the host cache
  2681. */
  2682. Connection.prototype.onConnectionLost_ = function (everConnected) {
  2683. this.conn_ = null;
  2684. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2685. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2686. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2687. this.log_('Realtime connection failed.');
  2688. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2689. if (this.repoInfo_.isCacheableHost()) {
  2690. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2691. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2692. this.repoInfo_.internalHost = this.repoInfo_.host;
  2693. }
  2694. }
  2695. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2696. this.log_('Realtime connection lost.');
  2697. }
  2698. this.close();
  2699. };
  2700. Connection.prototype.onConnectionShutdown_ = function (reason) {
  2701. this.log_('Connection shutdown command received. Shutting down...');
  2702. if (this.onKill_) {
  2703. this.onKill_(reason);
  2704. this.onKill_ = null;
  2705. }
  2706. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2707. // so clear the callback.
  2708. this.onDisconnect_ = null;
  2709. this.close();
  2710. };
  2711. Connection.prototype.sendData_ = function (data) {
  2712. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2713. throw 'Connection is not connected';
  2714. }
  2715. else {
  2716. this.tx_.send(data);
  2717. }
  2718. };
  2719. /**
  2720. * Cleans up this connection, calling the appropriate callbacks
  2721. */
  2722. Connection.prototype.close = function () {
  2723. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2724. this.log_('Closing realtime connection.');
  2725. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2726. this.closeConnections_();
  2727. if (this.onDisconnect_) {
  2728. this.onDisconnect_();
  2729. this.onDisconnect_ = null;
  2730. }
  2731. }
  2732. };
  2733. Connection.prototype.closeConnections_ = function () {
  2734. this.log_('Shutting down all connections');
  2735. if (this.conn_) {
  2736. this.conn_.close();
  2737. this.conn_ = null;
  2738. }
  2739. if (this.secondaryConn_) {
  2740. this.secondaryConn_.close();
  2741. this.secondaryConn_ = null;
  2742. }
  2743. if (this.healthyTimeout_) {
  2744. clearTimeout(this.healthyTimeout_);
  2745. this.healthyTimeout_ = null;
  2746. }
  2747. };
  2748. return Connection;
  2749. }());
  2750. /**
  2751. * @license
  2752. * Copyright 2017 Google LLC
  2753. *
  2754. * Licensed under the Apache License, Version 2.0 (the "License");
  2755. * you may not use this file except in compliance with the License.
  2756. * You may obtain a copy of the License at
  2757. *
  2758. * http://www.apache.org/licenses/LICENSE-2.0
  2759. *
  2760. * Unless required by applicable law or agreed to in writing, software
  2761. * distributed under the License is distributed on an "AS IS" BASIS,
  2762. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2763. * See the License for the specific language governing permissions and
  2764. * limitations under the License.
  2765. */
  2766. /**
  2767. * Interface defining the set of actions that can be performed against the Firebase server
  2768. * (basically corresponds to our wire protocol).
  2769. *
  2770. * @interface
  2771. */
  2772. var ServerActions = /** @class */ (function () {
  2773. function ServerActions() {
  2774. }
  2775. ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
  2776. ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
  2777. /**
  2778. * Refreshes the auth token for the current connection.
  2779. * @param token - The authentication token
  2780. */
  2781. ServerActions.prototype.refreshAuthToken = function (token) { };
  2782. /**
  2783. * Refreshes the app check token for the current connection.
  2784. * @param token The app check token
  2785. */
  2786. ServerActions.prototype.refreshAppCheckToken = function (token) { };
  2787. ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
  2788. ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
  2789. ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
  2790. ServerActions.prototype.reportStats = function (stats) { };
  2791. return ServerActions;
  2792. }());
  2793. /**
  2794. * @license
  2795. * Copyright 2017 Google LLC
  2796. *
  2797. * Licensed under the Apache License, Version 2.0 (the "License");
  2798. * you may not use this file except in compliance with the License.
  2799. * You may obtain a copy of the License at
  2800. *
  2801. * http://www.apache.org/licenses/LICENSE-2.0
  2802. *
  2803. * Unless required by applicable law or agreed to in writing, software
  2804. * distributed under the License is distributed on an "AS IS" BASIS,
  2805. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2806. * See the License for the specific language governing permissions and
  2807. * limitations under the License.
  2808. */
  2809. /**
  2810. * Base class to be used if you want to emit events. Call the constructor with
  2811. * the set of allowed event names.
  2812. */
  2813. var EventEmitter = /** @class */ (function () {
  2814. function EventEmitter(allowedEvents_) {
  2815. this.allowedEvents_ = allowedEvents_;
  2816. this.listeners_ = {};
  2817. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2818. }
  2819. /**
  2820. * To be called by derived classes to trigger events.
  2821. */
  2822. EventEmitter.prototype.trigger = function (eventType) {
  2823. var varArgs = [];
  2824. for (var _i = 1; _i < arguments.length; _i++) {
  2825. varArgs[_i - 1] = arguments[_i];
  2826. }
  2827. if (Array.isArray(this.listeners_[eventType])) {
  2828. // Clone the list, since callbacks could add/remove listeners.
  2829. var listeners = tslib.__spreadArray([], tslib.__read(this.listeners_[eventType]), false);
  2830. for (var i = 0; i < listeners.length; i++) {
  2831. listeners[i].callback.apply(listeners[i].context, varArgs);
  2832. }
  2833. }
  2834. };
  2835. EventEmitter.prototype.on = function (eventType, callback, context) {
  2836. this.validateEventType_(eventType);
  2837. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2838. this.listeners_[eventType].push({ callback: callback, context: context });
  2839. var eventData = this.getInitialEvent(eventType);
  2840. if (eventData) {
  2841. callback.apply(context, eventData);
  2842. }
  2843. };
  2844. EventEmitter.prototype.off = function (eventType, callback, context) {
  2845. this.validateEventType_(eventType);
  2846. var listeners = this.listeners_[eventType] || [];
  2847. for (var i = 0; i < listeners.length; i++) {
  2848. if (listeners[i].callback === callback &&
  2849. (!context || context === listeners[i].context)) {
  2850. listeners.splice(i, 1);
  2851. return;
  2852. }
  2853. }
  2854. };
  2855. EventEmitter.prototype.validateEventType_ = function (eventType) {
  2856. util.assert(this.allowedEvents_.find(function (et) {
  2857. return et === eventType;
  2858. }), 'Unknown event: ' + eventType);
  2859. };
  2860. return EventEmitter;
  2861. }());
  2862. /**
  2863. * @license
  2864. * Copyright 2017 Google LLC
  2865. *
  2866. * Licensed under the Apache License, Version 2.0 (the "License");
  2867. * you may not use this file except in compliance with the License.
  2868. * You may obtain a copy of the License at
  2869. *
  2870. * http://www.apache.org/licenses/LICENSE-2.0
  2871. *
  2872. * Unless required by applicable law or agreed to in writing, software
  2873. * distributed under the License is distributed on an "AS IS" BASIS,
  2874. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2875. * See the License for the specific language governing permissions and
  2876. * limitations under the License.
  2877. */
  2878. /**
  2879. * Monitors online state (as reported by window.online/offline events).
  2880. *
  2881. * The expectation is that this could have many false positives (thinks we are online
  2882. * when we're not), but no false negatives. So we can safely use it to determine when
  2883. * we definitely cannot reach the internet.
  2884. */
  2885. var OnlineMonitor = /** @class */ (function (_super) {
  2886. tslib.__extends(OnlineMonitor, _super);
  2887. function OnlineMonitor() {
  2888. var _this = _super.call(this, ['online']) || this;
  2889. _this.online_ = true;
  2890. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2891. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2892. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2893. // for Cordova.
  2894. if (typeof window !== 'undefined' &&
  2895. typeof window.addEventListener !== 'undefined' &&
  2896. !util.isMobileCordova()) {
  2897. window.addEventListener('online', function () {
  2898. if (!_this.online_) {
  2899. _this.online_ = true;
  2900. _this.trigger('online', true);
  2901. }
  2902. }, false);
  2903. window.addEventListener('offline', function () {
  2904. if (_this.online_) {
  2905. _this.online_ = false;
  2906. _this.trigger('online', false);
  2907. }
  2908. }, false);
  2909. }
  2910. return _this;
  2911. }
  2912. OnlineMonitor.getInstance = function () {
  2913. return new OnlineMonitor();
  2914. };
  2915. OnlineMonitor.prototype.getInitialEvent = function (eventType) {
  2916. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2917. return [this.online_];
  2918. };
  2919. OnlineMonitor.prototype.currentlyOnline = function () {
  2920. return this.online_;
  2921. };
  2922. return OnlineMonitor;
  2923. }(EventEmitter));
  2924. /**
  2925. * @license
  2926. * Copyright 2017 Google LLC
  2927. *
  2928. * Licensed under the Apache License, Version 2.0 (the "License");
  2929. * you may not use this file except in compliance with the License.
  2930. * You may obtain a copy of the License at
  2931. *
  2932. * http://www.apache.org/licenses/LICENSE-2.0
  2933. *
  2934. * Unless required by applicable law or agreed to in writing, software
  2935. * distributed under the License is distributed on an "AS IS" BASIS,
  2936. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2937. * See the License for the specific language governing permissions and
  2938. * limitations under the License.
  2939. */
  2940. /** Maximum key depth. */
  2941. var MAX_PATH_DEPTH = 32;
  2942. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2943. var MAX_PATH_LENGTH_BYTES = 768;
  2944. /**
  2945. * An immutable object representing a parsed path. It's immutable so that you
  2946. * can pass them around to other functions without worrying about them changing
  2947. * it.
  2948. */
  2949. var Path = /** @class */ (function () {
  2950. /**
  2951. * @param pathOrString - Path string to parse, or another path, or the raw
  2952. * tokens array
  2953. */
  2954. function Path(pathOrString, pieceNum) {
  2955. if (pieceNum === void 0) {
  2956. this.pieces_ = pathOrString.split('/');
  2957. // Remove empty pieces.
  2958. var copyTo = 0;
  2959. for (var i = 0; i < this.pieces_.length; i++) {
  2960. if (this.pieces_[i].length > 0) {
  2961. this.pieces_[copyTo] = this.pieces_[i];
  2962. copyTo++;
  2963. }
  2964. }
  2965. this.pieces_.length = copyTo;
  2966. this.pieceNum_ = 0;
  2967. }
  2968. else {
  2969. this.pieces_ = pathOrString;
  2970. this.pieceNum_ = pieceNum;
  2971. }
  2972. }
  2973. Path.prototype.toString = function () {
  2974. var pathString = '';
  2975. for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
  2976. if (this.pieces_[i] !== '') {
  2977. pathString += '/' + this.pieces_[i];
  2978. }
  2979. }
  2980. return pathString || '/';
  2981. };
  2982. return Path;
  2983. }());
  2984. function newEmptyPath() {
  2985. return new Path('');
  2986. }
  2987. function pathGetFront(path) {
  2988. if (path.pieceNum_ >= path.pieces_.length) {
  2989. return null;
  2990. }
  2991. return path.pieces_[path.pieceNum_];
  2992. }
  2993. /**
  2994. * @returns The number of segments in this path
  2995. */
  2996. function pathGetLength(path) {
  2997. return path.pieces_.length - path.pieceNum_;
  2998. }
  2999. function pathPopFront(path) {
  3000. var pieceNum = path.pieceNum_;
  3001. if (pieceNum < path.pieces_.length) {
  3002. pieceNum++;
  3003. }
  3004. return new Path(path.pieces_, pieceNum);
  3005. }
  3006. function pathGetBack(path) {
  3007. if (path.pieceNum_ < path.pieces_.length) {
  3008. return path.pieces_[path.pieces_.length - 1];
  3009. }
  3010. return null;
  3011. }
  3012. function pathToUrlEncodedString(path) {
  3013. var pathString = '';
  3014. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3015. if (path.pieces_[i] !== '') {
  3016. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  3017. }
  3018. }
  3019. return pathString || '/';
  3020. }
  3021. /**
  3022. * Shallow copy of the parts of the path.
  3023. *
  3024. */
  3025. function pathSlice(path, begin) {
  3026. if (begin === void 0) { begin = 0; }
  3027. return path.pieces_.slice(path.pieceNum_ + begin);
  3028. }
  3029. function pathParent(path) {
  3030. if (path.pieceNum_ >= path.pieces_.length) {
  3031. return null;
  3032. }
  3033. var pieces = [];
  3034. for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  3035. pieces.push(path.pieces_[i]);
  3036. }
  3037. return new Path(pieces, 0);
  3038. }
  3039. function pathChild(path, childPathObj) {
  3040. var pieces = [];
  3041. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3042. pieces.push(path.pieces_[i]);
  3043. }
  3044. if (childPathObj instanceof Path) {
  3045. for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  3046. pieces.push(childPathObj.pieces_[i]);
  3047. }
  3048. }
  3049. else {
  3050. var childPieces = childPathObj.split('/');
  3051. for (var i = 0; i < childPieces.length; i++) {
  3052. if (childPieces[i].length > 0) {
  3053. pieces.push(childPieces[i]);
  3054. }
  3055. }
  3056. }
  3057. return new Path(pieces, 0);
  3058. }
  3059. /**
  3060. * @returns True if there are no segments in this path
  3061. */
  3062. function pathIsEmpty(path) {
  3063. return path.pieceNum_ >= path.pieces_.length;
  3064. }
  3065. /**
  3066. * @returns The path from outerPath to innerPath
  3067. */
  3068. function newRelativePath(outerPath, innerPath) {
  3069. var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  3070. if (outer === null) {
  3071. return innerPath;
  3072. }
  3073. else if (outer === inner) {
  3074. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  3075. }
  3076. else {
  3077. throw new Error('INTERNAL ERROR: innerPath (' +
  3078. innerPath +
  3079. ') is not within ' +
  3080. 'outerPath (' +
  3081. outerPath +
  3082. ')');
  3083. }
  3084. }
  3085. /**
  3086. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  3087. */
  3088. function pathCompare(left, right) {
  3089. var leftKeys = pathSlice(left, 0);
  3090. var rightKeys = pathSlice(right, 0);
  3091. for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  3092. var cmp = nameCompare(leftKeys[i], rightKeys[i]);
  3093. if (cmp !== 0) {
  3094. return cmp;
  3095. }
  3096. }
  3097. if (leftKeys.length === rightKeys.length) {
  3098. return 0;
  3099. }
  3100. return leftKeys.length < rightKeys.length ? -1 : 1;
  3101. }
  3102. /**
  3103. * @returns true if paths are the same.
  3104. */
  3105. function pathEquals(path, other) {
  3106. if (pathGetLength(path) !== pathGetLength(other)) {
  3107. return false;
  3108. }
  3109. for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3110. if (path.pieces_[i] !== other.pieces_[j]) {
  3111. return false;
  3112. }
  3113. }
  3114. return true;
  3115. }
  3116. /**
  3117. * @returns True if this path is a parent of (or the same as) other
  3118. */
  3119. function pathContains(path, other) {
  3120. var i = path.pieceNum_;
  3121. var j = other.pieceNum_;
  3122. if (pathGetLength(path) > pathGetLength(other)) {
  3123. return false;
  3124. }
  3125. while (i < path.pieces_.length) {
  3126. if (path.pieces_[i] !== other.pieces_[j]) {
  3127. return false;
  3128. }
  3129. ++i;
  3130. ++j;
  3131. }
  3132. return true;
  3133. }
  3134. /**
  3135. * Dynamic (mutable) path used to count path lengths.
  3136. *
  3137. * This class is used to efficiently check paths for valid
  3138. * length (in UTF8 bytes) and depth (used in path validation).
  3139. *
  3140. * Throws Error exception if path is ever invalid.
  3141. *
  3142. * The definition of a path always begins with '/'.
  3143. */
  3144. var ValidationPath = /** @class */ (function () {
  3145. /**
  3146. * @param path - Initial Path.
  3147. * @param errorPrefix_ - Prefix for any error messages.
  3148. */
  3149. function ValidationPath(path, errorPrefix_) {
  3150. this.errorPrefix_ = errorPrefix_;
  3151. this.parts_ = pathSlice(path, 0);
  3152. /** Initialize to number of '/' chars needed in path. */
  3153. this.byteLength_ = Math.max(1, this.parts_.length);
  3154. for (var i = 0; i < this.parts_.length; i++) {
  3155. this.byteLength_ += util.stringLength(this.parts_[i]);
  3156. }
  3157. validationPathCheckValid(this);
  3158. }
  3159. return ValidationPath;
  3160. }());
  3161. function validationPathPush(validationPath, child) {
  3162. // Count the needed '/'
  3163. if (validationPath.parts_.length > 0) {
  3164. validationPath.byteLength_ += 1;
  3165. }
  3166. validationPath.parts_.push(child);
  3167. validationPath.byteLength_ += util.stringLength(child);
  3168. validationPathCheckValid(validationPath);
  3169. }
  3170. function validationPathPop(validationPath) {
  3171. var last = validationPath.parts_.pop();
  3172. validationPath.byteLength_ -= util.stringLength(last);
  3173. // Un-count the previous '/'
  3174. if (validationPath.parts_.length > 0) {
  3175. validationPath.byteLength_ -= 1;
  3176. }
  3177. }
  3178. function validationPathCheckValid(validationPath) {
  3179. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3180. throw new Error(validationPath.errorPrefix_ +
  3181. 'has a key path longer than ' +
  3182. MAX_PATH_LENGTH_BYTES +
  3183. ' bytes (' +
  3184. validationPath.byteLength_ +
  3185. ').');
  3186. }
  3187. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3188. throw new Error(validationPath.errorPrefix_ +
  3189. 'path specified exceeds the maximum depth that can be written (' +
  3190. MAX_PATH_DEPTH +
  3191. ') or object contains a cycle ' +
  3192. validationPathToErrorString(validationPath));
  3193. }
  3194. }
  3195. /**
  3196. * String for use in error messages - uses '.' notation for path.
  3197. */
  3198. function validationPathToErrorString(validationPath) {
  3199. if (validationPath.parts_.length === 0) {
  3200. return '';
  3201. }
  3202. return "in property '" + validationPath.parts_.join('.') + "'";
  3203. }
  3204. /**
  3205. * @license
  3206. * Copyright 2017 Google LLC
  3207. *
  3208. * Licensed under the Apache License, Version 2.0 (the "License");
  3209. * you may not use this file except in compliance with the License.
  3210. * You may obtain a copy of the License at
  3211. *
  3212. * http://www.apache.org/licenses/LICENSE-2.0
  3213. *
  3214. * Unless required by applicable law or agreed to in writing, software
  3215. * distributed under the License is distributed on an "AS IS" BASIS,
  3216. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3217. * See the License for the specific language governing permissions and
  3218. * limitations under the License.
  3219. */
  3220. var VisibilityMonitor = /** @class */ (function (_super) {
  3221. tslib.__extends(VisibilityMonitor, _super);
  3222. function VisibilityMonitor() {
  3223. var _this = _super.call(this, ['visible']) || this;
  3224. var hidden;
  3225. var visibilityChange;
  3226. if (typeof document !== 'undefined' &&
  3227. typeof document.addEventListener !== 'undefined') {
  3228. if (typeof document['hidden'] !== 'undefined') {
  3229. // Opera 12.10 and Firefox 18 and later support
  3230. visibilityChange = 'visibilitychange';
  3231. hidden = 'hidden';
  3232. }
  3233. else if (typeof document['mozHidden'] !== 'undefined') {
  3234. visibilityChange = 'mozvisibilitychange';
  3235. hidden = 'mozHidden';
  3236. }
  3237. else if (typeof document['msHidden'] !== 'undefined') {
  3238. visibilityChange = 'msvisibilitychange';
  3239. hidden = 'msHidden';
  3240. }
  3241. else if (typeof document['webkitHidden'] !== 'undefined') {
  3242. visibilityChange = 'webkitvisibilitychange';
  3243. hidden = 'webkitHidden';
  3244. }
  3245. }
  3246. // Initially, we always assume we are visible. This ensures that in browsers
  3247. // without page visibility support or in cases where we are never visible
  3248. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3249. // reconnects
  3250. _this.visible_ = true;
  3251. if (visibilityChange) {
  3252. document.addEventListener(visibilityChange, function () {
  3253. var visible = !document[hidden];
  3254. if (visible !== _this.visible_) {
  3255. _this.visible_ = visible;
  3256. _this.trigger('visible', visible);
  3257. }
  3258. }, false);
  3259. }
  3260. return _this;
  3261. }
  3262. VisibilityMonitor.getInstance = function () {
  3263. return new VisibilityMonitor();
  3264. };
  3265. VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
  3266. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3267. return [this.visible_];
  3268. };
  3269. return VisibilityMonitor;
  3270. }(EventEmitter));
  3271. /**
  3272. * @license
  3273. * Copyright 2017 Google LLC
  3274. *
  3275. * Licensed under the Apache License, Version 2.0 (the "License");
  3276. * you may not use this file except in compliance with the License.
  3277. * You may obtain a copy of the License at
  3278. *
  3279. * http://www.apache.org/licenses/LICENSE-2.0
  3280. *
  3281. * Unless required by applicable law or agreed to in writing, software
  3282. * distributed under the License is distributed on an "AS IS" BASIS,
  3283. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3284. * See the License for the specific language governing permissions and
  3285. * limitations under the License.
  3286. */
  3287. var RECONNECT_MIN_DELAY = 1000;
  3288. var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3289. var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3290. var RECONNECT_DELAY_MULTIPLIER = 1.3;
  3291. var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3292. var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3293. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3294. var INVALID_TOKEN_THRESHOLD = 3;
  3295. /**
  3296. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3297. *
  3298. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3299. * in quotes to make sure the closure compiler does not minify them.
  3300. */
  3301. var PersistentConnection = /** @class */ (function (_super) {
  3302. tslib.__extends(PersistentConnection, _super);
  3303. /**
  3304. * @param repoInfo_ - Data about the namespace we are connecting to
  3305. * @param applicationId_ - The Firebase App ID for this project
  3306. * @param onDataUpdate_ - A callback for new data from the server
  3307. */
  3308. function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3309. var _this = _super.call(this) || this;
  3310. _this.repoInfo_ = repoInfo_;
  3311. _this.applicationId_ = applicationId_;
  3312. _this.onDataUpdate_ = onDataUpdate_;
  3313. _this.onConnectStatus_ = onConnectStatus_;
  3314. _this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3315. _this.authTokenProvider_ = authTokenProvider_;
  3316. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3317. _this.authOverride_ = authOverride_;
  3318. // Used for diagnostic logging.
  3319. _this.id = PersistentConnection.nextPersistentConnectionId_++;
  3320. _this.log_ = logWrapper('p:' + _this.id + ':');
  3321. _this.interruptReasons_ = {};
  3322. _this.listens = new Map();
  3323. _this.outstandingPuts_ = [];
  3324. _this.outstandingGets_ = [];
  3325. _this.outstandingPutCount_ = 0;
  3326. _this.outstandingGetCount_ = 0;
  3327. _this.onDisconnectRequestQueue_ = [];
  3328. _this.connected_ = false;
  3329. _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3330. _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3331. _this.securityDebugCallback_ = null;
  3332. _this.lastSessionId = null;
  3333. _this.establishConnectionTimer_ = null;
  3334. _this.visible_ = false;
  3335. // Before we get connected, we keep a queue of pending messages to send.
  3336. _this.requestCBHash_ = {};
  3337. _this.requestNumber_ = 0;
  3338. _this.realtime_ = null;
  3339. _this.authToken_ = null;
  3340. _this.appCheckToken_ = null;
  3341. _this.forceTokenRefresh_ = false;
  3342. _this.invalidAuthTokenCount_ = 0;
  3343. _this.invalidAppCheckTokenCount_ = 0;
  3344. _this.firstConnection_ = true;
  3345. _this.lastConnectionAttemptTime_ = null;
  3346. _this.lastConnectionEstablishedTime_ = null;
  3347. if (authOverride_ && !util.isNodeSdk()) {
  3348. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3349. }
  3350. VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
  3351. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3352. OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
  3353. }
  3354. return _this;
  3355. }
  3356. PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
  3357. var curReqNum = ++this.requestNumber_;
  3358. var msg = { r: curReqNum, a: action, b: body };
  3359. this.log_(util.stringify(msg));
  3360. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3361. this.realtime_.sendRequest(msg);
  3362. if (onResponse) {
  3363. this.requestCBHash_[curReqNum] = onResponse;
  3364. }
  3365. };
  3366. PersistentConnection.prototype.get = function (query) {
  3367. this.initConnection_();
  3368. var deferred = new util.Deferred();
  3369. var request = {
  3370. p: query._path.toString(),
  3371. q: query._queryObject
  3372. };
  3373. var outstandingGet = {
  3374. action: 'g',
  3375. request: request,
  3376. onComplete: function (message) {
  3377. var payload = message['d'];
  3378. if (message['s'] === 'ok') {
  3379. deferred.resolve(payload);
  3380. }
  3381. else {
  3382. deferred.reject(payload);
  3383. }
  3384. }
  3385. };
  3386. this.outstandingGets_.push(outstandingGet);
  3387. this.outstandingGetCount_++;
  3388. var index = this.outstandingGets_.length - 1;
  3389. if (this.connected_) {
  3390. this.sendGet_(index);
  3391. }
  3392. return deferred.promise;
  3393. };
  3394. PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  3395. this.initConnection_();
  3396. var queryId = query._queryIdentifier;
  3397. var pathString = query._path.toString();
  3398. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3399. if (!this.listens.has(pathString)) {
  3400. this.listens.set(pathString, new Map());
  3401. }
  3402. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3403. util.assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
  3404. var listenSpec = {
  3405. onComplete: onComplete,
  3406. hashFn: currentHashFn,
  3407. query: query,
  3408. tag: tag
  3409. };
  3410. this.listens.get(pathString).set(queryId, listenSpec);
  3411. if (this.connected_) {
  3412. this.sendListen_(listenSpec);
  3413. }
  3414. };
  3415. PersistentConnection.prototype.sendGet_ = function (index) {
  3416. var _this = this;
  3417. var get = this.outstandingGets_[index];
  3418. this.sendRequest('g', get.request, function (message) {
  3419. delete _this.outstandingGets_[index];
  3420. _this.outstandingGetCount_--;
  3421. if (_this.outstandingGetCount_ === 0) {
  3422. _this.outstandingGets_ = [];
  3423. }
  3424. if (get.onComplete) {
  3425. get.onComplete(message);
  3426. }
  3427. });
  3428. };
  3429. PersistentConnection.prototype.sendListen_ = function (listenSpec) {
  3430. var _this = this;
  3431. var query = listenSpec.query;
  3432. var pathString = query._path.toString();
  3433. var queryId = query._queryIdentifier;
  3434. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3435. var req = { /*path*/ p: pathString };
  3436. var action = 'q';
  3437. // Only bother to send query if it's non-default.
  3438. if (listenSpec.tag) {
  3439. req['q'] = query._queryObject;
  3440. req['t'] = listenSpec.tag;
  3441. }
  3442. req[ /*hash*/'h'] = listenSpec.hashFn();
  3443. this.sendRequest(action, req, function (message) {
  3444. var payload = message[ /*data*/'d'];
  3445. var status = message[ /*status*/'s'];
  3446. // print warnings in any case...
  3447. PersistentConnection.warnOnListenWarnings_(payload, query);
  3448. var currentListenSpec = _this.listens.get(pathString) &&
  3449. _this.listens.get(pathString).get(queryId);
  3450. // only trigger actions if the listen hasn't been removed and readded
  3451. if (currentListenSpec === listenSpec) {
  3452. _this.log_('listen response', message);
  3453. if (status !== 'ok') {
  3454. _this.removeListen_(pathString, queryId);
  3455. }
  3456. if (listenSpec.onComplete) {
  3457. listenSpec.onComplete(status, payload);
  3458. }
  3459. }
  3460. });
  3461. };
  3462. PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
  3463. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  3464. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3465. var warnings = util.safeGet(payload, 'w');
  3466. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3467. var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3468. var indexPath = query._path.toString();
  3469. warn("Using an unspecified index. Your data will be downloaded and " +
  3470. "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
  3471. "".concat(indexPath, " to your security rules for better performance."));
  3472. }
  3473. }
  3474. };
  3475. PersistentConnection.prototype.refreshAuthToken = function (token) {
  3476. this.authToken_ = token;
  3477. this.log_('Auth token refreshed');
  3478. if (this.authToken_) {
  3479. this.tryAuth();
  3480. }
  3481. else {
  3482. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3483. //the credential so we dont become authenticated next time we connect.
  3484. if (this.connected_) {
  3485. this.sendRequest('unauth', {}, function () { });
  3486. }
  3487. }
  3488. this.reduceReconnectDelayIfAdminCredential_(token);
  3489. };
  3490. PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
  3491. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3492. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3493. var isFirebaseSecret = credential && credential.length === 40;
  3494. if (isFirebaseSecret || util.isAdmin(credential)) {
  3495. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3496. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3497. }
  3498. };
  3499. PersistentConnection.prototype.refreshAppCheckToken = function (token) {
  3500. this.appCheckToken_ = token;
  3501. this.log_('App check token refreshed');
  3502. if (this.appCheckToken_) {
  3503. this.tryAppCheck();
  3504. }
  3505. else {
  3506. //If we're connected we want to let the server know to unauthenticate us.
  3507. //If we're not connected, simply delete the credential so we dont become
  3508. // authenticated next time we connect.
  3509. if (this.connected_) {
  3510. this.sendRequest('unappeck', {}, function () { });
  3511. }
  3512. }
  3513. };
  3514. /**
  3515. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3516. * a auth revoked (the connection is closed).
  3517. */
  3518. PersistentConnection.prototype.tryAuth = function () {
  3519. var _this = this;
  3520. if (this.connected_ && this.authToken_) {
  3521. var token_1 = this.authToken_;
  3522. var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth';
  3523. var requestData = { cred: token_1 };
  3524. if (this.authOverride_ === null) {
  3525. requestData['noauth'] = true;
  3526. }
  3527. else if (typeof this.authOverride_ === 'object') {
  3528. requestData['authvar'] = this.authOverride_;
  3529. }
  3530. this.sendRequest(authMethod, requestData, function (res) {
  3531. var status = res[ /*status*/'s'];
  3532. var data = res[ /*data*/'d'] || 'error';
  3533. if (_this.authToken_ === token_1) {
  3534. if (status === 'ok') {
  3535. _this.invalidAuthTokenCount_ = 0;
  3536. }
  3537. else {
  3538. // Triggers reconnect and force refresh for auth token
  3539. _this.onAuthRevoked_(status, data);
  3540. }
  3541. }
  3542. });
  3543. }
  3544. };
  3545. /**
  3546. * Attempts to authenticate with the given token. If the authentication
  3547. * attempt fails, it's triggered like the token was revoked (the connection is
  3548. * closed).
  3549. */
  3550. PersistentConnection.prototype.tryAppCheck = function () {
  3551. var _this = this;
  3552. if (this.connected_ && this.appCheckToken_) {
  3553. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
  3554. var status = res[ /*status*/'s'];
  3555. var data = res[ /*data*/'d'] || 'error';
  3556. if (status === 'ok') {
  3557. _this.invalidAppCheckTokenCount_ = 0;
  3558. }
  3559. else {
  3560. _this.onAppCheckRevoked_(status, data);
  3561. }
  3562. });
  3563. }
  3564. };
  3565. /**
  3566. * @inheritDoc
  3567. */
  3568. PersistentConnection.prototype.unlisten = function (query, tag) {
  3569. var pathString = query._path.toString();
  3570. var queryId = query._queryIdentifier;
  3571. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3572. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3573. var listen = this.removeListen_(pathString, queryId);
  3574. if (listen && this.connected_) {
  3575. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3576. }
  3577. };
  3578. PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
  3579. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3580. var req = { /*path*/ p: pathString };
  3581. var action = 'n';
  3582. // Only bother sending queryId if it's non-default.
  3583. if (tag) {
  3584. req['q'] = queryObj;
  3585. req['t'] = tag;
  3586. }
  3587. this.sendRequest(action, req);
  3588. };
  3589. PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
  3590. this.initConnection_();
  3591. if (this.connected_) {
  3592. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3593. }
  3594. else {
  3595. this.onDisconnectRequestQueue_.push({
  3596. pathString: pathString,
  3597. action: 'o',
  3598. data: data,
  3599. onComplete: onComplete
  3600. });
  3601. }
  3602. };
  3603. PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
  3604. this.initConnection_();
  3605. if (this.connected_) {
  3606. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3607. }
  3608. else {
  3609. this.onDisconnectRequestQueue_.push({
  3610. pathString: pathString,
  3611. action: 'om',
  3612. data: data,
  3613. onComplete: onComplete
  3614. });
  3615. }
  3616. };
  3617. PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
  3618. this.initConnection_();
  3619. if (this.connected_) {
  3620. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3621. }
  3622. else {
  3623. this.onDisconnectRequestQueue_.push({
  3624. pathString: pathString,
  3625. action: 'oc',
  3626. data: null,
  3627. onComplete: onComplete
  3628. });
  3629. }
  3630. };
  3631. PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
  3632. var request = { /*path*/ p: pathString, /*data*/ d: data };
  3633. this.log_('onDisconnect ' + action, request);
  3634. this.sendRequest(action, request, function (response) {
  3635. if (onComplete) {
  3636. setTimeout(function () {
  3637. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3638. }, Math.floor(0));
  3639. }
  3640. });
  3641. };
  3642. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  3643. this.putInternal('p', pathString, data, onComplete, hash);
  3644. };
  3645. PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
  3646. this.putInternal('m', pathString, data, onComplete, hash);
  3647. };
  3648. PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
  3649. this.initConnection_();
  3650. var request = {
  3651. /*path*/ p: pathString,
  3652. /*data*/ d: data
  3653. };
  3654. if (hash !== undefined) {
  3655. request[ /*hash*/'h'] = hash;
  3656. }
  3657. // TODO: Only keep track of the most recent put for a given path?
  3658. this.outstandingPuts_.push({
  3659. action: action,
  3660. request: request,
  3661. onComplete: onComplete
  3662. });
  3663. this.outstandingPutCount_++;
  3664. var index = this.outstandingPuts_.length - 1;
  3665. if (this.connected_) {
  3666. this.sendPut_(index);
  3667. }
  3668. else {
  3669. this.log_('Buffering put: ' + pathString);
  3670. }
  3671. };
  3672. PersistentConnection.prototype.sendPut_ = function (index) {
  3673. var _this = this;
  3674. var action = this.outstandingPuts_[index].action;
  3675. var request = this.outstandingPuts_[index].request;
  3676. var onComplete = this.outstandingPuts_[index].onComplete;
  3677. this.outstandingPuts_[index].queued = this.connected_;
  3678. this.sendRequest(action, request, function (message) {
  3679. _this.log_(action + ' response', message);
  3680. delete _this.outstandingPuts_[index];
  3681. _this.outstandingPutCount_--;
  3682. // Clean up array occasionally.
  3683. if (_this.outstandingPutCount_ === 0) {
  3684. _this.outstandingPuts_ = [];
  3685. }
  3686. if (onComplete) {
  3687. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3688. }
  3689. });
  3690. };
  3691. PersistentConnection.prototype.reportStats = function (stats) {
  3692. var _this = this;
  3693. // If we're not connected, we just drop the stats.
  3694. if (this.connected_) {
  3695. var request = { /*counters*/ c: stats };
  3696. this.log_('reportStats', request);
  3697. this.sendRequest(/*stats*/ 's', request, function (result) {
  3698. var status = result[ /*status*/'s'];
  3699. if (status !== 'ok') {
  3700. var errorReason = result[ /* data */'d'];
  3701. _this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3702. }
  3703. });
  3704. }
  3705. };
  3706. PersistentConnection.prototype.onDataMessage_ = function (message) {
  3707. if ('r' in message) {
  3708. // this is a response
  3709. this.log_('from server: ' + util.stringify(message));
  3710. var reqNum = message['r'];
  3711. var onResponse = this.requestCBHash_[reqNum];
  3712. if (onResponse) {
  3713. delete this.requestCBHash_[reqNum];
  3714. onResponse(message[ /*body*/'b']);
  3715. }
  3716. }
  3717. else if ('error' in message) {
  3718. throw 'A server-side error has occurred: ' + message['error'];
  3719. }
  3720. else if ('a' in message) {
  3721. // a and b are action and body, respectively
  3722. this.onDataPush_(message['a'], message['b']);
  3723. }
  3724. };
  3725. PersistentConnection.prototype.onDataPush_ = function (action, body) {
  3726. this.log_('handleServerMessage', action, body);
  3727. if (action === 'd') {
  3728. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3729. /*isMerge*/ false, body['t']);
  3730. }
  3731. else if (action === 'm') {
  3732. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3733. /*isMerge=*/ true, body['t']);
  3734. }
  3735. else if (action === 'c') {
  3736. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3737. }
  3738. else if (action === 'ac') {
  3739. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3740. }
  3741. else if (action === 'apc') {
  3742. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3743. }
  3744. else if (action === 'sd') {
  3745. this.onSecurityDebugPacket_(body);
  3746. }
  3747. else {
  3748. error('Unrecognized action received from server: ' +
  3749. util.stringify(action) +
  3750. '\nAre you using the latest client?');
  3751. }
  3752. };
  3753. PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
  3754. this.log_('connection ready');
  3755. this.connected_ = true;
  3756. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3757. this.handleTimestamp_(timestamp);
  3758. this.lastSessionId = sessionId;
  3759. if (this.firstConnection_) {
  3760. this.sendConnectStats_();
  3761. }
  3762. this.restoreState_();
  3763. this.firstConnection_ = false;
  3764. this.onConnectStatus_(true);
  3765. };
  3766. PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
  3767. var _this = this;
  3768. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3769. if (this.establishConnectionTimer_) {
  3770. clearTimeout(this.establishConnectionTimer_);
  3771. }
  3772. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3773. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3774. this.establishConnectionTimer_ = setTimeout(function () {
  3775. _this.establishConnectionTimer_ = null;
  3776. _this.establishConnection_();
  3777. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3778. }, Math.floor(timeout));
  3779. };
  3780. PersistentConnection.prototype.initConnection_ = function () {
  3781. if (!this.realtime_ && this.firstConnection_) {
  3782. this.scheduleConnect_(0);
  3783. }
  3784. };
  3785. PersistentConnection.prototype.onVisible_ = function (visible) {
  3786. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3787. if (visible &&
  3788. !this.visible_ &&
  3789. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3790. this.log_('Window became visible. Reducing delay.');
  3791. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3792. if (!this.realtime_) {
  3793. this.scheduleConnect_(0);
  3794. }
  3795. }
  3796. this.visible_ = visible;
  3797. };
  3798. PersistentConnection.prototype.onOnline_ = function (online) {
  3799. if (online) {
  3800. this.log_('Browser went online.');
  3801. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3802. if (!this.realtime_) {
  3803. this.scheduleConnect_(0);
  3804. }
  3805. }
  3806. else {
  3807. this.log_('Browser went offline. Killing connection.');
  3808. if (this.realtime_) {
  3809. this.realtime_.close();
  3810. }
  3811. }
  3812. };
  3813. PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
  3814. this.log_('data client disconnected');
  3815. this.connected_ = false;
  3816. this.realtime_ = null;
  3817. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3818. this.cancelSentTransactions_();
  3819. // Clear out the pending requests.
  3820. this.requestCBHash_ = {};
  3821. if (this.shouldReconnect_()) {
  3822. if (!this.visible_) {
  3823. this.log_("Window isn't visible. Delaying reconnect.");
  3824. this.reconnectDelay_ = this.maxReconnectDelay_;
  3825. this.lastConnectionAttemptTime_ = new Date().getTime();
  3826. }
  3827. else if (this.lastConnectionEstablishedTime_) {
  3828. // If we've been connected long enough, reset reconnect delay to minimum.
  3829. var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3830. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3831. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3832. }
  3833. this.lastConnectionEstablishedTime_ = null;
  3834. }
  3835. var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3836. var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3837. reconnectDelay = Math.random() * reconnectDelay;
  3838. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3839. this.scheduleConnect_(reconnectDelay);
  3840. // Adjust reconnect delay for next time.
  3841. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3842. }
  3843. this.onConnectStatus_(false);
  3844. };
  3845. PersistentConnection.prototype.establishConnection_ = function () {
  3846. return tslib.__awaiter(this, void 0, void 0, function () {
  3847. var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
  3848. var _this = this;
  3849. return tslib.__generator(this, function (_b) {
  3850. switch (_b.label) {
  3851. case 0:
  3852. if (!this.shouldReconnect_()) return [3 /*break*/, 4];
  3853. this.log_('Making a connection attempt');
  3854. this.lastConnectionAttemptTime_ = new Date().getTime();
  3855. this.lastConnectionEstablishedTime_ = null;
  3856. onDataMessage = this.onDataMessage_.bind(this);
  3857. onReady = this.onReady_.bind(this);
  3858. onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
  3859. connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3860. lastSessionId = this.lastSessionId;
  3861. canceled_1 = false;
  3862. connection_1 = null;
  3863. closeFn = function () {
  3864. if (connection_1) {
  3865. connection_1.close();
  3866. }
  3867. else {
  3868. canceled_1 = true;
  3869. onDisconnect_1();
  3870. }
  3871. };
  3872. sendRequestFn = function (msg) {
  3873. util.assert(connection_1, "sendRequest call when we're not connected not allowed.");
  3874. connection_1.sendRequest(msg);
  3875. };
  3876. this.realtime_ = {
  3877. close: closeFn,
  3878. sendRequest: sendRequestFn
  3879. };
  3880. forceRefresh = this.forceTokenRefresh_;
  3881. this.forceTokenRefresh_ = false;
  3882. _b.label = 1;
  3883. case 1:
  3884. _b.trys.push([1, 3, , 4]);
  3885. return [4 /*yield*/, Promise.all([
  3886. this.authTokenProvider_.getToken(forceRefresh),
  3887. this.appCheckTokenProvider_.getToken(forceRefresh)
  3888. ])];
  3889. case 2:
  3890. _a = tslib.__read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
  3891. if (!canceled_1) {
  3892. log('getToken() completed. Creating connection.');
  3893. this.authToken_ = authToken && authToken.accessToken;
  3894. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3895. connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
  3896. /* onKill= */ function (reason) {
  3897. warn(reason + ' (' + _this.repoInfo_.toString() + ')');
  3898. _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3899. }, lastSessionId);
  3900. }
  3901. else {
  3902. log('getToken() completed but was canceled');
  3903. }
  3904. return [3 /*break*/, 4];
  3905. case 3:
  3906. error_1 = _b.sent();
  3907. this.log_('Failed to get token: ' + error_1);
  3908. if (!canceled_1) {
  3909. if (this.repoInfo_.nodeAdmin) {
  3910. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3911. // But getToken() may also just have temporarily failed, so we still want to
  3912. // continue retrying.
  3913. warn(error_1);
  3914. }
  3915. closeFn();
  3916. }
  3917. return [3 /*break*/, 4];
  3918. case 4: return [2 /*return*/];
  3919. }
  3920. });
  3921. });
  3922. };
  3923. PersistentConnection.prototype.interrupt = function (reason) {
  3924. log('Interrupting connection for reason: ' + reason);
  3925. this.interruptReasons_[reason] = true;
  3926. if (this.realtime_) {
  3927. this.realtime_.close();
  3928. }
  3929. else {
  3930. if (this.establishConnectionTimer_) {
  3931. clearTimeout(this.establishConnectionTimer_);
  3932. this.establishConnectionTimer_ = null;
  3933. }
  3934. if (this.connected_) {
  3935. this.onRealtimeDisconnect_();
  3936. }
  3937. }
  3938. };
  3939. PersistentConnection.prototype.resume = function (reason) {
  3940. log('Resuming connection for reason: ' + reason);
  3941. delete this.interruptReasons_[reason];
  3942. if (util.isEmpty(this.interruptReasons_)) {
  3943. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3944. if (!this.realtime_) {
  3945. this.scheduleConnect_(0);
  3946. }
  3947. }
  3948. };
  3949. PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
  3950. var delta = timestamp - new Date().getTime();
  3951. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3952. };
  3953. PersistentConnection.prototype.cancelSentTransactions_ = function () {
  3954. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  3955. var put = this.outstandingPuts_[i];
  3956. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3957. if (put.onComplete) {
  3958. put.onComplete('disconnect');
  3959. }
  3960. delete this.outstandingPuts_[i];
  3961. this.outstandingPutCount_--;
  3962. }
  3963. }
  3964. // Clean up array occasionally.
  3965. if (this.outstandingPutCount_ === 0) {
  3966. this.outstandingPuts_ = [];
  3967. }
  3968. };
  3969. PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
  3970. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3971. var queryId;
  3972. if (!query) {
  3973. queryId = 'default';
  3974. }
  3975. else {
  3976. queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
  3977. }
  3978. var listen = this.removeListen_(pathString, queryId);
  3979. if (listen && listen.onComplete) {
  3980. listen.onComplete('permission_denied');
  3981. }
  3982. };
  3983. PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
  3984. var normalizedPathString = new Path(pathString).toString(); // normalize path.
  3985. var listen;
  3986. if (this.listens.has(normalizedPathString)) {
  3987. var map = this.listens.get(normalizedPathString);
  3988. listen = map.get(queryId);
  3989. map.delete(queryId);
  3990. if (map.size === 0) {
  3991. this.listens.delete(normalizedPathString);
  3992. }
  3993. }
  3994. else {
  3995. // all listens for this path has already been removed
  3996. listen = undefined;
  3997. }
  3998. return listen;
  3999. };
  4000. PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
  4001. log('Auth token revoked: ' + statusCode + '/' + explanation);
  4002. this.authToken_ = null;
  4003. this.forceTokenRefresh_ = true;
  4004. this.realtime_.close();
  4005. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4006. // We'll wait a couple times before logging the warning / increasing the
  4007. // retry period since oauth tokens will report as "invalid" if they're
  4008. // just expired. Plus there may be transient issues that resolve themselves.
  4009. this.invalidAuthTokenCount_++;
  4010. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4011. // Set a long reconnect delay because recovery is unlikely
  4012. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  4013. // Notify the auth token provider that the token is invalid, which will log
  4014. // a warning
  4015. this.authTokenProvider_.notifyForInvalidToken();
  4016. }
  4017. }
  4018. };
  4019. PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
  4020. log('App check token revoked: ' + statusCode + '/' + explanation);
  4021. this.appCheckToken_ = null;
  4022. this.forceTokenRefresh_ = true;
  4023. // Note: We don't close the connection as the developer may not have
  4024. // enforcement enabled. The backend closes connections with enforcements.
  4025. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4026. // We'll wait a couple times before logging the warning / increasing the
  4027. // retry period since oauth tokens will report as "invalid" if they're
  4028. // just expired. Plus there may be transient issues that resolve themselves.
  4029. this.invalidAppCheckTokenCount_++;
  4030. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4031. this.appCheckTokenProvider_.notifyForInvalidToken();
  4032. }
  4033. }
  4034. };
  4035. PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
  4036. if (this.securityDebugCallback_) {
  4037. this.securityDebugCallback_(body);
  4038. }
  4039. else {
  4040. if ('msg' in body) {
  4041. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  4042. }
  4043. }
  4044. };
  4045. PersistentConnection.prototype.restoreState_ = function () {
  4046. var e_1, _a, e_2, _b;
  4047. //Re-authenticate ourselves if we have a credential stored.
  4048. this.tryAuth();
  4049. this.tryAppCheck();
  4050. try {
  4051. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  4052. // make sure to send listens before puts.
  4053. for (var _c = tslib.__values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
  4054. var queries = _d.value;
  4055. try {
  4056. for (var _e = (e_2 = void 0, tslib.__values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
  4057. var listenSpec = _f.value;
  4058. this.sendListen_(listenSpec);
  4059. }
  4060. }
  4061. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  4062. finally {
  4063. try {
  4064. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  4065. }
  4066. finally { if (e_2) throw e_2.error; }
  4067. }
  4068. }
  4069. }
  4070. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4071. finally {
  4072. try {
  4073. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  4074. }
  4075. finally { if (e_1) throw e_1.error; }
  4076. }
  4077. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  4078. if (this.outstandingPuts_[i]) {
  4079. this.sendPut_(i);
  4080. }
  4081. }
  4082. while (this.onDisconnectRequestQueue_.length) {
  4083. var request = this.onDisconnectRequestQueue_.shift();
  4084. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  4085. }
  4086. for (var i = 0; i < this.outstandingGets_.length; i++) {
  4087. if (this.outstandingGets_[i]) {
  4088. this.sendGet_(i);
  4089. }
  4090. }
  4091. };
  4092. /**
  4093. * Sends client stats for first connection
  4094. */
  4095. PersistentConnection.prototype.sendConnectStats_ = function () {
  4096. var stats = {};
  4097. var clientName = 'js';
  4098. if (util.isNodeSdk()) {
  4099. if (this.repoInfo_.nodeAdmin) {
  4100. clientName = 'admin_node';
  4101. }
  4102. else {
  4103. clientName = 'node';
  4104. }
  4105. }
  4106. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  4107. if (util.isMobileCordova()) {
  4108. stats['framework.cordova'] = 1;
  4109. }
  4110. else if (util.isReactNative()) {
  4111. stats['framework.reactnative'] = 1;
  4112. }
  4113. this.reportStats(stats);
  4114. };
  4115. PersistentConnection.prototype.shouldReconnect_ = function () {
  4116. var online = OnlineMonitor.getInstance().currentlyOnline();
  4117. return util.isEmpty(this.interruptReasons_) && online;
  4118. };
  4119. PersistentConnection.nextPersistentConnectionId_ = 0;
  4120. /**
  4121. * Counter for number of connections created. Mainly used for tagging in the logs
  4122. */
  4123. PersistentConnection.nextConnectionId_ = 0;
  4124. return PersistentConnection;
  4125. }(ServerActions));
  4126. /**
  4127. * @license
  4128. * Copyright 2017 Google LLC
  4129. *
  4130. * Licensed under the Apache License, Version 2.0 (the "License");
  4131. * you may not use this file except in compliance with the License.
  4132. * You may obtain a copy of the License at
  4133. *
  4134. * http://www.apache.org/licenses/LICENSE-2.0
  4135. *
  4136. * Unless required by applicable law or agreed to in writing, software
  4137. * distributed under the License is distributed on an "AS IS" BASIS,
  4138. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4139. * See the License for the specific language governing permissions and
  4140. * limitations under the License.
  4141. */
  4142. var NamedNode = /** @class */ (function () {
  4143. function NamedNode(name, node) {
  4144. this.name = name;
  4145. this.node = node;
  4146. }
  4147. NamedNode.Wrap = function (name, node) {
  4148. return new NamedNode(name, node);
  4149. };
  4150. return NamedNode;
  4151. }());
  4152. /**
  4153. * @license
  4154. * Copyright 2017 Google LLC
  4155. *
  4156. * Licensed under the Apache License, Version 2.0 (the "License");
  4157. * you may not use this file except in compliance with the License.
  4158. * You may obtain a copy of the License at
  4159. *
  4160. * http://www.apache.org/licenses/LICENSE-2.0
  4161. *
  4162. * Unless required by applicable law or agreed to in writing, software
  4163. * distributed under the License is distributed on an "AS IS" BASIS,
  4164. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4165. * See the License for the specific language governing permissions and
  4166. * limitations under the License.
  4167. */
  4168. var Index = /** @class */ (function () {
  4169. function Index() {
  4170. }
  4171. /**
  4172. * @returns A standalone comparison function for
  4173. * this index
  4174. */
  4175. Index.prototype.getCompare = function () {
  4176. return this.compare.bind(this);
  4177. };
  4178. /**
  4179. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4180. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4181. *
  4182. *
  4183. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4184. */
  4185. Index.prototype.indexedValueChanged = function (oldNode, newNode) {
  4186. var oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4187. var newWrapped = new NamedNode(MIN_NAME, newNode);
  4188. return this.compare(oldWrapped, newWrapped) !== 0;
  4189. };
  4190. /**
  4191. * @returns a node wrapper that will sort equal to or less than
  4192. * any other node wrapper, using this index
  4193. */
  4194. Index.prototype.minPost = function () {
  4195. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4196. return NamedNode.MIN;
  4197. };
  4198. return Index;
  4199. }());
  4200. /**
  4201. * @license
  4202. * Copyright 2017 Google LLC
  4203. *
  4204. * Licensed under the Apache License, Version 2.0 (the "License");
  4205. * you may not use this file except in compliance with the License.
  4206. * You may obtain a copy of the License at
  4207. *
  4208. * http://www.apache.org/licenses/LICENSE-2.0
  4209. *
  4210. * Unless required by applicable law or agreed to in writing, software
  4211. * distributed under the License is distributed on an "AS IS" BASIS,
  4212. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4213. * See the License for the specific language governing permissions and
  4214. * limitations under the License.
  4215. */
  4216. var __EMPTY_NODE;
  4217. var KeyIndex = /** @class */ (function (_super) {
  4218. tslib.__extends(KeyIndex, _super);
  4219. function KeyIndex() {
  4220. return _super !== null && _super.apply(this, arguments) || this;
  4221. }
  4222. Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
  4223. get: function () {
  4224. return __EMPTY_NODE;
  4225. },
  4226. set: function (val) {
  4227. __EMPTY_NODE = val;
  4228. },
  4229. enumerable: false,
  4230. configurable: true
  4231. });
  4232. KeyIndex.prototype.compare = function (a, b) {
  4233. return nameCompare(a.name, b.name);
  4234. };
  4235. KeyIndex.prototype.isDefinedOn = function (node) {
  4236. // We could probably return true here (since every node has a key), but it's never called
  4237. // so just leaving unimplemented for now.
  4238. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4239. };
  4240. KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  4241. return false; // The key for a node never changes.
  4242. };
  4243. KeyIndex.prototype.minPost = function () {
  4244. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4245. return NamedNode.MIN;
  4246. };
  4247. KeyIndex.prototype.maxPost = function () {
  4248. // TODO: This should really be created once and cached in a static property, but
  4249. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4250. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4251. };
  4252. KeyIndex.prototype.makePost = function (indexValue, name) {
  4253. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4254. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4255. return new NamedNode(indexValue, __EMPTY_NODE);
  4256. };
  4257. /**
  4258. * @returns String representation for inclusion in a query spec
  4259. */
  4260. KeyIndex.prototype.toString = function () {
  4261. return '.key';
  4262. };
  4263. return KeyIndex;
  4264. }(Index));
  4265. var KEY_INDEX = new KeyIndex();
  4266. /**
  4267. * @license
  4268. * Copyright 2017 Google LLC
  4269. *
  4270. * Licensed under the Apache License, Version 2.0 (the "License");
  4271. * you may not use this file except in compliance with the License.
  4272. * You may obtain a copy of the License at
  4273. *
  4274. * http://www.apache.org/licenses/LICENSE-2.0
  4275. *
  4276. * Unless required by applicable law or agreed to in writing, software
  4277. * distributed under the License is distributed on an "AS IS" BASIS,
  4278. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4279. * See the License for the specific language governing permissions and
  4280. * limitations under the License.
  4281. */
  4282. /**
  4283. * An iterator over an LLRBNode.
  4284. */
  4285. var SortedMapIterator = /** @class */ (function () {
  4286. /**
  4287. * @param node - Node to iterate.
  4288. * @param isReverse_ - Whether or not to iterate in reverse
  4289. */
  4290. function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
  4291. if (resultGenerator_ === void 0) { resultGenerator_ = null; }
  4292. this.isReverse_ = isReverse_;
  4293. this.resultGenerator_ = resultGenerator_;
  4294. this.nodeStack_ = [];
  4295. var cmp = 1;
  4296. while (!node.isEmpty()) {
  4297. node = node;
  4298. cmp = startKey ? comparator(node.key, startKey) : 1;
  4299. // flip the comparison if we're going in reverse
  4300. if (isReverse_) {
  4301. cmp *= -1;
  4302. }
  4303. if (cmp < 0) {
  4304. // This node is less than our start key. ignore it
  4305. if (this.isReverse_) {
  4306. node = node.left;
  4307. }
  4308. else {
  4309. node = node.right;
  4310. }
  4311. }
  4312. else if (cmp === 0) {
  4313. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4314. this.nodeStack_.push(node);
  4315. break;
  4316. }
  4317. else {
  4318. // This node is greater than our start key, add it to the stack and move to the next one
  4319. this.nodeStack_.push(node);
  4320. if (this.isReverse_) {
  4321. node = node.right;
  4322. }
  4323. else {
  4324. node = node.left;
  4325. }
  4326. }
  4327. }
  4328. }
  4329. SortedMapIterator.prototype.getNext = function () {
  4330. if (this.nodeStack_.length === 0) {
  4331. return null;
  4332. }
  4333. var node = this.nodeStack_.pop();
  4334. var result;
  4335. if (this.resultGenerator_) {
  4336. result = this.resultGenerator_(node.key, node.value);
  4337. }
  4338. else {
  4339. result = { key: node.key, value: node.value };
  4340. }
  4341. if (this.isReverse_) {
  4342. node = node.left;
  4343. while (!node.isEmpty()) {
  4344. this.nodeStack_.push(node);
  4345. node = node.right;
  4346. }
  4347. }
  4348. else {
  4349. node = node.right;
  4350. while (!node.isEmpty()) {
  4351. this.nodeStack_.push(node);
  4352. node = node.left;
  4353. }
  4354. }
  4355. return result;
  4356. };
  4357. SortedMapIterator.prototype.hasNext = function () {
  4358. return this.nodeStack_.length > 0;
  4359. };
  4360. SortedMapIterator.prototype.peek = function () {
  4361. if (this.nodeStack_.length === 0) {
  4362. return null;
  4363. }
  4364. var node = this.nodeStack_[this.nodeStack_.length - 1];
  4365. if (this.resultGenerator_) {
  4366. return this.resultGenerator_(node.key, node.value);
  4367. }
  4368. else {
  4369. return { key: node.key, value: node.value };
  4370. }
  4371. };
  4372. return SortedMapIterator;
  4373. }());
  4374. /**
  4375. * Represents a node in a Left-leaning Red-Black tree.
  4376. */
  4377. var LLRBNode = /** @class */ (function () {
  4378. /**
  4379. * @param key - Key associated with this node.
  4380. * @param value - Value associated with this node.
  4381. * @param color - Whether this node is red.
  4382. * @param left - Left child.
  4383. * @param right - Right child.
  4384. */
  4385. function LLRBNode(key, value, color, left, right) {
  4386. this.key = key;
  4387. this.value = value;
  4388. this.color = color != null ? color : LLRBNode.RED;
  4389. this.left =
  4390. left != null ? left : SortedMap.EMPTY_NODE;
  4391. this.right =
  4392. right != null ? right : SortedMap.EMPTY_NODE;
  4393. }
  4394. /**
  4395. * Returns a copy of the current node, optionally replacing pieces of it.
  4396. *
  4397. * @param key - New key for the node, or null.
  4398. * @param value - New value for the node, or null.
  4399. * @param color - New color for the node, or null.
  4400. * @param left - New left child for the node, or null.
  4401. * @param right - New right child for the node, or null.
  4402. * @returns The node copy.
  4403. */
  4404. LLRBNode.prototype.copy = function (key, value, color, left, right) {
  4405. return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
  4406. };
  4407. /**
  4408. * @returns The total number of nodes in the tree.
  4409. */
  4410. LLRBNode.prototype.count = function () {
  4411. return this.left.count() + 1 + this.right.count();
  4412. };
  4413. /**
  4414. * @returns True if the tree is empty.
  4415. */
  4416. LLRBNode.prototype.isEmpty = function () {
  4417. return false;
  4418. };
  4419. /**
  4420. * Traverses the tree in key order and calls the specified action function
  4421. * for each node.
  4422. *
  4423. * @param action - Callback function to be called for each
  4424. * node. If it returns true, traversal is aborted.
  4425. * @returns The first truthy value returned by action, or the last falsey
  4426. * value returned by action
  4427. */
  4428. LLRBNode.prototype.inorderTraversal = function (action) {
  4429. return (this.left.inorderTraversal(action) ||
  4430. !!action(this.key, this.value) ||
  4431. this.right.inorderTraversal(action));
  4432. };
  4433. /**
  4434. * Traverses the tree in reverse key order and calls the specified action function
  4435. * for each node.
  4436. *
  4437. * @param action - Callback function to be called for each
  4438. * node. If it returns true, traversal is aborted.
  4439. * @returns True if traversal was aborted.
  4440. */
  4441. LLRBNode.prototype.reverseTraversal = function (action) {
  4442. return (this.right.reverseTraversal(action) ||
  4443. action(this.key, this.value) ||
  4444. this.left.reverseTraversal(action));
  4445. };
  4446. /**
  4447. * @returns The minimum node in the tree.
  4448. */
  4449. LLRBNode.prototype.min_ = function () {
  4450. if (this.left.isEmpty()) {
  4451. return this;
  4452. }
  4453. else {
  4454. return this.left.min_();
  4455. }
  4456. };
  4457. /**
  4458. * @returns The maximum key in the tree.
  4459. */
  4460. LLRBNode.prototype.minKey = function () {
  4461. return this.min_().key;
  4462. };
  4463. /**
  4464. * @returns The maximum key in the tree.
  4465. */
  4466. LLRBNode.prototype.maxKey = function () {
  4467. if (this.right.isEmpty()) {
  4468. return this.key;
  4469. }
  4470. else {
  4471. return this.right.maxKey();
  4472. }
  4473. };
  4474. /**
  4475. * @param key - Key to insert.
  4476. * @param value - Value to insert.
  4477. * @param comparator - Comparator.
  4478. * @returns New tree, with the key/value added.
  4479. */
  4480. LLRBNode.prototype.insert = function (key, value, comparator) {
  4481. var n = this;
  4482. var cmp = comparator(key, n.key);
  4483. if (cmp < 0) {
  4484. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4485. }
  4486. else if (cmp === 0) {
  4487. n = n.copy(null, value, null, null, null);
  4488. }
  4489. else {
  4490. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4491. }
  4492. return n.fixUp_();
  4493. };
  4494. /**
  4495. * @returns New tree, with the minimum key removed.
  4496. */
  4497. LLRBNode.prototype.removeMin_ = function () {
  4498. if (this.left.isEmpty()) {
  4499. return SortedMap.EMPTY_NODE;
  4500. }
  4501. var n = this;
  4502. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4503. n = n.moveRedLeft_();
  4504. }
  4505. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4506. return n.fixUp_();
  4507. };
  4508. /**
  4509. * @param key - The key of the item to remove.
  4510. * @param comparator - Comparator.
  4511. * @returns New tree, with the specified item removed.
  4512. */
  4513. LLRBNode.prototype.remove = function (key, comparator) {
  4514. var n, smallest;
  4515. n = this;
  4516. if (comparator(key, n.key) < 0) {
  4517. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4518. n = n.moveRedLeft_();
  4519. }
  4520. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4521. }
  4522. else {
  4523. if (n.left.isRed_()) {
  4524. n = n.rotateRight_();
  4525. }
  4526. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4527. n = n.moveRedRight_();
  4528. }
  4529. if (comparator(key, n.key) === 0) {
  4530. if (n.right.isEmpty()) {
  4531. return SortedMap.EMPTY_NODE;
  4532. }
  4533. else {
  4534. smallest = n.right.min_();
  4535. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4536. }
  4537. }
  4538. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4539. }
  4540. return n.fixUp_();
  4541. };
  4542. /**
  4543. * @returns Whether this is a RED node.
  4544. */
  4545. LLRBNode.prototype.isRed_ = function () {
  4546. return this.color;
  4547. };
  4548. /**
  4549. * @returns New tree after performing any needed rotations.
  4550. */
  4551. LLRBNode.prototype.fixUp_ = function () {
  4552. var n = this;
  4553. if (n.right.isRed_() && !n.left.isRed_()) {
  4554. n = n.rotateLeft_();
  4555. }
  4556. if (n.left.isRed_() && n.left.left.isRed_()) {
  4557. n = n.rotateRight_();
  4558. }
  4559. if (n.left.isRed_() && n.right.isRed_()) {
  4560. n = n.colorFlip_();
  4561. }
  4562. return n;
  4563. };
  4564. /**
  4565. * @returns New tree, after moveRedLeft.
  4566. */
  4567. LLRBNode.prototype.moveRedLeft_ = function () {
  4568. var n = this.colorFlip_();
  4569. if (n.right.left.isRed_()) {
  4570. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4571. n = n.rotateLeft_();
  4572. n = n.colorFlip_();
  4573. }
  4574. return n;
  4575. };
  4576. /**
  4577. * @returns New tree, after moveRedRight.
  4578. */
  4579. LLRBNode.prototype.moveRedRight_ = function () {
  4580. var n = this.colorFlip_();
  4581. if (n.left.left.isRed_()) {
  4582. n = n.rotateRight_();
  4583. n = n.colorFlip_();
  4584. }
  4585. return n;
  4586. };
  4587. /**
  4588. * @returns New tree, after rotateLeft.
  4589. */
  4590. LLRBNode.prototype.rotateLeft_ = function () {
  4591. var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4592. return this.right.copy(null, null, this.color, nl, null);
  4593. };
  4594. /**
  4595. * @returns New tree, after rotateRight.
  4596. */
  4597. LLRBNode.prototype.rotateRight_ = function () {
  4598. var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4599. return this.left.copy(null, null, this.color, null, nr);
  4600. };
  4601. /**
  4602. * @returns Newt ree, after colorFlip.
  4603. */
  4604. LLRBNode.prototype.colorFlip_ = function () {
  4605. var left = this.left.copy(null, null, !this.left.color, null, null);
  4606. var right = this.right.copy(null, null, !this.right.color, null, null);
  4607. return this.copy(null, null, !this.color, left, right);
  4608. };
  4609. /**
  4610. * For testing.
  4611. *
  4612. * @returns True if all is well.
  4613. */
  4614. LLRBNode.prototype.checkMaxDepth_ = function () {
  4615. var blackDepth = this.check_();
  4616. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4617. };
  4618. LLRBNode.prototype.check_ = function () {
  4619. if (this.isRed_() && this.left.isRed_()) {
  4620. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4621. }
  4622. if (this.right.isRed_()) {
  4623. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4624. }
  4625. var blackDepth = this.left.check_();
  4626. if (blackDepth !== this.right.check_()) {
  4627. throw new Error('Black depths differ');
  4628. }
  4629. else {
  4630. return blackDepth + (this.isRed_() ? 0 : 1);
  4631. }
  4632. };
  4633. LLRBNode.RED = true;
  4634. LLRBNode.BLACK = false;
  4635. return LLRBNode;
  4636. }());
  4637. /**
  4638. * Represents an empty node (a leaf node in the Red-Black Tree).
  4639. */
  4640. var LLRBEmptyNode = /** @class */ (function () {
  4641. function LLRBEmptyNode() {
  4642. }
  4643. /**
  4644. * Returns a copy of the current node.
  4645. *
  4646. * @returns The node copy.
  4647. */
  4648. LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
  4649. return this;
  4650. };
  4651. /**
  4652. * Returns a copy of the tree, with the specified key/value added.
  4653. *
  4654. * @param key - Key to be added.
  4655. * @param value - Value to be added.
  4656. * @param comparator - Comparator.
  4657. * @returns New tree, with item added.
  4658. */
  4659. LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
  4660. return new LLRBNode(key, value, null);
  4661. };
  4662. /**
  4663. * Returns a copy of the tree, with the specified key removed.
  4664. *
  4665. * @param key - The key to remove.
  4666. * @param comparator - Comparator.
  4667. * @returns New tree, with item removed.
  4668. */
  4669. LLRBEmptyNode.prototype.remove = function (key, comparator) {
  4670. return this;
  4671. };
  4672. /**
  4673. * @returns The total number of nodes in the tree.
  4674. */
  4675. LLRBEmptyNode.prototype.count = function () {
  4676. return 0;
  4677. };
  4678. /**
  4679. * @returns True if the tree is empty.
  4680. */
  4681. LLRBEmptyNode.prototype.isEmpty = function () {
  4682. return true;
  4683. };
  4684. /**
  4685. * Traverses the tree in key order and calls the specified action function
  4686. * for each node.
  4687. *
  4688. * @param action - Callback function to be called for each
  4689. * node. If it returns true, traversal is aborted.
  4690. * @returns True if traversal was aborted.
  4691. */
  4692. LLRBEmptyNode.prototype.inorderTraversal = function (action) {
  4693. return false;
  4694. };
  4695. /**
  4696. * Traverses the tree in reverse key order and calls the specified action function
  4697. * for each node.
  4698. *
  4699. * @param action - Callback function to be called for each
  4700. * node. If it returns true, traversal is aborted.
  4701. * @returns True if traversal was aborted.
  4702. */
  4703. LLRBEmptyNode.prototype.reverseTraversal = function (action) {
  4704. return false;
  4705. };
  4706. LLRBEmptyNode.prototype.minKey = function () {
  4707. return null;
  4708. };
  4709. LLRBEmptyNode.prototype.maxKey = function () {
  4710. return null;
  4711. };
  4712. LLRBEmptyNode.prototype.check_ = function () {
  4713. return 0;
  4714. };
  4715. /**
  4716. * @returns Whether this node is red.
  4717. */
  4718. LLRBEmptyNode.prototype.isRed_ = function () {
  4719. return false;
  4720. };
  4721. return LLRBEmptyNode;
  4722. }());
  4723. /**
  4724. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4725. * tree.
  4726. */
  4727. var SortedMap = /** @class */ (function () {
  4728. /**
  4729. * @param comparator_ - Key comparator.
  4730. * @param root_ - Optional root node for the map.
  4731. */
  4732. function SortedMap(comparator_, root_) {
  4733. if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
  4734. this.comparator_ = comparator_;
  4735. this.root_ = root_;
  4736. }
  4737. /**
  4738. * Returns a copy of the map, with the specified key/value added or replaced.
  4739. * (TODO: We should perhaps rename this method to 'put')
  4740. *
  4741. * @param key - Key to be added.
  4742. * @param value - Value to be added.
  4743. * @returns New map, with item added.
  4744. */
  4745. SortedMap.prototype.insert = function (key, value) {
  4746. return new SortedMap(this.comparator_, this.root_
  4747. .insert(key, value, this.comparator_)
  4748. .copy(null, null, LLRBNode.BLACK, null, null));
  4749. };
  4750. /**
  4751. * Returns a copy of the map, with the specified key removed.
  4752. *
  4753. * @param key - The key to remove.
  4754. * @returns New map, with item removed.
  4755. */
  4756. SortedMap.prototype.remove = function (key) {
  4757. return new SortedMap(this.comparator_, this.root_
  4758. .remove(key, this.comparator_)
  4759. .copy(null, null, LLRBNode.BLACK, null, null));
  4760. };
  4761. /**
  4762. * Returns the value of the node with the given key, or null.
  4763. *
  4764. * @param key - The key to look up.
  4765. * @returns The value of the node with the given key, or null if the
  4766. * key doesn't exist.
  4767. */
  4768. SortedMap.prototype.get = function (key) {
  4769. var cmp;
  4770. var node = this.root_;
  4771. while (!node.isEmpty()) {
  4772. cmp = this.comparator_(key, node.key);
  4773. if (cmp === 0) {
  4774. return node.value;
  4775. }
  4776. else if (cmp < 0) {
  4777. node = node.left;
  4778. }
  4779. else if (cmp > 0) {
  4780. node = node.right;
  4781. }
  4782. }
  4783. return null;
  4784. };
  4785. /**
  4786. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4787. * @param key - The key to find the predecessor of
  4788. * @returns The predecessor key.
  4789. */
  4790. SortedMap.prototype.getPredecessorKey = function (key) {
  4791. var cmp, node = this.root_, rightParent = null;
  4792. while (!node.isEmpty()) {
  4793. cmp = this.comparator_(key, node.key);
  4794. if (cmp === 0) {
  4795. if (!node.left.isEmpty()) {
  4796. node = node.left;
  4797. while (!node.right.isEmpty()) {
  4798. node = node.right;
  4799. }
  4800. return node.key;
  4801. }
  4802. else if (rightParent) {
  4803. return rightParent.key;
  4804. }
  4805. else {
  4806. return null; // first item.
  4807. }
  4808. }
  4809. else if (cmp < 0) {
  4810. node = node.left;
  4811. }
  4812. else if (cmp > 0) {
  4813. rightParent = node;
  4814. node = node.right;
  4815. }
  4816. }
  4817. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4818. };
  4819. /**
  4820. * @returns True if the map is empty.
  4821. */
  4822. SortedMap.prototype.isEmpty = function () {
  4823. return this.root_.isEmpty();
  4824. };
  4825. /**
  4826. * @returns The total number of nodes in the map.
  4827. */
  4828. SortedMap.prototype.count = function () {
  4829. return this.root_.count();
  4830. };
  4831. /**
  4832. * @returns The minimum key in the map.
  4833. */
  4834. SortedMap.prototype.minKey = function () {
  4835. return this.root_.minKey();
  4836. };
  4837. /**
  4838. * @returns The maximum key in the map.
  4839. */
  4840. SortedMap.prototype.maxKey = function () {
  4841. return this.root_.maxKey();
  4842. };
  4843. /**
  4844. * Traverses the map in key order and calls the specified action function
  4845. * for each key/value pair.
  4846. *
  4847. * @param action - Callback function to be called
  4848. * for each key/value pair. If action returns true, traversal is aborted.
  4849. * @returns The first truthy value returned by action, or the last falsey
  4850. * value returned by action
  4851. */
  4852. SortedMap.prototype.inorderTraversal = function (action) {
  4853. return this.root_.inorderTraversal(action);
  4854. };
  4855. /**
  4856. * Traverses the map in reverse key order and calls the specified action function
  4857. * for each key/value pair.
  4858. *
  4859. * @param action - Callback function to be called
  4860. * for each key/value pair. If action returns true, traversal is aborted.
  4861. * @returns True if the traversal was aborted.
  4862. */
  4863. SortedMap.prototype.reverseTraversal = function (action) {
  4864. return this.root_.reverseTraversal(action);
  4865. };
  4866. /**
  4867. * Returns an iterator over the SortedMap.
  4868. * @returns The iterator.
  4869. */
  4870. SortedMap.prototype.getIterator = function (resultGenerator) {
  4871. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4872. };
  4873. SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
  4874. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4875. };
  4876. SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
  4877. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4878. };
  4879. SortedMap.prototype.getReverseIterator = function (resultGenerator) {
  4880. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4881. };
  4882. /**
  4883. * Always use the same empty node, to reduce memory.
  4884. */
  4885. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4886. return SortedMap;
  4887. }());
  4888. /**
  4889. * @license
  4890. * Copyright 2017 Google LLC
  4891. *
  4892. * Licensed under the Apache License, Version 2.0 (the "License");
  4893. * you may not use this file except in compliance with the License.
  4894. * You may obtain a copy of the License at
  4895. *
  4896. * http://www.apache.org/licenses/LICENSE-2.0
  4897. *
  4898. * Unless required by applicable law or agreed to in writing, software
  4899. * distributed under the License is distributed on an "AS IS" BASIS,
  4900. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4901. * See the License for the specific language governing permissions and
  4902. * limitations under the License.
  4903. */
  4904. function NAME_ONLY_COMPARATOR(left, right) {
  4905. return nameCompare(left.name, right.name);
  4906. }
  4907. function NAME_COMPARATOR(left, right) {
  4908. return nameCompare(left, right);
  4909. }
  4910. /**
  4911. * @license
  4912. * Copyright 2017 Google LLC
  4913. *
  4914. * Licensed under the Apache License, Version 2.0 (the "License");
  4915. * you may not use this file except in compliance with the License.
  4916. * You may obtain a copy of the License at
  4917. *
  4918. * http://www.apache.org/licenses/LICENSE-2.0
  4919. *
  4920. * Unless required by applicable law or agreed to in writing, software
  4921. * distributed under the License is distributed on an "AS IS" BASIS,
  4922. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4923. * See the License for the specific language governing permissions and
  4924. * limitations under the License.
  4925. */
  4926. var MAX_NODE$2;
  4927. function setMaxNode$1(val) {
  4928. MAX_NODE$2 = val;
  4929. }
  4930. var priorityHashText = function (priority) {
  4931. if (typeof priority === 'number') {
  4932. return 'number:' + doubleToIEEE754String(priority);
  4933. }
  4934. else {
  4935. return 'string:' + priority;
  4936. }
  4937. };
  4938. /**
  4939. * Validates that a priority snapshot Node is valid.
  4940. */
  4941. var validatePriorityNode = function (priorityNode) {
  4942. if (priorityNode.isLeafNode()) {
  4943. var val = priorityNode.val();
  4944. util.assert(typeof val === 'string' ||
  4945. typeof val === 'number' ||
  4946. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  4947. }
  4948. else {
  4949. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4950. }
  4951. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4952. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4953. };
  4954. /**
  4955. * @license
  4956. * Copyright 2017 Google LLC
  4957. *
  4958. * Licensed under the Apache License, Version 2.0 (the "License");
  4959. * you may not use this file except in compliance with the License.
  4960. * You may obtain a copy of the License at
  4961. *
  4962. * http://www.apache.org/licenses/LICENSE-2.0
  4963. *
  4964. * Unless required by applicable law or agreed to in writing, software
  4965. * distributed under the License is distributed on an "AS IS" BASIS,
  4966. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4967. * See the License for the specific language governing permissions and
  4968. * limitations under the License.
  4969. */
  4970. var __childrenNodeConstructor;
  4971. /**
  4972. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4973. * implements Node and stores the value of the node (a string,
  4974. * number, or boolean) accessible via getValue().
  4975. */
  4976. var LeafNode = /** @class */ (function () {
  4977. /**
  4978. * @param value_ - The value to store in this leaf node. The object type is
  4979. * possible in the event of a deferred value
  4980. * @param priorityNode_ - The priority of this node.
  4981. */
  4982. function LeafNode(value_, priorityNode_) {
  4983. if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
  4984. this.value_ = value_;
  4985. this.priorityNode_ = priorityNode_;
  4986. this.lazyHash_ = null;
  4987. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4988. validatePriorityNode(this.priorityNode_);
  4989. }
  4990. Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
  4991. get: function () {
  4992. return __childrenNodeConstructor;
  4993. },
  4994. set: function (val) {
  4995. __childrenNodeConstructor = val;
  4996. },
  4997. enumerable: false,
  4998. configurable: true
  4999. });
  5000. /** @inheritDoc */
  5001. LeafNode.prototype.isLeafNode = function () {
  5002. return true;
  5003. };
  5004. /** @inheritDoc */
  5005. LeafNode.prototype.getPriority = function () {
  5006. return this.priorityNode_;
  5007. };
  5008. /** @inheritDoc */
  5009. LeafNode.prototype.updatePriority = function (newPriorityNode) {
  5010. return new LeafNode(this.value_, newPriorityNode);
  5011. };
  5012. /** @inheritDoc */
  5013. LeafNode.prototype.getImmediateChild = function (childName) {
  5014. // Hack to treat priority as a regular child
  5015. if (childName === '.priority') {
  5016. return this.priorityNode_;
  5017. }
  5018. else {
  5019. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5020. }
  5021. };
  5022. /** @inheritDoc */
  5023. LeafNode.prototype.getChild = function (path) {
  5024. if (pathIsEmpty(path)) {
  5025. return this;
  5026. }
  5027. else if (pathGetFront(path) === '.priority') {
  5028. return this.priorityNode_;
  5029. }
  5030. else {
  5031. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5032. }
  5033. };
  5034. LeafNode.prototype.hasChild = function () {
  5035. return false;
  5036. };
  5037. /** @inheritDoc */
  5038. LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
  5039. return null;
  5040. };
  5041. /** @inheritDoc */
  5042. LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5043. if (childName === '.priority') {
  5044. return this.updatePriority(newChildNode);
  5045. }
  5046. else if (newChildNode.isEmpty() && childName !== '.priority') {
  5047. return this;
  5048. }
  5049. else {
  5050. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  5051. }
  5052. };
  5053. /** @inheritDoc */
  5054. LeafNode.prototype.updateChild = function (path, newChildNode) {
  5055. var front = pathGetFront(path);
  5056. if (front === null) {
  5057. return newChildNode;
  5058. }
  5059. else if (newChildNode.isEmpty() && front !== '.priority') {
  5060. return this;
  5061. }
  5062. else {
  5063. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5064. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  5065. }
  5066. };
  5067. /** @inheritDoc */
  5068. LeafNode.prototype.isEmpty = function () {
  5069. return false;
  5070. };
  5071. /** @inheritDoc */
  5072. LeafNode.prototype.numChildren = function () {
  5073. return 0;
  5074. };
  5075. /** @inheritDoc */
  5076. LeafNode.prototype.forEachChild = function (index, action) {
  5077. return false;
  5078. };
  5079. LeafNode.prototype.val = function (exportFormat) {
  5080. if (exportFormat && !this.getPriority().isEmpty()) {
  5081. return {
  5082. '.value': this.getValue(),
  5083. '.priority': this.getPriority().val()
  5084. };
  5085. }
  5086. else {
  5087. return this.getValue();
  5088. }
  5089. };
  5090. /** @inheritDoc */
  5091. LeafNode.prototype.hash = function () {
  5092. if (this.lazyHash_ === null) {
  5093. var toHash = '';
  5094. if (!this.priorityNode_.isEmpty()) {
  5095. toHash +=
  5096. 'priority:' +
  5097. priorityHashText(this.priorityNode_.val()) +
  5098. ':';
  5099. }
  5100. var type = typeof this.value_;
  5101. toHash += type + ':';
  5102. if (type === 'number') {
  5103. toHash += doubleToIEEE754String(this.value_);
  5104. }
  5105. else {
  5106. toHash += this.value_;
  5107. }
  5108. this.lazyHash_ = sha1(toHash);
  5109. }
  5110. return this.lazyHash_;
  5111. };
  5112. /**
  5113. * Returns the value of the leaf node.
  5114. * @returns The value of the node.
  5115. */
  5116. LeafNode.prototype.getValue = function () {
  5117. return this.value_;
  5118. };
  5119. LeafNode.prototype.compareTo = function (other) {
  5120. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  5121. return 1;
  5122. }
  5123. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  5124. return -1;
  5125. }
  5126. else {
  5127. util.assert(other.isLeafNode(), 'Unknown node type');
  5128. return this.compareToLeafNode_(other);
  5129. }
  5130. };
  5131. /**
  5132. * Comparison specifically for two leaf nodes
  5133. */
  5134. LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
  5135. var otherLeafType = typeof otherLeaf.value_;
  5136. var thisLeafType = typeof this.value_;
  5137. var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  5138. var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  5139. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  5140. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  5141. if (otherIndex === thisIndex) {
  5142. // Same type, compare values
  5143. if (thisLeafType === 'object') {
  5144. // Deferred value nodes are all equal, but we should also never get to this point...
  5145. return 0;
  5146. }
  5147. else {
  5148. // Note that this works because true > false, all others are number or string comparisons
  5149. if (this.value_ < otherLeaf.value_) {
  5150. return -1;
  5151. }
  5152. else if (this.value_ === otherLeaf.value_) {
  5153. return 0;
  5154. }
  5155. else {
  5156. return 1;
  5157. }
  5158. }
  5159. }
  5160. else {
  5161. return thisIndex - otherIndex;
  5162. }
  5163. };
  5164. LeafNode.prototype.withIndex = function () {
  5165. return this;
  5166. };
  5167. LeafNode.prototype.isIndexed = function () {
  5168. return true;
  5169. };
  5170. LeafNode.prototype.equals = function (other) {
  5171. if (other === this) {
  5172. return true;
  5173. }
  5174. else if (other.isLeafNode()) {
  5175. var otherLeaf = other;
  5176. return (this.value_ === otherLeaf.value_ &&
  5177. this.priorityNode_.equals(otherLeaf.priorityNode_));
  5178. }
  5179. else {
  5180. return false;
  5181. }
  5182. };
  5183. /**
  5184. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5185. * the same type, the comparison falls back to their value
  5186. */
  5187. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5188. return LeafNode;
  5189. }());
  5190. /**
  5191. * @license
  5192. * Copyright 2017 Google LLC
  5193. *
  5194. * Licensed under the Apache License, Version 2.0 (the "License");
  5195. * you may not use this file except in compliance with the License.
  5196. * You may obtain a copy of the License at
  5197. *
  5198. * http://www.apache.org/licenses/LICENSE-2.0
  5199. *
  5200. * Unless required by applicable law or agreed to in writing, software
  5201. * distributed under the License is distributed on an "AS IS" BASIS,
  5202. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5203. * See the License for the specific language governing permissions and
  5204. * limitations under the License.
  5205. */
  5206. var nodeFromJSON$1;
  5207. var MAX_NODE$1;
  5208. function setNodeFromJSON(val) {
  5209. nodeFromJSON$1 = val;
  5210. }
  5211. function setMaxNode(val) {
  5212. MAX_NODE$1 = val;
  5213. }
  5214. var PriorityIndex = /** @class */ (function (_super) {
  5215. tslib.__extends(PriorityIndex, _super);
  5216. function PriorityIndex() {
  5217. return _super !== null && _super.apply(this, arguments) || this;
  5218. }
  5219. PriorityIndex.prototype.compare = function (a, b) {
  5220. var aPriority = a.node.getPriority();
  5221. var bPriority = b.node.getPriority();
  5222. var indexCmp = aPriority.compareTo(bPriority);
  5223. if (indexCmp === 0) {
  5224. return nameCompare(a.name, b.name);
  5225. }
  5226. else {
  5227. return indexCmp;
  5228. }
  5229. };
  5230. PriorityIndex.prototype.isDefinedOn = function (node) {
  5231. return !node.getPriority().isEmpty();
  5232. };
  5233. PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  5234. return !oldNode.getPriority().equals(newNode.getPriority());
  5235. };
  5236. PriorityIndex.prototype.minPost = function () {
  5237. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5238. return NamedNode.MIN;
  5239. };
  5240. PriorityIndex.prototype.maxPost = function () {
  5241. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5242. };
  5243. PriorityIndex.prototype.makePost = function (indexValue, name) {
  5244. var priorityNode = nodeFromJSON$1(indexValue);
  5245. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5246. };
  5247. /**
  5248. * @returns String representation for inclusion in a query spec
  5249. */
  5250. PriorityIndex.prototype.toString = function () {
  5251. return '.priority';
  5252. };
  5253. return PriorityIndex;
  5254. }(Index));
  5255. var PRIORITY_INDEX = new PriorityIndex();
  5256. /**
  5257. * @license
  5258. * Copyright 2017 Google LLC
  5259. *
  5260. * Licensed under the Apache License, Version 2.0 (the "License");
  5261. * you may not use this file except in compliance with the License.
  5262. * You may obtain a copy of the License at
  5263. *
  5264. * http://www.apache.org/licenses/LICENSE-2.0
  5265. *
  5266. * Unless required by applicable law or agreed to in writing, software
  5267. * distributed under the License is distributed on an "AS IS" BASIS,
  5268. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5269. * See the License for the specific language governing permissions and
  5270. * limitations under the License.
  5271. */
  5272. var LOG_2 = Math.log(2);
  5273. var Base12Num = /** @class */ (function () {
  5274. function Base12Num(length) {
  5275. var logBase2 = function (num) {
  5276. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5277. return parseInt((Math.log(num) / LOG_2), 10);
  5278. };
  5279. var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
  5280. this.count = logBase2(length + 1);
  5281. this.current_ = this.count - 1;
  5282. var mask = bitMask(this.count);
  5283. this.bits_ = (length + 1) & mask;
  5284. }
  5285. Base12Num.prototype.nextBitIsOne = function () {
  5286. //noinspection JSBitwiseOperatorUsage
  5287. var result = !(this.bits_ & (0x1 << this.current_));
  5288. this.current_--;
  5289. return result;
  5290. };
  5291. return Base12Num;
  5292. }());
  5293. /**
  5294. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5295. * function
  5296. *
  5297. * Uses the algorithm described in the paper linked here:
  5298. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5299. *
  5300. * @param childList - Unsorted list of children
  5301. * @param cmp - The comparison method to be used
  5302. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5303. * type is not NamedNode
  5304. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5305. */
  5306. var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5307. childList.sort(cmp);
  5308. var buildBalancedTree = function (low, high) {
  5309. var length = high - low;
  5310. var namedNode;
  5311. var key;
  5312. if (length === 0) {
  5313. return null;
  5314. }
  5315. else if (length === 1) {
  5316. namedNode = childList[low];
  5317. key = keyFn ? keyFn(namedNode) : namedNode;
  5318. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5319. }
  5320. else {
  5321. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5322. var middle = parseInt((length / 2), 10) + low;
  5323. var left = buildBalancedTree(low, middle);
  5324. var right = buildBalancedTree(middle + 1, high);
  5325. namedNode = childList[middle];
  5326. key = keyFn ? keyFn(namedNode) : namedNode;
  5327. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5328. }
  5329. };
  5330. var buildFrom12Array = function (base12) {
  5331. var node = null;
  5332. var root = null;
  5333. var index = childList.length;
  5334. var buildPennant = function (chunkSize, color) {
  5335. var low = index - chunkSize;
  5336. var high = index;
  5337. index -= chunkSize;
  5338. var childTree = buildBalancedTree(low + 1, high);
  5339. var namedNode = childList[low];
  5340. var key = keyFn ? keyFn(namedNode) : namedNode;
  5341. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5342. };
  5343. var attachPennant = function (pennant) {
  5344. if (node) {
  5345. node.left = pennant;
  5346. node = pennant;
  5347. }
  5348. else {
  5349. root = pennant;
  5350. node = pennant;
  5351. }
  5352. };
  5353. for (var i = 0; i < base12.count; ++i) {
  5354. var isOne = base12.nextBitIsOne();
  5355. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5356. var chunkSize = Math.pow(2, base12.count - (i + 1));
  5357. if (isOne) {
  5358. buildPennant(chunkSize, LLRBNode.BLACK);
  5359. }
  5360. else {
  5361. // current == 2
  5362. buildPennant(chunkSize, LLRBNode.BLACK);
  5363. buildPennant(chunkSize, LLRBNode.RED);
  5364. }
  5365. }
  5366. return root;
  5367. };
  5368. var base12 = new Base12Num(childList.length);
  5369. var root = buildFrom12Array(base12);
  5370. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5371. return new SortedMap(mapSortFn || cmp, root);
  5372. };
  5373. /**
  5374. * @license
  5375. * Copyright 2017 Google LLC
  5376. *
  5377. * Licensed under the Apache License, Version 2.0 (the "License");
  5378. * you may not use this file except in compliance with the License.
  5379. * You may obtain a copy of the License at
  5380. *
  5381. * http://www.apache.org/licenses/LICENSE-2.0
  5382. *
  5383. * Unless required by applicable law or agreed to in writing, software
  5384. * distributed under the License is distributed on an "AS IS" BASIS,
  5385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5386. * See the License for the specific language governing permissions and
  5387. * limitations under the License.
  5388. */
  5389. var _defaultIndexMap;
  5390. var fallbackObject = {};
  5391. var IndexMap = /** @class */ (function () {
  5392. function IndexMap(indexes_, indexSet_) {
  5393. this.indexes_ = indexes_;
  5394. this.indexSet_ = indexSet_;
  5395. }
  5396. Object.defineProperty(IndexMap, "Default", {
  5397. /**
  5398. * The default IndexMap for nodes without a priority
  5399. */
  5400. get: function () {
  5401. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5402. _defaultIndexMap =
  5403. _defaultIndexMap ||
  5404. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5405. return _defaultIndexMap;
  5406. },
  5407. enumerable: false,
  5408. configurable: true
  5409. });
  5410. IndexMap.prototype.get = function (indexKey) {
  5411. var sortedMap = util.safeGet(this.indexes_, indexKey);
  5412. if (!sortedMap) {
  5413. throw new Error('No index defined for ' + indexKey);
  5414. }
  5415. if (sortedMap instanceof SortedMap) {
  5416. return sortedMap;
  5417. }
  5418. else {
  5419. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5420. // regular child map
  5421. return null;
  5422. }
  5423. };
  5424. IndexMap.prototype.hasIndex = function (indexDefinition) {
  5425. return util.contains(this.indexSet_, indexDefinition.toString());
  5426. };
  5427. IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
  5428. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5429. var childList = [];
  5430. var sawIndexedValue = false;
  5431. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5432. var next = iter.getNext();
  5433. while (next) {
  5434. sawIndexedValue =
  5435. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5436. childList.push(next);
  5437. next = iter.getNext();
  5438. }
  5439. var newIndex;
  5440. if (sawIndexedValue) {
  5441. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5442. }
  5443. else {
  5444. newIndex = fallbackObject;
  5445. }
  5446. var indexName = indexDefinition.toString();
  5447. var newIndexSet = tslib.__assign({}, this.indexSet_);
  5448. newIndexSet[indexName] = indexDefinition;
  5449. var newIndexes = tslib.__assign({}, this.indexes_);
  5450. newIndexes[indexName] = newIndex;
  5451. return new IndexMap(newIndexes, newIndexSet);
  5452. };
  5453. /**
  5454. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5455. */
  5456. IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
  5457. var _this = this;
  5458. var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) {
  5459. var index = util.safeGet(_this.indexSet_, indexName);
  5460. util.assert(index, 'Missing index implementation for ' + indexName);
  5461. if (indexedChildren === fallbackObject) {
  5462. // Check to see if we need to index everything
  5463. if (index.isDefinedOn(namedNode.node)) {
  5464. // We need to build this index
  5465. var childList = [];
  5466. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5467. var next = iter.getNext();
  5468. while (next) {
  5469. if (next.name !== namedNode.name) {
  5470. childList.push(next);
  5471. }
  5472. next = iter.getNext();
  5473. }
  5474. childList.push(namedNode);
  5475. return buildChildSet(childList, index.getCompare());
  5476. }
  5477. else {
  5478. // No change, this remains a fallback
  5479. return fallbackObject;
  5480. }
  5481. }
  5482. else {
  5483. var existingSnap = existingChildren.get(namedNode.name);
  5484. var newChildren = indexedChildren;
  5485. if (existingSnap) {
  5486. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5487. }
  5488. return newChildren.insert(namedNode, namedNode.node);
  5489. }
  5490. });
  5491. return new IndexMap(newIndexes, this.indexSet_);
  5492. };
  5493. /**
  5494. * Create a new IndexMap instance with the given value removed
  5495. */
  5496. IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
  5497. var newIndexes = util.map(this.indexes_, function (indexedChildren) {
  5498. if (indexedChildren === fallbackObject) {
  5499. // This is the fallback. Just return it, nothing to do in this case
  5500. return indexedChildren;
  5501. }
  5502. else {
  5503. var existingSnap = existingChildren.get(namedNode.name);
  5504. if (existingSnap) {
  5505. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5506. }
  5507. else {
  5508. // No record of this child
  5509. return indexedChildren;
  5510. }
  5511. }
  5512. });
  5513. return new IndexMap(newIndexes, this.indexSet_);
  5514. };
  5515. return IndexMap;
  5516. }());
  5517. /**
  5518. * @license
  5519. * Copyright 2017 Google LLC
  5520. *
  5521. * Licensed under the Apache License, Version 2.0 (the "License");
  5522. * you may not use this file except in compliance with the License.
  5523. * You may obtain a copy of the License at
  5524. *
  5525. * http://www.apache.org/licenses/LICENSE-2.0
  5526. *
  5527. * Unless required by applicable law or agreed to in writing, software
  5528. * distributed under the License is distributed on an "AS IS" BASIS,
  5529. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5530. * See the License for the specific language governing permissions and
  5531. * limitations under the License.
  5532. */
  5533. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5534. var EMPTY_NODE;
  5535. /**
  5536. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5537. * (i.e. nodes with children). It implements Node and stores the
  5538. * list of children in the children property, sorted by child name.
  5539. */
  5540. var ChildrenNode = /** @class */ (function () {
  5541. /**
  5542. * @param children_ - List of children of this node..
  5543. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5544. */
  5545. function ChildrenNode(children_, priorityNode_, indexMap_) {
  5546. this.children_ = children_;
  5547. this.priorityNode_ = priorityNode_;
  5548. this.indexMap_ = indexMap_;
  5549. this.lazyHash_ = null;
  5550. /**
  5551. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5552. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5553. * class instead of an empty ChildrenNode.
  5554. */
  5555. if (this.priorityNode_) {
  5556. validatePriorityNode(this.priorityNode_);
  5557. }
  5558. if (this.children_.isEmpty()) {
  5559. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5560. }
  5561. }
  5562. Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
  5563. get: function () {
  5564. return (EMPTY_NODE ||
  5565. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5566. },
  5567. enumerable: false,
  5568. configurable: true
  5569. });
  5570. /** @inheritDoc */
  5571. ChildrenNode.prototype.isLeafNode = function () {
  5572. return false;
  5573. };
  5574. /** @inheritDoc */
  5575. ChildrenNode.prototype.getPriority = function () {
  5576. return this.priorityNode_ || EMPTY_NODE;
  5577. };
  5578. /** @inheritDoc */
  5579. ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
  5580. if (this.children_.isEmpty()) {
  5581. // Don't allow priorities on empty nodes
  5582. return this;
  5583. }
  5584. else {
  5585. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5586. }
  5587. };
  5588. /** @inheritDoc */
  5589. ChildrenNode.prototype.getImmediateChild = function (childName) {
  5590. // Hack to treat priority as a regular child
  5591. if (childName === '.priority') {
  5592. return this.getPriority();
  5593. }
  5594. else {
  5595. var child = this.children_.get(childName);
  5596. return child === null ? EMPTY_NODE : child;
  5597. }
  5598. };
  5599. /** @inheritDoc */
  5600. ChildrenNode.prototype.getChild = function (path) {
  5601. var front = pathGetFront(path);
  5602. if (front === null) {
  5603. return this;
  5604. }
  5605. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5606. };
  5607. /** @inheritDoc */
  5608. ChildrenNode.prototype.hasChild = function (childName) {
  5609. return this.children_.get(childName) !== null;
  5610. };
  5611. /** @inheritDoc */
  5612. ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5613. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  5614. if (childName === '.priority') {
  5615. return this.updatePriority(newChildNode);
  5616. }
  5617. else {
  5618. var namedNode = new NamedNode(childName, newChildNode);
  5619. var newChildren = void 0, newIndexMap = void 0;
  5620. if (newChildNode.isEmpty()) {
  5621. newChildren = this.children_.remove(childName);
  5622. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5623. }
  5624. else {
  5625. newChildren = this.children_.insert(childName, newChildNode);
  5626. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5627. }
  5628. var newPriority = newChildren.isEmpty()
  5629. ? EMPTY_NODE
  5630. : this.priorityNode_;
  5631. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5632. }
  5633. };
  5634. /** @inheritDoc */
  5635. ChildrenNode.prototype.updateChild = function (path, newChildNode) {
  5636. var front = pathGetFront(path);
  5637. if (front === null) {
  5638. return newChildNode;
  5639. }
  5640. else {
  5641. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5642. var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5643. return this.updateImmediateChild(front, newImmediateChild);
  5644. }
  5645. };
  5646. /** @inheritDoc */
  5647. ChildrenNode.prototype.isEmpty = function () {
  5648. return this.children_.isEmpty();
  5649. };
  5650. /** @inheritDoc */
  5651. ChildrenNode.prototype.numChildren = function () {
  5652. return this.children_.count();
  5653. };
  5654. /** @inheritDoc */
  5655. ChildrenNode.prototype.val = function (exportFormat) {
  5656. if (this.isEmpty()) {
  5657. return null;
  5658. }
  5659. var obj = {};
  5660. var numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5661. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5662. obj[key] = childNode.val(exportFormat);
  5663. numKeys++;
  5664. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5665. maxKey = Math.max(maxKey, Number(key));
  5666. }
  5667. else {
  5668. allIntegerKeys = false;
  5669. }
  5670. });
  5671. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5672. // convert to array.
  5673. var array = [];
  5674. // eslint-disable-next-line guard-for-in
  5675. for (var key in obj) {
  5676. array[key] = obj[key];
  5677. }
  5678. return array;
  5679. }
  5680. else {
  5681. if (exportFormat && !this.getPriority().isEmpty()) {
  5682. obj['.priority'] = this.getPriority().val();
  5683. }
  5684. return obj;
  5685. }
  5686. };
  5687. /** @inheritDoc */
  5688. ChildrenNode.prototype.hash = function () {
  5689. if (this.lazyHash_ === null) {
  5690. var toHash_1 = '';
  5691. if (!this.getPriority().isEmpty()) {
  5692. toHash_1 +=
  5693. 'priority:' +
  5694. priorityHashText(this.getPriority().val()) +
  5695. ':';
  5696. }
  5697. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5698. var childHash = childNode.hash();
  5699. if (childHash !== '') {
  5700. toHash_1 += ':' + key + ':' + childHash;
  5701. }
  5702. });
  5703. this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
  5704. }
  5705. return this.lazyHash_;
  5706. };
  5707. /** @inheritDoc */
  5708. ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
  5709. var idx = this.resolveIndex_(index);
  5710. if (idx) {
  5711. var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5712. return predecessor ? predecessor.name : null;
  5713. }
  5714. else {
  5715. return this.children_.getPredecessorKey(childName);
  5716. }
  5717. };
  5718. ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
  5719. var idx = this.resolveIndex_(indexDefinition);
  5720. if (idx) {
  5721. var minKey = idx.minKey();
  5722. return minKey && minKey.name;
  5723. }
  5724. else {
  5725. return this.children_.minKey();
  5726. }
  5727. };
  5728. ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
  5729. var minKey = this.getFirstChildName(indexDefinition);
  5730. if (minKey) {
  5731. return new NamedNode(minKey, this.children_.get(minKey));
  5732. }
  5733. else {
  5734. return null;
  5735. }
  5736. };
  5737. /**
  5738. * Given an index, return the key name of the largest value we have, according to that index
  5739. */
  5740. ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
  5741. var idx = this.resolveIndex_(indexDefinition);
  5742. if (idx) {
  5743. var maxKey = idx.maxKey();
  5744. return maxKey && maxKey.name;
  5745. }
  5746. else {
  5747. return this.children_.maxKey();
  5748. }
  5749. };
  5750. ChildrenNode.prototype.getLastChild = function (indexDefinition) {
  5751. var maxKey = this.getLastChildName(indexDefinition);
  5752. if (maxKey) {
  5753. return new NamedNode(maxKey, this.children_.get(maxKey));
  5754. }
  5755. else {
  5756. return null;
  5757. }
  5758. };
  5759. ChildrenNode.prototype.forEachChild = function (index, action) {
  5760. var idx = this.resolveIndex_(index);
  5761. if (idx) {
  5762. return idx.inorderTraversal(function (wrappedNode) {
  5763. return action(wrappedNode.name, wrappedNode.node);
  5764. });
  5765. }
  5766. else {
  5767. return this.children_.inorderTraversal(action);
  5768. }
  5769. };
  5770. ChildrenNode.prototype.getIterator = function (indexDefinition) {
  5771. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5772. };
  5773. ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
  5774. var idx = this.resolveIndex_(indexDefinition);
  5775. if (idx) {
  5776. return idx.getIteratorFrom(startPost, function (key) { return key; });
  5777. }
  5778. else {
  5779. var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5780. var next = iterator.peek();
  5781. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5782. iterator.getNext();
  5783. next = iterator.peek();
  5784. }
  5785. return iterator;
  5786. }
  5787. };
  5788. ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
  5789. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5790. };
  5791. ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
  5792. var idx = this.resolveIndex_(indexDefinition);
  5793. if (idx) {
  5794. return idx.getReverseIteratorFrom(endPost, function (key) {
  5795. return key;
  5796. });
  5797. }
  5798. else {
  5799. var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5800. var next = iterator.peek();
  5801. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5802. iterator.getNext();
  5803. next = iterator.peek();
  5804. }
  5805. return iterator;
  5806. }
  5807. };
  5808. ChildrenNode.prototype.compareTo = function (other) {
  5809. if (this.isEmpty()) {
  5810. if (other.isEmpty()) {
  5811. return 0;
  5812. }
  5813. else {
  5814. return -1;
  5815. }
  5816. }
  5817. else if (other.isLeafNode() || other.isEmpty()) {
  5818. return 1;
  5819. }
  5820. else if (other === MAX_NODE) {
  5821. return -1;
  5822. }
  5823. else {
  5824. // Must be another node with children.
  5825. return 0;
  5826. }
  5827. };
  5828. ChildrenNode.prototype.withIndex = function (indexDefinition) {
  5829. if (indexDefinition === KEY_INDEX ||
  5830. this.indexMap_.hasIndex(indexDefinition)) {
  5831. return this;
  5832. }
  5833. else {
  5834. var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5835. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5836. }
  5837. };
  5838. ChildrenNode.prototype.isIndexed = function (index) {
  5839. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5840. };
  5841. ChildrenNode.prototype.equals = function (other) {
  5842. if (other === this) {
  5843. return true;
  5844. }
  5845. else if (other.isLeafNode()) {
  5846. return false;
  5847. }
  5848. else {
  5849. var otherChildrenNode = other;
  5850. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5851. return false;
  5852. }
  5853. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5854. var thisIter = this.getIterator(PRIORITY_INDEX);
  5855. var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5856. var thisCurrent = thisIter.getNext();
  5857. var otherCurrent = otherIter.getNext();
  5858. while (thisCurrent && otherCurrent) {
  5859. if (thisCurrent.name !== otherCurrent.name ||
  5860. !thisCurrent.node.equals(otherCurrent.node)) {
  5861. return false;
  5862. }
  5863. thisCurrent = thisIter.getNext();
  5864. otherCurrent = otherIter.getNext();
  5865. }
  5866. return thisCurrent === null && otherCurrent === null;
  5867. }
  5868. else {
  5869. return false;
  5870. }
  5871. }
  5872. };
  5873. /**
  5874. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5875. * instead.
  5876. *
  5877. */
  5878. ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
  5879. if (indexDefinition === KEY_INDEX) {
  5880. return null;
  5881. }
  5882. else {
  5883. return this.indexMap_.get(indexDefinition.toString());
  5884. }
  5885. };
  5886. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5887. return ChildrenNode;
  5888. }());
  5889. var MaxNode = /** @class */ (function (_super) {
  5890. tslib.__extends(MaxNode, _super);
  5891. function MaxNode() {
  5892. return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
  5893. }
  5894. MaxNode.prototype.compareTo = function (other) {
  5895. if (other === this) {
  5896. return 0;
  5897. }
  5898. else {
  5899. return 1;
  5900. }
  5901. };
  5902. MaxNode.prototype.equals = function (other) {
  5903. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5904. return other === this;
  5905. };
  5906. MaxNode.prototype.getPriority = function () {
  5907. return this;
  5908. };
  5909. MaxNode.prototype.getImmediateChild = function (childName) {
  5910. return ChildrenNode.EMPTY_NODE;
  5911. };
  5912. MaxNode.prototype.isEmpty = function () {
  5913. return false;
  5914. };
  5915. return MaxNode;
  5916. }(ChildrenNode));
  5917. /**
  5918. * Marker that will sort higher than any other snapshot.
  5919. */
  5920. var MAX_NODE = new MaxNode();
  5921. Object.defineProperties(NamedNode, {
  5922. MIN: {
  5923. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5924. },
  5925. MAX: {
  5926. value: new NamedNode(MAX_NAME, MAX_NODE)
  5927. }
  5928. });
  5929. /**
  5930. * Reference Extensions
  5931. */
  5932. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5933. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5934. setMaxNode$1(MAX_NODE);
  5935. setMaxNode(MAX_NODE);
  5936. /**
  5937. * @license
  5938. * Copyright 2017 Google LLC
  5939. *
  5940. * Licensed under the Apache License, Version 2.0 (the "License");
  5941. * you may not use this file except in compliance with the License.
  5942. * You may obtain a copy of the License at
  5943. *
  5944. * http://www.apache.org/licenses/LICENSE-2.0
  5945. *
  5946. * Unless required by applicable law or agreed to in writing, software
  5947. * distributed under the License is distributed on an "AS IS" BASIS,
  5948. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5949. * See the License for the specific language governing permissions and
  5950. * limitations under the License.
  5951. */
  5952. var USE_HINZE = true;
  5953. /**
  5954. * Constructs a snapshot node representing the passed JSON and returns it.
  5955. * @param json - JSON to create a node for.
  5956. * @param priority - Optional priority to use. This will be ignored if the
  5957. * passed JSON contains a .priority property.
  5958. */
  5959. function nodeFromJSON(json, priority) {
  5960. if (priority === void 0) { priority = null; }
  5961. if (json === null) {
  5962. return ChildrenNode.EMPTY_NODE;
  5963. }
  5964. if (typeof json === 'object' && '.priority' in json) {
  5965. priority = json['.priority'];
  5966. }
  5967. util.assert(priority === null ||
  5968. typeof priority === 'string' ||
  5969. typeof priority === 'number' ||
  5970. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5971. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5972. json = json['.value'];
  5973. }
  5974. // Valid leaf nodes include non-objects or server-value wrapper objects
  5975. if (typeof json !== 'object' || '.sv' in json) {
  5976. var jsonLeaf = json;
  5977. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5978. }
  5979. if (!(json instanceof Array) && USE_HINZE) {
  5980. var children_1 = [];
  5981. var childrenHavePriority_1 = false;
  5982. var hinzeJsonObj = json;
  5983. each(hinzeJsonObj, function (key, child) {
  5984. if (key.substring(0, 1) !== '.') {
  5985. // Ignore metadata nodes
  5986. var childNode = nodeFromJSON(child);
  5987. if (!childNode.isEmpty()) {
  5988. childrenHavePriority_1 =
  5989. childrenHavePriority_1 || !childNode.getPriority().isEmpty();
  5990. children_1.push(new NamedNode(key, childNode));
  5991. }
  5992. }
  5993. });
  5994. if (children_1.length === 0) {
  5995. return ChildrenNode.EMPTY_NODE;
  5996. }
  5997. var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
  5998. if (childrenHavePriority_1) {
  5999. var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
  6000. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  6001. }
  6002. else {
  6003. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  6004. }
  6005. }
  6006. else {
  6007. var node_1 = ChildrenNode.EMPTY_NODE;
  6008. each(json, function (key, childData) {
  6009. if (util.contains(json, key)) {
  6010. if (key.substring(0, 1) !== '.') {
  6011. // ignore metadata nodes.
  6012. var childNode = nodeFromJSON(childData);
  6013. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  6014. node_1 = node_1.updateImmediateChild(key, childNode);
  6015. }
  6016. }
  6017. }
  6018. });
  6019. return node_1.updatePriority(nodeFromJSON(priority));
  6020. }
  6021. }
  6022. setNodeFromJSON(nodeFromJSON);
  6023. /**
  6024. * @license
  6025. * Copyright 2017 Google LLC
  6026. *
  6027. * Licensed under the Apache License, Version 2.0 (the "License");
  6028. * you may not use this file except in compliance with the License.
  6029. * You may obtain a copy of the License at
  6030. *
  6031. * http://www.apache.org/licenses/LICENSE-2.0
  6032. *
  6033. * Unless required by applicable law or agreed to in writing, software
  6034. * distributed under the License is distributed on an "AS IS" BASIS,
  6035. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6036. * See the License for the specific language governing permissions and
  6037. * limitations under the License.
  6038. */
  6039. var PathIndex = /** @class */ (function (_super) {
  6040. tslib.__extends(PathIndex, _super);
  6041. function PathIndex(indexPath_) {
  6042. var _this = _super.call(this) || this;
  6043. _this.indexPath_ = indexPath_;
  6044. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  6045. return _this;
  6046. }
  6047. PathIndex.prototype.extractChild = function (snap) {
  6048. return snap.getChild(this.indexPath_);
  6049. };
  6050. PathIndex.prototype.isDefinedOn = function (node) {
  6051. return !node.getChild(this.indexPath_).isEmpty();
  6052. };
  6053. PathIndex.prototype.compare = function (a, b) {
  6054. var aChild = this.extractChild(a.node);
  6055. var bChild = this.extractChild(b.node);
  6056. var indexCmp = aChild.compareTo(bChild);
  6057. if (indexCmp === 0) {
  6058. return nameCompare(a.name, b.name);
  6059. }
  6060. else {
  6061. return indexCmp;
  6062. }
  6063. };
  6064. PathIndex.prototype.makePost = function (indexValue, name) {
  6065. var valueNode = nodeFromJSON(indexValue);
  6066. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  6067. return new NamedNode(name, node);
  6068. };
  6069. PathIndex.prototype.maxPost = function () {
  6070. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  6071. return new NamedNode(MAX_NAME, node);
  6072. };
  6073. PathIndex.prototype.toString = function () {
  6074. return pathSlice(this.indexPath_, 0).join('/');
  6075. };
  6076. return PathIndex;
  6077. }(Index));
  6078. /**
  6079. * @license
  6080. * Copyright 2017 Google LLC
  6081. *
  6082. * Licensed under the Apache License, Version 2.0 (the "License");
  6083. * you may not use this file except in compliance with the License.
  6084. * You may obtain a copy of the License at
  6085. *
  6086. * http://www.apache.org/licenses/LICENSE-2.0
  6087. *
  6088. * Unless required by applicable law or agreed to in writing, software
  6089. * distributed under the License is distributed on an "AS IS" BASIS,
  6090. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6091. * See the License for the specific language governing permissions and
  6092. * limitations under the License.
  6093. */
  6094. var ValueIndex = /** @class */ (function (_super) {
  6095. tslib.__extends(ValueIndex, _super);
  6096. function ValueIndex() {
  6097. return _super !== null && _super.apply(this, arguments) || this;
  6098. }
  6099. ValueIndex.prototype.compare = function (a, b) {
  6100. var indexCmp = a.node.compareTo(b.node);
  6101. if (indexCmp === 0) {
  6102. return nameCompare(a.name, b.name);
  6103. }
  6104. else {
  6105. return indexCmp;
  6106. }
  6107. };
  6108. ValueIndex.prototype.isDefinedOn = function (node) {
  6109. return true;
  6110. };
  6111. ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  6112. return !oldNode.equals(newNode);
  6113. };
  6114. ValueIndex.prototype.minPost = function () {
  6115. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6116. return NamedNode.MIN;
  6117. };
  6118. ValueIndex.prototype.maxPost = function () {
  6119. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6120. return NamedNode.MAX;
  6121. };
  6122. ValueIndex.prototype.makePost = function (indexValue, name) {
  6123. var valueNode = nodeFromJSON(indexValue);
  6124. return new NamedNode(name, valueNode);
  6125. };
  6126. /**
  6127. * @returns String representation for inclusion in a query spec
  6128. */
  6129. ValueIndex.prototype.toString = function () {
  6130. return '.value';
  6131. };
  6132. return ValueIndex;
  6133. }(Index));
  6134. var VALUE_INDEX = new ValueIndex();
  6135. /**
  6136. * @license
  6137. * Copyright 2017 Google LLC
  6138. *
  6139. * Licensed under the Apache License, Version 2.0 (the "License");
  6140. * you may not use this file except in compliance with the License.
  6141. * You may obtain a copy of the License at
  6142. *
  6143. * http://www.apache.org/licenses/LICENSE-2.0
  6144. *
  6145. * Unless required by applicable law or agreed to in writing, software
  6146. * distributed under the License is distributed on an "AS IS" BASIS,
  6147. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6148. * See the License for the specific language governing permissions and
  6149. * limitations under the License.
  6150. */
  6151. function changeValue(snapshotNode) {
  6152. return { type: "value" /* ChangeType.VALUE */, snapshotNode: snapshotNode };
  6153. }
  6154. function changeChildAdded(childName, snapshotNode) {
  6155. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode: snapshotNode, childName: childName };
  6156. }
  6157. function changeChildRemoved(childName, snapshotNode) {
  6158. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode: snapshotNode, childName: childName };
  6159. }
  6160. function changeChildChanged(childName, snapshotNode, oldSnap) {
  6161. return {
  6162. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  6163. snapshotNode: snapshotNode,
  6164. childName: childName,
  6165. oldSnap: oldSnap
  6166. };
  6167. }
  6168. function changeChildMoved(childName, snapshotNode) {
  6169. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode: snapshotNode, childName: childName };
  6170. }
  6171. /**
  6172. * @license
  6173. * Copyright 2017 Google LLC
  6174. *
  6175. * Licensed under the Apache License, Version 2.0 (the "License");
  6176. * you may not use this file except in compliance with the License.
  6177. * You may obtain a copy of the License at
  6178. *
  6179. * http://www.apache.org/licenses/LICENSE-2.0
  6180. *
  6181. * Unless required by applicable law or agreed to in writing, software
  6182. * distributed under the License is distributed on an "AS IS" BASIS,
  6183. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6184. * See the License for the specific language governing permissions and
  6185. * limitations under the License.
  6186. */
  6187. /**
  6188. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  6189. */
  6190. var IndexedFilter = /** @class */ (function () {
  6191. function IndexedFilter(index_) {
  6192. this.index_ = index_;
  6193. }
  6194. IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6195. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  6196. var oldChild = snap.getImmediateChild(key);
  6197. // Check if anything actually changed.
  6198. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  6199. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  6200. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  6201. // to avoid treating these cases as "nothing changed."
  6202. if (oldChild.isEmpty() === newChild.isEmpty()) {
  6203. // Nothing changed.
  6204. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  6205. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  6206. return snap;
  6207. }
  6208. }
  6209. if (optChangeAccumulator != null) {
  6210. if (newChild.isEmpty()) {
  6211. if (snap.hasChild(key)) {
  6212. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6213. }
  6214. else {
  6215. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6216. }
  6217. }
  6218. else if (oldChild.isEmpty()) {
  6219. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6220. }
  6221. else {
  6222. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6223. }
  6224. }
  6225. if (snap.isLeafNode() && newChild.isEmpty()) {
  6226. return snap;
  6227. }
  6228. else {
  6229. // Make sure the node is indexed
  6230. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6231. }
  6232. };
  6233. IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6234. if (optChangeAccumulator != null) {
  6235. if (!oldSnap.isLeafNode()) {
  6236. oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6237. if (!newSnap.hasChild(key)) {
  6238. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6239. }
  6240. });
  6241. }
  6242. if (!newSnap.isLeafNode()) {
  6243. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6244. if (oldSnap.hasChild(key)) {
  6245. var oldChild = oldSnap.getImmediateChild(key);
  6246. if (!oldChild.equals(childNode)) {
  6247. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6248. }
  6249. }
  6250. else {
  6251. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6252. }
  6253. });
  6254. }
  6255. }
  6256. return newSnap.withIndex(this.index_);
  6257. };
  6258. IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6259. if (oldSnap.isEmpty()) {
  6260. return ChildrenNode.EMPTY_NODE;
  6261. }
  6262. else {
  6263. return oldSnap.updatePriority(newPriority);
  6264. }
  6265. };
  6266. IndexedFilter.prototype.filtersNodes = function () {
  6267. return false;
  6268. };
  6269. IndexedFilter.prototype.getIndexedFilter = function () {
  6270. return this;
  6271. };
  6272. IndexedFilter.prototype.getIndex = function () {
  6273. return this.index_;
  6274. };
  6275. return IndexedFilter;
  6276. }());
  6277. /**
  6278. * @license
  6279. * Copyright 2017 Google LLC
  6280. *
  6281. * Licensed under the Apache License, Version 2.0 (the "License");
  6282. * you may not use this file except in compliance with the License.
  6283. * You may obtain a copy of the License at
  6284. *
  6285. * http://www.apache.org/licenses/LICENSE-2.0
  6286. *
  6287. * Unless required by applicable law or agreed to in writing, software
  6288. * distributed under the License is distributed on an "AS IS" BASIS,
  6289. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6290. * See the License for the specific language governing permissions and
  6291. * limitations under the License.
  6292. */
  6293. /**
  6294. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6295. */
  6296. var RangedFilter = /** @class */ (function () {
  6297. function RangedFilter(params) {
  6298. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6299. this.index_ = params.getIndex();
  6300. this.startPost_ = RangedFilter.getStartPost_(params);
  6301. this.endPost_ = RangedFilter.getEndPost_(params);
  6302. this.startIsInclusive_ = !params.startAfterSet_;
  6303. this.endIsInclusive_ = !params.endBeforeSet_;
  6304. }
  6305. RangedFilter.prototype.getStartPost = function () {
  6306. return this.startPost_;
  6307. };
  6308. RangedFilter.prototype.getEndPost = function () {
  6309. return this.endPost_;
  6310. };
  6311. RangedFilter.prototype.matches = function (node) {
  6312. var isWithinStart = this.startIsInclusive_
  6313. ? this.index_.compare(this.getStartPost(), node) <= 0
  6314. : this.index_.compare(this.getStartPost(), node) < 0;
  6315. var isWithinEnd = this.endIsInclusive_
  6316. ? this.index_.compare(node, this.getEndPost()) <= 0
  6317. : this.index_.compare(node, this.getEndPost()) < 0;
  6318. return isWithinStart && isWithinEnd;
  6319. };
  6320. RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6321. if (!this.matches(new NamedNode(key, newChild))) {
  6322. newChild = ChildrenNode.EMPTY_NODE;
  6323. }
  6324. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6325. };
  6326. RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6327. if (newSnap.isLeafNode()) {
  6328. // Make sure we have a children node with the correct index, not a leaf node;
  6329. newSnap = ChildrenNode.EMPTY_NODE;
  6330. }
  6331. var filtered = newSnap.withIndex(this.index_);
  6332. // Don't support priorities on queries
  6333. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6334. var self = this;
  6335. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6336. if (!self.matches(new NamedNode(key, childNode))) {
  6337. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6338. }
  6339. });
  6340. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6341. };
  6342. RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6343. // Don't support priorities on queries
  6344. return oldSnap;
  6345. };
  6346. RangedFilter.prototype.filtersNodes = function () {
  6347. return true;
  6348. };
  6349. RangedFilter.prototype.getIndexedFilter = function () {
  6350. return this.indexedFilter_;
  6351. };
  6352. RangedFilter.prototype.getIndex = function () {
  6353. return this.index_;
  6354. };
  6355. RangedFilter.getStartPost_ = function (params) {
  6356. if (params.hasStart()) {
  6357. var startName = params.getIndexStartName();
  6358. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6359. }
  6360. else {
  6361. return params.getIndex().minPost();
  6362. }
  6363. };
  6364. RangedFilter.getEndPost_ = function (params) {
  6365. if (params.hasEnd()) {
  6366. var endName = params.getIndexEndName();
  6367. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6368. }
  6369. else {
  6370. return params.getIndex().maxPost();
  6371. }
  6372. };
  6373. return RangedFilter;
  6374. }());
  6375. /**
  6376. * @license
  6377. * Copyright 2017 Google LLC
  6378. *
  6379. * Licensed under the Apache License, Version 2.0 (the "License");
  6380. * you may not use this file except in compliance with the License.
  6381. * You may obtain a copy of the License at
  6382. *
  6383. * http://www.apache.org/licenses/LICENSE-2.0
  6384. *
  6385. * Unless required by applicable law or agreed to in writing, software
  6386. * distributed under the License is distributed on an "AS IS" BASIS,
  6387. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6388. * See the License for the specific language governing permissions and
  6389. * limitations under the License.
  6390. */
  6391. /**
  6392. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6393. */
  6394. var LimitedFilter = /** @class */ (function () {
  6395. function LimitedFilter(params) {
  6396. var _this = this;
  6397. this.withinDirectionalStart = function (node) {
  6398. return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
  6399. };
  6400. this.withinDirectionalEnd = function (node) {
  6401. return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
  6402. };
  6403. this.withinStartPost = function (node) {
  6404. var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
  6405. return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6406. };
  6407. this.withinEndPost = function (node) {
  6408. var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
  6409. return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6410. };
  6411. this.rangedFilter_ = new RangedFilter(params);
  6412. this.index_ = params.getIndex();
  6413. this.limit_ = params.getLimit();
  6414. this.reverse_ = !params.isViewFromLeft();
  6415. this.startIsInclusive_ = !params.startAfterSet_;
  6416. this.endIsInclusive_ = !params.endBeforeSet_;
  6417. }
  6418. LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6419. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6420. newChild = ChildrenNode.EMPTY_NODE;
  6421. }
  6422. if (snap.getImmediateChild(key).equals(newChild)) {
  6423. // No change
  6424. return snap;
  6425. }
  6426. else if (snap.numChildren() < this.limit_) {
  6427. return this.rangedFilter_
  6428. .getIndexedFilter()
  6429. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6430. }
  6431. else {
  6432. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6433. }
  6434. };
  6435. LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6436. var filtered;
  6437. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6438. // Make sure we have a children node with the correct index, not a leaf node;
  6439. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6440. }
  6441. else {
  6442. if (this.limit_ * 2 < newSnap.numChildren() &&
  6443. newSnap.isIndexed(this.index_)) {
  6444. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6445. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6446. // anchor to the startPost, endPost, or last element as appropriate
  6447. var iterator = void 0;
  6448. if (this.reverse_) {
  6449. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6450. }
  6451. else {
  6452. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6453. }
  6454. var count = 0;
  6455. while (iterator.hasNext() && count < this.limit_) {
  6456. var next = iterator.getNext();
  6457. if (!this.withinDirectionalStart(next)) {
  6458. // if we have not reached the start, skip to the next element
  6459. continue;
  6460. }
  6461. else if (!this.withinDirectionalEnd(next)) {
  6462. // if we have reached the end, stop adding elements
  6463. break;
  6464. }
  6465. else {
  6466. filtered = filtered.updateImmediateChild(next.name, next.node);
  6467. count++;
  6468. }
  6469. }
  6470. }
  6471. else {
  6472. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6473. filtered = newSnap.withIndex(this.index_);
  6474. // Don't support priorities on queries
  6475. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6476. var iterator = void 0;
  6477. if (this.reverse_) {
  6478. iterator = filtered.getReverseIterator(this.index_);
  6479. }
  6480. else {
  6481. iterator = filtered.getIterator(this.index_);
  6482. }
  6483. var count = 0;
  6484. while (iterator.hasNext()) {
  6485. var next = iterator.getNext();
  6486. var inRange = count < this.limit_ &&
  6487. this.withinDirectionalStart(next) &&
  6488. this.withinDirectionalEnd(next);
  6489. if (inRange) {
  6490. count++;
  6491. }
  6492. else {
  6493. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6494. }
  6495. }
  6496. }
  6497. }
  6498. return this.rangedFilter_
  6499. .getIndexedFilter()
  6500. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6501. };
  6502. LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6503. // Don't support priorities on queries
  6504. return oldSnap;
  6505. };
  6506. LimitedFilter.prototype.filtersNodes = function () {
  6507. return true;
  6508. };
  6509. LimitedFilter.prototype.getIndexedFilter = function () {
  6510. return this.rangedFilter_.getIndexedFilter();
  6511. };
  6512. LimitedFilter.prototype.getIndex = function () {
  6513. return this.index_;
  6514. };
  6515. LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
  6516. // TODO: rename all cache stuff etc to general snap terminology
  6517. var cmp;
  6518. if (this.reverse_) {
  6519. var indexCmp_1 = this.index_.getCompare();
  6520. cmp = function (a, b) { return indexCmp_1(b, a); };
  6521. }
  6522. else {
  6523. cmp = this.index_.getCompare();
  6524. }
  6525. var oldEventCache = snap;
  6526. util.assert(oldEventCache.numChildren() === this.limit_, '');
  6527. var newChildNamedNode = new NamedNode(childKey, childSnap);
  6528. var windowBoundary = this.reverse_
  6529. ? oldEventCache.getFirstChild(this.index_)
  6530. : oldEventCache.getLastChild(this.index_);
  6531. var inRange = this.rangedFilter_.matches(newChildNamedNode);
  6532. if (oldEventCache.hasChild(childKey)) {
  6533. var oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6534. var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6535. while (nextChild != null &&
  6536. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6537. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6538. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6539. // the limited filter...
  6540. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6541. }
  6542. var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6543. var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6544. if (remainsInWindow) {
  6545. if (changeAccumulator != null) {
  6546. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6547. }
  6548. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6549. }
  6550. else {
  6551. if (changeAccumulator != null) {
  6552. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6553. }
  6554. var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6555. var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6556. if (nextChildInRange) {
  6557. if (changeAccumulator != null) {
  6558. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6559. }
  6560. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6561. }
  6562. else {
  6563. return newEventCache;
  6564. }
  6565. }
  6566. }
  6567. else if (childSnap.isEmpty()) {
  6568. // we're deleting a node, but it was not in the window, so ignore it
  6569. return snap;
  6570. }
  6571. else if (inRange) {
  6572. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6573. if (changeAccumulator != null) {
  6574. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6575. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6576. }
  6577. return oldEventCache
  6578. .updateImmediateChild(childKey, childSnap)
  6579. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6580. }
  6581. else {
  6582. return snap;
  6583. }
  6584. }
  6585. else {
  6586. return snap;
  6587. }
  6588. };
  6589. return LimitedFilter;
  6590. }());
  6591. /**
  6592. * @license
  6593. * Copyright 2017 Google LLC
  6594. *
  6595. * Licensed under the Apache License, Version 2.0 (the "License");
  6596. * you may not use this file except in compliance with the License.
  6597. * You may obtain a copy of the License at
  6598. *
  6599. * http://www.apache.org/licenses/LICENSE-2.0
  6600. *
  6601. * Unless required by applicable law or agreed to in writing, software
  6602. * distributed under the License is distributed on an "AS IS" BASIS,
  6603. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6604. * See the License for the specific language governing permissions and
  6605. * limitations under the License.
  6606. */
  6607. /**
  6608. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6609. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6610. * user-facing API level, so it is not done here.
  6611. *
  6612. * @internal
  6613. */
  6614. var QueryParams = /** @class */ (function () {
  6615. function QueryParams() {
  6616. this.limitSet_ = false;
  6617. this.startSet_ = false;
  6618. this.startNameSet_ = false;
  6619. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6620. this.endSet_ = false;
  6621. this.endNameSet_ = false;
  6622. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6623. this.limit_ = 0;
  6624. this.viewFrom_ = '';
  6625. this.indexStartValue_ = null;
  6626. this.indexStartName_ = '';
  6627. this.indexEndValue_ = null;
  6628. this.indexEndName_ = '';
  6629. this.index_ = PRIORITY_INDEX;
  6630. }
  6631. QueryParams.prototype.hasStart = function () {
  6632. return this.startSet_;
  6633. };
  6634. /**
  6635. * @returns True if it would return from left.
  6636. */
  6637. QueryParams.prototype.isViewFromLeft = function () {
  6638. if (this.viewFrom_ === '') {
  6639. // limit(), rather than limitToFirst or limitToLast was called.
  6640. // This means that only one of startSet_ and endSet_ is true. Use them
  6641. // to calculate which side of the view to anchor to. If neither is set,
  6642. // anchor to the end.
  6643. return this.startSet_;
  6644. }
  6645. else {
  6646. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6647. }
  6648. };
  6649. /**
  6650. * Only valid to call if hasStart() returns true
  6651. */
  6652. QueryParams.prototype.getIndexStartValue = function () {
  6653. util.assert(this.startSet_, 'Only valid if start has been set');
  6654. return this.indexStartValue_;
  6655. };
  6656. /**
  6657. * Only valid to call if hasStart() returns true.
  6658. * Returns the starting key name for the range defined by these query parameters
  6659. */
  6660. QueryParams.prototype.getIndexStartName = function () {
  6661. util.assert(this.startSet_, 'Only valid if start has been set');
  6662. if (this.startNameSet_) {
  6663. return this.indexStartName_;
  6664. }
  6665. else {
  6666. return MIN_NAME;
  6667. }
  6668. };
  6669. QueryParams.prototype.hasEnd = function () {
  6670. return this.endSet_;
  6671. };
  6672. /**
  6673. * Only valid to call if hasEnd() returns true.
  6674. */
  6675. QueryParams.prototype.getIndexEndValue = function () {
  6676. util.assert(this.endSet_, 'Only valid if end has been set');
  6677. return this.indexEndValue_;
  6678. };
  6679. /**
  6680. * Only valid to call if hasEnd() returns true.
  6681. * Returns the end key name for the range defined by these query parameters
  6682. */
  6683. QueryParams.prototype.getIndexEndName = function () {
  6684. util.assert(this.endSet_, 'Only valid if end has been set');
  6685. if (this.endNameSet_) {
  6686. return this.indexEndName_;
  6687. }
  6688. else {
  6689. return MAX_NAME;
  6690. }
  6691. };
  6692. QueryParams.prototype.hasLimit = function () {
  6693. return this.limitSet_;
  6694. };
  6695. /**
  6696. * @returns True if a limit has been set and it has been explicitly anchored
  6697. */
  6698. QueryParams.prototype.hasAnchoredLimit = function () {
  6699. return this.limitSet_ && this.viewFrom_ !== '';
  6700. };
  6701. /**
  6702. * Only valid to call if hasLimit() returns true
  6703. */
  6704. QueryParams.prototype.getLimit = function () {
  6705. util.assert(this.limitSet_, 'Only valid if limit has been set');
  6706. return this.limit_;
  6707. };
  6708. QueryParams.prototype.getIndex = function () {
  6709. return this.index_;
  6710. };
  6711. QueryParams.prototype.loadsAllData = function () {
  6712. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6713. };
  6714. QueryParams.prototype.isDefault = function () {
  6715. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6716. };
  6717. QueryParams.prototype.copy = function () {
  6718. var copy = new QueryParams();
  6719. copy.limitSet_ = this.limitSet_;
  6720. copy.limit_ = this.limit_;
  6721. copy.startSet_ = this.startSet_;
  6722. copy.startAfterSet_ = this.startAfterSet_;
  6723. copy.indexStartValue_ = this.indexStartValue_;
  6724. copy.startNameSet_ = this.startNameSet_;
  6725. copy.indexStartName_ = this.indexStartName_;
  6726. copy.endSet_ = this.endSet_;
  6727. copy.endBeforeSet_ = this.endBeforeSet_;
  6728. copy.indexEndValue_ = this.indexEndValue_;
  6729. copy.endNameSet_ = this.endNameSet_;
  6730. copy.indexEndName_ = this.indexEndName_;
  6731. copy.index_ = this.index_;
  6732. copy.viewFrom_ = this.viewFrom_;
  6733. return copy;
  6734. };
  6735. return QueryParams;
  6736. }());
  6737. function queryParamsGetNodeFilter(queryParams) {
  6738. if (queryParams.loadsAllData()) {
  6739. return new IndexedFilter(queryParams.getIndex());
  6740. }
  6741. else if (queryParams.hasLimit()) {
  6742. return new LimitedFilter(queryParams);
  6743. }
  6744. else {
  6745. return new RangedFilter(queryParams);
  6746. }
  6747. }
  6748. function queryParamsLimitToFirst(queryParams, newLimit) {
  6749. var newParams = queryParams.copy();
  6750. newParams.limitSet_ = true;
  6751. newParams.limit_ = newLimit;
  6752. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6753. return newParams;
  6754. }
  6755. function queryParamsLimitToLast(queryParams, newLimit) {
  6756. var newParams = queryParams.copy();
  6757. newParams.limitSet_ = true;
  6758. newParams.limit_ = newLimit;
  6759. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6760. return newParams;
  6761. }
  6762. function queryParamsStartAt(queryParams, indexValue, key) {
  6763. var newParams = queryParams.copy();
  6764. newParams.startSet_ = true;
  6765. if (indexValue === undefined) {
  6766. indexValue = null;
  6767. }
  6768. newParams.indexStartValue_ = indexValue;
  6769. if (key != null) {
  6770. newParams.startNameSet_ = true;
  6771. newParams.indexStartName_ = key;
  6772. }
  6773. else {
  6774. newParams.startNameSet_ = false;
  6775. newParams.indexStartName_ = '';
  6776. }
  6777. return newParams;
  6778. }
  6779. function queryParamsStartAfter(queryParams, indexValue, key) {
  6780. var params;
  6781. if (queryParams.index_ === KEY_INDEX || !!key) {
  6782. params = queryParamsStartAt(queryParams, indexValue, key);
  6783. }
  6784. else {
  6785. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6786. }
  6787. params.startAfterSet_ = true;
  6788. return params;
  6789. }
  6790. function queryParamsEndAt(queryParams, indexValue, key) {
  6791. var newParams = queryParams.copy();
  6792. newParams.endSet_ = true;
  6793. if (indexValue === undefined) {
  6794. indexValue = null;
  6795. }
  6796. newParams.indexEndValue_ = indexValue;
  6797. if (key !== undefined) {
  6798. newParams.endNameSet_ = true;
  6799. newParams.indexEndName_ = key;
  6800. }
  6801. else {
  6802. newParams.endNameSet_ = false;
  6803. newParams.indexEndName_ = '';
  6804. }
  6805. return newParams;
  6806. }
  6807. function queryParamsEndBefore(queryParams, indexValue, key) {
  6808. var params;
  6809. if (queryParams.index_ === KEY_INDEX || !!key) {
  6810. params = queryParamsEndAt(queryParams, indexValue, key);
  6811. }
  6812. else {
  6813. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6814. }
  6815. params.endBeforeSet_ = true;
  6816. return params;
  6817. }
  6818. function queryParamsOrderBy(queryParams, index) {
  6819. var newParams = queryParams.copy();
  6820. newParams.index_ = index;
  6821. return newParams;
  6822. }
  6823. /**
  6824. * Returns a set of REST query string parameters representing this query.
  6825. *
  6826. * @returns query string parameters
  6827. */
  6828. function queryParamsToRestQueryStringParameters(queryParams) {
  6829. var qs = {};
  6830. if (queryParams.isDefault()) {
  6831. return qs;
  6832. }
  6833. var orderBy;
  6834. if (queryParams.index_ === PRIORITY_INDEX) {
  6835. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6836. }
  6837. else if (queryParams.index_ === VALUE_INDEX) {
  6838. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6839. }
  6840. else if (queryParams.index_ === KEY_INDEX) {
  6841. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6842. }
  6843. else {
  6844. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6845. orderBy = queryParams.index_.toString();
  6846. }
  6847. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  6848. if (queryParams.startSet_) {
  6849. var startParam = queryParams.startAfterSet_
  6850. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6851. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6852. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  6853. if (queryParams.startNameSet_) {
  6854. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  6855. }
  6856. }
  6857. if (queryParams.endSet_) {
  6858. var endParam = queryParams.endBeforeSet_
  6859. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6860. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6861. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  6862. if (queryParams.endNameSet_) {
  6863. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  6864. }
  6865. }
  6866. if (queryParams.limitSet_) {
  6867. if (queryParams.isViewFromLeft()) {
  6868. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6869. }
  6870. else {
  6871. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6872. }
  6873. }
  6874. return qs;
  6875. }
  6876. function queryParamsGetQueryObject(queryParams) {
  6877. var obj = {};
  6878. if (queryParams.startSet_) {
  6879. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6880. queryParams.indexStartValue_;
  6881. if (queryParams.startNameSet_) {
  6882. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6883. queryParams.indexStartName_;
  6884. }
  6885. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6886. !queryParams.startAfterSet_;
  6887. }
  6888. if (queryParams.endSet_) {
  6889. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6890. if (queryParams.endNameSet_) {
  6891. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6892. }
  6893. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6894. !queryParams.endBeforeSet_;
  6895. }
  6896. if (queryParams.limitSet_) {
  6897. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6898. var viewFrom = queryParams.viewFrom_;
  6899. if (viewFrom === '') {
  6900. if (queryParams.isViewFromLeft()) {
  6901. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6902. }
  6903. else {
  6904. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6905. }
  6906. }
  6907. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6908. }
  6909. // For now, priority index is the default, so we only specify if it's some other index
  6910. if (queryParams.index_ !== PRIORITY_INDEX) {
  6911. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6912. }
  6913. return obj;
  6914. }
  6915. /**
  6916. * @license
  6917. * Copyright 2017 Google LLC
  6918. *
  6919. * Licensed under the Apache License, Version 2.0 (the "License");
  6920. * you may not use this file except in compliance with the License.
  6921. * You may obtain a copy of the License at
  6922. *
  6923. * http://www.apache.org/licenses/LICENSE-2.0
  6924. *
  6925. * Unless required by applicable law or agreed to in writing, software
  6926. * distributed under the License is distributed on an "AS IS" BASIS,
  6927. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6928. * See the License for the specific language governing permissions and
  6929. * limitations under the License.
  6930. */
  6931. /**
  6932. * An implementation of ServerActions that communicates with the server via REST requests.
  6933. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6934. * persistent connection (using WebSockets or long-polling)
  6935. */
  6936. var ReadonlyRestClient = /** @class */ (function (_super) {
  6937. tslib.__extends(ReadonlyRestClient, _super);
  6938. /**
  6939. * @param repoInfo_ - Data about the namespace we are connecting to
  6940. * @param onDataUpdate_ - A callback for new data from the server
  6941. */
  6942. function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6943. var _this = _super.call(this) || this;
  6944. _this.repoInfo_ = repoInfo_;
  6945. _this.onDataUpdate_ = onDataUpdate_;
  6946. _this.authTokenProvider_ = authTokenProvider_;
  6947. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6948. /** @private {function(...[*])} */
  6949. _this.log_ = logWrapper('p:rest:');
  6950. /**
  6951. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6952. * that's been removed. :-/
  6953. */
  6954. _this.listens_ = {};
  6955. return _this;
  6956. }
  6957. ReadonlyRestClient.prototype.reportStats = function (stats) {
  6958. throw new Error('Method not implemented.');
  6959. };
  6960. ReadonlyRestClient.getListenId_ = function (query, tag) {
  6961. if (tag !== undefined) {
  6962. return 'tag$' + tag;
  6963. }
  6964. else {
  6965. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6966. return query._path.toString();
  6967. }
  6968. };
  6969. /** @inheritDoc */
  6970. ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  6971. var _this = this;
  6972. var pathString = query._path.toString();
  6973. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6974. // Mark this listener so we can tell if it's removed.
  6975. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  6976. var thisListen = {};
  6977. this.listens_[listenId] = thisListen;
  6978. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6979. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  6980. var data = result;
  6981. if (error === 404) {
  6982. data = null;
  6983. error = null;
  6984. }
  6985. if (error === null) {
  6986. _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6987. }
  6988. if (util.safeGet(_this.listens_, listenId) === thisListen) {
  6989. var status_1;
  6990. if (!error) {
  6991. status_1 = 'ok';
  6992. }
  6993. else if (error === 401) {
  6994. status_1 = 'permission_denied';
  6995. }
  6996. else {
  6997. status_1 = 'rest_error:' + error;
  6998. }
  6999. onComplete(status_1, null);
  7000. }
  7001. });
  7002. };
  7003. /** @inheritDoc */
  7004. ReadonlyRestClient.prototype.unlisten = function (query, tag) {
  7005. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  7006. delete this.listens_[listenId];
  7007. };
  7008. ReadonlyRestClient.prototype.get = function (query) {
  7009. var _this = this;
  7010. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  7011. var pathString = query._path.toString();
  7012. var deferred = new util.Deferred();
  7013. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  7014. var data = result;
  7015. if (error === 404) {
  7016. data = null;
  7017. error = null;
  7018. }
  7019. if (error === null) {
  7020. _this.onDataUpdate_(pathString, data,
  7021. /*isMerge=*/ false,
  7022. /*tag=*/ null);
  7023. deferred.resolve(data);
  7024. }
  7025. else {
  7026. deferred.reject(new Error(data));
  7027. }
  7028. });
  7029. return deferred.promise;
  7030. };
  7031. /** @inheritDoc */
  7032. ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
  7033. // no-op since we just always call getToken.
  7034. };
  7035. /**
  7036. * Performs a REST request to the given path, with the provided query string parameters,
  7037. * and any auth credentials we have.
  7038. */
  7039. ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
  7040. var _this = this;
  7041. if (queryStringParameters === void 0) { queryStringParameters = {}; }
  7042. queryStringParameters['format'] = 'export';
  7043. return Promise.all([
  7044. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  7045. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  7046. ]).then(function (_a) {
  7047. var _b = tslib.__read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
  7048. if (authToken && authToken.accessToken) {
  7049. queryStringParameters['auth'] = authToken.accessToken;
  7050. }
  7051. if (appCheckToken && appCheckToken.token) {
  7052. queryStringParameters['ac'] = appCheckToken.token;
  7053. }
  7054. var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
  7055. _this.repoInfo_.host +
  7056. pathString +
  7057. '?' +
  7058. 'ns=' +
  7059. _this.repoInfo_.namespace +
  7060. util.querystring(queryStringParameters);
  7061. _this.log_('Sending REST request for ' + url);
  7062. var xhr = new XMLHttpRequest();
  7063. xhr.onreadystatechange = function () {
  7064. if (callback && xhr.readyState === 4) {
  7065. _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  7066. var res = null;
  7067. if (xhr.status >= 200 && xhr.status < 300) {
  7068. try {
  7069. res = util.jsonEval(xhr.responseText);
  7070. }
  7071. catch (e) {
  7072. warn('Failed to parse JSON response for ' +
  7073. url +
  7074. ': ' +
  7075. xhr.responseText);
  7076. }
  7077. callback(null, res);
  7078. }
  7079. else {
  7080. // 401 and 404 are expected.
  7081. if (xhr.status !== 401 && xhr.status !== 404) {
  7082. warn('Got unsuccessful REST response for ' +
  7083. url +
  7084. ' Status: ' +
  7085. xhr.status);
  7086. }
  7087. callback(xhr.status);
  7088. }
  7089. callback = null;
  7090. }
  7091. };
  7092. xhr.open('GET', url, /*asynchronous=*/ true);
  7093. xhr.send();
  7094. });
  7095. };
  7096. return ReadonlyRestClient;
  7097. }(ServerActions));
  7098. /**
  7099. * @license
  7100. * Copyright 2017 Google LLC
  7101. *
  7102. * Licensed under the Apache License, Version 2.0 (the "License");
  7103. * you may not use this file except in compliance with the License.
  7104. * You may obtain a copy of the License at
  7105. *
  7106. * http://www.apache.org/licenses/LICENSE-2.0
  7107. *
  7108. * Unless required by applicable law or agreed to in writing, software
  7109. * distributed under the License is distributed on an "AS IS" BASIS,
  7110. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7111. * See the License for the specific language governing permissions and
  7112. * limitations under the License.
  7113. */
  7114. /**
  7115. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  7116. */
  7117. var SnapshotHolder = /** @class */ (function () {
  7118. function SnapshotHolder() {
  7119. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  7120. }
  7121. SnapshotHolder.prototype.getNode = function (path) {
  7122. return this.rootNode_.getChild(path);
  7123. };
  7124. SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
  7125. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  7126. };
  7127. return SnapshotHolder;
  7128. }());
  7129. /**
  7130. * @license
  7131. * Copyright 2017 Google LLC
  7132. *
  7133. * Licensed under the Apache License, Version 2.0 (the "License");
  7134. * you may not use this file except in compliance with the License.
  7135. * You may obtain a copy of the License at
  7136. *
  7137. * http://www.apache.org/licenses/LICENSE-2.0
  7138. *
  7139. * Unless required by applicable law or agreed to in writing, software
  7140. * distributed under the License is distributed on an "AS IS" BASIS,
  7141. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7142. * See the License for the specific language governing permissions and
  7143. * limitations under the License.
  7144. */
  7145. function newSparseSnapshotTree() {
  7146. return {
  7147. value: null,
  7148. children: new Map()
  7149. };
  7150. }
  7151. /**
  7152. * Stores the given node at the specified path. If there is already a node
  7153. * at a shallower path, it merges the new data into that snapshot node.
  7154. *
  7155. * @param path - Path to look up snapshot for.
  7156. * @param data - The new data, or null.
  7157. */
  7158. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  7159. if (pathIsEmpty(path)) {
  7160. sparseSnapshotTree.value = data;
  7161. sparseSnapshotTree.children.clear();
  7162. }
  7163. else if (sparseSnapshotTree.value !== null) {
  7164. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  7165. }
  7166. else {
  7167. var childKey = pathGetFront(path);
  7168. if (!sparseSnapshotTree.children.has(childKey)) {
  7169. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  7170. }
  7171. var child = sparseSnapshotTree.children.get(childKey);
  7172. path = pathPopFront(path);
  7173. sparseSnapshotTreeRemember(child, path, data);
  7174. }
  7175. }
  7176. /**
  7177. * Purge the data at path from the cache.
  7178. *
  7179. * @param path - Path to look up snapshot for.
  7180. * @returns True if this node should now be removed.
  7181. */
  7182. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  7183. if (pathIsEmpty(path)) {
  7184. sparseSnapshotTree.value = null;
  7185. sparseSnapshotTree.children.clear();
  7186. return true;
  7187. }
  7188. else {
  7189. if (sparseSnapshotTree.value !== null) {
  7190. if (sparseSnapshotTree.value.isLeafNode()) {
  7191. // We're trying to forget a node that doesn't exist
  7192. return false;
  7193. }
  7194. else {
  7195. var value = sparseSnapshotTree.value;
  7196. sparseSnapshotTree.value = null;
  7197. value.forEachChild(PRIORITY_INDEX, function (key, tree) {
  7198. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  7199. });
  7200. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  7201. }
  7202. }
  7203. else if (sparseSnapshotTree.children.size > 0) {
  7204. var childKey = pathGetFront(path);
  7205. path = pathPopFront(path);
  7206. if (sparseSnapshotTree.children.has(childKey)) {
  7207. var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  7208. if (safeToRemove) {
  7209. sparseSnapshotTree.children.delete(childKey);
  7210. }
  7211. }
  7212. return sparseSnapshotTree.children.size === 0;
  7213. }
  7214. else {
  7215. return true;
  7216. }
  7217. }
  7218. }
  7219. /**
  7220. * Recursively iterates through all of the stored tree and calls the
  7221. * callback on each one.
  7222. *
  7223. * @param prefixPath - Path to look up node for.
  7224. * @param func - The function to invoke for each tree.
  7225. */
  7226. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7227. if (sparseSnapshotTree.value !== null) {
  7228. func(prefixPath, sparseSnapshotTree.value);
  7229. }
  7230. else {
  7231. sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
  7232. var path = new Path(prefixPath.toString() + '/' + key);
  7233. sparseSnapshotTreeForEachTree(tree, path, func);
  7234. });
  7235. }
  7236. }
  7237. /**
  7238. * Iterates through each immediate child and triggers the callback.
  7239. * Only seems to be used in tests.
  7240. *
  7241. * @param func - The function to invoke for each child.
  7242. */
  7243. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7244. sparseSnapshotTree.children.forEach(function (tree, key) {
  7245. func(key, tree);
  7246. });
  7247. }
  7248. /**
  7249. * @license
  7250. * Copyright 2017 Google LLC
  7251. *
  7252. * Licensed under the Apache License, Version 2.0 (the "License");
  7253. * you may not use this file except in compliance with the License.
  7254. * You may obtain a copy of the License at
  7255. *
  7256. * http://www.apache.org/licenses/LICENSE-2.0
  7257. *
  7258. * Unless required by applicable law or agreed to in writing, software
  7259. * distributed under the License is distributed on an "AS IS" BASIS,
  7260. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7261. * See the License for the specific language governing permissions and
  7262. * limitations under the License.
  7263. */
  7264. /**
  7265. * Returns the delta from the previous call to get stats.
  7266. *
  7267. * @param collection_ - The collection to "listen" to.
  7268. */
  7269. var StatsListener = /** @class */ (function () {
  7270. function StatsListener(collection_) {
  7271. this.collection_ = collection_;
  7272. this.last_ = null;
  7273. }
  7274. StatsListener.prototype.get = function () {
  7275. var newStats = this.collection_.get();
  7276. var delta = tslib.__assign({}, newStats);
  7277. if (this.last_) {
  7278. each(this.last_, function (stat, value) {
  7279. delta[stat] = delta[stat] - value;
  7280. });
  7281. }
  7282. this.last_ = newStats;
  7283. return delta;
  7284. };
  7285. return StatsListener;
  7286. }());
  7287. /**
  7288. * @license
  7289. * Copyright 2017 Google LLC
  7290. *
  7291. * Licensed under the Apache License, Version 2.0 (the "License");
  7292. * you may not use this file except in compliance with the License.
  7293. * You may obtain a copy of the License at
  7294. *
  7295. * http://www.apache.org/licenses/LICENSE-2.0
  7296. *
  7297. * Unless required by applicable law or agreed to in writing, software
  7298. * distributed under the License is distributed on an "AS IS" BASIS,
  7299. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7300. * See the License for the specific language governing permissions and
  7301. * limitations under the License.
  7302. */
  7303. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7304. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7305. // seconds to try to ensure the Firebase connection is established / settled.
  7306. var FIRST_STATS_MIN_TIME = 10 * 1000;
  7307. var FIRST_STATS_MAX_TIME = 30 * 1000;
  7308. // We'll continue to report stats on average every 5 minutes.
  7309. var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7310. var StatsReporter = /** @class */ (function () {
  7311. function StatsReporter(collection, server_) {
  7312. this.server_ = server_;
  7313. this.statsToReport_ = {};
  7314. this.statsListener_ = new StatsListener(collection);
  7315. var timeout = FIRST_STATS_MIN_TIME +
  7316. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7317. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7318. }
  7319. StatsReporter.prototype.reportStats_ = function () {
  7320. var _this = this;
  7321. var stats = this.statsListener_.get();
  7322. var reportedStats = {};
  7323. var haveStatsToReport = false;
  7324. each(stats, function (stat, value) {
  7325. if (value > 0 && util.contains(_this.statsToReport_, stat)) {
  7326. reportedStats[stat] = value;
  7327. haveStatsToReport = true;
  7328. }
  7329. });
  7330. if (haveStatsToReport) {
  7331. this.server_.reportStats(reportedStats);
  7332. }
  7333. // queue our next run.
  7334. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7335. };
  7336. return StatsReporter;
  7337. }());
  7338. /**
  7339. * @license
  7340. * Copyright 2017 Google LLC
  7341. *
  7342. * Licensed under the Apache License, Version 2.0 (the "License");
  7343. * you may not use this file except in compliance with the License.
  7344. * You may obtain a copy of the License at
  7345. *
  7346. * http://www.apache.org/licenses/LICENSE-2.0
  7347. *
  7348. * Unless required by applicable law or agreed to in writing, software
  7349. * distributed under the License is distributed on an "AS IS" BASIS,
  7350. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7351. * See the License for the specific language governing permissions and
  7352. * limitations under the License.
  7353. */
  7354. /**
  7355. *
  7356. * @enum
  7357. */
  7358. var OperationType;
  7359. (function (OperationType) {
  7360. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7361. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7362. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7363. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7364. })(OperationType || (OperationType = {}));
  7365. function newOperationSourceUser() {
  7366. return {
  7367. fromUser: true,
  7368. fromServer: false,
  7369. queryId: null,
  7370. tagged: false
  7371. };
  7372. }
  7373. function newOperationSourceServer() {
  7374. return {
  7375. fromUser: false,
  7376. fromServer: true,
  7377. queryId: null,
  7378. tagged: false
  7379. };
  7380. }
  7381. function newOperationSourceServerTaggedQuery(queryId) {
  7382. return {
  7383. fromUser: false,
  7384. fromServer: true,
  7385. queryId: queryId,
  7386. tagged: true
  7387. };
  7388. }
  7389. /**
  7390. * @license
  7391. * Copyright 2017 Google LLC
  7392. *
  7393. * Licensed under the Apache License, Version 2.0 (the "License");
  7394. * you may not use this file except in compliance with the License.
  7395. * You may obtain a copy of the License at
  7396. *
  7397. * http://www.apache.org/licenses/LICENSE-2.0
  7398. *
  7399. * Unless required by applicable law or agreed to in writing, software
  7400. * distributed under the License is distributed on an "AS IS" BASIS,
  7401. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7402. * See the License for the specific language governing permissions and
  7403. * limitations under the License.
  7404. */
  7405. var AckUserWrite = /** @class */ (function () {
  7406. /**
  7407. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7408. */
  7409. function AckUserWrite(
  7410. /** @inheritDoc */ path,
  7411. /** @inheritDoc */ affectedTree,
  7412. /** @inheritDoc */ revert) {
  7413. this.path = path;
  7414. this.affectedTree = affectedTree;
  7415. this.revert = revert;
  7416. /** @inheritDoc */
  7417. this.type = OperationType.ACK_USER_WRITE;
  7418. /** @inheritDoc */
  7419. this.source = newOperationSourceUser();
  7420. }
  7421. AckUserWrite.prototype.operationForChild = function (childName) {
  7422. if (!pathIsEmpty(this.path)) {
  7423. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7424. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7425. }
  7426. else if (this.affectedTree.value != null) {
  7427. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7428. // All child locations are affected as well; just return same operation.
  7429. return this;
  7430. }
  7431. else {
  7432. var childTree = this.affectedTree.subtree(new Path(childName));
  7433. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7434. }
  7435. };
  7436. return AckUserWrite;
  7437. }());
  7438. /**
  7439. * @license
  7440. * Copyright 2017 Google LLC
  7441. *
  7442. * Licensed under the Apache License, Version 2.0 (the "License");
  7443. * you may not use this file except in compliance with the License.
  7444. * You may obtain a copy of the License at
  7445. *
  7446. * http://www.apache.org/licenses/LICENSE-2.0
  7447. *
  7448. * Unless required by applicable law or agreed to in writing, software
  7449. * distributed under the License is distributed on an "AS IS" BASIS,
  7450. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7451. * See the License for the specific language governing permissions and
  7452. * limitations under the License.
  7453. */
  7454. var ListenComplete = /** @class */ (function () {
  7455. function ListenComplete(source, path) {
  7456. this.source = source;
  7457. this.path = path;
  7458. /** @inheritDoc */
  7459. this.type = OperationType.LISTEN_COMPLETE;
  7460. }
  7461. ListenComplete.prototype.operationForChild = function (childName) {
  7462. if (pathIsEmpty(this.path)) {
  7463. return new ListenComplete(this.source, newEmptyPath());
  7464. }
  7465. else {
  7466. return new ListenComplete(this.source, pathPopFront(this.path));
  7467. }
  7468. };
  7469. return ListenComplete;
  7470. }());
  7471. /**
  7472. * @license
  7473. * Copyright 2017 Google LLC
  7474. *
  7475. * Licensed under the Apache License, Version 2.0 (the "License");
  7476. * you may not use this file except in compliance with the License.
  7477. * You may obtain a copy of the License at
  7478. *
  7479. * http://www.apache.org/licenses/LICENSE-2.0
  7480. *
  7481. * Unless required by applicable law or agreed to in writing, software
  7482. * distributed under the License is distributed on an "AS IS" BASIS,
  7483. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7484. * See the License for the specific language governing permissions and
  7485. * limitations under the License.
  7486. */
  7487. var Overwrite = /** @class */ (function () {
  7488. function Overwrite(source, path, snap) {
  7489. this.source = source;
  7490. this.path = path;
  7491. this.snap = snap;
  7492. /** @inheritDoc */
  7493. this.type = OperationType.OVERWRITE;
  7494. }
  7495. Overwrite.prototype.operationForChild = function (childName) {
  7496. if (pathIsEmpty(this.path)) {
  7497. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7498. }
  7499. else {
  7500. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7501. }
  7502. };
  7503. return Overwrite;
  7504. }());
  7505. /**
  7506. * @license
  7507. * Copyright 2017 Google LLC
  7508. *
  7509. * Licensed under the Apache License, Version 2.0 (the "License");
  7510. * you may not use this file except in compliance with the License.
  7511. * You may obtain a copy of the License at
  7512. *
  7513. * http://www.apache.org/licenses/LICENSE-2.0
  7514. *
  7515. * Unless required by applicable law or agreed to in writing, software
  7516. * distributed under the License is distributed on an "AS IS" BASIS,
  7517. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7518. * See the License for the specific language governing permissions and
  7519. * limitations under the License.
  7520. */
  7521. var Merge = /** @class */ (function () {
  7522. function Merge(
  7523. /** @inheritDoc */ source,
  7524. /** @inheritDoc */ path,
  7525. /** @inheritDoc */ children) {
  7526. this.source = source;
  7527. this.path = path;
  7528. this.children = children;
  7529. /** @inheritDoc */
  7530. this.type = OperationType.MERGE;
  7531. }
  7532. Merge.prototype.operationForChild = function (childName) {
  7533. if (pathIsEmpty(this.path)) {
  7534. var childTree = this.children.subtree(new Path(childName));
  7535. if (childTree.isEmpty()) {
  7536. // This child is unaffected
  7537. return null;
  7538. }
  7539. else if (childTree.value) {
  7540. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7541. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7542. }
  7543. else {
  7544. // This is a merge at a deeper level
  7545. return new Merge(this.source, newEmptyPath(), childTree);
  7546. }
  7547. }
  7548. else {
  7549. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7550. return new Merge(this.source, pathPopFront(this.path), this.children);
  7551. }
  7552. };
  7553. Merge.prototype.toString = function () {
  7554. return ('Operation(' +
  7555. this.path +
  7556. ': ' +
  7557. this.source.toString() +
  7558. ' merge: ' +
  7559. this.children.toString() +
  7560. ')');
  7561. };
  7562. return Merge;
  7563. }());
  7564. /**
  7565. * @license
  7566. * Copyright 2017 Google LLC
  7567. *
  7568. * Licensed under the Apache License, Version 2.0 (the "License");
  7569. * you may not use this file except in compliance with the License.
  7570. * You may obtain a copy of the License at
  7571. *
  7572. * http://www.apache.org/licenses/LICENSE-2.0
  7573. *
  7574. * Unless required by applicable law or agreed to in writing, software
  7575. * distributed under the License is distributed on an "AS IS" BASIS,
  7576. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7577. * See the License for the specific language governing permissions and
  7578. * limitations under the License.
  7579. */
  7580. /**
  7581. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7582. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7583. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7584. * whether a node potentially had children removed due to a filter.
  7585. */
  7586. var CacheNode = /** @class */ (function () {
  7587. function CacheNode(node_, fullyInitialized_, filtered_) {
  7588. this.node_ = node_;
  7589. this.fullyInitialized_ = fullyInitialized_;
  7590. this.filtered_ = filtered_;
  7591. }
  7592. /**
  7593. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7594. */
  7595. CacheNode.prototype.isFullyInitialized = function () {
  7596. return this.fullyInitialized_;
  7597. };
  7598. /**
  7599. * Returns whether this node is potentially missing children due to a filter applied to the node
  7600. */
  7601. CacheNode.prototype.isFiltered = function () {
  7602. return this.filtered_;
  7603. };
  7604. CacheNode.prototype.isCompleteForPath = function (path) {
  7605. if (pathIsEmpty(path)) {
  7606. return this.isFullyInitialized() && !this.filtered_;
  7607. }
  7608. var childKey = pathGetFront(path);
  7609. return this.isCompleteForChild(childKey);
  7610. };
  7611. CacheNode.prototype.isCompleteForChild = function (key) {
  7612. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7613. };
  7614. CacheNode.prototype.getNode = function () {
  7615. return this.node_;
  7616. };
  7617. return CacheNode;
  7618. }());
  7619. /**
  7620. * @license
  7621. * Copyright 2017 Google LLC
  7622. *
  7623. * Licensed under the Apache License, Version 2.0 (the "License");
  7624. * you may not use this file except in compliance with the License.
  7625. * You may obtain a copy of the License at
  7626. *
  7627. * http://www.apache.org/licenses/LICENSE-2.0
  7628. *
  7629. * Unless required by applicable law or agreed to in writing, software
  7630. * distributed under the License is distributed on an "AS IS" BASIS,
  7631. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7632. * See the License for the specific language governing permissions and
  7633. * limitations under the License.
  7634. */
  7635. /**
  7636. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7637. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7638. * for details.
  7639. *
  7640. */
  7641. var EventGenerator = /** @class */ (function () {
  7642. function EventGenerator(query_) {
  7643. this.query_ = query_;
  7644. this.index_ = this.query_._queryParams.getIndex();
  7645. }
  7646. return EventGenerator;
  7647. }());
  7648. /**
  7649. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7650. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7651. *
  7652. * Notes:
  7653. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7654. * our index.
  7655. * - prevName will be calculated based on the index ordering.
  7656. */
  7657. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7658. var events = [];
  7659. var moves = [];
  7660. changes.forEach(function (change) {
  7661. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7662. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7663. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7664. }
  7665. });
  7666. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7667. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7668. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7669. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7670. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7671. return events;
  7672. }
  7673. /**
  7674. * Given changes of a single change type, generate the corresponding events.
  7675. */
  7676. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7677. var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
  7678. filteredChanges.sort(function (a, b) {
  7679. return eventGeneratorCompareChanges(eventGenerator, a, b);
  7680. });
  7681. filteredChanges.forEach(function (change) {
  7682. var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7683. registrations.forEach(function (registration) {
  7684. if (registration.respondsTo(change.type)) {
  7685. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7686. }
  7687. });
  7688. });
  7689. }
  7690. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7691. if (change.type === 'value' || change.type === 'child_removed') {
  7692. return change;
  7693. }
  7694. else {
  7695. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7696. return change;
  7697. }
  7698. }
  7699. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7700. if (a.childName == null || b.childName == null) {
  7701. throw util.assertionError('Should only compare child_ events.');
  7702. }
  7703. var aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7704. var bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7705. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7706. }
  7707. /**
  7708. * @license
  7709. * Copyright 2017 Google LLC
  7710. *
  7711. * Licensed under the Apache License, Version 2.0 (the "License");
  7712. * you may not use this file except in compliance with the License.
  7713. * You may obtain a copy of the License at
  7714. *
  7715. * http://www.apache.org/licenses/LICENSE-2.0
  7716. *
  7717. * Unless required by applicable law or agreed to in writing, software
  7718. * distributed under the License is distributed on an "AS IS" BASIS,
  7719. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7720. * See the License for the specific language governing permissions and
  7721. * limitations under the License.
  7722. */
  7723. function newViewCache(eventCache, serverCache) {
  7724. return { eventCache: eventCache, serverCache: serverCache };
  7725. }
  7726. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7727. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7728. }
  7729. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7730. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7731. }
  7732. function viewCacheGetCompleteEventSnap(viewCache) {
  7733. return viewCache.eventCache.isFullyInitialized()
  7734. ? viewCache.eventCache.getNode()
  7735. : null;
  7736. }
  7737. function viewCacheGetCompleteServerSnap(viewCache) {
  7738. return viewCache.serverCache.isFullyInitialized()
  7739. ? viewCache.serverCache.getNode()
  7740. : null;
  7741. }
  7742. /**
  7743. * @license
  7744. * Copyright 2017 Google LLC
  7745. *
  7746. * Licensed under the Apache License, Version 2.0 (the "License");
  7747. * you may not use this file except in compliance with the License.
  7748. * You may obtain a copy of the License at
  7749. *
  7750. * http://www.apache.org/licenses/LICENSE-2.0
  7751. *
  7752. * Unless required by applicable law or agreed to in writing, software
  7753. * distributed under the License is distributed on an "AS IS" BASIS,
  7754. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7755. * See the License for the specific language governing permissions and
  7756. * limitations under the License.
  7757. */
  7758. var emptyChildrenSingleton;
  7759. /**
  7760. * Singleton empty children collection.
  7761. *
  7762. */
  7763. var EmptyChildren = function () {
  7764. if (!emptyChildrenSingleton) {
  7765. emptyChildrenSingleton = new SortedMap(stringCompare);
  7766. }
  7767. return emptyChildrenSingleton;
  7768. };
  7769. /**
  7770. * A tree with immutable elements.
  7771. */
  7772. var ImmutableTree = /** @class */ (function () {
  7773. function ImmutableTree(value, children) {
  7774. if (children === void 0) { children = EmptyChildren(); }
  7775. this.value = value;
  7776. this.children = children;
  7777. }
  7778. ImmutableTree.fromObject = function (obj) {
  7779. var tree = new ImmutableTree(null);
  7780. each(obj, function (childPath, childSnap) {
  7781. tree = tree.set(new Path(childPath), childSnap);
  7782. });
  7783. return tree;
  7784. };
  7785. /**
  7786. * True if the value is empty and there are no children
  7787. */
  7788. ImmutableTree.prototype.isEmpty = function () {
  7789. return this.value === null && this.children.isEmpty();
  7790. };
  7791. /**
  7792. * Given a path and predicate, return the first node and the path to that node
  7793. * where the predicate returns true.
  7794. *
  7795. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7796. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7797. *
  7798. * @param relativePath - The remainder of the path
  7799. * @param predicate - The predicate to satisfy to return a node
  7800. */
  7801. ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
  7802. if (this.value != null && predicate(this.value)) {
  7803. return { path: newEmptyPath(), value: this.value };
  7804. }
  7805. else {
  7806. if (pathIsEmpty(relativePath)) {
  7807. return null;
  7808. }
  7809. else {
  7810. var front = pathGetFront(relativePath);
  7811. var child = this.children.get(front);
  7812. if (child !== null) {
  7813. var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7814. if (childExistingPathAndValue != null) {
  7815. var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7816. return { path: fullPath, value: childExistingPathAndValue.value };
  7817. }
  7818. else {
  7819. return null;
  7820. }
  7821. }
  7822. else {
  7823. return null;
  7824. }
  7825. }
  7826. }
  7827. };
  7828. /**
  7829. * Find, if it exists, the shortest subpath of the given path that points a defined
  7830. * value in the tree
  7831. */
  7832. ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
  7833. return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
  7834. };
  7835. /**
  7836. * @returns The subtree at the given path
  7837. */
  7838. ImmutableTree.prototype.subtree = function (relativePath) {
  7839. if (pathIsEmpty(relativePath)) {
  7840. return this;
  7841. }
  7842. else {
  7843. var front = pathGetFront(relativePath);
  7844. var childTree = this.children.get(front);
  7845. if (childTree !== null) {
  7846. return childTree.subtree(pathPopFront(relativePath));
  7847. }
  7848. else {
  7849. return new ImmutableTree(null);
  7850. }
  7851. }
  7852. };
  7853. /**
  7854. * Sets a value at the specified path.
  7855. *
  7856. * @param relativePath - Path to set value at.
  7857. * @param toSet - Value to set.
  7858. * @returns Resulting tree.
  7859. */
  7860. ImmutableTree.prototype.set = function (relativePath, toSet) {
  7861. if (pathIsEmpty(relativePath)) {
  7862. return new ImmutableTree(toSet, this.children);
  7863. }
  7864. else {
  7865. var front = pathGetFront(relativePath);
  7866. var child = this.children.get(front) || new ImmutableTree(null);
  7867. var newChild = child.set(pathPopFront(relativePath), toSet);
  7868. var newChildren = this.children.insert(front, newChild);
  7869. return new ImmutableTree(this.value, newChildren);
  7870. }
  7871. };
  7872. /**
  7873. * Removes the value at the specified path.
  7874. *
  7875. * @param relativePath - Path to value to remove.
  7876. * @returns Resulting tree.
  7877. */
  7878. ImmutableTree.prototype.remove = function (relativePath) {
  7879. if (pathIsEmpty(relativePath)) {
  7880. if (this.children.isEmpty()) {
  7881. return new ImmutableTree(null);
  7882. }
  7883. else {
  7884. return new ImmutableTree(null, this.children);
  7885. }
  7886. }
  7887. else {
  7888. var front = pathGetFront(relativePath);
  7889. var child = this.children.get(front);
  7890. if (child) {
  7891. var newChild = child.remove(pathPopFront(relativePath));
  7892. var newChildren = void 0;
  7893. if (newChild.isEmpty()) {
  7894. newChildren = this.children.remove(front);
  7895. }
  7896. else {
  7897. newChildren = this.children.insert(front, newChild);
  7898. }
  7899. if (this.value === null && newChildren.isEmpty()) {
  7900. return new ImmutableTree(null);
  7901. }
  7902. else {
  7903. return new ImmutableTree(this.value, newChildren);
  7904. }
  7905. }
  7906. else {
  7907. return this;
  7908. }
  7909. }
  7910. };
  7911. /**
  7912. * Gets a value from the tree.
  7913. *
  7914. * @param relativePath - Path to get value for.
  7915. * @returns Value at path, or null.
  7916. */
  7917. ImmutableTree.prototype.get = function (relativePath) {
  7918. if (pathIsEmpty(relativePath)) {
  7919. return this.value;
  7920. }
  7921. else {
  7922. var front = pathGetFront(relativePath);
  7923. var child = this.children.get(front);
  7924. if (child) {
  7925. return child.get(pathPopFront(relativePath));
  7926. }
  7927. else {
  7928. return null;
  7929. }
  7930. }
  7931. };
  7932. /**
  7933. * Replace the subtree at the specified path with the given new tree.
  7934. *
  7935. * @param relativePath - Path to replace subtree for.
  7936. * @param newTree - New tree.
  7937. * @returns Resulting tree.
  7938. */
  7939. ImmutableTree.prototype.setTree = function (relativePath, newTree) {
  7940. if (pathIsEmpty(relativePath)) {
  7941. return newTree;
  7942. }
  7943. else {
  7944. var front = pathGetFront(relativePath);
  7945. var child = this.children.get(front) || new ImmutableTree(null);
  7946. var newChild = child.setTree(pathPopFront(relativePath), newTree);
  7947. var newChildren = void 0;
  7948. if (newChild.isEmpty()) {
  7949. newChildren = this.children.remove(front);
  7950. }
  7951. else {
  7952. newChildren = this.children.insert(front, newChild);
  7953. }
  7954. return new ImmutableTree(this.value, newChildren);
  7955. }
  7956. };
  7957. /**
  7958. * Performs a depth first fold on this tree. Transforms a tree into a single
  7959. * value, given a function that operates on the path to a node, an optional
  7960. * current value, and a map of child names to folded subtrees
  7961. */
  7962. ImmutableTree.prototype.fold = function (fn) {
  7963. return this.fold_(newEmptyPath(), fn);
  7964. };
  7965. /**
  7966. * Recursive helper for public-facing fold() method
  7967. */
  7968. ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
  7969. var accum = {};
  7970. this.children.inorderTraversal(function (childKey, childTree) {
  7971. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7972. });
  7973. return fn(pathSoFar, this.value, accum);
  7974. };
  7975. /**
  7976. * Find the first matching value on the given path. Return the result of applying f to it.
  7977. */
  7978. ImmutableTree.prototype.findOnPath = function (path, f) {
  7979. return this.findOnPath_(path, newEmptyPath(), f);
  7980. };
  7981. ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
  7982. var result = this.value ? f(pathSoFar, this.value) : false;
  7983. if (result) {
  7984. return result;
  7985. }
  7986. else {
  7987. if (pathIsEmpty(pathToFollow)) {
  7988. return null;
  7989. }
  7990. else {
  7991. var front = pathGetFront(pathToFollow);
  7992. var nextChild = this.children.get(front);
  7993. if (nextChild) {
  7994. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7995. }
  7996. else {
  7997. return null;
  7998. }
  7999. }
  8000. }
  8001. };
  8002. ImmutableTree.prototype.foreachOnPath = function (path, f) {
  8003. return this.foreachOnPath_(path, newEmptyPath(), f);
  8004. };
  8005. ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
  8006. if (pathIsEmpty(pathToFollow)) {
  8007. return this;
  8008. }
  8009. else {
  8010. if (this.value) {
  8011. f(currentRelativePath, this.value);
  8012. }
  8013. var front = pathGetFront(pathToFollow);
  8014. var nextChild = this.children.get(front);
  8015. if (nextChild) {
  8016. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  8017. }
  8018. else {
  8019. return new ImmutableTree(null);
  8020. }
  8021. }
  8022. };
  8023. /**
  8024. * Calls the given function for each node in the tree that has a value.
  8025. *
  8026. * @param f - A function to be called with the path from the root of the tree to
  8027. * a node, and the value at that node. Called in depth-first order.
  8028. */
  8029. ImmutableTree.prototype.foreach = function (f) {
  8030. this.foreach_(newEmptyPath(), f);
  8031. };
  8032. ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
  8033. this.children.inorderTraversal(function (childName, childTree) {
  8034. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  8035. });
  8036. if (this.value) {
  8037. f(currentRelativePath, this.value);
  8038. }
  8039. };
  8040. ImmutableTree.prototype.foreachChild = function (f) {
  8041. this.children.inorderTraversal(function (childName, childTree) {
  8042. if (childTree.value) {
  8043. f(childName, childTree.value);
  8044. }
  8045. });
  8046. };
  8047. return ImmutableTree;
  8048. }());
  8049. /**
  8050. * @license
  8051. * Copyright 2017 Google LLC
  8052. *
  8053. * Licensed under the Apache License, Version 2.0 (the "License");
  8054. * you may not use this file except in compliance with the License.
  8055. * You may obtain a copy of the License at
  8056. *
  8057. * http://www.apache.org/licenses/LICENSE-2.0
  8058. *
  8059. * Unless required by applicable law or agreed to in writing, software
  8060. * distributed under the License is distributed on an "AS IS" BASIS,
  8061. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8062. * See the License for the specific language governing permissions and
  8063. * limitations under the License.
  8064. */
  8065. /**
  8066. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  8067. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  8068. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  8069. * to reflect the write added.
  8070. */
  8071. var CompoundWrite = /** @class */ (function () {
  8072. function CompoundWrite(writeTree_) {
  8073. this.writeTree_ = writeTree_;
  8074. }
  8075. CompoundWrite.empty = function () {
  8076. return new CompoundWrite(new ImmutableTree(null));
  8077. };
  8078. return CompoundWrite;
  8079. }());
  8080. function compoundWriteAddWrite(compoundWrite, path, node) {
  8081. if (pathIsEmpty(path)) {
  8082. return new CompoundWrite(new ImmutableTree(node));
  8083. }
  8084. else {
  8085. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8086. if (rootmost != null) {
  8087. var rootMostPath = rootmost.path;
  8088. var value = rootmost.value;
  8089. var relativePath = newRelativePath(rootMostPath, path);
  8090. value = value.updateChild(relativePath, node);
  8091. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  8092. }
  8093. else {
  8094. var subtree = new ImmutableTree(node);
  8095. var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  8096. return new CompoundWrite(newWriteTree);
  8097. }
  8098. }
  8099. }
  8100. function compoundWriteAddWrites(compoundWrite, path, updates) {
  8101. var newWrite = compoundWrite;
  8102. each(updates, function (childKey, node) {
  8103. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  8104. });
  8105. return newWrite;
  8106. }
  8107. /**
  8108. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  8109. * location, which must be removed by calling this method with that path.
  8110. *
  8111. * @param compoundWrite - The CompoundWrite to remove.
  8112. * @param path - The path at which a write and all deeper writes should be removed
  8113. * @returns The new CompoundWrite with the removed path
  8114. */
  8115. function compoundWriteRemoveWrite(compoundWrite, path) {
  8116. if (pathIsEmpty(path)) {
  8117. return CompoundWrite.empty();
  8118. }
  8119. else {
  8120. var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  8121. return new CompoundWrite(newWriteTree);
  8122. }
  8123. }
  8124. /**
  8125. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  8126. * considered "complete".
  8127. *
  8128. * @param compoundWrite - The CompoundWrite to check.
  8129. * @param path - The path to check for
  8130. * @returns Whether there is a complete write at that path
  8131. */
  8132. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  8133. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  8134. }
  8135. /**
  8136. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  8137. * writes from deeper paths, but will return child nodes from a more shallow path.
  8138. *
  8139. * @param compoundWrite - The CompoundWrite to get the node from.
  8140. * @param path - The path to get a complete write
  8141. * @returns The node if complete at that path, or null otherwise.
  8142. */
  8143. function compoundWriteGetCompleteNode(compoundWrite, path) {
  8144. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8145. if (rootmost != null) {
  8146. return compoundWrite.writeTree_
  8147. .get(rootmost.path)
  8148. .getChild(newRelativePath(rootmost.path, path));
  8149. }
  8150. else {
  8151. return null;
  8152. }
  8153. }
  8154. /**
  8155. * Returns all children that are guaranteed to be a complete overwrite.
  8156. *
  8157. * @param compoundWrite - The CompoundWrite to get children from.
  8158. * @returns A list of all complete children.
  8159. */
  8160. function compoundWriteGetCompleteChildren(compoundWrite) {
  8161. var children = [];
  8162. var node = compoundWrite.writeTree_.value;
  8163. if (node != null) {
  8164. // If it's a leaf node, it has no children; so nothing to do.
  8165. if (!node.isLeafNode()) {
  8166. node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8167. children.push(new NamedNode(childName, childNode));
  8168. });
  8169. }
  8170. }
  8171. else {
  8172. compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
  8173. if (childTree.value != null) {
  8174. children.push(new NamedNode(childName, childTree.value));
  8175. }
  8176. });
  8177. }
  8178. return children;
  8179. }
  8180. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  8181. if (pathIsEmpty(path)) {
  8182. return compoundWrite;
  8183. }
  8184. else {
  8185. var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  8186. if (shadowingNode != null) {
  8187. return new CompoundWrite(new ImmutableTree(shadowingNode));
  8188. }
  8189. else {
  8190. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  8191. }
  8192. }
  8193. }
  8194. /**
  8195. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  8196. * @returns Whether this CompoundWrite is empty
  8197. */
  8198. function compoundWriteIsEmpty(compoundWrite) {
  8199. return compoundWrite.writeTree_.isEmpty();
  8200. }
  8201. /**
  8202. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  8203. * node
  8204. * @param node - The node to apply this CompoundWrite to
  8205. * @returns The node with all writes applied
  8206. */
  8207. function compoundWriteApply(compoundWrite, node) {
  8208. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  8209. }
  8210. function applySubtreeWrite(relativePath, writeTree, node) {
  8211. if (writeTree.value != null) {
  8212. // Since there a write is always a leaf, we're done here
  8213. return node.updateChild(relativePath, writeTree.value);
  8214. }
  8215. else {
  8216. var priorityWrite_1 = null;
  8217. writeTree.children.inorderTraversal(function (childKey, childTree) {
  8218. if (childKey === '.priority') {
  8219. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  8220. // to apply priorities to empty nodes that are later filled
  8221. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  8222. priorityWrite_1 = childTree.value;
  8223. }
  8224. else {
  8225. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  8226. }
  8227. });
  8228. // If there was a priority write, we only apply it if the node is not empty
  8229. if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
  8230. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
  8231. }
  8232. return node;
  8233. }
  8234. }
  8235. /**
  8236. * @license
  8237. * Copyright 2017 Google LLC
  8238. *
  8239. * Licensed under the Apache License, Version 2.0 (the "License");
  8240. * you may not use this file except in compliance with the License.
  8241. * You may obtain a copy of the License at
  8242. *
  8243. * http://www.apache.org/licenses/LICENSE-2.0
  8244. *
  8245. * Unless required by applicable law or agreed to in writing, software
  8246. * distributed under the License is distributed on an "AS IS" BASIS,
  8247. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8248. * See the License for the specific language governing permissions and
  8249. * limitations under the License.
  8250. */
  8251. /**
  8252. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8253. *
  8254. */
  8255. function writeTreeChildWrites(writeTree, path) {
  8256. return newWriteTreeRef(path, writeTree);
  8257. }
  8258. /**
  8259. * Record a new overwrite from user code.
  8260. *
  8261. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8262. */
  8263. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8264. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8265. if (visible === undefined) {
  8266. visible = true;
  8267. }
  8268. writeTree.allWrites.push({
  8269. path: path,
  8270. snap: snap,
  8271. writeId: writeId,
  8272. visible: visible
  8273. });
  8274. if (visible) {
  8275. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8276. }
  8277. writeTree.lastWriteId = writeId;
  8278. }
  8279. /**
  8280. * Record a new merge from user code.
  8281. */
  8282. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8283. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8284. writeTree.allWrites.push({
  8285. path: path,
  8286. children: changedChildren,
  8287. writeId: writeId,
  8288. visible: true
  8289. });
  8290. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8291. writeTree.lastWriteId = writeId;
  8292. }
  8293. function writeTreeGetWrite(writeTree, writeId) {
  8294. for (var i = 0; i < writeTree.allWrites.length; i++) {
  8295. var record = writeTree.allWrites[i];
  8296. if (record.writeId === writeId) {
  8297. return record;
  8298. }
  8299. }
  8300. return null;
  8301. }
  8302. /**
  8303. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8304. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8305. *
  8306. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8307. * events as a result).
  8308. */
  8309. function writeTreeRemoveWrite(writeTree, writeId) {
  8310. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8311. // out of order.
  8312. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8313. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8314. var idx = writeTree.allWrites.findIndex(function (s) {
  8315. return s.writeId === writeId;
  8316. });
  8317. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8318. var writeToRemove = writeTree.allWrites[idx];
  8319. writeTree.allWrites.splice(idx, 1);
  8320. var removedWriteWasVisible = writeToRemove.visible;
  8321. var removedWriteOverlapsWithOtherWrites = false;
  8322. var i = writeTree.allWrites.length - 1;
  8323. while (removedWriteWasVisible && i >= 0) {
  8324. var currentWrite = writeTree.allWrites[i];
  8325. if (currentWrite.visible) {
  8326. if (i >= idx &&
  8327. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8328. // The removed write was completely shadowed by a subsequent write.
  8329. removedWriteWasVisible = false;
  8330. }
  8331. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8332. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8333. removedWriteOverlapsWithOtherWrites = true;
  8334. }
  8335. }
  8336. i--;
  8337. }
  8338. if (!removedWriteWasVisible) {
  8339. return false;
  8340. }
  8341. else if (removedWriteOverlapsWithOtherWrites) {
  8342. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8343. writeTreeResetTree_(writeTree);
  8344. return true;
  8345. }
  8346. else {
  8347. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8348. if (writeToRemove.snap) {
  8349. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8350. }
  8351. else {
  8352. var children = writeToRemove.children;
  8353. each(children, function (childName) {
  8354. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8355. });
  8356. }
  8357. return true;
  8358. }
  8359. }
  8360. function writeTreeRecordContainsPath_(writeRecord, path) {
  8361. if (writeRecord.snap) {
  8362. return pathContains(writeRecord.path, path);
  8363. }
  8364. else {
  8365. for (var childName in writeRecord.children) {
  8366. if (writeRecord.children.hasOwnProperty(childName) &&
  8367. pathContains(pathChild(writeRecord.path, childName), path)) {
  8368. return true;
  8369. }
  8370. }
  8371. return false;
  8372. }
  8373. }
  8374. /**
  8375. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8376. */
  8377. function writeTreeResetTree_(writeTree) {
  8378. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8379. if (writeTree.allWrites.length > 0) {
  8380. writeTree.lastWriteId =
  8381. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8382. }
  8383. else {
  8384. writeTree.lastWriteId = -1;
  8385. }
  8386. }
  8387. /**
  8388. * The default filter used when constructing the tree. Keep everything that's visible.
  8389. */
  8390. function writeTreeDefaultFilter_(write) {
  8391. return write.visible;
  8392. }
  8393. /**
  8394. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8395. * event data at that path.
  8396. */
  8397. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8398. var compoundWrite = CompoundWrite.empty();
  8399. for (var i = 0; i < writes.length; ++i) {
  8400. var write = writes[i];
  8401. // Theory, a later set will either:
  8402. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8403. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8404. if (filter(write)) {
  8405. var writePath = write.path;
  8406. var relativePath = void 0;
  8407. if (write.snap) {
  8408. if (pathContains(treeRoot, writePath)) {
  8409. relativePath = newRelativePath(treeRoot, writePath);
  8410. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8411. }
  8412. else if (pathContains(writePath, treeRoot)) {
  8413. relativePath = newRelativePath(writePath, treeRoot);
  8414. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8415. }
  8416. else ;
  8417. }
  8418. else if (write.children) {
  8419. if (pathContains(treeRoot, writePath)) {
  8420. relativePath = newRelativePath(treeRoot, writePath);
  8421. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8422. }
  8423. else if (pathContains(writePath, treeRoot)) {
  8424. relativePath = newRelativePath(writePath, treeRoot);
  8425. if (pathIsEmpty(relativePath)) {
  8426. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8427. }
  8428. else {
  8429. var child = util.safeGet(write.children, pathGetFront(relativePath));
  8430. if (child) {
  8431. // There exists a child in this node that matches the root path
  8432. var deepNode = child.getChild(pathPopFront(relativePath));
  8433. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8434. }
  8435. }
  8436. }
  8437. else ;
  8438. }
  8439. else {
  8440. throw util.assertionError('WriteRecord should have .snap or .children');
  8441. }
  8442. }
  8443. }
  8444. return compoundWrite;
  8445. }
  8446. /**
  8447. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8448. * writes), attempt to calculate a complete snapshot for the given path
  8449. *
  8450. * @param writeIdsToExclude - An optional set to be excluded
  8451. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8452. */
  8453. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8454. if (!writeIdsToExclude && !includeHiddenWrites) {
  8455. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8456. if (shadowingNode != null) {
  8457. return shadowingNode;
  8458. }
  8459. else {
  8460. var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8461. if (compoundWriteIsEmpty(subMerge)) {
  8462. return completeServerCache;
  8463. }
  8464. else if (completeServerCache == null &&
  8465. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8466. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8467. return null;
  8468. }
  8469. else {
  8470. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8471. return compoundWriteApply(subMerge, layeredCache);
  8472. }
  8473. }
  8474. }
  8475. else {
  8476. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8477. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8478. return completeServerCache;
  8479. }
  8480. else {
  8481. // If the server cache is null, and we don't have a complete cache, we need to return null
  8482. if (!includeHiddenWrites &&
  8483. completeServerCache == null &&
  8484. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8485. return null;
  8486. }
  8487. else {
  8488. var filter = function (write) {
  8489. return ((write.visible || includeHiddenWrites) &&
  8490. (!writeIdsToExclude ||
  8491. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8492. (pathContains(write.path, treePath) ||
  8493. pathContains(treePath, write.path)));
  8494. };
  8495. var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8496. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8497. return compoundWriteApply(mergeAtPath, layeredCache);
  8498. }
  8499. }
  8500. }
  8501. }
  8502. /**
  8503. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8504. * Used when creating new views, to pre-fill their complete event children snapshot.
  8505. */
  8506. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8507. var completeChildren = ChildrenNode.EMPTY_NODE;
  8508. var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8509. if (topLevelSet) {
  8510. if (!topLevelSet.isLeafNode()) {
  8511. // we're shadowing everything. Return the children.
  8512. topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
  8513. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8514. });
  8515. }
  8516. return completeChildren;
  8517. }
  8518. else if (completeServerChildren) {
  8519. // Layer any children we have on top of this
  8520. // We know we don't have a top-level set, so just enumerate existing children
  8521. var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8522. completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8523. var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
  8524. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8525. });
  8526. // Add any complete children we have from the set
  8527. compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
  8528. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8529. });
  8530. return completeChildren;
  8531. }
  8532. else {
  8533. // We don't have anything to layer on top of. Layer on any children we have
  8534. // Note that we can return an empty snap if we have a defined delete
  8535. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8536. compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
  8537. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8538. });
  8539. return completeChildren;
  8540. }
  8541. }
  8542. /**
  8543. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8544. * applied to the event cache.
  8545. *
  8546. * Possibilities:
  8547. *
  8548. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8549. *
  8550. * 2. Some write is completely shadowing. No events to be raised
  8551. *
  8552. * 3. Is partially shadowed. Events
  8553. *
  8554. * Either existingEventSnap or existingServerSnap must exist
  8555. */
  8556. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8557. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8558. var path = pathChild(treePath, childPath);
  8559. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8560. // At this point we can probably guarantee that we're in case 2, meaning no events
  8561. // May need to check visibility while doing the findRootMostValueAndPath call
  8562. return null;
  8563. }
  8564. else {
  8565. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8566. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8567. if (compoundWriteIsEmpty(childMerge)) {
  8568. // We're not shadowing at all. Case 1
  8569. return existingServerSnap.getChild(childPath);
  8570. }
  8571. else {
  8572. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8573. // However this is tricky to find out, since user updates don't necessary change the server
  8574. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8575. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8576. // only check if the updates change the serverNode.
  8577. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8578. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8579. }
  8580. }
  8581. }
  8582. /**
  8583. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8584. * complete child for this ChildKey.
  8585. */
  8586. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8587. var path = pathChild(treePath, childKey);
  8588. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8589. if (shadowingNode != null) {
  8590. return shadowingNode;
  8591. }
  8592. else {
  8593. if (existingServerSnap.isCompleteForChild(childKey)) {
  8594. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8595. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8596. }
  8597. else {
  8598. return null;
  8599. }
  8600. }
  8601. }
  8602. /**
  8603. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8604. * a higher path, this will return the child of that write relative to the write and this path.
  8605. * Returns null if there is no write at this path.
  8606. */
  8607. function writeTreeShadowingWrite(writeTree, path) {
  8608. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8609. }
  8610. /**
  8611. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8612. * the window, but may now be in the window.
  8613. */
  8614. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8615. var toIterate;
  8616. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8617. var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8618. if (shadowingNode != null) {
  8619. toIterate = shadowingNode;
  8620. }
  8621. else if (completeServerData != null) {
  8622. toIterate = compoundWriteApply(merge, completeServerData);
  8623. }
  8624. else {
  8625. // no children to iterate on
  8626. return [];
  8627. }
  8628. toIterate = toIterate.withIndex(index);
  8629. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8630. var nodes = [];
  8631. var cmp = index.getCompare();
  8632. var iter = reverse
  8633. ? toIterate.getReverseIteratorFrom(startPost, index)
  8634. : toIterate.getIteratorFrom(startPost, index);
  8635. var next = iter.getNext();
  8636. while (next && nodes.length < count) {
  8637. if (cmp(next, startPost) !== 0) {
  8638. nodes.push(next);
  8639. }
  8640. next = iter.getNext();
  8641. }
  8642. return nodes;
  8643. }
  8644. else {
  8645. return [];
  8646. }
  8647. }
  8648. function newWriteTree() {
  8649. return {
  8650. visibleWrites: CompoundWrite.empty(),
  8651. allWrites: [],
  8652. lastWriteId: -1
  8653. };
  8654. }
  8655. /**
  8656. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8657. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8658. * can lead to a more expensive calculation.
  8659. *
  8660. * @param writeIdsToExclude - Optional writes to exclude.
  8661. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8662. */
  8663. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8664. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8665. }
  8666. /**
  8667. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8668. * mix of the given server data and write data.
  8669. *
  8670. */
  8671. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8672. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8673. }
  8674. /**
  8675. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8676. * if anything, needs to be applied to the event cache.
  8677. *
  8678. * Possibilities:
  8679. *
  8680. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8681. *
  8682. * 2. Some write is completely shadowing. No events to be raised
  8683. *
  8684. * 3. Is partially shadowed. Events should be raised
  8685. *
  8686. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8687. *
  8688. *
  8689. */
  8690. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8691. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8692. }
  8693. /**
  8694. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8695. * a higher path, this will return the child of that write relative to the write and this path.
  8696. * Returns null if there is no write at this path.
  8697. *
  8698. */
  8699. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8700. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8701. }
  8702. /**
  8703. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8704. * the window, but may now be in the window
  8705. */
  8706. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8707. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8708. }
  8709. /**
  8710. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8711. * complete child for this ChildKey.
  8712. */
  8713. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8714. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8715. }
  8716. /**
  8717. * Return a WriteTreeRef for a child.
  8718. */
  8719. function writeTreeRefChild(writeTreeRef, childName) {
  8720. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8721. }
  8722. function newWriteTreeRef(path, writeTree) {
  8723. return {
  8724. treePath: path,
  8725. writeTree: writeTree
  8726. };
  8727. }
  8728. /**
  8729. * @license
  8730. * Copyright 2017 Google LLC
  8731. *
  8732. * Licensed under the Apache License, Version 2.0 (the "License");
  8733. * you may not use this file except in compliance with the License.
  8734. * You may obtain a copy of the License at
  8735. *
  8736. * http://www.apache.org/licenses/LICENSE-2.0
  8737. *
  8738. * Unless required by applicable law or agreed to in writing, software
  8739. * distributed under the License is distributed on an "AS IS" BASIS,
  8740. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8741. * See the License for the specific language governing permissions and
  8742. * limitations under the License.
  8743. */
  8744. var ChildChangeAccumulator = /** @class */ (function () {
  8745. function ChildChangeAccumulator() {
  8746. this.changeMap = new Map();
  8747. }
  8748. ChildChangeAccumulator.prototype.trackChildChange = function (change) {
  8749. var type = change.type;
  8750. var childKey = change.childName;
  8751. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8752. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8753. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8754. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8755. var oldChange = this.changeMap.get(childKey);
  8756. if (oldChange) {
  8757. var oldType = oldChange.type;
  8758. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8759. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8760. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8761. }
  8762. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8763. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8764. this.changeMap.delete(childKey);
  8765. }
  8766. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8767. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8768. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8769. }
  8770. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8771. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8772. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8773. }
  8774. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8775. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8776. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8777. }
  8778. else {
  8779. throw util.assertionError('Illegal combination of changes: ' +
  8780. change +
  8781. ' occurred after ' +
  8782. oldChange);
  8783. }
  8784. }
  8785. else {
  8786. this.changeMap.set(childKey, change);
  8787. }
  8788. };
  8789. ChildChangeAccumulator.prototype.getChanges = function () {
  8790. return Array.from(this.changeMap.values());
  8791. };
  8792. return ChildChangeAccumulator;
  8793. }());
  8794. /**
  8795. * @license
  8796. * Copyright 2017 Google LLC
  8797. *
  8798. * Licensed under the Apache License, Version 2.0 (the "License");
  8799. * you may not use this file except in compliance with the License.
  8800. * You may obtain a copy of the License at
  8801. *
  8802. * http://www.apache.org/licenses/LICENSE-2.0
  8803. *
  8804. * Unless required by applicable law or agreed to in writing, software
  8805. * distributed under the License is distributed on an "AS IS" BASIS,
  8806. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8807. * See the License for the specific language governing permissions and
  8808. * limitations under the License.
  8809. */
  8810. /**
  8811. * An implementation of CompleteChildSource that never returns any additional children
  8812. */
  8813. // eslint-disable-next-line @typescript-eslint/naming-convention
  8814. var NoCompleteChildSource_ = /** @class */ (function () {
  8815. function NoCompleteChildSource_() {
  8816. }
  8817. NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
  8818. return null;
  8819. };
  8820. NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
  8821. return null;
  8822. };
  8823. return NoCompleteChildSource_;
  8824. }());
  8825. /**
  8826. * Singleton instance.
  8827. */
  8828. var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8829. /**
  8830. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8831. * old event caches available to calculate complete children.
  8832. */
  8833. var WriteTreeCompleteChildSource = /** @class */ (function () {
  8834. function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
  8835. if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
  8836. this.writes_ = writes_;
  8837. this.viewCache_ = viewCache_;
  8838. this.optCompleteServerCache_ = optCompleteServerCache_;
  8839. }
  8840. WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
  8841. var node = this.viewCache_.eventCache;
  8842. if (node.isCompleteForChild(childKey)) {
  8843. return node.getNode().getImmediateChild(childKey);
  8844. }
  8845. else {
  8846. var serverNode = this.optCompleteServerCache_ != null
  8847. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8848. : this.viewCache_.serverCache;
  8849. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8850. }
  8851. };
  8852. WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
  8853. var completeServerData = this.optCompleteServerCache_ != null
  8854. ? this.optCompleteServerCache_
  8855. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8856. var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8857. if (nodes.length === 0) {
  8858. return null;
  8859. }
  8860. else {
  8861. return nodes[0];
  8862. }
  8863. };
  8864. return WriteTreeCompleteChildSource;
  8865. }());
  8866. /**
  8867. * @license
  8868. * Copyright 2017 Google LLC
  8869. *
  8870. * Licensed under the Apache License, Version 2.0 (the "License");
  8871. * you may not use this file except in compliance with the License.
  8872. * You may obtain a copy of the License at
  8873. *
  8874. * http://www.apache.org/licenses/LICENSE-2.0
  8875. *
  8876. * Unless required by applicable law or agreed to in writing, software
  8877. * distributed under the License is distributed on an "AS IS" BASIS,
  8878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8879. * See the License for the specific language governing permissions and
  8880. * limitations under the License.
  8881. */
  8882. function newViewProcessor(filter) {
  8883. return { filter: filter };
  8884. }
  8885. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8886. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8887. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8888. }
  8889. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8890. var accumulator = new ChildChangeAccumulator();
  8891. var newViewCache, filterServerNode;
  8892. if (operation.type === OperationType.OVERWRITE) {
  8893. var overwrite = operation;
  8894. if (overwrite.source.fromUser) {
  8895. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8896. }
  8897. else {
  8898. util.assert(overwrite.source.fromServer, 'Unknown source.');
  8899. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8900. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8901. // again
  8902. filterServerNode =
  8903. overwrite.source.tagged ||
  8904. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8905. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8906. }
  8907. }
  8908. else if (operation.type === OperationType.MERGE) {
  8909. var merge = operation;
  8910. if (merge.source.fromUser) {
  8911. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8912. }
  8913. else {
  8914. util.assert(merge.source.fromServer, 'Unknown source.');
  8915. // We filter the node if it's a tagged update or the node has been previously filtered
  8916. filterServerNode =
  8917. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8918. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8919. }
  8920. }
  8921. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8922. var ackUserWrite = operation;
  8923. if (!ackUserWrite.revert) {
  8924. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8925. }
  8926. else {
  8927. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8928. }
  8929. }
  8930. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8931. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8932. }
  8933. else {
  8934. throw util.assertionError('Unknown operation type: ' + operation.type);
  8935. }
  8936. var changes = accumulator.getChanges();
  8937. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8938. return { viewCache: newViewCache, changes: changes };
  8939. }
  8940. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8941. var eventSnap = newViewCache.eventCache;
  8942. if (eventSnap.isFullyInitialized()) {
  8943. var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8944. var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8945. if (accumulator.length > 0 ||
  8946. !oldViewCache.eventCache.isFullyInitialized() ||
  8947. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8948. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8949. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8950. }
  8951. }
  8952. }
  8953. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8954. var oldEventSnap = viewCache.eventCache;
  8955. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8956. // we have a shadowing write, ignore changes
  8957. return viewCache;
  8958. }
  8959. else {
  8960. var newEventCache = void 0, serverNode = void 0;
  8961. if (pathIsEmpty(changePath)) {
  8962. // TODO: figure out how this plays with "sliding ack windows"
  8963. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8964. if (viewCache.serverCache.isFiltered()) {
  8965. // We need to special case this, because we need to only apply writes to complete children, or
  8966. // we might end up raising events for incomplete children. If the server data is filtered deep
  8967. // writes cannot be guaranteed to be complete
  8968. var serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8969. var completeChildren = serverCache instanceof ChildrenNode
  8970. ? serverCache
  8971. : ChildrenNode.EMPTY_NODE;
  8972. var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8973. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8974. }
  8975. else {
  8976. var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8977. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8978. }
  8979. }
  8980. else {
  8981. var childKey = pathGetFront(changePath);
  8982. if (childKey === '.priority') {
  8983. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8984. var oldEventNode = oldEventSnap.getNode();
  8985. serverNode = viewCache.serverCache.getNode();
  8986. // we might have overwrites for this priority
  8987. var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8988. if (updatedPriority != null) {
  8989. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8990. }
  8991. else {
  8992. // priority didn't change, keep old node
  8993. newEventCache = oldEventSnap.getNode();
  8994. }
  8995. }
  8996. else {
  8997. var childChangePath = pathPopFront(changePath);
  8998. // update child
  8999. var newEventChild = void 0;
  9000. if (oldEventSnap.isCompleteForChild(childKey)) {
  9001. serverNode = viewCache.serverCache.getNode();
  9002. var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  9003. if (eventChildUpdate != null) {
  9004. newEventChild = oldEventSnap
  9005. .getNode()
  9006. .getImmediateChild(childKey)
  9007. .updateChild(childChangePath, eventChildUpdate);
  9008. }
  9009. else {
  9010. // Nothing changed, just keep the old child
  9011. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9012. }
  9013. }
  9014. else {
  9015. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9016. }
  9017. if (newEventChild != null) {
  9018. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  9019. }
  9020. else {
  9021. // no complete child available or no change
  9022. newEventCache = oldEventSnap.getNode();
  9023. }
  9024. }
  9025. }
  9026. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  9027. }
  9028. }
  9029. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  9030. var oldServerSnap = oldViewCache.serverCache;
  9031. var newServerCache;
  9032. var serverFilter = filterServerNode
  9033. ? viewProcessor.filter
  9034. : viewProcessor.filter.getIndexedFilter();
  9035. if (pathIsEmpty(changePath)) {
  9036. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  9037. }
  9038. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  9039. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  9040. var newServerNode = oldServerSnap
  9041. .getNode()
  9042. .updateChild(changePath, changedSnap);
  9043. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  9044. }
  9045. else {
  9046. var childKey = pathGetFront(changePath);
  9047. if (!oldServerSnap.isCompleteForPath(changePath) &&
  9048. pathGetLength(changePath) > 1) {
  9049. // We don't update incomplete nodes with updates intended for other listeners
  9050. return oldViewCache;
  9051. }
  9052. var childChangePath = pathPopFront(changePath);
  9053. var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  9054. var newChildNode = childNode.updateChild(childChangePath, changedSnap);
  9055. if (childKey === '.priority') {
  9056. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  9057. }
  9058. else {
  9059. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  9060. }
  9061. }
  9062. var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  9063. var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  9064. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  9065. }
  9066. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  9067. var oldEventSnap = oldViewCache.eventCache;
  9068. var newViewCache, newEventCache;
  9069. var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  9070. if (pathIsEmpty(changePath)) {
  9071. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  9072. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  9073. }
  9074. else {
  9075. var childKey = pathGetFront(changePath);
  9076. if (childKey === '.priority') {
  9077. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  9078. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  9079. }
  9080. else {
  9081. var childChangePath = pathPopFront(changePath);
  9082. var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9083. var newChild = void 0;
  9084. if (pathIsEmpty(childChangePath)) {
  9085. // Child overwrite, we can replace the child
  9086. newChild = changedSnap;
  9087. }
  9088. else {
  9089. var childNode = source.getCompleteChild(childKey);
  9090. if (childNode != null) {
  9091. if (pathGetBack(childChangePath) === '.priority' &&
  9092. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  9093. // This is a priority update on an empty node. If this node exists on the server, the
  9094. // server will send down the priority in the update, so ignore for now
  9095. newChild = childNode;
  9096. }
  9097. else {
  9098. newChild = childNode.updateChild(childChangePath, changedSnap);
  9099. }
  9100. }
  9101. else {
  9102. // There is no complete child node available
  9103. newChild = ChildrenNode.EMPTY_NODE;
  9104. }
  9105. }
  9106. if (!oldChild.equals(newChild)) {
  9107. var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  9108. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  9109. }
  9110. else {
  9111. newViewCache = oldViewCache;
  9112. }
  9113. }
  9114. }
  9115. return newViewCache;
  9116. }
  9117. function viewProcessorCacheHasChild(viewCache, childKey) {
  9118. return viewCache.eventCache.isCompleteForChild(childKey);
  9119. }
  9120. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  9121. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9122. // window leaving room for new items. It's important we process these changes first, so we
  9123. // iterate the changes twice, first processing any that affect items currently in view.
  9124. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9125. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9126. // not the other.
  9127. var curViewCache = viewCache;
  9128. changedChildren.foreach(function (relativePath, childNode) {
  9129. var writePath = pathChild(path, relativePath);
  9130. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9131. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9132. }
  9133. });
  9134. changedChildren.foreach(function (relativePath, childNode) {
  9135. var writePath = pathChild(path, relativePath);
  9136. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9137. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9138. }
  9139. });
  9140. return curViewCache;
  9141. }
  9142. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  9143. merge.foreach(function (relativePath, childNode) {
  9144. node = node.updateChild(relativePath, childNode);
  9145. });
  9146. return node;
  9147. }
  9148. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  9149. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  9150. // wait for the complete data update coming soon.
  9151. if (viewCache.serverCache.getNode().isEmpty() &&
  9152. !viewCache.serverCache.isFullyInitialized()) {
  9153. return viewCache;
  9154. }
  9155. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9156. // window leaving room for new items. It's important we process these changes first, so we
  9157. // iterate the changes twice, first processing any that affect items currently in view.
  9158. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9159. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9160. // not the other.
  9161. var curViewCache = viewCache;
  9162. var viewMergeTree;
  9163. if (pathIsEmpty(path)) {
  9164. viewMergeTree = changedChildren;
  9165. }
  9166. else {
  9167. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  9168. }
  9169. var serverNode = viewCache.serverCache.getNode();
  9170. viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
  9171. if (serverNode.hasChild(childKey)) {
  9172. var serverChild = viewCache.serverCache
  9173. .getNode()
  9174. .getImmediateChild(childKey);
  9175. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  9176. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9177. }
  9178. });
  9179. viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
  9180. var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  9181. childMergeTree.value === null;
  9182. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  9183. var serverChild = viewCache.serverCache
  9184. .getNode()
  9185. .getImmediateChild(childKey);
  9186. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  9187. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9188. }
  9189. });
  9190. return curViewCache;
  9191. }
  9192. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  9193. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  9194. return viewCache;
  9195. }
  9196. // Only filter server node if it is currently filtered
  9197. var filterServerNode = viewCache.serverCache.isFiltered();
  9198. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  9199. // now that it won't be shadowed.
  9200. var serverCache = viewCache.serverCache;
  9201. if (affectedTree.value != null) {
  9202. // This is an overwrite.
  9203. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  9204. serverCache.isCompleteForPath(ackPath)) {
  9205. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  9206. }
  9207. else if (pathIsEmpty(ackPath)) {
  9208. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  9209. // should just re-apply whatever we have in our cache as a merge.
  9210. var changedChildren_1 = new ImmutableTree(null);
  9211. serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
  9212. changedChildren_1 = changedChildren_1.set(new Path(name), node);
  9213. });
  9214. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
  9215. }
  9216. else {
  9217. return viewCache;
  9218. }
  9219. }
  9220. else {
  9221. // This is a merge.
  9222. var changedChildren_2 = new ImmutableTree(null);
  9223. affectedTree.foreach(function (mergePath, value) {
  9224. var serverCachePath = pathChild(ackPath, mergePath);
  9225. if (serverCache.isCompleteForPath(serverCachePath)) {
  9226. changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  9227. }
  9228. });
  9229. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
  9230. }
  9231. }
  9232. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  9233. var oldServerNode = viewCache.serverCache;
  9234. var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  9235. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  9236. }
  9237. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  9238. var complete;
  9239. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  9240. return viewCache;
  9241. }
  9242. else {
  9243. var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  9244. var oldEventCache = viewCache.eventCache.getNode();
  9245. var newEventCache = void 0;
  9246. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9247. var newNode = void 0;
  9248. if (viewCache.serverCache.isFullyInitialized()) {
  9249. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9250. }
  9251. else {
  9252. var serverChildren = viewCache.serverCache.getNode();
  9253. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9254. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9255. }
  9256. newNode = newNode;
  9257. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9258. }
  9259. else {
  9260. var childKey = pathGetFront(path);
  9261. var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9262. if (newChild == null &&
  9263. viewCache.serverCache.isCompleteForChild(childKey)) {
  9264. newChild = oldEventCache.getImmediateChild(childKey);
  9265. }
  9266. if (newChild != null) {
  9267. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9268. }
  9269. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9270. // No complete child available, delete the existing one, if any
  9271. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9272. }
  9273. else {
  9274. newEventCache = oldEventCache;
  9275. }
  9276. if (newEventCache.isEmpty() &&
  9277. viewCache.serverCache.isFullyInitialized()) {
  9278. // We might have reverted all child writes. Maybe the old event was a leaf node
  9279. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9280. if (complete.isLeafNode()) {
  9281. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9282. }
  9283. }
  9284. }
  9285. complete =
  9286. viewCache.serverCache.isFullyInitialized() ||
  9287. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9288. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9289. }
  9290. }
  9291. /**
  9292. * @license
  9293. * Copyright 2017 Google LLC
  9294. *
  9295. * Licensed under the Apache License, Version 2.0 (the "License");
  9296. * you may not use this file except in compliance with the License.
  9297. * You may obtain a copy of the License at
  9298. *
  9299. * http://www.apache.org/licenses/LICENSE-2.0
  9300. *
  9301. * Unless required by applicable law or agreed to in writing, software
  9302. * distributed under the License is distributed on an "AS IS" BASIS,
  9303. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9304. * See the License for the specific language governing permissions and
  9305. * limitations under the License.
  9306. */
  9307. /**
  9308. * A view represents a specific location and query that has 1 or more event registrations.
  9309. *
  9310. * It does several things:
  9311. * - Maintains the list of event registrations for this location/query.
  9312. * - Maintains a cache of the data visible for this location/query.
  9313. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9314. * registrations returns the set of events to be raised.
  9315. */
  9316. var View = /** @class */ (function () {
  9317. function View(query_, initialViewCache) {
  9318. this.query_ = query_;
  9319. this.eventRegistrations_ = [];
  9320. var params = this.query_._queryParams;
  9321. var indexFilter = new IndexedFilter(params.getIndex());
  9322. var filter = queryParamsGetNodeFilter(params);
  9323. this.processor_ = newViewProcessor(filter);
  9324. var initialServerCache = initialViewCache.serverCache;
  9325. var initialEventCache = initialViewCache.eventCache;
  9326. // Don't filter server node with other filter than index, wait for tagged listen
  9327. var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9328. var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9329. var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9330. var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9331. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9332. this.eventGenerator_ = new EventGenerator(this.query_);
  9333. }
  9334. Object.defineProperty(View.prototype, "query", {
  9335. get: function () {
  9336. return this.query_;
  9337. },
  9338. enumerable: false,
  9339. configurable: true
  9340. });
  9341. return View;
  9342. }());
  9343. function viewGetServerCache(view) {
  9344. return view.viewCache_.serverCache.getNode();
  9345. }
  9346. function viewGetCompleteNode(view) {
  9347. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9348. }
  9349. function viewGetCompleteServerCache(view, path) {
  9350. var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9351. if (cache) {
  9352. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9353. // we need to see if it contains the child we're interested in.
  9354. if (view.query._queryParams.loadsAllData() ||
  9355. (!pathIsEmpty(path) &&
  9356. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9357. return cache.getChild(path);
  9358. }
  9359. }
  9360. return null;
  9361. }
  9362. function viewIsEmpty(view) {
  9363. return view.eventRegistrations_.length === 0;
  9364. }
  9365. function viewAddEventRegistration(view, eventRegistration) {
  9366. view.eventRegistrations_.push(eventRegistration);
  9367. }
  9368. /**
  9369. * @param eventRegistration - If null, remove all callbacks.
  9370. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9371. * @returns Cancel events, if cancelError was provided.
  9372. */
  9373. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9374. var cancelEvents = [];
  9375. if (cancelError) {
  9376. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9377. var path_1 = view.query._path;
  9378. view.eventRegistrations_.forEach(function (registration) {
  9379. var maybeEvent = registration.createCancelEvent(cancelError, path_1);
  9380. if (maybeEvent) {
  9381. cancelEvents.push(maybeEvent);
  9382. }
  9383. });
  9384. }
  9385. if (eventRegistration) {
  9386. var remaining = [];
  9387. for (var i = 0; i < view.eventRegistrations_.length; ++i) {
  9388. var existing = view.eventRegistrations_[i];
  9389. if (!existing.matches(eventRegistration)) {
  9390. remaining.push(existing);
  9391. }
  9392. else if (eventRegistration.hasAnyCallback()) {
  9393. // We're removing just this one
  9394. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9395. break;
  9396. }
  9397. }
  9398. view.eventRegistrations_ = remaining;
  9399. }
  9400. else {
  9401. view.eventRegistrations_ = [];
  9402. }
  9403. return cancelEvents;
  9404. }
  9405. /**
  9406. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9407. */
  9408. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9409. if (operation.type === OperationType.MERGE &&
  9410. operation.source.queryId !== null) {
  9411. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9412. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9413. }
  9414. var oldViewCache = view.viewCache_;
  9415. var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9416. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9417. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  9418. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9419. view.viewCache_ = result.viewCache;
  9420. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9421. }
  9422. function viewGetInitialEvents(view, registration) {
  9423. var eventSnap = view.viewCache_.eventCache;
  9424. var initialChanges = [];
  9425. if (!eventSnap.getNode().isLeafNode()) {
  9426. var eventNode = eventSnap.getNode();
  9427. eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  9428. initialChanges.push(changeChildAdded(key, childNode));
  9429. });
  9430. }
  9431. if (eventSnap.isFullyInitialized()) {
  9432. initialChanges.push(changeValue(eventSnap.getNode()));
  9433. }
  9434. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9435. }
  9436. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9437. var registrations = eventRegistration
  9438. ? [eventRegistration]
  9439. : view.eventRegistrations_;
  9440. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9441. }
  9442. /**
  9443. * @license
  9444. * Copyright 2017 Google LLC
  9445. *
  9446. * Licensed under the Apache License, Version 2.0 (the "License");
  9447. * you may not use this file except in compliance with the License.
  9448. * You may obtain a copy of the License at
  9449. *
  9450. * http://www.apache.org/licenses/LICENSE-2.0
  9451. *
  9452. * Unless required by applicable law or agreed to in writing, software
  9453. * distributed under the License is distributed on an "AS IS" BASIS,
  9454. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9455. * See the License for the specific language governing permissions and
  9456. * limitations under the License.
  9457. */
  9458. var referenceConstructor$1;
  9459. /**
  9460. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9461. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9462. * and user writes (set, transaction, update).
  9463. *
  9464. * It's responsible for:
  9465. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9466. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9467. * applyUserOverwrite, etc.)
  9468. */
  9469. var SyncPoint = /** @class */ (function () {
  9470. function SyncPoint() {
  9471. /**
  9472. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9473. * queryId and the value is the View for that query.
  9474. *
  9475. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9476. */
  9477. this.views = new Map();
  9478. }
  9479. return SyncPoint;
  9480. }());
  9481. function syncPointSetReferenceConstructor(val) {
  9482. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9483. referenceConstructor$1 = val;
  9484. }
  9485. function syncPointGetReferenceConstructor() {
  9486. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9487. return referenceConstructor$1;
  9488. }
  9489. function syncPointIsEmpty(syncPoint) {
  9490. return syncPoint.views.size === 0;
  9491. }
  9492. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9493. var e_1, _a;
  9494. var queryId = operation.source.queryId;
  9495. if (queryId !== null) {
  9496. var view = syncPoint.views.get(queryId);
  9497. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9498. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9499. }
  9500. else {
  9501. var events = [];
  9502. try {
  9503. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9504. var view = _c.value;
  9505. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9506. }
  9507. }
  9508. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  9509. finally {
  9510. try {
  9511. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9512. }
  9513. finally { if (e_1) throw e_1.error; }
  9514. }
  9515. return events;
  9516. }
  9517. }
  9518. /**
  9519. * Get a view for the specified query.
  9520. *
  9521. * @param query - The query to return a view for
  9522. * @param writesCache
  9523. * @param serverCache
  9524. * @param serverCacheComplete
  9525. * @returns Events to raise.
  9526. */
  9527. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9528. var queryId = query._queryIdentifier;
  9529. var view = syncPoint.views.get(queryId);
  9530. if (!view) {
  9531. // TODO: make writesCache take flag for complete server node
  9532. var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9533. var eventCacheComplete = false;
  9534. if (eventCache) {
  9535. eventCacheComplete = true;
  9536. }
  9537. else if (serverCache instanceof ChildrenNode) {
  9538. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9539. eventCacheComplete = false;
  9540. }
  9541. else {
  9542. eventCache = ChildrenNode.EMPTY_NODE;
  9543. eventCacheComplete = false;
  9544. }
  9545. var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9546. return new View(query, viewCache);
  9547. }
  9548. return view;
  9549. }
  9550. /**
  9551. * Add an event callback for the specified query.
  9552. *
  9553. * @param query
  9554. * @param eventRegistration
  9555. * @param writesCache
  9556. * @param serverCache - Complete server cache, if we have it.
  9557. * @param serverCacheComplete
  9558. * @returns Events to raise.
  9559. */
  9560. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9561. var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9562. if (!syncPoint.views.has(query._queryIdentifier)) {
  9563. syncPoint.views.set(query._queryIdentifier, view);
  9564. }
  9565. // This is guaranteed to exist now, we just created anything that was missing
  9566. viewAddEventRegistration(view, eventRegistration);
  9567. return viewGetInitialEvents(view, eventRegistration);
  9568. }
  9569. /**
  9570. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9571. *
  9572. * If query is the default query, we'll check all views for the specified eventRegistration.
  9573. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9574. *
  9575. * @param eventRegistration - If null, remove all callbacks.
  9576. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9577. * @returns removed queries and any cancel events
  9578. */
  9579. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9580. var e_2, _a;
  9581. var queryId = query._queryIdentifier;
  9582. var removed = [];
  9583. var cancelEvents = [];
  9584. var hadCompleteView = syncPointHasCompleteView(syncPoint);
  9585. if (queryId === 'default') {
  9586. try {
  9587. // When you do ref.off(...), we search all views for the registration to remove.
  9588. for (var _b = tslib.__values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9589. var _d = tslib.__read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
  9590. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9591. if (viewIsEmpty(view)) {
  9592. syncPoint.views.delete(viewQueryId);
  9593. // We'll deal with complete views later.
  9594. if (!view.query._queryParams.loadsAllData()) {
  9595. removed.push(view.query);
  9596. }
  9597. }
  9598. }
  9599. }
  9600. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  9601. finally {
  9602. try {
  9603. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9604. }
  9605. finally { if (e_2) throw e_2.error; }
  9606. }
  9607. }
  9608. else {
  9609. // remove the callback from the specific view.
  9610. var view = syncPoint.views.get(queryId);
  9611. if (view) {
  9612. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9613. if (viewIsEmpty(view)) {
  9614. syncPoint.views.delete(queryId);
  9615. // We'll deal with complete views later.
  9616. if (!view.query._queryParams.loadsAllData()) {
  9617. removed.push(view.query);
  9618. }
  9619. }
  9620. }
  9621. }
  9622. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9623. // We removed our last complete view.
  9624. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9625. }
  9626. return { removed: removed, events: cancelEvents };
  9627. }
  9628. function syncPointGetQueryViews(syncPoint) {
  9629. var e_3, _a;
  9630. var result = [];
  9631. try {
  9632. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9633. var view = _c.value;
  9634. if (!view.query._queryParams.loadsAllData()) {
  9635. result.push(view);
  9636. }
  9637. }
  9638. }
  9639. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  9640. finally {
  9641. try {
  9642. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9643. }
  9644. finally { if (e_3) throw e_3.error; }
  9645. }
  9646. return result;
  9647. }
  9648. /**
  9649. * @param path - The path to the desired complete snapshot
  9650. * @returns A complete cache, if it exists
  9651. */
  9652. function syncPointGetCompleteServerCache(syncPoint, path) {
  9653. var e_4, _a;
  9654. var serverCache = null;
  9655. try {
  9656. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9657. var view = _c.value;
  9658. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9659. }
  9660. }
  9661. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  9662. finally {
  9663. try {
  9664. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9665. }
  9666. finally { if (e_4) throw e_4.error; }
  9667. }
  9668. return serverCache;
  9669. }
  9670. function syncPointViewForQuery(syncPoint, query) {
  9671. var params = query._queryParams;
  9672. if (params.loadsAllData()) {
  9673. return syncPointGetCompleteView(syncPoint);
  9674. }
  9675. else {
  9676. var queryId = query._queryIdentifier;
  9677. return syncPoint.views.get(queryId);
  9678. }
  9679. }
  9680. function syncPointViewExistsForQuery(syncPoint, query) {
  9681. return syncPointViewForQuery(syncPoint, query) != null;
  9682. }
  9683. function syncPointHasCompleteView(syncPoint) {
  9684. return syncPointGetCompleteView(syncPoint) != null;
  9685. }
  9686. function syncPointGetCompleteView(syncPoint) {
  9687. var e_5, _a;
  9688. try {
  9689. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9690. var view = _c.value;
  9691. if (view.query._queryParams.loadsAllData()) {
  9692. return view;
  9693. }
  9694. }
  9695. }
  9696. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  9697. finally {
  9698. try {
  9699. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9700. }
  9701. finally { if (e_5) throw e_5.error; }
  9702. }
  9703. return null;
  9704. }
  9705. /**
  9706. * @license
  9707. * Copyright 2017 Google LLC
  9708. *
  9709. * Licensed under the Apache License, Version 2.0 (the "License");
  9710. * you may not use this file except in compliance with the License.
  9711. * You may obtain a copy of the License at
  9712. *
  9713. * http://www.apache.org/licenses/LICENSE-2.0
  9714. *
  9715. * Unless required by applicable law or agreed to in writing, software
  9716. * distributed under the License is distributed on an "AS IS" BASIS,
  9717. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9718. * See the License for the specific language governing permissions and
  9719. * limitations under the License.
  9720. */
  9721. var referenceConstructor;
  9722. function syncTreeSetReferenceConstructor(val) {
  9723. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9724. referenceConstructor = val;
  9725. }
  9726. function syncTreeGetReferenceConstructor() {
  9727. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  9728. return referenceConstructor;
  9729. }
  9730. /**
  9731. * Static tracker for next query tag.
  9732. */
  9733. var syncTreeNextQueryTag_ = 1;
  9734. /**
  9735. * SyncTree is the central class for managing event callback registration, data caching, views
  9736. * (query processing), and event generation. There are typically two SyncTree instances for
  9737. * each Repo, one for the normal Firebase data, and one for the .info data.
  9738. *
  9739. * It has a number of responsibilities, including:
  9740. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9741. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9742. * (applyUserOverwrite(), applyUserMerge()).
  9743. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9744. * applyServerMerge()).
  9745. * - Generating user-facing events for server and user changes (all of the apply* methods
  9746. * return the set of events that need to be raised as a result).
  9747. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9748. * to the correct set of paths and queries to satisfy the current set of user event
  9749. * callbacks (listens are started/stopped using the provided listenProvider).
  9750. *
  9751. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9752. * events are returned to the caller rather than raised synchronously.
  9753. *
  9754. */
  9755. var SyncTree = /** @class */ (function () {
  9756. /**
  9757. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9758. * to server data.
  9759. */
  9760. function SyncTree(listenProvider_) {
  9761. this.listenProvider_ = listenProvider_;
  9762. /**
  9763. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9764. */
  9765. this.syncPointTree_ = new ImmutableTree(null);
  9766. /**
  9767. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9768. */
  9769. this.pendingWriteTree_ = newWriteTree();
  9770. this.tagToQueryMap = new Map();
  9771. this.queryToTagMap = new Map();
  9772. }
  9773. return SyncTree;
  9774. }());
  9775. /**
  9776. * Apply the data changes for a user-generated set() or transaction() call.
  9777. *
  9778. * @returns Events to raise.
  9779. */
  9780. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9781. // Record pending write.
  9782. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9783. if (!visible) {
  9784. return [];
  9785. }
  9786. else {
  9787. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9788. }
  9789. }
  9790. /**
  9791. * Apply the data from a user-generated update() call
  9792. *
  9793. * @returns Events to raise.
  9794. */
  9795. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9796. // Record pending merge.
  9797. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9798. var changeTree = ImmutableTree.fromObject(changedChildren);
  9799. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9800. }
  9801. /**
  9802. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9803. *
  9804. * @param revert - True if the given write failed and needs to be reverted
  9805. * @returns Events to raise.
  9806. */
  9807. function syncTreeAckUserWrite(syncTree, writeId, revert) {
  9808. if (revert === void 0) { revert = false; }
  9809. var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9810. var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9811. if (!needToReevaluate) {
  9812. return [];
  9813. }
  9814. else {
  9815. var affectedTree_1 = new ImmutableTree(null);
  9816. if (write.snap != null) {
  9817. // overwrite
  9818. affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
  9819. }
  9820. else {
  9821. each(write.children, function (pathString) {
  9822. affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
  9823. });
  9824. }
  9825. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
  9826. }
  9827. }
  9828. /**
  9829. * Apply new server data for the specified path..
  9830. *
  9831. * @returns Events to raise.
  9832. */
  9833. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9834. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9835. }
  9836. /**
  9837. * Apply new server data to be merged in at the specified path.
  9838. *
  9839. * @returns Events to raise.
  9840. */
  9841. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9842. var changeTree = ImmutableTree.fromObject(changedChildren);
  9843. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9844. }
  9845. /**
  9846. * Apply a listen complete for a query
  9847. *
  9848. * @returns Events to raise.
  9849. */
  9850. function syncTreeApplyListenComplete(syncTree, path) {
  9851. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9852. }
  9853. /**
  9854. * Apply a listen complete for a tagged query
  9855. *
  9856. * @returns Events to raise.
  9857. */
  9858. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9859. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9860. if (queryKey) {
  9861. var r = syncTreeParseQueryKey_(queryKey);
  9862. var queryPath = r.path, queryId = r.queryId;
  9863. var relativePath = newRelativePath(queryPath, path);
  9864. var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9865. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9866. }
  9867. else {
  9868. // We've already removed the query. No big deal, ignore the update
  9869. return [];
  9870. }
  9871. }
  9872. /**
  9873. * Remove event callback(s).
  9874. *
  9875. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9876. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9877. *
  9878. * @param eventRegistration - If null, all callbacks are removed.
  9879. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9880. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9881. * deduping needs to take place. This flag allows toggling of that behavior
  9882. * @returns Cancel events, if cancelError was provided.
  9883. */
  9884. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
  9885. if (skipListenerDedup === void 0) { skipListenerDedup = false; }
  9886. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9887. var path = query._path;
  9888. var maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9889. var cancelEvents = [];
  9890. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9891. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9892. // not loadsAllData().
  9893. if (maybeSyncPoint &&
  9894. (query._queryIdentifier === 'default' ||
  9895. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9896. var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9897. if (syncPointIsEmpty(maybeSyncPoint)) {
  9898. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9899. }
  9900. var removed = removedAndEvents.removed;
  9901. cancelEvents = removedAndEvents.events;
  9902. if (!skipListenerDedup) {
  9903. /**
  9904. * We may have just removed one of many listeners and can short-circuit this whole process
  9905. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9906. * properly set up.
  9907. */
  9908. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9909. // queryId === 'default'
  9910. var removingDefault = -1 !==
  9911. removed.findIndex(function (query) {
  9912. return query._queryParams.loadsAllData();
  9913. });
  9914. var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
  9915. return syncPointHasCompleteView(parentSyncPoint);
  9916. });
  9917. if (removingDefault && !covered) {
  9918. var subtree = syncTree.syncPointTree_.subtree(path);
  9919. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9920. // removal
  9921. if (!subtree.isEmpty()) {
  9922. // We need to fold over our subtree and collect the listeners to send
  9923. var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9924. // Ok, we've collected all the listens we need. Set them up.
  9925. for (var i = 0; i < newViews.length; ++i) {
  9926. var view = newViews[i], newQuery = view.query;
  9927. var listener = syncTreeCreateListenerForView_(syncTree, view);
  9928. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9929. }
  9930. }
  9931. // Otherwise there's nothing below us, so nothing we need to start listening on
  9932. }
  9933. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9934. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9935. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9936. if (!covered && removed.length > 0 && !cancelError) {
  9937. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9938. // default. Otherwise, we need to iterate through and cancel each individual query
  9939. if (removingDefault) {
  9940. // We don't tag default listeners
  9941. var defaultTag = null;
  9942. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9943. }
  9944. else {
  9945. removed.forEach(function (queryToRemove) {
  9946. var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9947. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9948. });
  9949. }
  9950. }
  9951. }
  9952. // Now, clear all of the tags we're tracking for the removed listens
  9953. syncTreeRemoveTags_(syncTree, removed);
  9954. }
  9955. return cancelEvents;
  9956. }
  9957. /**
  9958. * Apply new server data for the specified tagged query.
  9959. *
  9960. * @returns Events to raise.
  9961. */
  9962. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9963. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9964. if (queryKey != null) {
  9965. var r = syncTreeParseQueryKey_(queryKey);
  9966. var queryPath = r.path, queryId = r.queryId;
  9967. var relativePath = newRelativePath(queryPath, path);
  9968. var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9969. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9970. }
  9971. else {
  9972. // Query must have been removed already
  9973. return [];
  9974. }
  9975. }
  9976. /**
  9977. * Apply server data to be merged in for the specified tagged query.
  9978. *
  9979. * @returns Events to raise.
  9980. */
  9981. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9982. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9983. if (queryKey) {
  9984. var r = syncTreeParseQueryKey_(queryKey);
  9985. var queryPath = r.path, queryId = r.queryId;
  9986. var relativePath = newRelativePath(queryPath, path);
  9987. var changeTree = ImmutableTree.fromObject(changedChildren);
  9988. var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9989. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9990. }
  9991. else {
  9992. // We've already removed the query. No big deal, ignore the update
  9993. return [];
  9994. }
  9995. }
  9996. /**
  9997. * Add an event callback for the specified query.
  9998. *
  9999. * @returns Events to raise.
  10000. */
  10001. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
  10002. if (skipSetupListener === void 0) { skipSetupListener = false; }
  10003. var path = query._path;
  10004. var serverCache = null;
  10005. var foundAncestorDefaultView = false;
  10006. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10007. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10008. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10009. var relativePath = newRelativePath(pathToSyncPoint, path);
  10010. serverCache =
  10011. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10012. foundAncestorDefaultView =
  10013. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  10014. });
  10015. var syncPoint = syncTree.syncPointTree_.get(path);
  10016. if (!syncPoint) {
  10017. syncPoint = new SyncPoint();
  10018. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10019. }
  10020. else {
  10021. foundAncestorDefaultView =
  10022. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  10023. serverCache =
  10024. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10025. }
  10026. var serverCacheComplete;
  10027. if (serverCache != null) {
  10028. serverCacheComplete = true;
  10029. }
  10030. else {
  10031. serverCacheComplete = false;
  10032. serverCache = ChildrenNode.EMPTY_NODE;
  10033. var subtree = syncTree.syncPointTree_.subtree(path);
  10034. subtree.foreachChild(function (childName, childSyncPoint) {
  10035. var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  10036. if (completeCache) {
  10037. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  10038. }
  10039. });
  10040. }
  10041. var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  10042. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  10043. // We need to track a tag for this query
  10044. var queryKey = syncTreeMakeQueryKey_(query);
  10045. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  10046. var tag = syncTreeGetNextQueryTag_();
  10047. syncTree.queryToTagMap.set(queryKey, tag);
  10048. syncTree.tagToQueryMap.set(tag, queryKey);
  10049. }
  10050. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  10051. var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  10052. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  10053. var view = syncPointViewForQuery(syncPoint, query);
  10054. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  10055. }
  10056. return events;
  10057. }
  10058. /**
  10059. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  10060. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  10061. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  10062. * <incremented total> as the write is applied locally and then acknowledged at the server.
  10063. *
  10064. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  10065. *
  10066. * @param path - The path to the data we want
  10067. * @param writeIdsToExclude - A specific set to be excluded
  10068. */
  10069. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  10070. var includeHiddenSets = true;
  10071. var writeTree = syncTree.pendingWriteTree_;
  10072. var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
  10073. var relativePath = newRelativePath(pathSoFar, path);
  10074. var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  10075. if (serverCache) {
  10076. return serverCache;
  10077. }
  10078. });
  10079. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  10080. }
  10081. function syncTreeGetServerValue(syncTree, query) {
  10082. var path = query._path;
  10083. var serverCache = null;
  10084. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10085. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10086. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10087. var relativePath = newRelativePath(pathToSyncPoint, path);
  10088. serverCache =
  10089. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10090. });
  10091. var syncPoint = syncTree.syncPointTree_.get(path);
  10092. if (!syncPoint) {
  10093. syncPoint = new SyncPoint();
  10094. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10095. }
  10096. else {
  10097. serverCache =
  10098. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10099. }
  10100. var serverCacheComplete = serverCache != null;
  10101. var serverCacheNode = serverCacheComplete
  10102. ? new CacheNode(serverCache, true, false)
  10103. : null;
  10104. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  10105. var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  10106. return viewGetCompleteNode(view);
  10107. }
  10108. /**
  10109. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  10110. *
  10111. * NOTES:
  10112. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  10113. *
  10114. * - We call applyOperation() on each SyncPoint passing three things:
  10115. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  10116. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  10117. * 3. A snapshot Node with cached server data, if we have it.
  10118. *
  10119. * - We concatenate all of the events returned by each SyncPoint and return the result.
  10120. */
  10121. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  10122. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  10123. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  10124. }
  10125. /**
  10126. * Recursive helper for applyOperationToSyncPoints_
  10127. */
  10128. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  10129. if (pathIsEmpty(operation.path)) {
  10130. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  10131. }
  10132. else {
  10133. var syncPoint = syncPointTree.get(newEmptyPath());
  10134. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10135. if (serverCache == null && syncPoint != null) {
  10136. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10137. }
  10138. var events = [];
  10139. var childName = pathGetFront(operation.path);
  10140. var childOperation = operation.operationForChild(childName);
  10141. var childTree = syncPointTree.children.get(childName);
  10142. if (childTree && childOperation) {
  10143. var childServerCache = serverCache
  10144. ? serverCache.getImmediateChild(childName)
  10145. : null;
  10146. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10147. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10148. }
  10149. if (syncPoint) {
  10150. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10151. }
  10152. return events;
  10153. }
  10154. }
  10155. /**
  10156. * Recursive helper for applyOperationToSyncPoints_
  10157. */
  10158. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  10159. var syncPoint = syncPointTree.get(newEmptyPath());
  10160. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10161. if (serverCache == null && syncPoint != null) {
  10162. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10163. }
  10164. var events = [];
  10165. syncPointTree.children.inorderTraversal(function (childName, childTree) {
  10166. var childServerCache = serverCache
  10167. ? serverCache.getImmediateChild(childName)
  10168. : null;
  10169. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10170. var childOperation = operation.operationForChild(childName);
  10171. if (childOperation) {
  10172. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10173. }
  10174. });
  10175. if (syncPoint) {
  10176. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10177. }
  10178. return events;
  10179. }
  10180. function syncTreeCreateListenerForView_(syncTree, view) {
  10181. var query = view.query;
  10182. var tag = syncTreeTagForQuery(syncTree, query);
  10183. return {
  10184. hashFn: function () {
  10185. var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  10186. return cache.hash();
  10187. },
  10188. onComplete: function (status) {
  10189. if (status === 'ok') {
  10190. if (tag) {
  10191. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  10192. }
  10193. else {
  10194. return syncTreeApplyListenComplete(syncTree, query._path);
  10195. }
  10196. }
  10197. else {
  10198. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  10199. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  10200. var error = errorForServerCode(status, query);
  10201. return syncTreeRemoveEventRegistration(syncTree, query,
  10202. /*eventRegistration*/ null, error);
  10203. }
  10204. }
  10205. };
  10206. }
  10207. /**
  10208. * Return the tag associated with the given query.
  10209. */
  10210. function syncTreeTagForQuery(syncTree, query) {
  10211. var queryKey = syncTreeMakeQueryKey_(query);
  10212. return syncTree.queryToTagMap.get(queryKey);
  10213. }
  10214. /**
  10215. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  10216. */
  10217. function syncTreeMakeQueryKey_(query) {
  10218. return query._path.toString() + '$' + query._queryIdentifier;
  10219. }
  10220. /**
  10221. * Return the query associated with the given tag, if we have one
  10222. */
  10223. function syncTreeQueryKeyForTag_(syncTree, tag) {
  10224. return syncTree.tagToQueryMap.get(tag);
  10225. }
  10226. /**
  10227. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  10228. */
  10229. function syncTreeParseQueryKey_(queryKey) {
  10230. var splitIndex = queryKey.indexOf('$');
  10231. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  10232. return {
  10233. queryId: queryKey.substr(splitIndex + 1),
  10234. path: new Path(queryKey.substr(0, splitIndex))
  10235. };
  10236. }
  10237. /**
  10238. * A helper method to apply tagged operations
  10239. */
  10240. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  10241. var syncPoint = syncTree.syncPointTree_.get(queryPath);
  10242. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  10243. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  10244. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  10245. }
  10246. /**
  10247. * This collapses multiple unfiltered views into a single view, since we only need a single
  10248. * listener for them.
  10249. */
  10250. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  10251. return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10252. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  10253. var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  10254. return [completeView];
  10255. }
  10256. else {
  10257. // No complete view here, flatten any deeper listens into an array
  10258. var views_1 = [];
  10259. if (maybeChildSyncPoint) {
  10260. views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
  10261. }
  10262. each(childMap, function (_key, childViews) {
  10263. views_1 = views_1.concat(childViews);
  10264. });
  10265. return views_1;
  10266. }
  10267. });
  10268. }
  10269. /**
  10270. * Normalizes a query to a query we send the server for listening
  10271. *
  10272. * @returns The normalized query
  10273. */
  10274. function syncTreeQueryForListening_(query) {
  10275. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  10276. // We treat queries that load all data as default queries
  10277. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  10278. // from Query
  10279. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  10280. }
  10281. else {
  10282. return query;
  10283. }
  10284. }
  10285. function syncTreeRemoveTags_(syncTree, queries) {
  10286. for (var j = 0; j < queries.length; ++j) {
  10287. var removedQuery = queries[j];
  10288. if (!removedQuery._queryParams.loadsAllData()) {
  10289. // We should have a tag for this
  10290. var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  10291. var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  10292. syncTree.queryToTagMap.delete(removedQueryKey);
  10293. syncTree.tagToQueryMap.delete(removedQueryTag);
  10294. }
  10295. }
  10296. }
  10297. /**
  10298. * Static accessor for query tags.
  10299. */
  10300. function syncTreeGetNextQueryTag_() {
  10301. return syncTreeNextQueryTag_++;
  10302. }
  10303. /**
  10304. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  10305. *
  10306. * @returns This method can return events to support synchronous data sources
  10307. */
  10308. function syncTreeSetupListener_(syncTree, query, view) {
  10309. var path = query._path;
  10310. var tag = syncTreeTagForQuery(syncTree, query);
  10311. var listener = syncTreeCreateListenerForView_(syncTree, view);
  10312. var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  10313. var subtree = syncTree.syncPointTree_.subtree(path);
  10314. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10315. // may need to shadow other listens as well.
  10316. if (tag) {
  10317. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10318. }
  10319. else {
  10320. // Shadow everything at or below this location, this is a default listener.
  10321. var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10322. if (!pathIsEmpty(relativePath) &&
  10323. maybeChildSyncPoint &&
  10324. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10325. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10326. }
  10327. else {
  10328. // No default listener here, flatten any deeper queries into an array
  10329. var queries_1 = [];
  10330. if (maybeChildSyncPoint) {
  10331. queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
  10332. }
  10333. each(childMap, function (_key, childQueries) {
  10334. queries_1 = queries_1.concat(childQueries);
  10335. });
  10336. return queries_1;
  10337. }
  10338. });
  10339. for (var i = 0; i < queriesToStop.length; ++i) {
  10340. var queryToStop = queriesToStop[i];
  10341. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10342. }
  10343. }
  10344. return events;
  10345. }
  10346. /**
  10347. * @license
  10348. * Copyright 2017 Google LLC
  10349. *
  10350. * Licensed under the Apache License, Version 2.0 (the "License");
  10351. * you may not use this file except in compliance with the License.
  10352. * You may obtain a copy of the License at
  10353. *
  10354. * http://www.apache.org/licenses/LICENSE-2.0
  10355. *
  10356. * Unless required by applicable law or agreed to in writing, software
  10357. * distributed under the License is distributed on an "AS IS" BASIS,
  10358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10359. * See the License for the specific language governing permissions and
  10360. * limitations under the License.
  10361. */
  10362. var ExistingValueProvider = /** @class */ (function () {
  10363. function ExistingValueProvider(node_) {
  10364. this.node_ = node_;
  10365. }
  10366. ExistingValueProvider.prototype.getImmediateChild = function (childName) {
  10367. var child = this.node_.getImmediateChild(childName);
  10368. return new ExistingValueProvider(child);
  10369. };
  10370. ExistingValueProvider.prototype.node = function () {
  10371. return this.node_;
  10372. };
  10373. return ExistingValueProvider;
  10374. }());
  10375. var DeferredValueProvider = /** @class */ (function () {
  10376. function DeferredValueProvider(syncTree, path) {
  10377. this.syncTree_ = syncTree;
  10378. this.path_ = path;
  10379. }
  10380. DeferredValueProvider.prototype.getImmediateChild = function (childName) {
  10381. var childPath = pathChild(this.path_, childName);
  10382. return new DeferredValueProvider(this.syncTree_, childPath);
  10383. };
  10384. DeferredValueProvider.prototype.node = function () {
  10385. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10386. };
  10387. return DeferredValueProvider;
  10388. }());
  10389. /**
  10390. * Generate placeholders for deferred values.
  10391. */
  10392. var generateWithValues = function (values) {
  10393. values = values || {};
  10394. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10395. return values;
  10396. };
  10397. /**
  10398. * Value to use when firing local events. When writing server values, fire
  10399. * local events with an approximate value, otherwise return value as-is.
  10400. */
  10401. var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10402. if (!value || typeof value !== 'object') {
  10403. return value;
  10404. }
  10405. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10406. if (typeof value['.sv'] === 'string') {
  10407. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10408. }
  10409. else if (typeof value['.sv'] === 'object') {
  10410. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10411. }
  10412. else {
  10413. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10414. }
  10415. };
  10416. var resolveScalarDeferredValue = function (op, existing, serverValues) {
  10417. switch (op) {
  10418. case 'timestamp':
  10419. return serverValues['timestamp'];
  10420. default:
  10421. util.assert(false, 'Unexpected server value: ' + op);
  10422. }
  10423. };
  10424. var resolveComplexDeferredValue = function (op, existing, unused) {
  10425. if (!op.hasOwnProperty('increment')) {
  10426. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10427. }
  10428. var delta = op['increment'];
  10429. if (typeof delta !== 'number') {
  10430. util.assert(false, 'Unexpected increment value: ' + delta);
  10431. }
  10432. var existingNode = existing.node();
  10433. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10434. // Incrementing a non-number sets the value to the incremented amount
  10435. if (!existingNode.isLeafNode()) {
  10436. return delta;
  10437. }
  10438. var leaf = existingNode;
  10439. var existingVal = leaf.getValue();
  10440. if (typeof existingVal !== 'number') {
  10441. return delta;
  10442. }
  10443. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10444. return existingVal + delta;
  10445. };
  10446. /**
  10447. * Recursively replace all deferred values and priorities in the tree with the
  10448. * specified generated replacement values.
  10449. * @param path - path to which write is relative
  10450. * @param node - new data written at path
  10451. * @param syncTree - current data
  10452. */
  10453. var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10454. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10455. };
  10456. /**
  10457. * Recursively replace all deferred values and priorities in the node with the
  10458. * specified generated replacement values. If there are no server values in the node,
  10459. * it'll be returned as-is.
  10460. */
  10461. var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10462. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10463. };
  10464. function resolveDeferredValue(node, existingVal, serverValues) {
  10465. var rawPri = node.getPriority().val();
  10466. var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10467. var newNode;
  10468. if (node.isLeafNode()) {
  10469. var leafNode = node;
  10470. var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10471. if (value !== leafNode.getValue() ||
  10472. priority !== leafNode.getPriority().val()) {
  10473. return new LeafNode(value, nodeFromJSON(priority));
  10474. }
  10475. else {
  10476. return node;
  10477. }
  10478. }
  10479. else {
  10480. var childrenNode = node;
  10481. newNode = childrenNode;
  10482. if (priority !== childrenNode.getPriority().val()) {
  10483. newNode = newNode.updatePriority(new LeafNode(priority));
  10484. }
  10485. childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  10486. var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10487. if (newChildNode !== childNode) {
  10488. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10489. }
  10490. });
  10491. return newNode;
  10492. }
  10493. }
  10494. /**
  10495. * @license
  10496. * Copyright 2017 Google LLC
  10497. *
  10498. * Licensed under the Apache License, Version 2.0 (the "License");
  10499. * you may not use this file except in compliance with the License.
  10500. * You may obtain a copy of the License at
  10501. *
  10502. * http://www.apache.org/licenses/LICENSE-2.0
  10503. *
  10504. * Unless required by applicable law or agreed to in writing, software
  10505. * distributed under the License is distributed on an "AS IS" BASIS,
  10506. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10507. * See the License for the specific language governing permissions and
  10508. * limitations under the License.
  10509. */
  10510. /**
  10511. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10512. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10513. * children.
  10514. */
  10515. var Tree = /** @class */ (function () {
  10516. /**
  10517. * @param name - Optional name of the node.
  10518. * @param parent - Optional parent node.
  10519. * @param node - Optional node to wrap.
  10520. */
  10521. function Tree(name, parent, node) {
  10522. if (name === void 0) { name = ''; }
  10523. if (parent === void 0) { parent = null; }
  10524. if (node === void 0) { node = { children: {}, childCount: 0 }; }
  10525. this.name = name;
  10526. this.parent = parent;
  10527. this.node = node;
  10528. }
  10529. return Tree;
  10530. }());
  10531. /**
  10532. * Returns a sub-Tree for the given path.
  10533. *
  10534. * @param pathObj - Path to look up.
  10535. * @returns Tree for path.
  10536. */
  10537. function treeSubTree(tree, pathObj) {
  10538. // TODO: Require pathObj to be Path?
  10539. var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10540. var child = tree, next = pathGetFront(path);
  10541. while (next !== null) {
  10542. var childNode = util.safeGet(child.node.children, next) || {
  10543. children: {},
  10544. childCount: 0
  10545. };
  10546. child = new Tree(next, child, childNode);
  10547. path = pathPopFront(path);
  10548. next = pathGetFront(path);
  10549. }
  10550. return child;
  10551. }
  10552. /**
  10553. * Returns the data associated with this tree node.
  10554. *
  10555. * @returns The data or null if no data exists.
  10556. */
  10557. function treeGetValue(tree) {
  10558. return tree.node.value;
  10559. }
  10560. /**
  10561. * Sets data to this tree node.
  10562. *
  10563. * @param value - Value to set.
  10564. */
  10565. function treeSetValue(tree, value) {
  10566. tree.node.value = value;
  10567. treeUpdateParents(tree);
  10568. }
  10569. /**
  10570. * @returns Whether the tree has any children.
  10571. */
  10572. function treeHasChildren(tree) {
  10573. return tree.node.childCount > 0;
  10574. }
  10575. /**
  10576. * @returns Whethe rthe tree is empty (no value or children).
  10577. */
  10578. function treeIsEmpty(tree) {
  10579. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10580. }
  10581. /**
  10582. * Calls action for each child of this tree node.
  10583. *
  10584. * @param action - Action to be called for each child.
  10585. */
  10586. function treeForEachChild(tree, action) {
  10587. each(tree.node.children, function (child, childTree) {
  10588. action(new Tree(child, tree, childTree));
  10589. });
  10590. }
  10591. /**
  10592. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10593. *
  10594. * @param action - Action to be called for each child.
  10595. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10596. * false.
  10597. * @param childrenFirst - Whether to call action on children before calling it on
  10598. * parent.
  10599. */
  10600. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10601. if (includeSelf && !childrenFirst) {
  10602. action(tree);
  10603. }
  10604. treeForEachChild(tree, function (child) {
  10605. treeForEachDescendant(child, action, true, childrenFirst);
  10606. });
  10607. if (includeSelf && childrenFirst) {
  10608. action(tree);
  10609. }
  10610. }
  10611. /**
  10612. * Calls action on each ancestor node.
  10613. *
  10614. * @param action - Action to be called on each parent; return
  10615. * true to abort.
  10616. * @param includeSelf - Whether to call action on this node as well.
  10617. * @returns true if the action callback returned true.
  10618. */
  10619. function treeForEachAncestor(tree, action, includeSelf) {
  10620. var node = includeSelf ? tree : tree.parent;
  10621. while (node !== null) {
  10622. if (action(node)) {
  10623. return true;
  10624. }
  10625. node = node.parent;
  10626. }
  10627. return false;
  10628. }
  10629. /**
  10630. * @returns The path of this tree node, as a Path.
  10631. */
  10632. function treeGetPath(tree) {
  10633. return new Path(tree.parent === null
  10634. ? tree.name
  10635. : treeGetPath(tree.parent) + '/' + tree.name);
  10636. }
  10637. /**
  10638. * Adds or removes this child from its parent based on whether it's empty or not.
  10639. */
  10640. function treeUpdateParents(tree) {
  10641. if (tree.parent !== null) {
  10642. treeUpdateChild(tree.parent, tree.name, tree);
  10643. }
  10644. }
  10645. /**
  10646. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10647. *
  10648. * @param childName - The name of the child to update.
  10649. * @param child - The child to update.
  10650. */
  10651. function treeUpdateChild(tree, childName, child) {
  10652. var childEmpty = treeIsEmpty(child);
  10653. var childExists = util.contains(tree.node.children, childName);
  10654. if (childEmpty && childExists) {
  10655. delete tree.node.children[childName];
  10656. tree.node.childCount--;
  10657. treeUpdateParents(tree);
  10658. }
  10659. else if (!childEmpty && !childExists) {
  10660. tree.node.children[childName] = child.node;
  10661. tree.node.childCount++;
  10662. treeUpdateParents(tree);
  10663. }
  10664. }
  10665. /**
  10666. * @license
  10667. * Copyright 2017 Google LLC
  10668. *
  10669. * Licensed under the Apache License, Version 2.0 (the "License");
  10670. * you may not use this file except in compliance with the License.
  10671. * You may obtain a copy of the License at
  10672. *
  10673. * http://www.apache.org/licenses/LICENSE-2.0
  10674. *
  10675. * Unless required by applicable law or agreed to in writing, software
  10676. * distributed under the License is distributed on an "AS IS" BASIS,
  10677. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10678. * See the License for the specific language governing permissions and
  10679. * limitations under the License.
  10680. */
  10681. /**
  10682. * True for invalid Firebase keys
  10683. */
  10684. var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10685. /**
  10686. * True for invalid Firebase paths.
  10687. * Allows '/' in paths.
  10688. */
  10689. var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10690. /**
  10691. * Maximum number of characters to allow in leaf value
  10692. */
  10693. var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10694. var isValidKey = function (key) {
  10695. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10696. };
  10697. var isValidPathString = function (pathString) {
  10698. return (typeof pathString === 'string' &&
  10699. pathString.length !== 0 &&
  10700. !INVALID_PATH_REGEX_.test(pathString));
  10701. };
  10702. var isValidRootPathString = function (pathString) {
  10703. if (pathString) {
  10704. // Allow '/.info/' at the beginning.
  10705. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10706. }
  10707. return isValidPathString(pathString);
  10708. };
  10709. var isValidPriority = function (priority) {
  10710. return (priority === null ||
  10711. typeof priority === 'string' ||
  10712. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10713. (priority &&
  10714. typeof priority === 'object' &&
  10715. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10716. util.contains(priority, '.sv')));
  10717. };
  10718. /**
  10719. * Pre-validate a datum passed as an argument to Firebase function.
  10720. */
  10721. var validateFirebaseDataArg = function (fnName, value, path, optional) {
  10722. if (optional && value === undefined) {
  10723. return;
  10724. }
  10725. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  10726. };
  10727. /**
  10728. * Validate a data object client-side before sending to server.
  10729. */
  10730. var validateFirebaseData = function (errorPrefix, data, path_) {
  10731. var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10732. if (data === undefined) {
  10733. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10734. }
  10735. if (typeof data === 'function') {
  10736. throw new Error(errorPrefix +
  10737. 'contains a function ' +
  10738. validationPathToErrorString(path) +
  10739. ' with contents = ' +
  10740. data.toString());
  10741. }
  10742. if (isInvalidJSONNumber(data)) {
  10743. throw new Error(errorPrefix +
  10744. 'contains ' +
  10745. data.toString() +
  10746. ' ' +
  10747. validationPathToErrorString(path));
  10748. }
  10749. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10750. if (typeof data === 'string' &&
  10751. data.length > MAX_LEAF_SIZE_ / 3 &&
  10752. util.stringLength(data) > MAX_LEAF_SIZE_) {
  10753. throw new Error(errorPrefix +
  10754. 'contains a string greater than ' +
  10755. MAX_LEAF_SIZE_ +
  10756. ' utf8 bytes ' +
  10757. validationPathToErrorString(path) +
  10758. " ('" +
  10759. data.substring(0, 50) +
  10760. "...')");
  10761. }
  10762. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10763. // to save extra walking of large objects.
  10764. if (data && typeof data === 'object') {
  10765. var hasDotValue_1 = false;
  10766. var hasActualChild_1 = false;
  10767. each(data, function (key, value) {
  10768. if (key === '.value') {
  10769. hasDotValue_1 = true;
  10770. }
  10771. else if (key !== '.priority' && key !== '.sv') {
  10772. hasActualChild_1 = true;
  10773. if (!isValidKey(key)) {
  10774. throw new Error(errorPrefix +
  10775. ' contains an invalid key (' +
  10776. key +
  10777. ') ' +
  10778. validationPathToErrorString(path) +
  10779. '. Keys must be non-empty strings ' +
  10780. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10781. }
  10782. }
  10783. validationPathPush(path, key);
  10784. validateFirebaseData(errorPrefix, value, path);
  10785. validationPathPop(path);
  10786. });
  10787. if (hasDotValue_1 && hasActualChild_1) {
  10788. throw new Error(errorPrefix +
  10789. ' contains ".value" child ' +
  10790. validationPathToErrorString(path) +
  10791. ' in addition to actual children.');
  10792. }
  10793. }
  10794. };
  10795. /**
  10796. * Pre-validate paths passed in the firebase function.
  10797. */
  10798. var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10799. var i, curPath;
  10800. for (i = 0; i < mergePaths.length; i++) {
  10801. curPath = mergePaths[i];
  10802. var keys = pathSlice(curPath);
  10803. for (var j = 0; j < keys.length; j++) {
  10804. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10805. else if (!isValidKey(keys[j])) {
  10806. throw new Error(errorPrefix +
  10807. 'contains an invalid key (' +
  10808. keys[j] +
  10809. ') in path ' +
  10810. curPath.toString() +
  10811. '. Keys must be non-empty strings ' +
  10812. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10813. }
  10814. }
  10815. }
  10816. // Check that update keys are not descendants of each other.
  10817. // We rely on the property that sorting guarantees that ancestors come
  10818. // right before descendants.
  10819. mergePaths.sort(pathCompare);
  10820. var prevPath = null;
  10821. for (i = 0; i < mergePaths.length; i++) {
  10822. curPath = mergePaths[i];
  10823. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10824. throw new Error(errorPrefix +
  10825. 'contains a path ' +
  10826. prevPath.toString() +
  10827. ' that is ancestor of another path ' +
  10828. curPath.toString());
  10829. }
  10830. prevPath = curPath;
  10831. }
  10832. };
  10833. /**
  10834. * pre-validate an object passed as an argument to firebase function (
  10835. * must be an object - e.g. for firebase.update()).
  10836. */
  10837. var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10838. if (optional && data === undefined) {
  10839. return;
  10840. }
  10841. var errorPrefix = util.errorPrefix(fnName, 'values');
  10842. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10843. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  10844. }
  10845. var mergePaths = [];
  10846. each(data, function (key, value) {
  10847. var curPath = new Path(key);
  10848. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  10849. if (pathGetBack(curPath) === '.priority') {
  10850. if (!isValidPriority(value)) {
  10851. throw new Error(errorPrefix +
  10852. "contains an invalid value for '" +
  10853. curPath.toString() +
  10854. "', which must be a valid " +
  10855. 'Firebase priority (a string, finite number, server value, or null).');
  10856. }
  10857. }
  10858. mergePaths.push(curPath);
  10859. });
  10860. validateFirebaseMergePaths(errorPrefix, mergePaths);
  10861. };
  10862. var validatePriority = function (fnName, priority, optional) {
  10863. if (optional && priority === undefined) {
  10864. return;
  10865. }
  10866. if (isInvalidJSONNumber(priority)) {
  10867. throw new Error(util.errorPrefix(fnName, 'priority') +
  10868. 'is ' +
  10869. priority.toString() +
  10870. ', but must be a valid Firebase priority (a string, finite number, ' +
  10871. 'server value, or null).');
  10872. }
  10873. // Special case to allow importing data with a .sv.
  10874. if (!isValidPriority(priority)) {
  10875. throw new Error(util.errorPrefix(fnName, 'priority') +
  10876. 'must be a valid Firebase priority ' +
  10877. '(a string, finite number, server value, or null).');
  10878. }
  10879. };
  10880. var validateKey = function (fnName, argumentName, key, optional) {
  10881. if (optional && key === undefined) {
  10882. return;
  10883. }
  10884. if (!isValidKey(key)) {
  10885. throw new Error(util.errorPrefix(fnName, argumentName) +
  10886. 'was an invalid key = "' +
  10887. key +
  10888. '". Firebase keys must be non-empty strings and ' +
  10889. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10890. }
  10891. };
  10892. /**
  10893. * @internal
  10894. */
  10895. var validatePathString = function (fnName, argumentName, pathString, optional) {
  10896. if (optional && pathString === undefined) {
  10897. return;
  10898. }
  10899. if (!isValidPathString(pathString)) {
  10900. throw new Error(util.errorPrefix(fnName, argumentName) +
  10901. 'was an invalid path = "' +
  10902. pathString +
  10903. '". Paths must be non-empty strings and ' +
  10904. 'can\'t contain ".", "#", "$", "[", or "]"');
  10905. }
  10906. };
  10907. var validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10908. if (pathString) {
  10909. // Allow '/.info/' at the beginning.
  10910. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10911. }
  10912. validatePathString(fnName, argumentName, pathString, optional);
  10913. };
  10914. /**
  10915. * @internal
  10916. */
  10917. var validateWritablePath = function (fnName, path) {
  10918. if (pathGetFront(path) === '.info') {
  10919. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10920. }
  10921. };
  10922. var validateUrl = function (fnName, parsedUrl) {
  10923. // TODO = Validate server better.
  10924. var pathString = parsedUrl.path.toString();
  10925. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10926. parsedUrl.repoInfo.host.length === 0 ||
  10927. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10928. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10929. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10930. throw new Error(util.errorPrefix(fnName, 'url') +
  10931. 'must be a valid firebase URL and ' +
  10932. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10933. }
  10934. };
  10935. /**
  10936. * @license
  10937. * Copyright 2017 Google LLC
  10938. *
  10939. * Licensed under the Apache License, Version 2.0 (the "License");
  10940. * you may not use this file except in compliance with the License.
  10941. * You may obtain a copy of the License at
  10942. *
  10943. * http://www.apache.org/licenses/LICENSE-2.0
  10944. *
  10945. * Unless required by applicable law or agreed to in writing, software
  10946. * distributed under the License is distributed on an "AS IS" BASIS,
  10947. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10948. * See the License for the specific language governing permissions and
  10949. * limitations under the License.
  10950. */
  10951. /**
  10952. * The event queue serves a few purposes:
  10953. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10954. * events being queued.
  10955. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10956. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10957. * left off, ensuring that the events are still raised synchronously and in order.
  10958. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10959. * events are raised synchronously.
  10960. *
  10961. * NOTE: This can all go away if/when we move to async events.
  10962. *
  10963. */
  10964. var EventQueue = /** @class */ (function () {
  10965. function EventQueue() {
  10966. this.eventLists_ = [];
  10967. /**
  10968. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10969. */
  10970. this.recursionDepth_ = 0;
  10971. }
  10972. return EventQueue;
  10973. }());
  10974. /**
  10975. * @param eventDataList - The new events to queue.
  10976. */
  10977. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10978. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10979. var currList = null;
  10980. for (var i = 0; i < eventDataList.length; i++) {
  10981. var data = eventDataList[i];
  10982. var path = data.getPath();
  10983. if (currList !== null && !pathEquals(path, currList.path)) {
  10984. eventQueue.eventLists_.push(currList);
  10985. currList = null;
  10986. }
  10987. if (currList === null) {
  10988. currList = { events: [], path: path };
  10989. }
  10990. currList.events.push(data);
  10991. }
  10992. if (currList) {
  10993. eventQueue.eventLists_.push(currList);
  10994. }
  10995. }
  10996. /**
  10997. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10998. * for the specified path.
  10999. *
  11000. * It is assumed that the new events are all for the specified path.
  11001. *
  11002. * @param path - The path to raise events for.
  11003. * @param eventDataList - The new events to raise.
  11004. */
  11005. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  11006. eventQueueQueueEvents(eventQueue, eventDataList);
  11007. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11008. return pathEquals(eventPath, path);
  11009. });
  11010. }
  11011. /**
  11012. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  11013. * locations related to the specified change path (i.e. all ancestors and descendants).
  11014. *
  11015. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  11016. *
  11017. * @param changedPath - The path to raise events for.
  11018. * @param eventDataList - The events to raise
  11019. */
  11020. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  11021. eventQueueQueueEvents(eventQueue, eventDataList);
  11022. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11023. return pathContains(eventPath, changedPath) ||
  11024. pathContains(changedPath, eventPath);
  11025. });
  11026. }
  11027. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  11028. eventQueue.recursionDepth_++;
  11029. var sentAll = true;
  11030. for (var i = 0; i < eventQueue.eventLists_.length; i++) {
  11031. var eventList = eventQueue.eventLists_[i];
  11032. if (eventList) {
  11033. var eventPath = eventList.path;
  11034. if (predicate(eventPath)) {
  11035. eventListRaise(eventQueue.eventLists_[i]);
  11036. eventQueue.eventLists_[i] = null;
  11037. }
  11038. else {
  11039. sentAll = false;
  11040. }
  11041. }
  11042. }
  11043. if (sentAll) {
  11044. eventQueue.eventLists_ = [];
  11045. }
  11046. eventQueue.recursionDepth_--;
  11047. }
  11048. /**
  11049. * Iterates through the list and raises each event
  11050. */
  11051. function eventListRaise(eventList) {
  11052. for (var i = 0; i < eventList.events.length; i++) {
  11053. var eventData = eventList.events[i];
  11054. if (eventData !== null) {
  11055. eventList.events[i] = null;
  11056. var eventFn = eventData.getEventRunner();
  11057. if (logger) {
  11058. log('event: ' + eventData.toString());
  11059. }
  11060. exceptionGuard(eventFn);
  11061. }
  11062. }
  11063. }
  11064. /**
  11065. * @license
  11066. * Copyright 2017 Google LLC
  11067. *
  11068. * Licensed under the Apache License, Version 2.0 (the "License");
  11069. * you may not use this file except in compliance with the License.
  11070. * You may obtain a copy of the License at
  11071. *
  11072. * http://www.apache.org/licenses/LICENSE-2.0
  11073. *
  11074. * Unless required by applicable law or agreed to in writing, software
  11075. * distributed under the License is distributed on an "AS IS" BASIS,
  11076. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11077. * See the License for the specific language governing permissions and
  11078. * limitations under the License.
  11079. */
  11080. var INTERRUPT_REASON = 'repo_interrupt';
  11081. /**
  11082. * If a transaction does not succeed after 25 retries, we abort it. Among other
  11083. * things this ensure that if there's ever a bug causing a mismatch between
  11084. * client / server hashes for some data, we won't retry indefinitely.
  11085. */
  11086. var MAX_TRANSACTION_RETRIES = 25;
  11087. /**
  11088. * A connection to a single data repository.
  11089. */
  11090. var Repo = /** @class */ (function () {
  11091. function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  11092. this.repoInfo_ = repoInfo_;
  11093. this.forceRestClient_ = forceRestClient_;
  11094. this.authTokenProvider_ = authTokenProvider_;
  11095. this.appCheckProvider_ = appCheckProvider_;
  11096. this.dataUpdateCount = 0;
  11097. this.statsListener_ = null;
  11098. this.eventQueue_ = new EventQueue();
  11099. this.nextWriteId_ = 1;
  11100. this.interceptServerDataCallback_ = null;
  11101. /** A list of data pieces and paths to be set when this client disconnects. */
  11102. this.onDisconnect_ = newSparseSnapshotTree();
  11103. /** Stores queues of outstanding transactions for Firebase locations. */
  11104. this.transactionQueueTree_ = new Tree();
  11105. // TODO: This should be @private but it's used by test_access.js and internal.js
  11106. this.persistentConnection_ = null;
  11107. // This key is intentionally not updated if RepoInfo is later changed or replaced
  11108. this.key = this.repoInfo_.toURLString();
  11109. }
  11110. /**
  11111. * @returns The URL corresponding to the root of this Firebase.
  11112. */
  11113. Repo.prototype.toString = function () {
  11114. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  11115. };
  11116. return Repo;
  11117. }());
  11118. function repoStart(repo, appId, authOverride) {
  11119. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  11120. if (repo.forceRestClient_ || beingCrawled()) {
  11121. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
  11122. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11123. }, repo.authTokenProvider_, repo.appCheckProvider_);
  11124. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  11125. setTimeout(function () { return repoOnConnectStatus(repo, /* connectStatus= */ true); }, 0);
  11126. }
  11127. else {
  11128. // Validate authOverride
  11129. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  11130. if (typeof authOverride !== 'object') {
  11131. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  11132. }
  11133. try {
  11134. util.stringify(authOverride);
  11135. }
  11136. catch (e) {
  11137. throw new Error('Invalid authOverride provided: ' + e);
  11138. }
  11139. }
  11140. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
  11141. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11142. }, function (connectStatus) {
  11143. repoOnConnectStatus(repo, connectStatus);
  11144. }, function (updates) {
  11145. repoOnServerInfoUpdate(repo, updates);
  11146. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  11147. repo.server_ = repo.persistentConnection_;
  11148. }
  11149. repo.authTokenProvider_.addTokenChangeListener(function (token) {
  11150. repo.server_.refreshAuthToken(token);
  11151. });
  11152. repo.appCheckProvider_.addTokenChangeListener(function (result) {
  11153. repo.server_.refreshAppCheckToken(result.token);
  11154. });
  11155. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  11156. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  11157. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
  11158. // Used for .info.
  11159. repo.infoData_ = new SnapshotHolder();
  11160. repo.infoSyncTree_ = new SyncTree({
  11161. startListening: function (query, tag, currentHashFn, onComplete) {
  11162. var infoEvents = [];
  11163. var node = repo.infoData_.getNode(query._path);
  11164. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  11165. // on initial data...
  11166. if (!node.isEmpty()) {
  11167. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  11168. setTimeout(function () {
  11169. onComplete('ok');
  11170. }, 0);
  11171. }
  11172. return infoEvents;
  11173. },
  11174. stopListening: function () { }
  11175. });
  11176. repoUpdateInfo(repo, 'connected', false);
  11177. repo.serverSyncTree_ = new SyncTree({
  11178. startListening: function (query, tag, currentHashFn, onComplete) {
  11179. repo.server_.listen(query, currentHashFn, tag, function (status, data) {
  11180. var events = onComplete(status, data);
  11181. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11182. });
  11183. // No synchronous events for network-backed sync trees
  11184. return [];
  11185. },
  11186. stopListening: function (query, tag) {
  11187. repo.server_.unlisten(query, tag);
  11188. }
  11189. });
  11190. }
  11191. /**
  11192. * @returns The time in milliseconds, taking the server offset into account if we have one.
  11193. */
  11194. function repoServerTime(repo) {
  11195. var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  11196. var offset = offsetNode.val() || 0;
  11197. return new Date().getTime() + offset;
  11198. }
  11199. /**
  11200. * Generate ServerValues using some variables from the repo object.
  11201. */
  11202. function repoGenerateServerValues(repo) {
  11203. return generateWithValues({
  11204. timestamp: repoServerTime(repo)
  11205. });
  11206. }
  11207. /**
  11208. * Called by realtime when we get new messages from the server.
  11209. */
  11210. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  11211. // For testing.
  11212. repo.dataUpdateCount++;
  11213. var path = new Path(pathString);
  11214. data = repo.interceptServerDataCallback_
  11215. ? repo.interceptServerDataCallback_(pathString, data)
  11216. : data;
  11217. var events = [];
  11218. if (tag) {
  11219. if (isMerge) {
  11220. var taggedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  11221. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  11222. }
  11223. else {
  11224. var taggedSnap = nodeFromJSON(data);
  11225. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  11226. }
  11227. }
  11228. else if (isMerge) {
  11229. var changedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  11230. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  11231. }
  11232. else {
  11233. var snap = nodeFromJSON(data);
  11234. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  11235. }
  11236. var affectedPath = path;
  11237. if (events.length > 0) {
  11238. // Since we have a listener outstanding for each transaction, receiving any events
  11239. // is a proxy for some change having occurred.
  11240. affectedPath = repoRerunTransactions(repo, path);
  11241. }
  11242. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  11243. }
  11244. function repoOnConnectStatus(repo, connectStatus) {
  11245. repoUpdateInfo(repo, 'connected', connectStatus);
  11246. if (connectStatus === false) {
  11247. repoRunOnDisconnectEvents(repo);
  11248. }
  11249. }
  11250. function repoOnServerInfoUpdate(repo, updates) {
  11251. each(updates, function (key, value) {
  11252. repoUpdateInfo(repo, key, value);
  11253. });
  11254. }
  11255. function repoUpdateInfo(repo, pathString, value) {
  11256. var path = new Path('/.info/' + pathString);
  11257. var newNode = nodeFromJSON(value);
  11258. repo.infoData_.updateSnapshot(path, newNode);
  11259. var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  11260. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11261. }
  11262. function repoGetNextWriteId(repo) {
  11263. return repo.nextWriteId_++;
  11264. }
  11265. /**
  11266. * The purpose of `getValue` is to return the latest known value
  11267. * satisfying `query`.
  11268. *
  11269. * This method will first check for in-memory cached values
  11270. * belonging to active listeners. If they are found, such values
  11271. * are considered to be the most up-to-date.
  11272. *
  11273. * If the client is not connected, this method will wait until the
  11274. * repo has established a connection and then request the value for `query`.
  11275. * If the client is not able to retrieve the query result for another reason,
  11276. * it reports an error.
  11277. *
  11278. * @param query - The query to surface a value for.
  11279. */
  11280. function repoGetValue(repo, query, eventRegistration) {
  11281. // Only active queries are cached. There is no persisted cache.
  11282. var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  11283. if (cached != null) {
  11284. return Promise.resolve(cached);
  11285. }
  11286. return repo.server_.get(query).then(function (payload) {
  11287. var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  11288. /**
  11289. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  11290. * Add an event registration,
  11291. * Update data at the path,
  11292. * Raise any events,
  11293. * Cleanup the SyncTree
  11294. */
  11295. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  11296. var events;
  11297. if (query._queryParams.loadsAllData()) {
  11298. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  11299. }
  11300. else {
  11301. var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  11302. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  11303. }
  11304. /*
  11305. * We need to raise events in the scenario where `get()` is called at a parent path, and
  11306. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  11307. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  11308. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  11309. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  11310. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  11311. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  11312. * ensure the corresponding child events will get fired.
  11313. */
  11314. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11315. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  11316. return node;
  11317. }, function (err) {
  11318. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  11319. return Promise.reject(new Error(err));
  11320. });
  11321. }
  11322. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  11323. repoLog(repo, 'set', {
  11324. path: path.toString(),
  11325. value: newVal,
  11326. priority: newPriority
  11327. });
  11328. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11329. // (b) store unresolved paths on JSON parse
  11330. var serverValues = repoGenerateServerValues(repo);
  11331. var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11332. var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11333. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11334. var writeId = repoGetNextWriteId(repo);
  11335. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11336. eventQueueQueueEvents(repo.eventQueue_, events);
  11337. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {
  11338. var success = status === 'ok';
  11339. if (!success) {
  11340. warn('set at ' + path + ' failed: ' + status);
  11341. }
  11342. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11343. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11344. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11345. });
  11346. var affectedPath = repoAbortTransactions(repo, path);
  11347. repoRerunTransactions(repo, affectedPath);
  11348. // We queued the events above, so just flush the queue here
  11349. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11350. }
  11351. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11352. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11353. // Start with our existing data and merge each child into it.
  11354. var empty = true;
  11355. var serverValues = repoGenerateServerValues(repo);
  11356. var changedChildren = {};
  11357. each(childrenToMerge, function (changedKey, changedValue) {
  11358. empty = false;
  11359. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11360. });
  11361. if (!empty) {
  11362. var writeId_1 = repoGetNextWriteId(repo);
  11363. var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
  11364. eventQueueQueueEvents(repo.eventQueue_, events);
  11365. repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
  11366. var success = status === 'ok';
  11367. if (!success) {
  11368. warn('update at ' + path + ' failed: ' + status);
  11369. }
  11370. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
  11371. var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11372. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11373. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11374. });
  11375. each(childrenToMerge, function (changedPath) {
  11376. var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11377. repoRerunTransactions(repo, affectedPath);
  11378. });
  11379. // We queued the events above, so just flush the queue here
  11380. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11381. }
  11382. else {
  11383. log("update() called with empty data. Don't do anything.");
  11384. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11385. }
  11386. }
  11387. /**
  11388. * Applies all of the changes stored up in the onDisconnect_ tree.
  11389. */
  11390. function repoRunOnDisconnectEvents(repo) {
  11391. repoLog(repo, 'onDisconnectEvents');
  11392. var serverValues = repoGenerateServerValues(repo);
  11393. var resolvedOnDisconnectTree = newSparseSnapshotTree();
  11394. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
  11395. var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11396. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11397. });
  11398. var events = [];
  11399. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
  11400. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11401. var affectedPath = repoAbortTransactions(repo, path);
  11402. repoRerunTransactions(repo, affectedPath);
  11403. });
  11404. repo.onDisconnect_ = newSparseSnapshotTree();
  11405. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11406. }
  11407. function repoOnDisconnectCancel(repo, path, onComplete) {
  11408. repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
  11409. if (status === 'ok') {
  11410. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11411. }
  11412. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11413. });
  11414. }
  11415. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11416. var newNode = nodeFromJSON(value);
  11417. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11418. if (status === 'ok') {
  11419. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11420. }
  11421. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11422. });
  11423. }
  11424. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11425. var newNode = nodeFromJSON(value, priority);
  11426. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11427. if (status === 'ok') {
  11428. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11429. }
  11430. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11431. });
  11432. }
  11433. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11434. if (util.isEmpty(childrenToMerge)) {
  11435. log("onDisconnect().update() called with empty data. Don't do anything.");
  11436. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11437. return;
  11438. }
  11439. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
  11440. if (status === 'ok') {
  11441. each(childrenToMerge, function (childName, childNode) {
  11442. var newChildNode = nodeFromJSON(childNode);
  11443. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11444. });
  11445. }
  11446. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11447. });
  11448. }
  11449. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11450. var events;
  11451. if (pathGetFront(query._path) === '.info') {
  11452. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11453. }
  11454. else {
  11455. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11456. }
  11457. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11458. }
  11459. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11460. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11461. // a little bit by handling the return values anyways.
  11462. var events;
  11463. if (pathGetFront(query._path) === '.info') {
  11464. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11465. }
  11466. else {
  11467. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11468. }
  11469. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11470. }
  11471. function repoInterrupt(repo) {
  11472. if (repo.persistentConnection_) {
  11473. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11474. }
  11475. }
  11476. function repoResume(repo) {
  11477. if (repo.persistentConnection_) {
  11478. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11479. }
  11480. }
  11481. function repoLog(repo) {
  11482. var varArgs = [];
  11483. for (var _i = 1; _i < arguments.length; _i++) {
  11484. varArgs[_i - 1] = arguments[_i];
  11485. }
  11486. var prefix = '';
  11487. if (repo.persistentConnection_) {
  11488. prefix = repo.persistentConnection_.id + ':';
  11489. }
  11490. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  11491. }
  11492. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11493. if (callback) {
  11494. exceptionGuard(function () {
  11495. if (status === 'ok') {
  11496. callback(null);
  11497. }
  11498. else {
  11499. var code = (status || 'error').toUpperCase();
  11500. var message = code;
  11501. if (errorReason) {
  11502. message += ': ' + errorReason;
  11503. }
  11504. var error = new Error(message);
  11505. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11506. error.code = code;
  11507. callback(error);
  11508. }
  11509. });
  11510. }
  11511. }
  11512. /**
  11513. * Creates a new transaction, adds it to the transactions we're tracking, and
  11514. * sends it to the server if possible.
  11515. *
  11516. * @param path - Path at which to do transaction.
  11517. * @param transactionUpdate - Update callback.
  11518. * @param onComplete - Completion callback.
  11519. * @param unwatcher - Function that will be called when the transaction no longer
  11520. * need data updates for `path`.
  11521. * @param applyLocally - Whether or not to make intermediate results visible
  11522. */
  11523. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11524. repoLog(repo, 'transaction on ' + path);
  11525. // Initialize transaction.
  11526. var transaction = {
  11527. path: path,
  11528. update: transactionUpdate,
  11529. onComplete: onComplete,
  11530. // One of TransactionStatus enums.
  11531. status: null,
  11532. // Used when combining transactions at different locations to figure out
  11533. // which one goes first.
  11534. order: LUIDGenerator(),
  11535. // Whether to raise local events for this transaction.
  11536. applyLocally: applyLocally,
  11537. // Count of how many times we've retried the transaction.
  11538. retryCount: 0,
  11539. // Function to call to clean up our .on() listener.
  11540. unwatcher: unwatcher,
  11541. // Stores why a transaction was aborted.
  11542. abortReason: null,
  11543. currentWriteId: null,
  11544. currentInputSnapshot: null,
  11545. currentOutputSnapshotRaw: null,
  11546. currentOutputSnapshotResolved: null
  11547. };
  11548. // Run transaction initially.
  11549. var currentState = repoGetLatestState(repo, path, undefined);
  11550. transaction.currentInputSnapshot = currentState;
  11551. var newVal = transaction.update(currentState.val());
  11552. if (newVal === undefined) {
  11553. // Abort transaction.
  11554. transaction.unwatcher();
  11555. transaction.currentOutputSnapshotRaw = null;
  11556. transaction.currentOutputSnapshotResolved = null;
  11557. if (transaction.onComplete) {
  11558. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11559. }
  11560. }
  11561. else {
  11562. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11563. // Mark as run and add to our queue.
  11564. transaction.status = 0 /* TransactionStatus.RUN */;
  11565. var queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11566. var nodeQueue = treeGetValue(queueNode) || [];
  11567. nodeQueue.push(transaction);
  11568. treeSetValue(queueNode, nodeQueue);
  11569. // Update visibleData and raise events
  11570. // Note: We intentionally raise events after updating all of our
  11571. // transaction state, since the user could start new transactions from the
  11572. // event callbacks.
  11573. var priorityForNode = void 0;
  11574. if (typeof newVal === 'object' &&
  11575. newVal !== null &&
  11576. util.contains(newVal, '.priority')) {
  11577. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11578. priorityForNode = util.safeGet(newVal, '.priority');
  11579. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11580. 'Priority must be a valid string, finite number, server value, or null.');
  11581. }
  11582. else {
  11583. var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11584. ChildrenNode.EMPTY_NODE;
  11585. priorityForNode = currentNode.getPriority().val();
  11586. }
  11587. var serverValues = repoGenerateServerValues(repo);
  11588. var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11589. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11590. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11591. transaction.currentOutputSnapshotResolved = newNode;
  11592. transaction.currentWriteId = repoGetNextWriteId(repo);
  11593. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11594. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11595. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11596. }
  11597. }
  11598. /**
  11599. * @param excludeSets - A specific set to exclude
  11600. */
  11601. function repoGetLatestState(repo, path, excludeSets) {
  11602. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11603. ChildrenNode.EMPTY_NODE);
  11604. }
  11605. /**
  11606. * Sends any already-run transactions that aren't waiting for outstanding
  11607. * transactions to complete.
  11608. *
  11609. * Externally it's called with no arguments, but it calls itself recursively
  11610. * with a particular transactionQueueTree node to recurse through the tree.
  11611. *
  11612. * @param node - transactionQueueTree node to start at.
  11613. */
  11614. function repoSendReadyTransactions(repo, node) {
  11615. if (node === void 0) { node = repo.transactionQueueTree_; }
  11616. // Before recursing, make sure any completed transactions are removed.
  11617. if (!node) {
  11618. repoPruneCompletedTransactionsBelowNode(repo, node);
  11619. }
  11620. if (treeGetValue(node)) {
  11621. var queue = repoBuildTransactionQueue(repo, node);
  11622. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  11623. var allRun = queue.every(function (transaction) { return transaction.status === 0 /* TransactionStatus.RUN */; });
  11624. // If they're all run (and not sent), we can send them. Else, we must wait.
  11625. if (allRun) {
  11626. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11627. }
  11628. }
  11629. else if (treeHasChildren(node)) {
  11630. treeForEachChild(node, function (childNode) {
  11631. repoSendReadyTransactions(repo, childNode);
  11632. });
  11633. }
  11634. }
  11635. /**
  11636. * Given a list of run transactions, send them to the server and then handle
  11637. * the result (success or failure).
  11638. *
  11639. * @param path - The location of the queue.
  11640. * @param queue - Queue of transactions under the specified location.
  11641. */
  11642. function repoSendTransactionQueue(repo, path, queue) {
  11643. // Mark transactions as sent and increment retry count!
  11644. var setsToIgnore = queue.map(function (txn) {
  11645. return txn.currentWriteId;
  11646. });
  11647. var latestState = repoGetLatestState(repo, path, setsToIgnore);
  11648. var snapToSend = latestState;
  11649. var latestHash = latestState.hash();
  11650. for (var i = 0; i < queue.length; i++) {
  11651. var txn = queue[i];
  11652. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11653. txn.status = 1 /* TransactionStatus.SENT */;
  11654. txn.retryCount++;
  11655. var relativePath = newRelativePath(path, txn.path);
  11656. // If we've gotten to this point, the output snapshot must be defined.
  11657. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11658. }
  11659. var dataToSend = snapToSend.val(true);
  11660. var pathToSend = path;
  11661. // Send the put.
  11662. repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
  11663. repoLog(repo, 'transaction put response', {
  11664. path: pathToSend.toString(),
  11665. status: status
  11666. });
  11667. var events = [];
  11668. if (status === 'ok') {
  11669. // Queue up the callbacks and fire them after cleaning up all of our
  11670. // transaction state, since the callback could trigger more
  11671. // transactions or sets.
  11672. var callbacks = [];
  11673. var _loop_1 = function (i) {
  11674. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11675. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11676. if (queue[i].onComplete) {
  11677. // We never unset the output snapshot, and given that this
  11678. // transaction is complete, it should be set
  11679. callbacks.push(function () {
  11680. return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
  11681. });
  11682. }
  11683. queue[i].unwatcher();
  11684. };
  11685. for (var i = 0; i < queue.length; i++) {
  11686. _loop_1(i);
  11687. }
  11688. // Now remove the completed transactions.
  11689. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11690. // There may be pending transactions that we can now send.
  11691. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11692. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11693. // Finally, trigger onComplete callbacks.
  11694. for (var i = 0; i < callbacks.length; i++) {
  11695. exceptionGuard(callbacks[i]);
  11696. }
  11697. }
  11698. else {
  11699. // transactions are no longer sent. Update their status appropriately.
  11700. if (status === 'datastale') {
  11701. for (var i = 0; i < queue.length; i++) {
  11702. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11703. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11704. }
  11705. else {
  11706. queue[i].status = 0 /* TransactionStatus.RUN */;
  11707. }
  11708. }
  11709. }
  11710. else {
  11711. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11712. for (var i = 0; i < queue.length; i++) {
  11713. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11714. queue[i].abortReason = status;
  11715. }
  11716. }
  11717. repoRerunTransactions(repo, path);
  11718. }
  11719. }, latestHash);
  11720. }
  11721. /**
  11722. * Finds all transactions dependent on the data at changedPath and reruns them.
  11723. *
  11724. * Should be called any time cached data changes.
  11725. *
  11726. * Return the highest path that was affected by rerunning transactions. This
  11727. * is the path at which events need to be raised for.
  11728. *
  11729. * @param changedPath - The path in mergedData that changed.
  11730. * @returns The rootmost path that was affected by rerunning transactions.
  11731. */
  11732. function repoRerunTransactions(repo, changedPath) {
  11733. var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11734. var path = treeGetPath(rootMostTransactionNode);
  11735. var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11736. repoRerunTransactionQueue(repo, queue, path);
  11737. return path;
  11738. }
  11739. /**
  11740. * Does all the work of rerunning transactions (as well as cleans up aborted
  11741. * transactions and whatnot).
  11742. *
  11743. * @param queue - The queue of transactions to run.
  11744. * @param path - The path the queue is for.
  11745. */
  11746. function repoRerunTransactionQueue(repo, queue, path) {
  11747. if (queue.length === 0) {
  11748. return; // Nothing to do!
  11749. }
  11750. // Queue up the callbacks and fire them after cleaning up all of our
  11751. // transaction state, since the callback could trigger more transactions or
  11752. // sets.
  11753. var callbacks = [];
  11754. var events = [];
  11755. // Ignore all of the sets we're going to re-run.
  11756. var txnsToRerun = queue.filter(function (q) {
  11757. return q.status === 0 /* TransactionStatus.RUN */;
  11758. });
  11759. var setsToIgnore = txnsToRerun.map(function (q) {
  11760. return q.currentWriteId;
  11761. });
  11762. var _loop_2 = function (i) {
  11763. var transaction = queue[i];
  11764. var relativePath = newRelativePath(path, transaction.path);
  11765. var abortTransaction = false, abortReason;
  11766. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11767. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11768. abortTransaction = true;
  11769. abortReason = transaction.abortReason;
  11770. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11771. }
  11772. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11773. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11774. abortTransaction = true;
  11775. abortReason = 'maxretry';
  11776. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11777. }
  11778. else {
  11779. // This code reruns a transaction
  11780. var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11781. transaction.currentInputSnapshot = currentNode;
  11782. var newData = queue[i].update(currentNode.val());
  11783. if (newData !== undefined) {
  11784. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11785. var newDataNode = nodeFromJSON(newData);
  11786. var hasExplicitPriority = typeof newData === 'object' &&
  11787. newData != null &&
  11788. util.contains(newData, '.priority');
  11789. if (!hasExplicitPriority) {
  11790. // Keep the old priority if there wasn't a priority explicitly specified.
  11791. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11792. }
  11793. var oldWriteId = transaction.currentWriteId;
  11794. var serverValues = repoGenerateServerValues(repo);
  11795. var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11796. transaction.currentOutputSnapshotRaw = newDataNode;
  11797. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11798. transaction.currentWriteId = repoGetNextWriteId(repo);
  11799. // Mutates setsToIgnore in place
  11800. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11801. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11802. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11803. }
  11804. else {
  11805. abortTransaction = true;
  11806. abortReason = 'nodata';
  11807. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11808. }
  11809. }
  11810. }
  11811. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11812. events = [];
  11813. if (abortTransaction) {
  11814. // Abort.
  11815. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11816. // Removing a listener can trigger pruning which can muck with
  11817. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11818. // until we're done.
  11819. (function (unwatcher) {
  11820. setTimeout(unwatcher, Math.floor(0));
  11821. })(queue[i].unwatcher);
  11822. if (queue[i].onComplete) {
  11823. if (abortReason === 'nodata') {
  11824. callbacks.push(function () {
  11825. return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
  11826. });
  11827. }
  11828. else {
  11829. callbacks.push(function () {
  11830. return queue[i].onComplete(new Error(abortReason), false, null);
  11831. });
  11832. }
  11833. }
  11834. }
  11835. };
  11836. for (var i = 0; i < queue.length; i++) {
  11837. _loop_2(i);
  11838. }
  11839. // Clean up completed transactions.
  11840. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11841. // Now fire callbacks, now that we're in a good, known state.
  11842. for (var i = 0; i < callbacks.length; i++) {
  11843. exceptionGuard(callbacks[i]);
  11844. }
  11845. // Try to send the transaction result to the server.
  11846. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11847. }
  11848. /**
  11849. * Returns the rootmost ancestor node of the specified path that has a pending
  11850. * transaction on it, or just returns the node for the given path if there are
  11851. * no pending transactions on any ancestor.
  11852. *
  11853. * @param path - The location to start at.
  11854. * @returns The rootmost node with a transaction.
  11855. */
  11856. function repoGetAncestorTransactionNode(repo, path) {
  11857. var front;
  11858. // Start at the root and walk deeper into the tree towards path until we
  11859. // find a node with pending transactions.
  11860. var transactionNode = repo.transactionQueueTree_;
  11861. front = pathGetFront(path);
  11862. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11863. transactionNode = treeSubTree(transactionNode, front);
  11864. path = pathPopFront(path);
  11865. front = pathGetFront(path);
  11866. }
  11867. return transactionNode;
  11868. }
  11869. /**
  11870. * Builds the queue of all transactions at or below the specified
  11871. * transactionNode.
  11872. *
  11873. * @param transactionNode
  11874. * @returns The generated queue.
  11875. */
  11876. function repoBuildTransactionQueue(repo, transactionNode) {
  11877. // Walk any child transaction queues and aggregate them into a single queue.
  11878. var transactionQueue = [];
  11879. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11880. // Sort them by the order the transactions were created.
  11881. transactionQueue.sort(function (a, b) { return a.order - b.order; });
  11882. return transactionQueue;
  11883. }
  11884. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11885. var nodeQueue = treeGetValue(node);
  11886. if (nodeQueue) {
  11887. for (var i = 0; i < nodeQueue.length; i++) {
  11888. queue.push(nodeQueue[i]);
  11889. }
  11890. }
  11891. treeForEachChild(node, function (child) {
  11892. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11893. });
  11894. }
  11895. /**
  11896. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11897. */
  11898. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11899. var queue = treeGetValue(node);
  11900. if (queue) {
  11901. var to = 0;
  11902. for (var from = 0; from < queue.length; from++) {
  11903. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11904. queue[to] = queue[from];
  11905. to++;
  11906. }
  11907. }
  11908. queue.length = to;
  11909. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11910. }
  11911. treeForEachChild(node, function (childNode) {
  11912. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11913. });
  11914. }
  11915. /**
  11916. * Aborts all transactions on ancestors or descendants of the specified path.
  11917. * Called when doing a set() or update() since we consider them incompatible
  11918. * with transactions.
  11919. *
  11920. * @param path - Path for which we want to abort related transactions.
  11921. */
  11922. function repoAbortTransactions(repo, path) {
  11923. var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11924. var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11925. treeForEachAncestor(transactionNode, function (node) {
  11926. repoAbortTransactionsOnNode(repo, node);
  11927. });
  11928. repoAbortTransactionsOnNode(repo, transactionNode);
  11929. treeForEachDescendant(transactionNode, function (node) {
  11930. repoAbortTransactionsOnNode(repo, node);
  11931. });
  11932. return affectedPath;
  11933. }
  11934. /**
  11935. * Abort transactions stored in this transaction queue node.
  11936. *
  11937. * @param node - Node to abort transactions for.
  11938. */
  11939. function repoAbortTransactionsOnNode(repo, node) {
  11940. var queue = treeGetValue(node);
  11941. if (queue) {
  11942. // Queue up the callbacks and fire them after cleaning up all of our
  11943. // transaction state, since the callback could trigger more transactions
  11944. // or sets.
  11945. var callbacks = [];
  11946. // Go through queue. Any already-sent transactions must be marked for
  11947. // abort, while the unsent ones can be immediately aborted and removed.
  11948. var events = [];
  11949. var lastSent = -1;
  11950. for (var i = 0; i < queue.length; i++) {
  11951. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11952. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11953. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11954. lastSent = i;
  11955. // Mark transaction for abort when it comes back.
  11956. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11957. queue[i].abortReason = 'set';
  11958. }
  11959. else {
  11960. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11961. // We can abort it immediately.
  11962. queue[i].unwatcher();
  11963. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11964. if (queue[i].onComplete) {
  11965. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11966. }
  11967. }
  11968. }
  11969. if (lastSent === -1) {
  11970. // We're not waiting for any sent transactions. We can clear the queue.
  11971. treeSetValue(node, undefined);
  11972. }
  11973. else {
  11974. // Remove the transactions we aborted.
  11975. queue.length = lastSent + 1;
  11976. }
  11977. // Now fire the callbacks.
  11978. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11979. for (var i = 0; i < callbacks.length; i++) {
  11980. exceptionGuard(callbacks[i]);
  11981. }
  11982. }
  11983. }
  11984. /**
  11985. * @license
  11986. * Copyright 2017 Google LLC
  11987. *
  11988. * Licensed under the Apache License, Version 2.0 (the "License");
  11989. * you may not use this file except in compliance with the License.
  11990. * You may obtain a copy of the License at
  11991. *
  11992. * http://www.apache.org/licenses/LICENSE-2.0
  11993. *
  11994. * Unless required by applicable law or agreed to in writing, software
  11995. * distributed under the License is distributed on an "AS IS" BASIS,
  11996. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11997. * See the License for the specific language governing permissions and
  11998. * limitations under the License.
  11999. */
  12000. function decodePath(pathString) {
  12001. var pathStringDecoded = '';
  12002. var pieces = pathString.split('/');
  12003. for (var i = 0; i < pieces.length; i++) {
  12004. if (pieces[i].length > 0) {
  12005. var piece = pieces[i];
  12006. try {
  12007. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  12008. }
  12009. catch (e) { }
  12010. pathStringDecoded += '/' + piece;
  12011. }
  12012. }
  12013. return pathStringDecoded;
  12014. }
  12015. /**
  12016. * @returns key value hash
  12017. */
  12018. function decodeQuery(queryString) {
  12019. var e_1, _a;
  12020. var results = {};
  12021. if (queryString.charAt(0) === '?') {
  12022. queryString = queryString.substring(1);
  12023. }
  12024. try {
  12025. for (var _b = tslib.__values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
  12026. var segment = _c.value;
  12027. if (segment.length === 0) {
  12028. continue;
  12029. }
  12030. var kv = segment.split('=');
  12031. if (kv.length === 2) {
  12032. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  12033. }
  12034. else {
  12035. warn("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
  12036. }
  12037. }
  12038. }
  12039. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  12040. finally {
  12041. try {
  12042. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12043. }
  12044. finally { if (e_1) throw e_1.error; }
  12045. }
  12046. return results;
  12047. }
  12048. var parseRepoInfo = function (dataURL, nodeAdmin) {
  12049. var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  12050. if (parsedUrl.domain === 'firebase.com') {
  12051. fatal(parsedUrl.host +
  12052. ' is no longer supported. ' +
  12053. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  12054. }
  12055. // Catch common error of uninitialized namespace value.
  12056. if ((!namespace || namespace === 'undefined') &&
  12057. parsedUrl.domain !== 'localhost') {
  12058. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  12059. }
  12060. if (!parsedUrl.secure) {
  12061. warnIfPageIsSecure();
  12062. }
  12063. var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  12064. return {
  12065. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  12066. /*persistenceKey=*/ '',
  12067. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  12068. path: new Path(parsedUrl.pathString)
  12069. };
  12070. };
  12071. var parseDatabaseURL = function (dataURL) {
  12072. // Default to empty strings in the event of a malformed string.
  12073. var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  12074. // Always default to SSL, unless otherwise specified.
  12075. var secure = true, scheme = 'https', port = 443;
  12076. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  12077. if (typeof dataURL === 'string') {
  12078. // Parse scheme.
  12079. var colonInd = dataURL.indexOf('//');
  12080. if (colonInd >= 0) {
  12081. scheme = dataURL.substring(0, colonInd - 1);
  12082. dataURL = dataURL.substring(colonInd + 2);
  12083. }
  12084. // Parse host, path, and query string.
  12085. var slashInd = dataURL.indexOf('/');
  12086. if (slashInd === -1) {
  12087. slashInd = dataURL.length;
  12088. }
  12089. var questionMarkInd = dataURL.indexOf('?');
  12090. if (questionMarkInd === -1) {
  12091. questionMarkInd = dataURL.length;
  12092. }
  12093. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  12094. if (slashInd < questionMarkInd) {
  12095. // For pathString, questionMarkInd will always come after slashInd
  12096. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  12097. }
  12098. var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  12099. // If we have a port, use scheme for determining if it's secure.
  12100. colonInd = host.indexOf(':');
  12101. if (colonInd >= 0) {
  12102. secure = scheme === 'https' || scheme === 'wss';
  12103. port = parseInt(host.substring(colonInd + 1), 10);
  12104. }
  12105. else {
  12106. colonInd = host.length;
  12107. }
  12108. var hostWithoutPort = host.slice(0, colonInd);
  12109. if (hostWithoutPort.toLowerCase() === 'localhost') {
  12110. domain = 'localhost';
  12111. }
  12112. else if (hostWithoutPort.split('.').length <= 2) {
  12113. domain = hostWithoutPort;
  12114. }
  12115. else {
  12116. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  12117. var dotInd = host.indexOf('.');
  12118. subdomain = host.substring(0, dotInd).toLowerCase();
  12119. domain = host.substring(dotInd + 1);
  12120. // Normalize namespaces to lowercase to share storage / connection.
  12121. namespace = subdomain;
  12122. }
  12123. // Always treat the value of the `ns` as the namespace name if it is present.
  12124. if ('ns' in queryParams) {
  12125. namespace = queryParams['ns'];
  12126. }
  12127. }
  12128. return {
  12129. host: host,
  12130. port: port,
  12131. domain: domain,
  12132. subdomain: subdomain,
  12133. secure: secure,
  12134. scheme: scheme,
  12135. pathString: pathString,
  12136. namespace: namespace
  12137. };
  12138. };
  12139. /**
  12140. * @license
  12141. * Copyright 2017 Google LLC
  12142. *
  12143. * Licensed under the Apache License, Version 2.0 (the "License");
  12144. * you may not use this file except in compliance with the License.
  12145. * You may obtain a copy of the License at
  12146. *
  12147. * http://www.apache.org/licenses/LICENSE-2.0
  12148. *
  12149. * Unless required by applicable law or agreed to in writing, software
  12150. * distributed under the License is distributed on an "AS IS" BASIS,
  12151. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12152. * See the License for the specific language governing permissions and
  12153. * limitations under the License.
  12154. */
  12155. // Modeled after base64 web-safe chars, but ordered by ASCII.
  12156. var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  12157. /**
  12158. * Fancy ID generator that creates 20-character string identifiers with the
  12159. * following properties:
  12160. *
  12161. * 1. They're based on timestamp so that they sort *after* any existing ids.
  12162. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  12163. * collide with other clients' IDs.
  12164. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  12165. * that will sort properly).
  12166. * 4. They're monotonically increasing. Even if you generate more than one in
  12167. * the same timestamp, the latter ones will sort after the former ones. We do
  12168. * this by using the previous random bits but "incrementing" them by 1 (only
  12169. * in the case of a timestamp collision).
  12170. */
  12171. var nextPushId = (function () {
  12172. // Timestamp of last push, used to prevent local collisions if you push twice
  12173. // in one ms.
  12174. var lastPushTime = 0;
  12175. // We generate 72-bits of randomness which get turned into 12 characters and
  12176. // appended to the timestamp to prevent collisions with other clients. We
  12177. // store the last characters we generated because in the event of a collision,
  12178. // we'll use those same characters except "incremented" by one.
  12179. var lastRandChars = [];
  12180. return function (now) {
  12181. var duplicateTime = now === lastPushTime;
  12182. lastPushTime = now;
  12183. var i;
  12184. var timeStampChars = new Array(8);
  12185. for (i = 7; i >= 0; i--) {
  12186. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  12187. // NOTE: Can't use << here because javascript will convert to int and lose
  12188. // the upper bits.
  12189. now = Math.floor(now / 64);
  12190. }
  12191. util.assert(now === 0, 'Cannot push at time == 0');
  12192. var id = timeStampChars.join('');
  12193. if (!duplicateTime) {
  12194. for (i = 0; i < 12; i++) {
  12195. lastRandChars[i] = Math.floor(Math.random() * 64);
  12196. }
  12197. }
  12198. else {
  12199. // If the timestamp hasn't changed since last push, use the same random
  12200. // number, except incremented by 1.
  12201. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  12202. lastRandChars[i] = 0;
  12203. }
  12204. lastRandChars[i]++;
  12205. }
  12206. for (i = 0; i < 12; i++) {
  12207. id += PUSH_CHARS.charAt(lastRandChars[i]);
  12208. }
  12209. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  12210. return id;
  12211. };
  12212. })();
  12213. /**
  12214. * @license
  12215. * Copyright 2017 Google LLC
  12216. *
  12217. * Licensed under the Apache License, Version 2.0 (the "License");
  12218. * you may not use this file except in compliance with the License.
  12219. * You may obtain a copy of the License at
  12220. *
  12221. * http://www.apache.org/licenses/LICENSE-2.0
  12222. *
  12223. * Unless required by applicable law or agreed to in writing, software
  12224. * distributed under the License is distributed on an "AS IS" BASIS,
  12225. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12226. * See the License for the specific language governing permissions and
  12227. * limitations under the License.
  12228. */
  12229. /**
  12230. * Encapsulates the data needed to raise an event
  12231. */
  12232. var DataEvent = /** @class */ (function () {
  12233. /**
  12234. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  12235. * @param eventRegistration - The function to call to with the event data. User provided
  12236. * @param snapshot - The data backing the event
  12237. * @param prevName - Optional, the name of the previous child for child_* events.
  12238. */
  12239. function DataEvent(eventType, eventRegistration, snapshot, prevName) {
  12240. this.eventType = eventType;
  12241. this.eventRegistration = eventRegistration;
  12242. this.snapshot = snapshot;
  12243. this.prevName = prevName;
  12244. }
  12245. DataEvent.prototype.getPath = function () {
  12246. var ref = this.snapshot.ref;
  12247. if (this.eventType === 'value') {
  12248. return ref._path;
  12249. }
  12250. else {
  12251. return ref.parent._path;
  12252. }
  12253. };
  12254. DataEvent.prototype.getEventType = function () {
  12255. return this.eventType;
  12256. };
  12257. DataEvent.prototype.getEventRunner = function () {
  12258. return this.eventRegistration.getEventRunner(this);
  12259. };
  12260. DataEvent.prototype.toString = function () {
  12261. return (this.getPath().toString() +
  12262. ':' +
  12263. this.eventType +
  12264. ':' +
  12265. util.stringify(this.snapshot.exportVal()));
  12266. };
  12267. return DataEvent;
  12268. }());
  12269. var CancelEvent = /** @class */ (function () {
  12270. function CancelEvent(eventRegistration, error, path) {
  12271. this.eventRegistration = eventRegistration;
  12272. this.error = error;
  12273. this.path = path;
  12274. }
  12275. CancelEvent.prototype.getPath = function () {
  12276. return this.path;
  12277. };
  12278. CancelEvent.prototype.getEventType = function () {
  12279. return 'cancel';
  12280. };
  12281. CancelEvent.prototype.getEventRunner = function () {
  12282. return this.eventRegistration.getEventRunner(this);
  12283. };
  12284. CancelEvent.prototype.toString = function () {
  12285. return this.path.toString() + ':cancel';
  12286. };
  12287. return CancelEvent;
  12288. }());
  12289. /**
  12290. * @license
  12291. * Copyright 2017 Google LLC
  12292. *
  12293. * Licensed under the Apache License, Version 2.0 (the "License");
  12294. * you may not use this file except in compliance with the License.
  12295. * You may obtain a copy of the License at
  12296. *
  12297. * http://www.apache.org/licenses/LICENSE-2.0
  12298. *
  12299. * Unless required by applicable law or agreed to in writing, software
  12300. * distributed under the License is distributed on an "AS IS" BASIS,
  12301. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12302. * See the License for the specific language governing permissions and
  12303. * limitations under the License.
  12304. */
  12305. /**
  12306. * A wrapper class that converts events from the database@exp SDK to the legacy
  12307. * Database SDK. Events are not converted directly as event registration relies
  12308. * on reference comparison of the original user callback (see `matches()`) and
  12309. * relies on equality of the legacy SDK's `context` object.
  12310. */
  12311. var CallbackContext = /** @class */ (function () {
  12312. function CallbackContext(snapshotCallback, cancelCallback) {
  12313. this.snapshotCallback = snapshotCallback;
  12314. this.cancelCallback = cancelCallback;
  12315. }
  12316. CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
  12317. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  12318. };
  12319. CallbackContext.prototype.onCancel = function (error) {
  12320. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  12321. return this.cancelCallback.call(null, error);
  12322. };
  12323. Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
  12324. get: function () {
  12325. return !!this.cancelCallback;
  12326. },
  12327. enumerable: false,
  12328. configurable: true
  12329. });
  12330. CallbackContext.prototype.matches = function (other) {
  12331. return (this.snapshotCallback === other.snapshotCallback ||
  12332. (this.snapshotCallback.userCallback !== undefined &&
  12333. this.snapshotCallback.userCallback ===
  12334. other.snapshotCallback.userCallback &&
  12335. this.snapshotCallback.context === other.snapshotCallback.context));
  12336. };
  12337. return CallbackContext;
  12338. }());
  12339. /**
  12340. * @license
  12341. * Copyright 2021 Google LLC
  12342. *
  12343. * Licensed under the Apache License, Version 2.0 (the "License");
  12344. * you may not use this file except in compliance with the License.
  12345. * You may obtain a copy of the License at
  12346. *
  12347. * http://www.apache.org/licenses/LICENSE-2.0
  12348. *
  12349. * Unless required by applicable law or agreed to in writing, software
  12350. * distributed under the License is distributed on an "AS IS" BASIS,
  12351. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12352. * See the License for the specific language governing permissions and
  12353. * limitations under the License.
  12354. */
  12355. /**
  12356. * The `onDisconnect` class allows you to write or clear data when your client
  12357. * disconnects from the Database server. These updates occur whether your
  12358. * client disconnects cleanly or not, so you can rely on them to clean up data
  12359. * even if a connection is dropped or a client crashes.
  12360. *
  12361. * The `onDisconnect` class is most commonly used to manage presence in
  12362. * applications where it is useful to detect how many clients are connected and
  12363. * when other clients disconnect. See
  12364. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12365. * for more information.
  12366. *
  12367. * To avoid problems when a connection is dropped before the requests can be
  12368. * transferred to the Database server, these functions should be called before
  12369. * writing any data.
  12370. *
  12371. * Note that `onDisconnect` operations are only triggered once. If you want an
  12372. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12373. * the `onDisconnect` operations each time you reconnect.
  12374. */
  12375. var OnDisconnect = /** @class */ (function () {
  12376. /** @hideconstructor */
  12377. function OnDisconnect(_repo, _path) {
  12378. this._repo = _repo;
  12379. this._path = _path;
  12380. }
  12381. /**
  12382. * Cancels all previously queued `onDisconnect()` set or update events for this
  12383. * location and all children.
  12384. *
  12385. * If a write has been queued for this location via a `set()` or `update()` at a
  12386. * parent location, the write at this location will be canceled, though writes
  12387. * to sibling locations will still occur.
  12388. *
  12389. * @returns Resolves when synchronization to the server is complete.
  12390. */
  12391. OnDisconnect.prototype.cancel = function () {
  12392. var deferred = new util.Deferred();
  12393. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
  12394. return deferred.promise;
  12395. };
  12396. /**
  12397. * Ensures the data at this location is deleted when the client is disconnected
  12398. * (due to closing the browser, navigating to a new page, or network issues).
  12399. *
  12400. * @returns Resolves when synchronization to the server is complete.
  12401. */
  12402. OnDisconnect.prototype.remove = function () {
  12403. validateWritablePath('OnDisconnect.remove', this._path);
  12404. var deferred = new util.Deferred();
  12405. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
  12406. return deferred.promise;
  12407. };
  12408. /**
  12409. * Ensures the data at this location is set to the specified value when the
  12410. * client is disconnected (due to closing the browser, navigating to a new page,
  12411. * or network issues).
  12412. *
  12413. * `set()` is especially useful for implementing "presence" systems, where a
  12414. * value should be changed or cleared when a user disconnects so that they
  12415. * appear "offline" to other users. See
  12416. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12417. * for more information.
  12418. *
  12419. * Note that `onDisconnect` operations are only triggered once. If you want an
  12420. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12421. * the `onDisconnect` operations each time.
  12422. *
  12423. * @param value - The value to be written to this location on disconnect (can
  12424. * be an object, array, string, number, boolean, or null).
  12425. * @returns Resolves when synchronization to the Database is complete.
  12426. */
  12427. OnDisconnect.prototype.set = function (value) {
  12428. validateWritablePath('OnDisconnect.set', this._path);
  12429. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12430. var deferred = new util.Deferred();
  12431. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
  12432. return deferred.promise;
  12433. };
  12434. /**
  12435. * Ensures the data at this location is set to the specified value and priority
  12436. * when the client is disconnected (due to closing the browser, navigating to a
  12437. * new page, or network issues).
  12438. *
  12439. * @param value - The value to be written to this location on disconnect (can
  12440. * be an object, array, string, number, boolean, or null).
  12441. * @param priority - The priority to be written (string, number, or null).
  12442. * @returns Resolves when synchronization to the Database is complete.
  12443. */
  12444. OnDisconnect.prototype.setWithPriority = function (value, priority) {
  12445. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12446. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12447. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12448. var deferred = new util.Deferred();
  12449. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
  12450. return deferred.promise;
  12451. };
  12452. /**
  12453. * Writes multiple values at this location when the client is disconnected (due
  12454. * to closing the browser, navigating to a new page, or network issues).
  12455. *
  12456. * The `values` argument contains multiple property-value pairs that will be
  12457. * written to the Database together. Each child property can either be a simple
  12458. * property (for example, "name") or a relative path (for example, "name/first")
  12459. * from the current location to the data to update.
  12460. *
  12461. * As opposed to the `set()` method, `update()` can be use to selectively update
  12462. * only the referenced properties at the current location (instead of replacing
  12463. * all the child properties at the current location).
  12464. *
  12465. * @param values - Object containing multiple values.
  12466. * @returns Resolves when synchronization to the Database is complete.
  12467. */
  12468. OnDisconnect.prototype.update = function (values) {
  12469. validateWritablePath('OnDisconnect.update', this._path);
  12470. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12471. var deferred = new util.Deferred();
  12472. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
  12473. return deferred.promise;
  12474. };
  12475. return OnDisconnect;
  12476. }());
  12477. /**
  12478. * @license
  12479. * Copyright 2020 Google LLC
  12480. *
  12481. * Licensed under the Apache License, Version 2.0 (the "License");
  12482. * you may not use this file except in compliance with the License.
  12483. * You may obtain a copy of the License at
  12484. *
  12485. * http://www.apache.org/licenses/LICENSE-2.0
  12486. *
  12487. * Unless required by applicable law or agreed to in writing, software
  12488. * distributed under the License is distributed on an "AS IS" BASIS,
  12489. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12490. * See the License for the specific language governing permissions and
  12491. * limitations under the License.
  12492. */
  12493. /**
  12494. * @internal
  12495. */
  12496. var QueryImpl = /** @class */ (function () {
  12497. /**
  12498. * @hideconstructor
  12499. */
  12500. function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
  12501. this._repo = _repo;
  12502. this._path = _path;
  12503. this._queryParams = _queryParams;
  12504. this._orderByCalled = _orderByCalled;
  12505. }
  12506. Object.defineProperty(QueryImpl.prototype, "key", {
  12507. get: function () {
  12508. if (pathIsEmpty(this._path)) {
  12509. return null;
  12510. }
  12511. else {
  12512. return pathGetBack(this._path);
  12513. }
  12514. },
  12515. enumerable: false,
  12516. configurable: true
  12517. });
  12518. Object.defineProperty(QueryImpl.prototype, "ref", {
  12519. get: function () {
  12520. return new ReferenceImpl(this._repo, this._path);
  12521. },
  12522. enumerable: false,
  12523. configurable: true
  12524. });
  12525. Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
  12526. get: function () {
  12527. var obj = queryParamsGetQueryObject(this._queryParams);
  12528. var id = ObjectToUniqueKey(obj);
  12529. return id === '{}' ? 'default' : id;
  12530. },
  12531. enumerable: false,
  12532. configurable: true
  12533. });
  12534. Object.defineProperty(QueryImpl.prototype, "_queryObject", {
  12535. /**
  12536. * An object representation of the query parameters used by this Query.
  12537. */
  12538. get: function () {
  12539. return queryParamsGetQueryObject(this._queryParams);
  12540. },
  12541. enumerable: false,
  12542. configurable: true
  12543. });
  12544. QueryImpl.prototype.isEqual = function (other) {
  12545. other = util.getModularInstance(other);
  12546. if (!(other instanceof QueryImpl)) {
  12547. return false;
  12548. }
  12549. var sameRepo = this._repo === other._repo;
  12550. var samePath = pathEquals(this._path, other._path);
  12551. var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12552. return sameRepo && samePath && sameQueryIdentifier;
  12553. };
  12554. QueryImpl.prototype.toJSON = function () {
  12555. return this.toString();
  12556. };
  12557. QueryImpl.prototype.toString = function () {
  12558. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12559. };
  12560. return QueryImpl;
  12561. }());
  12562. /**
  12563. * Validates that no other order by call has been made
  12564. */
  12565. function validateNoPreviousOrderByCall(query, fnName) {
  12566. if (query._orderByCalled === true) {
  12567. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12568. }
  12569. }
  12570. /**
  12571. * Validates start/end values for queries.
  12572. */
  12573. function validateQueryEndpoints(params) {
  12574. var startNode = null;
  12575. var endNode = null;
  12576. if (params.hasStart()) {
  12577. startNode = params.getIndexStartValue();
  12578. }
  12579. if (params.hasEnd()) {
  12580. endNode = params.getIndexEndValue();
  12581. }
  12582. if (params.getIndex() === KEY_INDEX) {
  12583. var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12584. 'startAt(), endAt(), or equalTo().';
  12585. var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12586. 'endAt(), endBefore(), or equalTo() must be a string.';
  12587. if (params.hasStart()) {
  12588. var startName = params.getIndexStartName();
  12589. if (startName !== MIN_NAME) {
  12590. throw new Error(tooManyArgsError);
  12591. }
  12592. else if (typeof startNode !== 'string') {
  12593. throw new Error(wrongArgTypeError);
  12594. }
  12595. }
  12596. if (params.hasEnd()) {
  12597. var endName = params.getIndexEndName();
  12598. if (endName !== MAX_NAME) {
  12599. throw new Error(tooManyArgsError);
  12600. }
  12601. else if (typeof endNode !== 'string') {
  12602. throw new Error(wrongArgTypeError);
  12603. }
  12604. }
  12605. }
  12606. else if (params.getIndex() === PRIORITY_INDEX) {
  12607. if ((startNode != null && !isValidPriority(startNode)) ||
  12608. (endNode != null && !isValidPriority(endNode))) {
  12609. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12610. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12611. '(null, a number, or a string).');
  12612. }
  12613. }
  12614. else {
  12615. util.assert(params.getIndex() instanceof PathIndex ||
  12616. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12617. if ((startNode != null && typeof startNode === 'object') ||
  12618. (endNode != null && typeof endNode === 'object')) {
  12619. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12620. 'equalTo() cannot be an object.');
  12621. }
  12622. }
  12623. }
  12624. /**
  12625. * Validates that limit* has been called with the correct combination of parameters
  12626. */
  12627. function validateLimit(params) {
  12628. if (params.hasStart() &&
  12629. params.hasEnd() &&
  12630. params.hasLimit() &&
  12631. !params.hasAnchoredLimit()) {
  12632. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12633. 'limitToFirst() or limitToLast() instead.');
  12634. }
  12635. }
  12636. /**
  12637. * @internal
  12638. */
  12639. var ReferenceImpl = /** @class */ (function (_super) {
  12640. tslib.__extends(ReferenceImpl, _super);
  12641. /** @hideconstructor */
  12642. function ReferenceImpl(repo, path) {
  12643. return _super.call(this, repo, path, new QueryParams(), false) || this;
  12644. }
  12645. Object.defineProperty(ReferenceImpl.prototype, "parent", {
  12646. get: function () {
  12647. var parentPath = pathParent(this._path);
  12648. return parentPath === null
  12649. ? null
  12650. : new ReferenceImpl(this._repo, parentPath);
  12651. },
  12652. enumerable: false,
  12653. configurable: true
  12654. });
  12655. Object.defineProperty(ReferenceImpl.prototype, "root", {
  12656. get: function () {
  12657. var ref = this;
  12658. while (ref.parent !== null) {
  12659. ref = ref.parent;
  12660. }
  12661. return ref;
  12662. },
  12663. enumerable: false,
  12664. configurable: true
  12665. });
  12666. return ReferenceImpl;
  12667. }(QueryImpl));
  12668. /**
  12669. * A `DataSnapshot` contains data from a Database location.
  12670. *
  12671. * Any time you read data from the Database, you receive the data as a
  12672. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12673. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12674. * JavaScript object by calling the `val()` method. Alternatively, you can
  12675. * traverse into the snapshot by calling `child()` to return child snapshots
  12676. * (which you could then call `val()` on).
  12677. *
  12678. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12679. * a Database location. It cannot be modified and will never change (to modify
  12680. * data, you always call the `set()` method on a `Reference` directly).
  12681. */
  12682. var DataSnapshot = /** @class */ (function () {
  12683. /**
  12684. * @param _node - A SnapshotNode to wrap.
  12685. * @param ref - The location this snapshot came from.
  12686. * @param _index - The iteration order for this snapshot
  12687. * @hideconstructor
  12688. */
  12689. function DataSnapshot(_node,
  12690. /**
  12691. * The location of this DataSnapshot.
  12692. */
  12693. ref, _index) {
  12694. this._node = _node;
  12695. this.ref = ref;
  12696. this._index = _index;
  12697. }
  12698. Object.defineProperty(DataSnapshot.prototype, "priority", {
  12699. /**
  12700. * Gets the priority value of the data in this `DataSnapshot`.
  12701. *
  12702. * Applications need not use priority but can order collections by
  12703. * ordinary properties (see
  12704. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12705. * ).
  12706. */
  12707. get: function () {
  12708. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12709. return this._node.getPriority().val();
  12710. },
  12711. enumerable: false,
  12712. configurable: true
  12713. });
  12714. Object.defineProperty(DataSnapshot.prototype, "key", {
  12715. /**
  12716. * The key (last part of the path) of the location of this `DataSnapshot`.
  12717. *
  12718. * The last token in a Database location is considered its key. For example,
  12719. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12720. * `DataSnapshot` will return the key for the location that generated it.
  12721. * However, accessing the key on the root URL of a Database will return
  12722. * `null`.
  12723. */
  12724. get: function () {
  12725. return this.ref.key;
  12726. },
  12727. enumerable: false,
  12728. configurable: true
  12729. });
  12730. Object.defineProperty(DataSnapshot.prototype, "size", {
  12731. /** Returns the number of child properties of this `DataSnapshot`. */
  12732. get: function () {
  12733. return this._node.numChildren();
  12734. },
  12735. enumerable: false,
  12736. configurable: true
  12737. });
  12738. /**
  12739. * Gets another `DataSnapshot` for the location at the specified relative path.
  12740. *
  12741. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12742. * another `DataSnapshot` for the location at the specified relative path. The
  12743. * relative path can either be a simple child name (for example, "ada") or a
  12744. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12745. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12746. * whose value is `null`) is returned.
  12747. *
  12748. * @param path - A relative path to the location of child data.
  12749. */
  12750. DataSnapshot.prototype.child = function (path) {
  12751. var childPath = new Path(path);
  12752. var childRef = child(this.ref, path);
  12753. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12754. };
  12755. /**
  12756. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12757. * efficient than using `snapshot.val() !== null`.
  12758. */
  12759. DataSnapshot.prototype.exists = function () {
  12760. return !this._node.isEmpty();
  12761. };
  12762. /**
  12763. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12764. *
  12765. * The `exportVal()` method is similar to `val()`, except priority information
  12766. * is included (if available), making it suitable for backing up your data.
  12767. *
  12768. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12769. * Array, string, number, boolean, or `null`).
  12770. */
  12771. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12772. DataSnapshot.prototype.exportVal = function () {
  12773. return this._node.val(true);
  12774. };
  12775. /**
  12776. * Enumerates the top-level children in the `DataSnapshot`.
  12777. *
  12778. * Because of the way JavaScript objects work, the ordering of data in the
  12779. * JavaScript object returned by `val()` is not guaranteed to match the
  12780. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12781. * where `forEach()` comes in handy. It guarantees the children of a
  12782. * `DataSnapshot` will be iterated in their query order.
  12783. *
  12784. * If no explicit `orderBy*()` method is used, results are returned
  12785. * ordered by key (unless priorities are used, in which case, results are
  12786. * returned by priority).
  12787. *
  12788. * @param action - A function that will be called for each child DataSnapshot.
  12789. * The callback can return true to cancel further enumeration.
  12790. * @returns true if enumeration was canceled due to your callback returning
  12791. * true.
  12792. */
  12793. DataSnapshot.prototype.forEach = function (action) {
  12794. var _this = this;
  12795. if (this._node.isLeafNode()) {
  12796. return false;
  12797. }
  12798. var childrenNode = this._node;
  12799. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12800. return !!childrenNode.forEachChild(this._index, function (key, node) {
  12801. return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
  12802. });
  12803. };
  12804. /**
  12805. * Returns true if the specified child path has (non-null) data.
  12806. *
  12807. * @param path - A relative path to the location of a potential child.
  12808. * @returns `true` if data exists at the specified child path; else
  12809. * `false`.
  12810. */
  12811. DataSnapshot.prototype.hasChild = function (path) {
  12812. var childPath = new Path(path);
  12813. return !this._node.getChild(childPath).isEmpty();
  12814. };
  12815. /**
  12816. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12817. * properties.
  12818. *
  12819. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12820. * children. If it does, you can enumerate them using `forEach()`. If it
  12821. * doesn't, then either this snapshot contains a primitive value (which can be
  12822. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12823. * `null`).
  12824. *
  12825. * @returns true if this snapshot has any children; else false.
  12826. */
  12827. DataSnapshot.prototype.hasChildren = function () {
  12828. if (this._node.isLeafNode()) {
  12829. return false;
  12830. }
  12831. else {
  12832. return !this._node.isEmpty();
  12833. }
  12834. };
  12835. /**
  12836. * Returns a JSON-serializable representation of this object.
  12837. */
  12838. DataSnapshot.prototype.toJSON = function () {
  12839. return this.exportVal();
  12840. };
  12841. /**
  12842. * Extracts a JavaScript value from a `DataSnapshot`.
  12843. *
  12844. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12845. * scalar type (string, number, or boolean), an array, or an object. It may
  12846. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12847. * data).
  12848. *
  12849. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12850. * Array, string, number, boolean, or `null`).
  12851. */
  12852. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12853. DataSnapshot.prototype.val = function () {
  12854. return this._node.val();
  12855. };
  12856. return DataSnapshot;
  12857. }());
  12858. /**
  12859. *
  12860. * Returns a `Reference` representing the location in the Database
  12861. * corresponding to the provided path. If no path is provided, the `Reference`
  12862. * will point to the root of the Database.
  12863. *
  12864. * @param db - The database instance to obtain a reference for.
  12865. * @param path - Optional path representing the location the returned
  12866. * `Reference` will point. If not provided, the returned `Reference` will
  12867. * point to the root of the Database.
  12868. * @returns If a path is provided, a `Reference`
  12869. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12870. * root of the Database.
  12871. */
  12872. function ref(db, path) {
  12873. db = util.getModularInstance(db);
  12874. db._checkNotDeleted('ref');
  12875. return path !== undefined ? child(db._root, path) : db._root;
  12876. }
  12877. /**
  12878. * Returns a `Reference` representing the location in the Database
  12879. * corresponding to the provided Firebase URL.
  12880. *
  12881. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12882. * has a different domain than the current `Database` instance.
  12883. *
  12884. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12885. * and are not applied to the returned `Reference`.
  12886. *
  12887. * @param db - The database instance to obtain a reference for.
  12888. * @param url - The Firebase URL at which the returned `Reference` will
  12889. * point.
  12890. * @returns A `Reference` pointing to the provided
  12891. * Firebase URL.
  12892. */
  12893. function refFromURL(db, url) {
  12894. db = util.getModularInstance(db);
  12895. db._checkNotDeleted('refFromURL');
  12896. var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12897. validateUrl('refFromURL', parsedURL);
  12898. var repoInfo = parsedURL.repoInfo;
  12899. if (!db._repo.repoInfo_.isCustomHost() &&
  12900. repoInfo.host !== db._repo.repoInfo_.host) {
  12901. fatal('refFromURL' +
  12902. ': Host name does not match the current database: ' +
  12903. '(found ' +
  12904. repoInfo.host +
  12905. ' but expected ' +
  12906. db._repo.repoInfo_.host +
  12907. ')');
  12908. }
  12909. return ref(db, parsedURL.path.toString());
  12910. }
  12911. /**
  12912. * Gets a `Reference` for the location at the specified relative path.
  12913. *
  12914. * The relative path can either be a simple child name (for example, "ada") or
  12915. * a deeper slash-separated path (for example, "ada/name/first").
  12916. *
  12917. * @param parent - The parent location.
  12918. * @param path - A relative path from this location to the desired child
  12919. * location.
  12920. * @returns The specified child location.
  12921. */
  12922. function child(parent, path) {
  12923. parent = util.getModularInstance(parent);
  12924. if (pathGetFront(parent._path) === null) {
  12925. validateRootPathString('child', 'path', path, false);
  12926. }
  12927. else {
  12928. validatePathString('child', 'path', path, false);
  12929. }
  12930. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12931. }
  12932. /**
  12933. * Returns an `OnDisconnect` object - see
  12934. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12935. * for more information on how to use it.
  12936. *
  12937. * @param ref - The reference to add OnDisconnect triggers for.
  12938. */
  12939. function onDisconnect(ref) {
  12940. ref = util.getModularInstance(ref);
  12941. return new OnDisconnect(ref._repo, ref._path);
  12942. }
  12943. /**
  12944. * Generates a new child location using a unique key and returns its
  12945. * `Reference`.
  12946. *
  12947. * This is the most common pattern for adding data to a collection of items.
  12948. *
  12949. * If you provide a value to `push()`, the value is written to the
  12950. * generated location. If you don't pass a value, nothing is written to the
  12951. * database and the child remains empty (but you can use the `Reference`
  12952. * elsewhere).
  12953. *
  12954. * The unique keys generated by `push()` are ordered by the current time, so the
  12955. * resulting list of items is chronologically sorted. The keys are also
  12956. * designed to be unguessable (they contain 72 random bits of entropy).
  12957. *
  12958. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12959. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12960. *
  12961. * @param parent - The parent location.
  12962. * @param value - Optional value to be written at the generated location.
  12963. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12964. * but can be used immediately as the `Reference` to the child location.
  12965. */
  12966. function push(parent, value) {
  12967. parent = util.getModularInstance(parent);
  12968. validateWritablePath('push', parent._path);
  12969. validateFirebaseDataArg('push', value, parent._path, true);
  12970. var now = repoServerTime(parent._repo);
  12971. var name = nextPushId(now);
  12972. // push() returns a ThennableReference whose promise is fulfilled with a
  12973. // regular Reference. We use child() to create handles to two different
  12974. // references. The first is turned into a ThennableReference below by adding
  12975. // then() and catch() methods and is used as the return value of push(). The
  12976. // second remains a regular Reference and is used as the fulfilled value of
  12977. // the first ThennableReference.
  12978. var thennablePushRef = child(parent, name);
  12979. var pushRef = child(parent, name);
  12980. var promise;
  12981. if (value != null) {
  12982. promise = set(pushRef, value).then(function () { return pushRef; });
  12983. }
  12984. else {
  12985. promise = Promise.resolve(pushRef);
  12986. }
  12987. thennablePushRef.then = promise.then.bind(promise);
  12988. thennablePushRef.catch = promise.then.bind(promise, undefined);
  12989. return thennablePushRef;
  12990. }
  12991. /**
  12992. * Removes the data at this Database location.
  12993. *
  12994. * Any data at child locations will also be deleted.
  12995. *
  12996. * The effect of the remove will be visible immediately and the corresponding
  12997. * event 'value' will be triggered. Synchronization of the remove to the
  12998. * Firebase servers will also be started, and the returned Promise will resolve
  12999. * when complete. If provided, the onComplete callback will be called
  13000. * asynchronously after synchronization has finished.
  13001. *
  13002. * @param ref - The location to remove.
  13003. * @returns Resolves when remove on server is complete.
  13004. */
  13005. function remove(ref) {
  13006. validateWritablePath('remove', ref._path);
  13007. return set(ref, null);
  13008. }
  13009. /**
  13010. * Writes data to this Database location.
  13011. *
  13012. * This will overwrite any data at this location and all child locations.
  13013. *
  13014. * The effect of the write will be visible immediately, and the corresponding
  13015. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  13016. * the data to the Firebase servers will also be started, and the returned
  13017. * Promise will resolve when complete. If provided, the `onComplete` callback
  13018. * will be called asynchronously after synchronization has finished.
  13019. *
  13020. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  13021. * all data at this location and all child locations will be deleted.
  13022. *
  13023. * `set()` will remove any priority stored at this location, so if priority is
  13024. * meant to be preserved, you need to use `setWithPriority()` instead.
  13025. *
  13026. * Note that modifying data with `set()` will cancel any pending transactions
  13027. * at that location, so extreme care should be taken if mixing `set()` and
  13028. * `transaction()` to modify the same data.
  13029. *
  13030. * A single `set()` will generate a single "value" event at the location where
  13031. * the `set()` was performed.
  13032. *
  13033. * @param ref - The location to write to.
  13034. * @param value - The value to be written (string, number, boolean, object,
  13035. * array, or null).
  13036. * @returns Resolves when write to server is complete.
  13037. */
  13038. function set(ref, value) {
  13039. ref = util.getModularInstance(ref);
  13040. validateWritablePath('set', ref._path);
  13041. validateFirebaseDataArg('set', value, ref._path, false);
  13042. var deferred = new util.Deferred();
  13043. repoSetWithPriority(ref._repo, ref._path, value,
  13044. /*priority=*/ null, deferred.wrapCallback(function () { }));
  13045. return deferred.promise;
  13046. }
  13047. /**
  13048. * Sets a priority for the data at this Database location.
  13049. *
  13050. * Applications need not use priority but can order collections by
  13051. * ordinary properties (see
  13052. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13053. * ).
  13054. *
  13055. * @param ref - The location to write to.
  13056. * @param priority - The priority to be written (string, number, or null).
  13057. * @returns Resolves when write to server is complete.
  13058. */
  13059. function setPriority(ref, priority) {
  13060. ref = util.getModularInstance(ref);
  13061. validateWritablePath('setPriority', ref._path);
  13062. validatePriority('setPriority', priority, false);
  13063. var deferred = new util.Deferred();
  13064. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
  13065. return deferred.promise;
  13066. }
  13067. /**
  13068. * Writes data the Database location. Like `set()` but also specifies the
  13069. * priority for that data.
  13070. *
  13071. * Applications need not use priority but can order collections by
  13072. * ordinary properties (see
  13073. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13074. * ).
  13075. *
  13076. * @param ref - The location to write to.
  13077. * @param value - The value to be written (string, number, boolean, object,
  13078. * array, or null).
  13079. * @param priority - The priority to be written (string, number, or null).
  13080. * @returns Resolves when write to server is complete.
  13081. */
  13082. function setWithPriority(ref, value, priority) {
  13083. validateWritablePath('setWithPriority', ref._path);
  13084. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  13085. validatePriority('setWithPriority', priority, false);
  13086. if (ref.key === '.length' || ref.key === '.keys') {
  13087. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  13088. }
  13089. var deferred = new util.Deferred();
  13090. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
  13091. return deferred.promise;
  13092. }
  13093. /**
  13094. * Writes multiple values to the Database at once.
  13095. *
  13096. * The `values` argument contains multiple property-value pairs that will be
  13097. * written to the Database together. Each child property can either be a simple
  13098. * property (for example, "name") or a relative path (for example,
  13099. * "name/first") from the current location to the data to update.
  13100. *
  13101. * As opposed to the `set()` method, `update()` can be use to selectively update
  13102. * only the referenced properties at the current location (instead of replacing
  13103. * all the child properties at the current location).
  13104. *
  13105. * The effect of the write will be visible immediately, and the corresponding
  13106. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  13107. * the data to the Firebase servers will also be started, and the returned
  13108. * Promise will resolve when complete. If provided, the `onComplete` callback
  13109. * will be called asynchronously after synchronization has finished.
  13110. *
  13111. * A single `update()` will generate a single "value" event at the location
  13112. * where the `update()` was performed, regardless of how many children were
  13113. * modified.
  13114. *
  13115. * Note that modifying data with `update()` will cancel any pending
  13116. * transactions at that location, so extreme care should be taken if mixing
  13117. * `update()` and `transaction()` to modify the same data.
  13118. *
  13119. * Passing `null` to `update()` will remove the data at this location.
  13120. *
  13121. * See
  13122. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  13123. *
  13124. * @param ref - The location to write to.
  13125. * @param values - Object containing multiple values.
  13126. * @returns Resolves when update on server is complete.
  13127. */
  13128. function update(ref, values) {
  13129. validateFirebaseMergeDataArg('update', values, ref._path, false);
  13130. var deferred = new util.Deferred();
  13131. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
  13132. return deferred.promise;
  13133. }
  13134. /**
  13135. * Gets the most up-to-date result for this query.
  13136. *
  13137. * @param query - The query to run.
  13138. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  13139. * available, or rejects if the client is unable to return a value (e.g., if the
  13140. * server is unreachable and there is nothing cached).
  13141. */
  13142. function get(query) {
  13143. query = util.getModularInstance(query);
  13144. var callbackContext = new CallbackContext(function () { });
  13145. var container = new ValueEventRegistration(callbackContext);
  13146. return repoGetValue(query._repo, query, container).then(function (node) {
  13147. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  13148. });
  13149. }
  13150. /**
  13151. * Represents registration for 'value' events.
  13152. */
  13153. var ValueEventRegistration = /** @class */ (function () {
  13154. function ValueEventRegistration(callbackContext) {
  13155. this.callbackContext = callbackContext;
  13156. }
  13157. ValueEventRegistration.prototype.respondsTo = function (eventType) {
  13158. return eventType === 'value';
  13159. };
  13160. ValueEventRegistration.prototype.createEvent = function (change, query) {
  13161. var index = query._queryParams.getIndex();
  13162. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  13163. };
  13164. ValueEventRegistration.prototype.getEventRunner = function (eventData) {
  13165. var _this = this;
  13166. if (eventData.getEventType() === 'cancel') {
  13167. return function () {
  13168. return _this.callbackContext.onCancel(eventData.error);
  13169. };
  13170. }
  13171. else {
  13172. return function () {
  13173. return _this.callbackContext.onValue(eventData.snapshot, null);
  13174. };
  13175. }
  13176. };
  13177. ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
  13178. if (this.callbackContext.hasCancelCallback) {
  13179. return new CancelEvent(this, error, path);
  13180. }
  13181. else {
  13182. return null;
  13183. }
  13184. };
  13185. ValueEventRegistration.prototype.matches = function (other) {
  13186. if (!(other instanceof ValueEventRegistration)) {
  13187. return false;
  13188. }
  13189. else if (!other.callbackContext || !this.callbackContext) {
  13190. // If no callback specified, we consider it to match any callback.
  13191. return true;
  13192. }
  13193. else {
  13194. return other.callbackContext.matches(this.callbackContext);
  13195. }
  13196. };
  13197. ValueEventRegistration.prototype.hasAnyCallback = function () {
  13198. return this.callbackContext !== null;
  13199. };
  13200. return ValueEventRegistration;
  13201. }());
  13202. /**
  13203. * Represents the registration of a child_x event.
  13204. */
  13205. var ChildEventRegistration = /** @class */ (function () {
  13206. function ChildEventRegistration(eventType, callbackContext) {
  13207. this.eventType = eventType;
  13208. this.callbackContext = callbackContext;
  13209. }
  13210. ChildEventRegistration.prototype.respondsTo = function (eventType) {
  13211. var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  13212. eventToCheck =
  13213. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  13214. return this.eventType === eventToCheck;
  13215. };
  13216. ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
  13217. if (this.callbackContext.hasCancelCallback) {
  13218. return new CancelEvent(this, error, path);
  13219. }
  13220. else {
  13221. return null;
  13222. }
  13223. };
  13224. ChildEventRegistration.prototype.createEvent = function (change, query) {
  13225. util.assert(change.childName != null, 'Child events should have a childName.');
  13226. var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  13227. var index = query._queryParams.getIndex();
  13228. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  13229. };
  13230. ChildEventRegistration.prototype.getEventRunner = function (eventData) {
  13231. var _this = this;
  13232. if (eventData.getEventType() === 'cancel') {
  13233. return function () {
  13234. return _this.callbackContext.onCancel(eventData.error);
  13235. };
  13236. }
  13237. else {
  13238. return function () {
  13239. return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  13240. };
  13241. }
  13242. };
  13243. ChildEventRegistration.prototype.matches = function (other) {
  13244. if (other instanceof ChildEventRegistration) {
  13245. return (this.eventType === other.eventType &&
  13246. (!this.callbackContext ||
  13247. !other.callbackContext ||
  13248. this.callbackContext.matches(other.callbackContext)));
  13249. }
  13250. return false;
  13251. };
  13252. ChildEventRegistration.prototype.hasAnyCallback = function () {
  13253. return !!this.callbackContext;
  13254. };
  13255. return ChildEventRegistration;
  13256. }());
  13257. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  13258. var cancelCallback;
  13259. if (typeof cancelCallbackOrListenOptions === 'object') {
  13260. cancelCallback = undefined;
  13261. options = cancelCallbackOrListenOptions;
  13262. }
  13263. if (typeof cancelCallbackOrListenOptions === 'function') {
  13264. cancelCallback = cancelCallbackOrListenOptions;
  13265. }
  13266. if (options && options.onlyOnce) {
  13267. var userCallback_1 = callback;
  13268. var onceCallback = function (dataSnapshot, previousChildName) {
  13269. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13270. userCallback_1(dataSnapshot, previousChildName);
  13271. };
  13272. onceCallback.userCallback = callback.userCallback;
  13273. onceCallback.context = callback.context;
  13274. callback = onceCallback;
  13275. }
  13276. var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  13277. var container = eventType === 'value'
  13278. ? new ValueEventRegistration(callbackContext)
  13279. : new ChildEventRegistration(eventType, callbackContext);
  13280. repoAddEventCallbackForQuery(query._repo, query, container);
  13281. return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
  13282. }
  13283. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  13284. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  13285. }
  13286. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  13287. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  13288. }
  13289. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  13290. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  13291. }
  13292. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  13293. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  13294. }
  13295. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  13296. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  13297. }
  13298. /**
  13299. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  13300. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  13301. * the respective `on*` callbacks.
  13302. *
  13303. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  13304. * will not automatically remove listeners registered on child nodes, `off()`
  13305. * must also be called on any child listeners to remove the callback.
  13306. *
  13307. * If a callback is not specified, all callbacks for the specified eventType
  13308. * will be removed. Similarly, if no eventType is specified, all callbacks
  13309. * for the `Reference` will be removed.
  13310. *
  13311. * Individual listeners can also be removed by invoking their unsubscribe
  13312. * callbacks.
  13313. *
  13314. * @param query - The query that the listener was registered with.
  13315. * @param eventType - One of the following strings: "value", "child_added",
  13316. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  13317. * for the `Reference` will be removed.
  13318. * @param callback - The callback function that was passed to `on()` or
  13319. * `undefined` to remove all callbacks.
  13320. */
  13321. function off(query, eventType, callback) {
  13322. var container = null;
  13323. var expCallback = callback ? new CallbackContext(callback) : null;
  13324. if (eventType === 'value') {
  13325. container = new ValueEventRegistration(expCallback);
  13326. }
  13327. else if (eventType) {
  13328. container = new ChildEventRegistration(eventType, expCallback);
  13329. }
  13330. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13331. }
  13332. /**
  13333. * A `QueryConstraint` is used to narrow the set of documents returned by a
  13334. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  13335. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  13336. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  13337. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  13338. * {@link orderByValue} or {@link equalTo} and
  13339. * can then be passed to {@link query} to create a new query instance that
  13340. * also contains this `QueryConstraint`.
  13341. */
  13342. var QueryConstraint = /** @class */ (function () {
  13343. function QueryConstraint() {
  13344. }
  13345. return QueryConstraint;
  13346. }());
  13347. var QueryEndAtConstraint = /** @class */ (function (_super) {
  13348. tslib.__extends(QueryEndAtConstraint, _super);
  13349. function QueryEndAtConstraint(_value, _key) {
  13350. var _this = _super.call(this) || this;
  13351. _this._value = _value;
  13352. _this._key = _key;
  13353. return _this;
  13354. }
  13355. QueryEndAtConstraint.prototype._apply = function (query) {
  13356. validateFirebaseDataArg('endAt', this._value, query._path, true);
  13357. var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  13358. validateLimit(newParams);
  13359. validateQueryEndpoints(newParams);
  13360. if (query._queryParams.hasEnd()) {
  13361. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  13362. 'endBefore or equalTo).');
  13363. }
  13364. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13365. };
  13366. return QueryEndAtConstraint;
  13367. }(QueryConstraint));
  13368. /**
  13369. * Creates a `QueryConstraint` with the specified ending point.
  13370. *
  13371. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13372. * allows you to choose arbitrary starting and ending points for your queries.
  13373. *
  13374. * The ending point is inclusive, so children with exactly the specified value
  13375. * will be included in the query. The optional key argument can be used to
  13376. * further limit the range of the query. If it is specified, then children that
  13377. * have exactly the specified value must also have a key name less than or equal
  13378. * to the specified key.
  13379. *
  13380. * You can read more about `endAt()` in
  13381. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13382. *
  13383. * @param value - The value to end at. The argument type depends on which
  13384. * `orderBy*()` function was used in this query. Specify a value that matches
  13385. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13386. * value must be a string.
  13387. * @param key - The child key to end at, among the children with the previously
  13388. * specified priority. This argument is only allowed if ordering by child,
  13389. * value, or priority.
  13390. */
  13391. function endAt(value, key) {
  13392. validateKey('endAt', 'key', key, true);
  13393. return new QueryEndAtConstraint(value, key);
  13394. }
  13395. var QueryEndBeforeConstraint = /** @class */ (function (_super) {
  13396. tslib.__extends(QueryEndBeforeConstraint, _super);
  13397. function QueryEndBeforeConstraint(_value, _key) {
  13398. var _this = _super.call(this) || this;
  13399. _this._value = _value;
  13400. _this._key = _key;
  13401. return _this;
  13402. }
  13403. QueryEndBeforeConstraint.prototype._apply = function (query) {
  13404. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  13405. var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  13406. validateLimit(newParams);
  13407. validateQueryEndpoints(newParams);
  13408. if (query._queryParams.hasEnd()) {
  13409. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  13410. 'endBefore or equalTo).');
  13411. }
  13412. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13413. };
  13414. return QueryEndBeforeConstraint;
  13415. }(QueryConstraint));
  13416. /**
  13417. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  13418. *
  13419. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13420. * allows you to choose arbitrary starting and ending points for your queries.
  13421. *
  13422. * The ending point is exclusive. If only a value is provided, children
  13423. * with a value less than the specified value will be included in the query.
  13424. * If a key is specified, then children must have a value less than or equal
  13425. * to the specified value and a key name less than the specified key.
  13426. *
  13427. * @param value - The value to end before. The argument type depends on which
  13428. * `orderBy*()` function was used in this query. Specify a value that matches
  13429. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13430. * value must be a string.
  13431. * @param key - The child key to end before, among the children with the
  13432. * previously specified priority. This argument is only allowed if ordering by
  13433. * child, value, or priority.
  13434. */
  13435. function endBefore(value, key) {
  13436. validateKey('endBefore', 'key', key, true);
  13437. return new QueryEndBeforeConstraint(value, key);
  13438. }
  13439. var QueryStartAtConstraint = /** @class */ (function (_super) {
  13440. tslib.__extends(QueryStartAtConstraint, _super);
  13441. function QueryStartAtConstraint(_value, _key) {
  13442. var _this = _super.call(this) || this;
  13443. _this._value = _value;
  13444. _this._key = _key;
  13445. return _this;
  13446. }
  13447. QueryStartAtConstraint.prototype._apply = function (query) {
  13448. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13449. var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13450. validateLimit(newParams);
  13451. validateQueryEndpoints(newParams);
  13452. if (query._queryParams.hasStart()) {
  13453. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13454. 'startBefore or equalTo).');
  13455. }
  13456. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13457. };
  13458. return QueryStartAtConstraint;
  13459. }(QueryConstraint));
  13460. /**
  13461. * Creates a `QueryConstraint` with the specified starting point.
  13462. *
  13463. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13464. * allows you to choose arbitrary starting and ending points for your queries.
  13465. *
  13466. * The starting point is inclusive, so children with exactly the specified value
  13467. * will be included in the query. The optional key argument can be used to
  13468. * further limit the range of the query. If it is specified, then children that
  13469. * have exactly the specified value must also have a key name greater than or
  13470. * equal to the specified key.
  13471. *
  13472. * You can read more about `startAt()` in
  13473. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13474. *
  13475. * @param value - The value to start at. The argument type depends on which
  13476. * `orderBy*()` function was used in this query. Specify a value that matches
  13477. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13478. * value must be a string.
  13479. * @param key - The child key to start at. This argument is only allowed if
  13480. * ordering by child, value, or priority.
  13481. */
  13482. function startAt(value, key) {
  13483. if (value === void 0) { value = null; }
  13484. validateKey('startAt', 'key', key, true);
  13485. return new QueryStartAtConstraint(value, key);
  13486. }
  13487. var QueryStartAfterConstraint = /** @class */ (function (_super) {
  13488. tslib.__extends(QueryStartAfterConstraint, _super);
  13489. function QueryStartAfterConstraint(_value, _key) {
  13490. var _this = _super.call(this) || this;
  13491. _this._value = _value;
  13492. _this._key = _key;
  13493. return _this;
  13494. }
  13495. QueryStartAfterConstraint.prototype._apply = function (query) {
  13496. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13497. var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13498. validateLimit(newParams);
  13499. validateQueryEndpoints(newParams);
  13500. if (query._queryParams.hasStart()) {
  13501. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13502. 'startAfter, or equalTo).');
  13503. }
  13504. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13505. };
  13506. return QueryStartAfterConstraint;
  13507. }(QueryConstraint));
  13508. /**
  13509. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13510. *
  13511. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13512. * allows you to choose arbitrary starting and ending points for your queries.
  13513. *
  13514. * The starting point is exclusive. If only a value is provided, children
  13515. * with a value greater than the specified value will be included in the query.
  13516. * If a key is specified, then children must have a value greater than or equal
  13517. * to the specified value and a a key name greater than the specified key.
  13518. *
  13519. * @param value - The value to start after. The argument type depends on which
  13520. * `orderBy*()` function was used in this query. Specify a value that matches
  13521. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13522. * value must be a string.
  13523. * @param key - The child key to start after. This argument is only allowed if
  13524. * ordering by child, value, or priority.
  13525. */
  13526. function startAfter(value, key) {
  13527. validateKey('startAfter', 'key', key, true);
  13528. return new QueryStartAfterConstraint(value, key);
  13529. }
  13530. var QueryLimitToFirstConstraint = /** @class */ (function (_super) {
  13531. tslib.__extends(QueryLimitToFirstConstraint, _super);
  13532. function QueryLimitToFirstConstraint(_limit) {
  13533. var _this = _super.call(this) || this;
  13534. _this._limit = _limit;
  13535. return _this;
  13536. }
  13537. QueryLimitToFirstConstraint.prototype._apply = function (query) {
  13538. if (query._queryParams.hasLimit()) {
  13539. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13540. 'or limitToLast).');
  13541. }
  13542. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13543. };
  13544. return QueryLimitToFirstConstraint;
  13545. }(QueryConstraint));
  13546. /**
  13547. * Creates a new `QueryConstraint` that if limited to the first specific number
  13548. * of children.
  13549. *
  13550. * The `limitToFirst()` method is used to set a maximum number of children to be
  13551. * synced for a given callback. If we set a limit of 100, we will initially only
  13552. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13553. * stored in our Database, a `child_added` event will fire for each message.
  13554. * However, if we have over 100 messages, we will only receive a `child_added`
  13555. * event for the first 100 ordered messages. As items change, we will receive
  13556. * `child_removed` events for each item that drops out of the active list so
  13557. * that the total number stays at 100.
  13558. *
  13559. * You can read more about `limitToFirst()` in
  13560. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13561. *
  13562. * @param limit - The maximum number of nodes to include in this query.
  13563. */
  13564. function limitToFirst(limit) {
  13565. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13566. throw new Error('limitToFirst: First argument must be a positive integer.');
  13567. }
  13568. return new QueryLimitToFirstConstraint(limit);
  13569. }
  13570. var QueryLimitToLastConstraint = /** @class */ (function (_super) {
  13571. tslib.__extends(QueryLimitToLastConstraint, _super);
  13572. function QueryLimitToLastConstraint(_limit) {
  13573. var _this = _super.call(this) || this;
  13574. _this._limit = _limit;
  13575. return _this;
  13576. }
  13577. QueryLimitToLastConstraint.prototype._apply = function (query) {
  13578. if (query._queryParams.hasLimit()) {
  13579. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13580. 'or limitToLast).');
  13581. }
  13582. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13583. };
  13584. return QueryLimitToLastConstraint;
  13585. }(QueryConstraint));
  13586. /**
  13587. * Creates a new `QueryConstraint` that is limited to return only the last
  13588. * specified number of children.
  13589. *
  13590. * The `limitToLast()` method is used to set a maximum number of children to be
  13591. * synced for a given callback. If we set a limit of 100, we will initially only
  13592. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13593. * stored in our Database, a `child_added` event will fire for each message.
  13594. * However, if we have over 100 messages, we will only receive a `child_added`
  13595. * event for the last 100 ordered messages. As items change, we will receive
  13596. * `child_removed` events for each item that drops out of the active list so
  13597. * that the total number stays at 100.
  13598. *
  13599. * You can read more about `limitToLast()` in
  13600. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13601. *
  13602. * @param limit - The maximum number of nodes to include in this query.
  13603. */
  13604. function limitToLast(limit) {
  13605. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13606. throw new Error('limitToLast: First argument must be a positive integer.');
  13607. }
  13608. return new QueryLimitToLastConstraint(limit);
  13609. }
  13610. var QueryOrderByChildConstraint = /** @class */ (function (_super) {
  13611. tslib.__extends(QueryOrderByChildConstraint, _super);
  13612. function QueryOrderByChildConstraint(_path) {
  13613. var _this = _super.call(this) || this;
  13614. _this._path = _path;
  13615. return _this;
  13616. }
  13617. QueryOrderByChildConstraint.prototype._apply = function (query) {
  13618. validateNoPreviousOrderByCall(query, 'orderByChild');
  13619. var parsedPath = new Path(this._path);
  13620. if (pathIsEmpty(parsedPath)) {
  13621. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13622. }
  13623. var index = new PathIndex(parsedPath);
  13624. var newParams = queryParamsOrderBy(query._queryParams, index);
  13625. validateQueryEndpoints(newParams);
  13626. return new QueryImpl(query._repo, query._path, newParams,
  13627. /*orderByCalled=*/ true);
  13628. };
  13629. return QueryOrderByChildConstraint;
  13630. }(QueryConstraint));
  13631. /**
  13632. * Creates a new `QueryConstraint` that orders by the specified child key.
  13633. *
  13634. * Queries can only order by one key at a time. Calling `orderByChild()`
  13635. * multiple times on the same query is an error.
  13636. *
  13637. * Firebase queries allow you to order your data by any child key on the fly.
  13638. * However, if you know in advance what your indexes will be, you can define
  13639. * them via the .indexOn rule in your Security Rules for better performance. See
  13640. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13641. * rule for more information.
  13642. *
  13643. * You can read more about `orderByChild()` in
  13644. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13645. *
  13646. * @param path - The path to order by.
  13647. */
  13648. function orderByChild(path) {
  13649. if (path === '$key') {
  13650. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13651. }
  13652. else if (path === '$priority') {
  13653. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13654. }
  13655. else if (path === '$value') {
  13656. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13657. }
  13658. validatePathString('orderByChild', 'path', path, false);
  13659. return new QueryOrderByChildConstraint(path);
  13660. }
  13661. var QueryOrderByKeyConstraint = /** @class */ (function (_super) {
  13662. tslib.__extends(QueryOrderByKeyConstraint, _super);
  13663. function QueryOrderByKeyConstraint() {
  13664. return _super !== null && _super.apply(this, arguments) || this;
  13665. }
  13666. QueryOrderByKeyConstraint.prototype._apply = function (query) {
  13667. validateNoPreviousOrderByCall(query, 'orderByKey');
  13668. var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13669. validateQueryEndpoints(newParams);
  13670. return new QueryImpl(query._repo, query._path, newParams,
  13671. /*orderByCalled=*/ true);
  13672. };
  13673. return QueryOrderByKeyConstraint;
  13674. }(QueryConstraint));
  13675. /**
  13676. * Creates a new `QueryConstraint` that orders by the key.
  13677. *
  13678. * Sorts the results of a query by their (ascending) key values.
  13679. *
  13680. * You can read more about `orderByKey()` in
  13681. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13682. */
  13683. function orderByKey() {
  13684. return new QueryOrderByKeyConstraint();
  13685. }
  13686. var QueryOrderByPriorityConstraint = /** @class */ (function (_super) {
  13687. tslib.__extends(QueryOrderByPriorityConstraint, _super);
  13688. function QueryOrderByPriorityConstraint() {
  13689. return _super !== null && _super.apply(this, arguments) || this;
  13690. }
  13691. QueryOrderByPriorityConstraint.prototype._apply = function (query) {
  13692. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13693. var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13694. validateQueryEndpoints(newParams);
  13695. return new QueryImpl(query._repo, query._path, newParams,
  13696. /*orderByCalled=*/ true);
  13697. };
  13698. return QueryOrderByPriorityConstraint;
  13699. }(QueryConstraint));
  13700. /**
  13701. * Creates a new `QueryConstraint` that orders by priority.
  13702. *
  13703. * Applications need not use priority but can order collections by
  13704. * ordinary properties (see
  13705. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13706. * for alternatives to priority.
  13707. */
  13708. function orderByPriority() {
  13709. return new QueryOrderByPriorityConstraint();
  13710. }
  13711. var QueryOrderByValueConstraint = /** @class */ (function (_super) {
  13712. tslib.__extends(QueryOrderByValueConstraint, _super);
  13713. function QueryOrderByValueConstraint() {
  13714. return _super !== null && _super.apply(this, arguments) || this;
  13715. }
  13716. QueryOrderByValueConstraint.prototype._apply = function (query) {
  13717. validateNoPreviousOrderByCall(query, 'orderByValue');
  13718. var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13719. validateQueryEndpoints(newParams);
  13720. return new QueryImpl(query._repo, query._path, newParams,
  13721. /*orderByCalled=*/ true);
  13722. };
  13723. return QueryOrderByValueConstraint;
  13724. }(QueryConstraint));
  13725. /**
  13726. * Creates a new `QueryConstraint` that orders by value.
  13727. *
  13728. * If the children of a query are all scalar values (string, number, or
  13729. * boolean), you can order the results by their (ascending) values.
  13730. *
  13731. * You can read more about `orderByValue()` in
  13732. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13733. */
  13734. function orderByValue() {
  13735. return new QueryOrderByValueConstraint();
  13736. }
  13737. var QueryEqualToValueConstraint = /** @class */ (function (_super) {
  13738. tslib.__extends(QueryEqualToValueConstraint, _super);
  13739. function QueryEqualToValueConstraint(_value, _key) {
  13740. var _this = _super.call(this) || this;
  13741. _this._value = _value;
  13742. _this._key = _key;
  13743. return _this;
  13744. }
  13745. QueryEqualToValueConstraint.prototype._apply = function (query) {
  13746. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13747. if (query._queryParams.hasStart()) {
  13748. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13749. 'equalTo).');
  13750. }
  13751. if (query._queryParams.hasEnd()) {
  13752. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13753. 'equalTo).');
  13754. }
  13755. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13756. };
  13757. return QueryEqualToValueConstraint;
  13758. }(QueryConstraint));
  13759. /**
  13760. * Creates a `QueryConstraint` that includes children that match the specified
  13761. * value.
  13762. *
  13763. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13764. * allows you to choose arbitrary starting and ending points for your queries.
  13765. *
  13766. * The optional key argument can be used to further limit the range of the
  13767. * query. If it is specified, then children that have exactly the specified
  13768. * value must also have exactly the specified key as their key name. This can be
  13769. * used to filter result sets with many matches for the same value.
  13770. *
  13771. * You can read more about `equalTo()` in
  13772. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13773. *
  13774. * @param value - The value to match for. The argument type depends on which
  13775. * `orderBy*()` function was used in this query. Specify a value that matches
  13776. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13777. * value must be a string.
  13778. * @param key - The child key to start at, among the children with the
  13779. * previously specified priority. This argument is only allowed if ordering by
  13780. * child, value, or priority.
  13781. */
  13782. function equalTo(value, key) {
  13783. validateKey('equalTo', 'key', key, true);
  13784. return new QueryEqualToValueConstraint(value, key);
  13785. }
  13786. /**
  13787. * Creates a new immutable instance of `Query` that is extended to also include
  13788. * additional query constraints.
  13789. *
  13790. * @param query - The Query instance to use as a base for the new constraints.
  13791. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13792. * @throws if any of the provided query constraints cannot be combined with the
  13793. * existing or new constraints.
  13794. */
  13795. function query(query) {
  13796. var e_1, _a;
  13797. var queryConstraints = [];
  13798. for (var _i = 1; _i < arguments.length; _i++) {
  13799. queryConstraints[_i - 1] = arguments[_i];
  13800. }
  13801. var queryImpl = util.getModularInstance(query);
  13802. try {
  13803. for (var queryConstraints_1 = tslib.__values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
  13804. var constraint = queryConstraints_1_1.value;
  13805. queryImpl = constraint._apply(queryImpl);
  13806. }
  13807. }
  13808. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  13809. finally {
  13810. try {
  13811. if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
  13812. }
  13813. finally { if (e_1) throw e_1.error; }
  13814. }
  13815. return queryImpl;
  13816. }
  13817. /**
  13818. * Define reference constructor in various modules
  13819. *
  13820. * We are doing this here to avoid several circular
  13821. * dependency issues
  13822. */
  13823. syncPointSetReferenceConstructor(ReferenceImpl);
  13824. syncTreeSetReferenceConstructor(ReferenceImpl);
  13825. /**
  13826. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13827. * modifying this definition, consult the definition in:
  13828. *
  13829. * https://github.com/firebase/firebase-admin-node
  13830. *
  13831. * and make sure the two are consistent.
  13832. */
  13833. var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13834. /**
  13835. * Creates and caches `Repo` instances.
  13836. */
  13837. var repos = {};
  13838. /**
  13839. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13840. */
  13841. var useRestClient = false;
  13842. /**
  13843. * Update an existing `Repo` in place to point to a new host/port.
  13844. */
  13845. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13846. repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
  13847. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
  13848. if (tokenProvider) {
  13849. repo.authTokenProvider_ = tokenProvider;
  13850. }
  13851. }
  13852. /**
  13853. * This function should only ever be called to CREATE a new database instance.
  13854. * @internal
  13855. */
  13856. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13857. var dbUrl = url || app.options.databaseURL;
  13858. if (dbUrl === undefined) {
  13859. if (!app.options.projectId) {
  13860. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13861. ' a Project ID when calling firebase.initializeApp().');
  13862. }
  13863. log('Using default host for project ', app.options.projectId);
  13864. dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
  13865. }
  13866. var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13867. var repoInfo = parsedUrl.repoInfo;
  13868. var isEmulator;
  13869. var dbEmulatorHost = undefined;
  13870. if (typeof process !== 'undefined' && process.env) {
  13871. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13872. }
  13873. if (dbEmulatorHost) {
  13874. isEmulator = true;
  13875. dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
  13876. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13877. repoInfo = parsedUrl.repoInfo;
  13878. }
  13879. else {
  13880. isEmulator = !parsedUrl.repoInfo.secure;
  13881. }
  13882. var authTokenProvider = nodeAdmin && isEmulator
  13883. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13884. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13885. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13886. if (!pathIsEmpty(parsedUrl.path)) {
  13887. fatal('Database URL must point to the root of a Firebase Database ' +
  13888. '(not including a child path).');
  13889. }
  13890. var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13891. return new Database(repo, app);
  13892. }
  13893. /**
  13894. * Remove the repo and make sure it is disconnected.
  13895. *
  13896. */
  13897. function repoManagerDeleteRepo(repo, appName) {
  13898. var appRepos = repos[appName];
  13899. // This should never happen...
  13900. if (!appRepos || appRepos[repo.key] !== repo) {
  13901. fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
  13902. }
  13903. repoInterrupt(repo);
  13904. delete appRepos[repo.key];
  13905. }
  13906. /**
  13907. * Ensures a repo doesn't already exist and then creates one using the
  13908. * provided app.
  13909. *
  13910. * @param repoInfo - The metadata about the Repo
  13911. * @returns The Repo object for the specified server / repoName.
  13912. */
  13913. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13914. var appRepos = repos[app.name];
  13915. if (!appRepos) {
  13916. appRepos = {};
  13917. repos[app.name] = appRepos;
  13918. }
  13919. var repo = appRepos[repoInfo.toURLString()];
  13920. if (repo) {
  13921. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13922. }
  13923. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13924. appRepos[repoInfo.toURLString()] = repo;
  13925. return repo;
  13926. }
  13927. /**
  13928. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13929. */
  13930. function repoManagerForceRestClient(forceRestClient) {
  13931. useRestClient = forceRestClient;
  13932. }
  13933. /**
  13934. * Class representing a Firebase Realtime Database.
  13935. */
  13936. var Database = /** @class */ (function () {
  13937. /** @hideconstructor */
  13938. function Database(_repoInternal,
  13939. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13940. app) {
  13941. this._repoInternal = _repoInternal;
  13942. this.app = app;
  13943. /** Represents a `Database` instance. */
  13944. this['type'] = 'database';
  13945. /** Track if the instance has been used (root or repo accessed) */
  13946. this._instanceStarted = false;
  13947. }
  13948. Object.defineProperty(Database.prototype, "_repo", {
  13949. get: function () {
  13950. if (!this._instanceStarted) {
  13951. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13952. this._instanceStarted = true;
  13953. }
  13954. return this._repoInternal;
  13955. },
  13956. enumerable: false,
  13957. configurable: true
  13958. });
  13959. Object.defineProperty(Database.prototype, "_root", {
  13960. get: function () {
  13961. if (!this._rootInternal) {
  13962. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13963. }
  13964. return this._rootInternal;
  13965. },
  13966. enumerable: false,
  13967. configurable: true
  13968. });
  13969. Database.prototype._delete = function () {
  13970. if (this._rootInternal !== null) {
  13971. repoManagerDeleteRepo(this._repo, this.app.name);
  13972. this._repoInternal = null;
  13973. this._rootInternal = null;
  13974. }
  13975. return Promise.resolve();
  13976. };
  13977. Database.prototype._checkNotDeleted = function (apiName) {
  13978. if (this._rootInternal === null) {
  13979. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13980. }
  13981. };
  13982. return Database;
  13983. }());
  13984. function checkTransportInit() {
  13985. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13986. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13987. }
  13988. }
  13989. /**
  13990. * Force the use of websockets instead of longPolling.
  13991. */
  13992. function forceWebSockets() {
  13993. checkTransportInit();
  13994. BrowserPollConnection.forceDisallow();
  13995. }
  13996. /**
  13997. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13998. */
  13999. function forceLongPolling() {
  14000. checkTransportInit();
  14001. WebSocketConnection.forceDisallow();
  14002. BrowserPollConnection.forceAllow();
  14003. }
  14004. /**
  14005. * Modify the provided instance to communicate with the Realtime Database
  14006. * emulator.
  14007. *
  14008. * <p>Note: This method must be called before performing any other operation.
  14009. *
  14010. * @param db - The instance to modify.
  14011. * @param host - The emulator host (ex: localhost)
  14012. * @param port - The emulator port (ex: 8080)
  14013. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  14014. */
  14015. function connectDatabaseEmulator(db, host, port, options) {
  14016. if (options === void 0) { options = {}; }
  14017. db = util.getModularInstance(db);
  14018. db._checkNotDeleted('useEmulator');
  14019. if (db._instanceStarted) {
  14020. fatal('Cannot call useEmulator() after instance has already been initialized.');
  14021. }
  14022. var repo = db._repoInternal;
  14023. var tokenProvider = undefined;
  14024. if (repo.repoInfo_.nodeAdmin) {
  14025. if (options.mockUserToken) {
  14026. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  14027. }
  14028. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  14029. }
  14030. else if (options.mockUserToken) {
  14031. var token = typeof options.mockUserToken === 'string'
  14032. ? options.mockUserToken
  14033. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  14034. tokenProvider = new EmulatorTokenProvider(token);
  14035. }
  14036. // Modify the repo to apply emulator settings
  14037. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  14038. }
  14039. /**
  14040. * Disconnects from the server (all Database operations will be completed
  14041. * offline).
  14042. *
  14043. * The client automatically maintains a persistent connection to the Database
  14044. * server, which will remain active indefinitely and reconnect when
  14045. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  14046. * to control the client connection in cases where a persistent connection is
  14047. * undesirable.
  14048. *
  14049. * While offline, the client will no longer receive data updates from the
  14050. * Database. However, all Database operations performed locally will continue to
  14051. * immediately fire events, allowing your application to continue behaving
  14052. * normally. Additionally, each operation performed locally will automatically
  14053. * be queued and retried upon reconnection to the Database server.
  14054. *
  14055. * To reconnect to the Database and begin receiving remote events, see
  14056. * `goOnline()`.
  14057. *
  14058. * @param db - The instance to disconnect.
  14059. */
  14060. function goOffline(db) {
  14061. db = util.getModularInstance(db);
  14062. db._checkNotDeleted('goOffline');
  14063. repoInterrupt(db._repo);
  14064. }
  14065. /**
  14066. * Reconnects to the server and synchronizes the offline Database state
  14067. * with the server state.
  14068. *
  14069. * This method should be used after disabling the active connection with
  14070. * `goOffline()`. Once reconnected, the client will transmit the proper data
  14071. * and fire the appropriate events so that your client "catches up"
  14072. * automatically.
  14073. *
  14074. * @param db - The instance to reconnect.
  14075. */
  14076. function goOnline(db) {
  14077. db = util.getModularInstance(db);
  14078. db._checkNotDeleted('goOnline');
  14079. repoResume(db._repo);
  14080. }
  14081. function enableLogging(logger, persistent) {
  14082. enableLogging$1(logger, persistent);
  14083. }
  14084. /**
  14085. * @license
  14086. * Copyright 2020 Google LLC
  14087. *
  14088. * Licensed under the Apache License, Version 2.0 (the "License");
  14089. * you may not use this file except in compliance with the License.
  14090. * You may obtain a copy of the License at
  14091. *
  14092. * http://www.apache.org/licenses/LICENSE-2.0
  14093. *
  14094. * Unless required by applicable law or agreed to in writing, software
  14095. * distributed under the License is distributed on an "AS IS" BASIS,
  14096. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14097. * See the License for the specific language governing permissions and
  14098. * limitations under the License.
  14099. */
  14100. var SERVER_TIMESTAMP = {
  14101. '.sv': 'timestamp'
  14102. };
  14103. /**
  14104. * Returns a placeholder value for auto-populating the current timestamp (time
  14105. * since the Unix epoch, in milliseconds) as determined by the Firebase
  14106. * servers.
  14107. */
  14108. function serverTimestamp() {
  14109. return SERVER_TIMESTAMP;
  14110. }
  14111. /**
  14112. * Returns a placeholder value that can be used to atomically increment the
  14113. * current database value by the provided delta.
  14114. *
  14115. * @param delta - the amount to modify the current value atomically.
  14116. * @returns A placeholder value for modifying data atomically server-side.
  14117. */
  14118. function increment(delta) {
  14119. return {
  14120. '.sv': {
  14121. 'increment': delta
  14122. }
  14123. };
  14124. }
  14125. /**
  14126. * @license
  14127. * Copyright 2020 Google LLC
  14128. *
  14129. * Licensed under the Apache License, Version 2.0 (the "License");
  14130. * you may not use this file except in compliance with the License.
  14131. * You may obtain a copy of the License at
  14132. *
  14133. * http://www.apache.org/licenses/LICENSE-2.0
  14134. *
  14135. * Unless required by applicable law or agreed to in writing, software
  14136. * distributed under the License is distributed on an "AS IS" BASIS,
  14137. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14138. * See the License for the specific language governing permissions and
  14139. * limitations under the License.
  14140. */
  14141. /**
  14142. * A type for the resolve value of {@link runTransaction}.
  14143. */
  14144. var TransactionResult = /** @class */ (function () {
  14145. /** @hideconstructor */
  14146. function TransactionResult(
  14147. /** Whether the transaction was successfully committed. */
  14148. committed,
  14149. /** The resulting data snapshot. */
  14150. snapshot) {
  14151. this.committed = committed;
  14152. this.snapshot = snapshot;
  14153. }
  14154. /** Returns a JSON-serializable representation of this object. */
  14155. TransactionResult.prototype.toJSON = function () {
  14156. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  14157. };
  14158. return TransactionResult;
  14159. }());
  14160. /**
  14161. * Atomically modifies the data at this location.
  14162. *
  14163. * Atomically modify the data at this location. Unlike a normal `set()`, which
  14164. * just overwrites the data regardless of its previous value, `runTransaction()` is
  14165. * used to modify the existing value to a new value, ensuring there are no
  14166. * conflicts with other clients writing to the same location at the same time.
  14167. *
  14168. * To accomplish this, you pass `runTransaction()` an update function which is
  14169. * used to transform the current value into a new value. If another client
  14170. * writes to the location before your new value is successfully written, your
  14171. * update function will be called again with the new current value, and the
  14172. * write will be retried. This will happen repeatedly until your write succeeds
  14173. * without conflict or you abort the transaction by not returning a value from
  14174. * your update function.
  14175. *
  14176. * Note: Modifying data with `set()` will cancel any pending transactions at
  14177. * that location, so extreme care should be taken if mixing `set()` and
  14178. * `runTransaction()` to update the same data.
  14179. *
  14180. * Note: When using transactions with Security and Firebase Rules in place, be
  14181. * aware that a client needs `.read` access in addition to `.write` access in
  14182. * order to perform a transaction. This is because the client-side nature of
  14183. * transactions requires the client to read the data in order to transactionally
  14184. * update it.
  14185. *
  14186. * @param ref - The location to atomically modify.
  14187. * @param transactionUpdate - A developer-supplied function which will be passed
  14188. * the current data stored at this location (as a JavaScript object). The
  14189. * function should return the new value it would like written (as a JavaScript
  14190. * object). If `undefined` is returned (i.e. you return with no arguments) the
  14191. * transaction will be aborted and the data at this location will not be
  14192. * modified.
  14193. * @param options - An options object to configure transactions.
  14194. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  14195. * callback to handle success and failure.
  14196. */
  14197. function runTransaction(ref,
  14198. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14199. transactionUpdate, options) {
  14200. var _a;
  14201. ref = util.getModularInstance(ref);
  14202. validateWritablePath('Reference.transaction', ref._path);
  14203. if (ref.key === '.length' || ref.key === '.keys') {
  14204. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  14205. }
  14206. var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  14207. var deferred = new util.Deferred();
  14208. var promiseComplete = function (error, committed, node) {
  14209. var dataSnapshot = null;
  14210. if (error) {
  14211. deferred.reject(error);
  14212. }
  14213. else {
  14214. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  14215. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  14216. }
  14217. };
  14218. // Add a watch to make sure we get server updates.
  14219. var unwatcher = onValue(ref, function () { });
  14220. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  14221. return deferred.promise;
  14222. }
  14223. /**
  14224. * @license
  14225. * Copyright 2017 Google LLC
  14226. *
  14227. * Licensed under the Apache License, Version 2.0 (the "License");
  14228. * you may not use this file except in compliance with the License.
  14229. * You may obtain a copy of the License at
  14230. *
  14231. * http://www.apache.org/licenses/LICENSE-2.0
  14232. *
  14233. * Unless required by applicable law or agreed to in writing, software
  14234. * distributed under the License is distributed on an "AS IS" BASIS,
  14235. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14236. * See the License for the specific language governing permissions and
  14237. * limitations under the License.
  14238. */
  14239. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14240. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  14241. this.sendRequest('q', { p: pathString }, onComplete);
  14242. };
  14243. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14244. PersistentConnection.prototype.echo = function (data, onEcho) {
  14245. this.sendRequest('echo', { d: data }, onEcho);
  14246. };
  14247. /**
  14248. * @internal
  14249. */
  14250. var hijackHash = function (newHash) {
  14251. var oldPut = PersistentConnection.prototype.put;
  14252. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  14253. if (hash !== undefined) {
  14254. hash = newHash();
  14255. }
  14256. oldPut.call(this, pathString, data, onComplete, hash);
  14257. };
  14258. return function () {
  14259. PersistentConnection.prototype.put = oldPut;
  14260. };
  14261. };
  14262. /**
  14263. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  14264. * @internal
  14265. */
  14266. var forceRestClient = function (forceRestClient) {
  14267. repoManagerForceRestClient(forceRestClient);
  14268. };
  14269. /**
  14270. * @license
  14271. * Copyright 2021 Google LLC
  14272. *
  14273. * Licensed under the Apache License, Version 2.0 (the "License");
  14274. * you may not use this file except in compliance with the License.
  14275. * You may obtain a copy of the License at
  14276. *
  14277. * http://www.apache.org/licenses/LICENSE-2.0
  14278. *
  14279. * Unless required by applicable law or agreed to in writing, software
  14280. * distributed under the License is distributed on an "AS IS" BASIS,
  14281. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14282. * See the License for the specific language governing permissions and
  14283. * limitations under the License.
  14284. */
  14285. setWebSocketImpl(Websocket__default["default"].Client);
  14286. exports.DataSnapshot = DataSnapshot;
  14287. exports.Database = Database;
  14288. exports.OnDisconnect = OnDisconnect;
  14289. exports.QueryConstraint = QueryConstraint;
  14290. exports.TransactionResult = TransactionResult;
  14291. exports._QueryImpl = QueryImpl;
  14292. exports._QueryParams = QueryParams;
  14293. exports._ReferenceImpl = ReferenceImpl;
  14294. exports._TEST_ACCESS_forceRestClient = forceRestClient;
  14295. exports._TEST_ACCESS_hijackHash = hijackHash;
  14296. exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  14297. exports._setSDKVersion = setSDKVersion;
  14298. exports._validatePathString = validatePathString;
  14299. exports._validateWritablePath = validateWritablePath;
  14300. exports.child = child;
  14301. exports.connectDatabaseEmulator = connectDatabaseEmulator;
  14302. exports.enableLogging = enableLogging;
  14303. exports.endAt = endAt;
  14304. exports.endBefore = endBefore;
  14305. exports.equalTo = equalTo;
  14306. exports.forceLongPolling = forceLongPolling;
  14307. exports.forceWebSockets = forceWebSockets;
  14308. exports.get = get;
  14309. exports.goOffline = goOffline;
  14310. exports.goOnline = goOnline;
  14311. exports.increment = increment;
  14312. exports.limitToFirst = limitToFirst;
  14313. exports.limitToLast = limitToLast;
  14314. exports.off = off;
  14315. exports.onChildAdded = onChildAdded;
  14316. exports.onChildChanged = onChildChanged;
  14317. exports.onChildMoved = onChildMoved;
  14318. exports.onChildRemoved = onChildRemoved;
  14319. exports.onDisconnect = onDisconnect;
  14320. exports.onValue = onValue;
  14321. exports.orderByChild = orderByChild;
  14322. exports.orderByKey = orderByKey;
  14323. exports.orderByPriority = orderByPriority;
  14324. exports.orderByValue = orderByValue;
  14325. exports.push = push;
  14326. exports.query = query;
  14327. exports.ref = ref;
  14328. exports.refFromURL = refFromURL;
  14329. exports.remove = remove;
  14330. exports.runTransaction = runTransaction;
  14331. exports.serverTimestamp = serverTimestamp;
  14332. exports.set = set;
  14333. exports.setPriority = setPriority;
  14334. exports.setWithPriority = setWithPriority;
  14335. exports.startAfter = startAfter;
  14336. exports.startAt = startAt;
  14337. exports.update = update;
  14338. //# sourceMappingURL=index.standalone.js.map