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.

13952 lines
535 KiB

2 months ago
  1. import Websocket from 'faye-websocket';
  2. import { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';
  3. import { Logger, LogLevel } from '@firebase/logger';
  4. import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';
  5. import { Component } from '@firebase/component';
  6. /**
  7. * @license
  8. * Copyright 2017 Google LLC
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. */
  22. const PROTOCOL_VERSION = '5';
  23. const VERSION_PARAM = 'v';
  24. const TRANSPORT_SESSION_PARAM = 's';
  25. const REFERER_PARAM = 'r';
  26. const FORGE_REF = 'f';
  27. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  28. // firebase.corp.google.com
  29. const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  30. const LAST_SESSION_PARAM = 'ls';
  31. const APPLICATION_ID_PARAM = 'p';
  32. const APP_CHECK_TOKEN_PARAM = 'ac';
  33. const WEBSOCKET = 'websocket';
  34. const LONG_POLLING = 'long_polling';
  35. /**
  36. * @license
  37. * Copyright 2017 Google LLC
  38. *
  39. * Licensed under the Apache License, Version 2.0 (the "License");
  40. * you may not use this file except in compliance with the License.
  41. * You may obtain a copy of the License at
  42. *
  43. * http://www.apache.org/licenses/LICENSE-2.0
  44. *
  45. * Unless required by applicable law or agreed to in writing, software
  46. * distributed under the License is distributed on an "AS IS" BASIS,
  47. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  48. * See the License for the specific language governing permissions and
  49. * limitations under the License.
  50. */
  51. /**
  52. * Wraps a DOM Storage object and:
  53. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  54. * - prefixes names with "firebase:" to avoid collisions with app data.
  55. *
  56. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  57. * and one for localStorage.
  58. *
  59. */
  60. class DOMStorageWrapper {
  61. /**
  62. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  63. */
  64. constructor(domStorage_) {
  65. this.domStorage_ = domStorage_;
  66. // Use a prefix to avoid collisions with other stuff saved by the app.
  67. this.prefix_ = 'firebase:';
  68. }
  69. /**
  70. * @param key - The key to save the value under
  71. * @param value - The value being stored, or null to remove the key.
  72. */
  73. set(key, value) {
  74. if (value == null) {
  75. this.domStorage_.removeItem(this.prefixedName_(key));
  76. }
  77. else {
  78. this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
  79. }
  80. }
  81. /**
  82. * @returns The value that was stored under this key, or null
  83. */
  84. get(key) {
  85. const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  86. if (storedVal == null) {
  87. return null;
  88. }
  89. else {
  90. return jsonEval(storedVal);
  91. }
  92. }
  93. remove(key) {
  94. this.domStorage_.removeItem(this.prefixedName_(key));
  95. }
  96. prefixedName_(name) {
  97. return this.prefix_ + name;
  98. }
  99. toString() {
  100. return this.domStorage_.toString();
  101. }
  102. }
  103. /**
  104. * @license
  105. * Copyright 2017 Google LLC
  106. *
  107. * Licensed under the Apache License, Version 2.0 (the "License");
  108. * you may not use this file except in compliance with the License.
  109. * You may obtain a copy of the License at
  110. *
  111. * http://www.apache.org/licenses/LICENSE-2.0
  112. *
  113. * Unless required by applicable law or agreed to in writing, software
  114. * distributed under the License is distributed on an "AS IS" BASIS,
  115. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  116. * See the License for the specific language governing permissions and
  117. * limitations under the License.
  118. */
  119. /**
  120. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  121. * (TODO: create interface for both to implement).
  122. */
  123. class MemoryStorage {
  124. constructor() {
  125. this.cache_ = {};
  126. this.isInMemoryStorage = true;
  127. }
  128. set(key, value) {
  129. if (value == null) {
  130. delete this.cache_[key];
  131. }
  132. else {
  133. this.cache_[key] = value;
  134. }
  135. }
  136. get(key) {
  137. if (contains(this.cache_, key)) {
  138. return this.cache_[key];
  139. }
  140. return null;
  141. }
  142. remove(key) {
  143. delete this.cache_[key];
  144. }
  145. }
  146. /**
  147. * @license
  148. * Copyright 2017 Google LLC
  149. *
  150. * Licensed under the Apache License, Version 2.0 (the "License");
  151. * you may not use this file except in compliance with the License.
  152. * You may obtain a copy of the License at
  153. *
  154. * http://www.apache.org/licenses/LICENSE-2.0
  155. *
  156. * Unless required by applicable law or agreed to in writing, software
  157. * distributed under the License is distributed on an "AS IS" BASIS,
  158. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  159. * See the License for the specific language governing permissions and
  160. * limitations under the License.
  161. */
  162. /**
  163. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  164. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  165. * to reflect this type
  166. *
  167. * @param domStorageName - Name of the underlying storage object
  168. * (e.g. 'localStorage' or 'sessionStorage').
  169. * @returns Turning off type information until a common interface is defined.
  170. */
  171. const createStoragefor = function (domStorageName) {
  172. try {
  173. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  174. // so it must be inside the try/catch.
  175. if (typeof window !== 'undefined' &&
  176. typeof window[domStorageName] !== 'undefined') {
  177. // Need to test cache. Just because it's here doesn't mean it works
  178. const domStorage = window[domStorageName];
  179. domStorage.setItem('firebase:sentinel', 'cache');
  180. domStorage.removeItem('firebase:sentinel');
  181. return new DOMStorageWrapper(domStorage);
  182. }
  183. }
  184. catch (e) { }
  185. // Failed to create wrapper. Just return in-memory storage.
  186. // TODO: log?
  187. return new MemoryStorage();
  188. };
  189. /** A storage object that lasts across sessions */
  190. const PersistentStorage = createStoragefor('localStorage');
  191. /** A storage object that only lasts one session */
  192. const SessionStorage = createStoragefor('sessionStorage');
  193. /**
  194. * @license
  195. * Copyright 2017 Google LLC
  196. *
  197. * Licensed under the Apache License, Version 2.0 (the "License");
  198. * you may not use this file except in compliance with the License.
  199. * You may obtain a copy of the License at
  200. *
  201. * http://www.apache.org/licenses/LICENSE-2.0
  202. *
  203. * Unless required by applicable law or agreed to in writing, software
  204. * distributed under the License is distributed on an "AS IS" BASIS,
  205. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  206. * See the License for the specific language governing permissions and
  207. * limitations under the License.
  208. */
  209. const logClient = new Logger('@firebase/database');
  210. /**
  211. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  212. */
  213. const LUIDGenerator = (function () {
  214. let id = 1;
  215. return function () {
  216. return id++;
  217. };
  218. })();
  219. /**
  220. * Sha1 hash of the input string
  221. * @param str - The string to hash
  222. * @returns {!string} The resulting hash
  223. */
  224. const sha1 = function (str) {
  225. const utf8Bytes = stringToByteArray(str);
  226. const sha1 = new Sha1();
  227. sha1.update(utf8Bytes);
  228. const sha1Bytes = sha1.digest();
  229. return base64.encodeByteArray(sha1Bytes);
  230. };
  231. const buildLogMessage_ = function (...varArgs) {
  232. let message = '';
  233. for (let i = 0; i < varArgs.length; i++) {
  234. const arg = varArgs[i];
  235. if (Array.isArray(arg) ||
  236. (arg &&
  237. typeof arg === 'object' &&
  238. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  239. typeof arg.length === 'number')) {
  240. message += buildLogMessage_.apply(null, arg);
  241. }
  242. else if (typeof arg === 'object') {
  243. message += stringify(arg);
  244. }
  245. else {
  246. message += arg;
  247. }
  248. message += ' ';
  249. }
  250. return message;
  251. };
  252. /**
  253. * Use this for all debug messages in Firebase.
  254. */
  255. let logger = null;
  256. /**
  257. * Flag to check for log availability on first log message
  258. */
  259. let firstLog_ = true;
  260. /**
  261. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  262. * @param logger_ - A flag to turn on logging, or a custom logger
  263. * @param persistent - Whether or not to persist logging settings across refreshes
  264. */
  265. const enableLogging$1 = function (logger_, persistent) {
  266. assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  267. if (logger_ === true) {
  268. logClient.logLevel = LogLevel.VERBOSE;
  269. logger = logClient.log.bind(logClient);
  270. if (persistent) {
  271. SessionStorage.set('logging_enabled', true);
  272. }
  273. }
  274. else if (typeof logger_ === 'function') {
  275. logger = logger_;
  276. }
  277. else {
  278. logger = null;
  279. SessionStorage.remove('logging_enabled');
  280. }
  281. };
  282. const log = function (...varArgs) {
  283. if (firstLog_ === true) {
  284. firstLog_ = false;
  285. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  286. enableLogging$1(true);
  287. }
  288. }
  289. if (logger) {
  290. const message = buildLogMessage_.apply(null, varArgs);
  291. logger(message);
  292. }
  293. };
  294. const logWrapper = function (prefix) {
  295. return function (...varArgs) {
  296. log(prefix, ...varArgs);
  297. };
  298. };
  299. const error = function (...varArgs) {
  300. const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
  301. logClient.error(message);
  302. };
  303. const fatal = function (...varArgs) {
  304. const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
  305. logClient.error(message);
  306. throw new Error(message);
  307. };
  308. const warn = function (...varArgs) {
  309. const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
  310. logClient.warn(message);
  311. };
  312. /**
  313. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  314. * does not use https.
  315. */
  316. const warnIfPageIsSecure = function () {
  317. // Be very careful accessing browser globals. Who knows what may or may not exist.
  318. if (typeof window !== 'undefined' &&
  319. window.location &&
  320. window.location.protocol &&
  321. window.location.protocol.indexOf('https:') !== -1) {
  322. warn('Insecure Firebase access from a secure page. ' +
  323. 'Please use https in calls to new Firebase().');
  324. }
  325. };
  326. /**
  327. * Returns true if data is NaN, or +/- Infinity.
  328. */
  329. const isInvalidJSONNumber = function (data) {
  330. return (typeof data === 'number' &&
  331. (data !== data || // NaN
  332. data === Number.POSITIVE_INFINITY ||
  333. data === Number.NEGATIVE_INFINITY));
  334. };
  335. const executeWhenDOMReady = function (fn) {
  336. if (isNodeSdk() || document.readyState === 'complete') {
  337. fn();
  338. }
  339. else {
  340. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  341. // fire before onload), but fall back to onload.
  342. let called = false;
  343. const wrappedFn = function () {
  344. if (!document.body) {
  345. setTimeout(wrappedFn, Math.floor(10));
  346. return;
  347. }
  348. if (!called) {
  349. called = true;
  350. fn();
  351. }
  352. };
  353. if (document.addEventListener) {
  354. document.addEventListener('DOMContentLoaded', wrappedFn, false);
  355. // fallback to onload.
  356. window.addEventListener('load', wrappedFn, false);
  357. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  358. }
  359. else if (document.attachEvent) {
  360. // IE.
  361. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  362. document.attachEvent('onreadystatechange', () => {
  363. if (document.readyState === 'complete') {
  364. wrappedFn();
  365. }
  366. });
  367. // fallback to onload.
  368. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  369. window.attachEvent('onload', wrappedFn);
  370. // jQuery has an extra hack for IE that we could employ (based on
  371. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  372. // I'm hoping we don't need it.
  373. }
  374. }
  375. };
  376. /**
  377. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  378. */
  379. const MIN_NAME = '[MIN_NAME]';
  380. /**
  381. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  382. */
  383. const MAX_NAME = '[MAX_NAME]';
  384. /**
  385. * Compares valid Firebase key names, plus min and max name
  386. */
  387. const nameCompare = function (a, b) {
  388. if (a === b) {
  389. return 0;
  390. }
  391. else if (a === MIN_NAME || b === MAX_NAME) {
  392. return -1;
  393. }
  394. else if (b === MIN_NAME || a === MAX_NAME) {
  395. return 1;
  396. }
  397. else {
  398. const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  399. if (aAsInt !== null) {
  400. if (bAsInt !== null) {
  401. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  402. }
  403. else {
  404. return -1;
  405. }
  406. }
  407. else if (bAsInt !== null) {
  408. return 1;
  409. }
  410. else {
  411. return a < b ? -1 : 1;
  412. }
  413. }
  414. };
  415. /**
  416. * @returns {!number} comparison result.
  417. */
  418. const stringCompare = function (a, b) {
  419. if (a === b) {
  420. return 0;
  421. }
  422. else if (a < b) {
  423. return -1;
  424. }
  425. else {
  426. return 1;
  427. }
  428. };
  429. const requireKey = function (key, obj) {
  430. if (obj && key in obj) {
  431. return obj[key];
  432. }
  433. else {
  434. throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
  435. }
  436. };
  437. const ObjectToUniqueKey = function (obj) {
  438. if (typeof obj !== 'object' || obj === null) {
  439. return stringify(obj);
  440. }
  441. const keys = [];
  442. // eslint-disable-next-line guard-for-in
  443. for (const k in obj) {
  444. keys.push(k);
  445. }
  446. // Export as json, but with the keys sorted.
  447. keys.sort();
  448. let key = '{';
  449. for (let i = 0; i < keys.length; i++) {
  450. if (i !== 0) {
  451. key += ',';
  452. }
  453. key += stringify(keys[i]);
  454. key += ':';
  455. key += ObjectToUniqueKey(obj[keys[i]]);
  456. }
  457. key += '}';
  458. return key;
  459. };
  460. /**
  461. * Splits a string into a number of smaller segments of maximum size
  462. * @param str - The string
  463. * @param segsize - The maximum number of chars in the string.
  464. * @returns The string, split into appropriately-sized chunks
  465. */
  466. const splitStringBySize = function (str, segsize) {
  467. const len = str.length;
  468. if (len <= segsize) {
  469. return [str];
  470. }
  471. const dataSegs = [];
  472. for (let c = 0; c < len; c += segsize) {
  473. if (c + segsize > len) {
  474. dataSegs.push(str.substring(c, len));
  475. }
  476. else {
  477. dataSegs.push(str.substring(c, c + segsize));
  478. }
  479. }
  480. return dataSegs;
  481. };
  482. /**
  483. * Apply a function to each (key, value) pair in an object or
  484. * apply a function to each (index, value) pair in an array
  485. * @param obj - The object or array to iterate over
  486. * @param fn - The function to apply
  487. */
  488. function each(obj, fn) {
  489. for (const key in obj) {
  490. if (obj.hasOwnProperty(key)) {
  491. fn(key, obj[key]);
  492. }
  493. }
  494. }
  495. /**
  496. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  497. * I made one modification at the end and removed the NaN / Infinity
  498. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  499. * @param v - A double
  500. *
  501. */
  502. const doubleToIEEE754String = function (v) {
  503. assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  504. const ebits = 11, fbits = 52;
  505. const bias = (1 << (ebits - 1)) - 1;
  506. let s, e, f, ln, i;
  507. // Compute sign, exponent, fraction
  508. // Skip NaN / Infinity handling --MJL.
  509. if (v === 0) {
  510. e = 0;
  511. f = 0;
  512. s = 1 / v === -Infinity ? 1 : 0;
  513. }
  514. else {
  515. s = v < 0;
  516. v = Math.abs(v);
  517. if (v >= Math.pow(2, 1 - bias)) {
  518. // Normalized
  519. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  520. e = ln + bias;
  521. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  522. }
  523. else {
  524. // Denormalized
  525. e = 0;
  526. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  527. }
  528. }
  529. // Pack sign, exponent, fraction
  530. const bits = [];
  531. for (i = fbits; i; i -= 1) {
  532. bits.push(f % 2 ? 1 : 0);
  533. f = Math.floor(f / 2);
  534. }
  535. for (i = ebits; i; i -= 1) {
  536. bits.push(e % 2 ? 1 : 0);
  537. e = Math.floor(e / 2);
  538. }
  539. bits.push(s ? 1 : 0);
  540. bits.reverse();
  541. const str = bits.join('');
  542. // Return the data as a hex string. --MJL
  543. let hexByteString = '';
  544. for (i = 0; i < 64; i += 8) {
  545. let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  546. if (hexByte.length === 1) {
  547. hexByte = '0' + hexByte;
  548. }
  549. hexByteString = hexByteString + hexByte;
  550. }
  551. return hexByteString.toLowerCase();
  552. };
  553. /**
  554. * Used to detect if we're in a Chrome content script (which executes in an
  555. * isolated environment where long-polling doesn't work).
  556. */
  557. const isChromeExtensionContentScript = function () {
  558. return !!(typeof window === 'object' &&
  559. window['chrome'] &&
  560. window['chrome']['extension'] &&
  561. !/^chrome/.test(window.location.href));
  562. };
  563. /**
  564. * Used to detect if we're in a Windows 8 Store app.
  565. */
  566. const isWindowsStoreApp = function () {
  567. // Check for the presence of a couple WinRT globals
  568. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  569. };
  570. /**
  571. * Converts a server error code to a Javascript Error
  572. */
  573. function errorForServerCode(code, query) {
  574. let reason = 'Unknown Error';
  575. if (code === 'too_big') {
  576. reason =
  577. 'The data requested exceeds the maximum size ' +
  578. 'that can be accessed with a single request.';
  579. }
  580. else if (code === 'permission_denied') {
  581. reason = "Client doesn't have permission to access the desired data.";
  582. }
  583. else if (code === 'unavailable') {
  584. reason = 'The service is unavailable';
  585. }
  586. const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  587. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  588. error.code = code.toUpperCase();
  589. return error;
  590. }
  591. /**
  592. * Used to test for integer-looking strings
  593. */
  594. const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  595. /**
  596. * For use in keys, the minimum possible 32-bit integer.
  597. */
  598. const INTEGER_32_MIN = -2147483648;
  599. /**
  600. * For use in kyes, the maximum possible 32-bit integer.
  601. */
  602. const INTEGER_32_MAX = 2147483647;
  603. /**
  604. * If the string contains a 32-bit integer, return it. Else return null.
  605. */
  606. const tryParseInt = function (str) {
  607. if (INTEGER_REGEXP_.test(str)) {
  608. const intVal = Number(str);
  609. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  610. return intVal;
  611. }
  612. }
  613. return null;
  614. };
  615. /**
  616. * Helper to run some code but catch any exceptions and re-throw them later.
  617. * Useful for preventing user callbacks from breaking internal code.
  618. *
  619. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  620. * convenient (we don't have to try to figure out when is a safe point to
  621. * re-throw it), and the behavior seems reasonable:
  622. *
  623. * * If you aren't pausing on exceptions, you get an error in the console with
  624. * the correct stack trace.
  625. * * If you're pausing on all exceptions, the debugger will pause on your
  626. * exception and then again when we rethrow it.
  627. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  628. * on us re-throwing it.
  629. *
  630. * @param fn - The code to guard.
  631. */
  632. const exceptionGuard = function (fn) {
  633. try {
  634. fn();
  635. }
  636. catch (e) {
  637. // Re-throw exception when it's safe.
  638. setTimeout(() => {
  639. // It used to be that "throw e" would result in a good console error with
  640. // relevant context, but as of Chrome 39, you just get the firebase.js
  641. // file/line number where we re-throw it, which is useless. So we log
  642. // e.stack explicitly.
  643. const stack = e.stack || '';
  644. warn('Exception was thrown by user callback.', stack);
  645. throw e;
  646. }, Math.floor(0));
  647. }
  648. };
  649. /**
  650. * @returns {boolean} true if we think we're currently being crawled.
  651. */
  652. const beingCrawled = function () {
  653. const userAgent = (typeof window === 'object' &&
  654. window['navigator'] &&
  655. window['navigator']['userAgent']) ||
  656. '';
  657. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  658. // believe to support JavaScript/AJAX rendering.
  659. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  660. // would have seen the page" is flaky if we don't treat it as a crawler.
  661. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  662. };
  663. /**
  664. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  665. *
  666. * It is removed with clearTimeout() as normal.
  667. *
  668. * @param fn - Function to run.
  669. * @param time - Milliseconds to wait before running.
  670. * @returns The setTimeout() return value.
  671. */
  672. const setTimeoutNonBlocking = function (fn, time) {
  673. const timeout = setTimeout(fn, time);
  674. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  675. if (typeof timeout === 'number' &&
  676. // @ts-ignore Is only defined in Deno environments.
  677. typeof Deno !== 'undefined' &&
  678. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  679. Deno['unrefTimer']) {
  680. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  681. Deno.unrefTimer(timeout);
  682. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  683. }
  684. else if (typeof timeout === 'object' && timeout['unref']) {
  685. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  686. timeout['unref']();
  687. }
  688. return timeout;
  689. };
  690. /**
  691. * @license
  692. * Copyright 2017 Google LLC
  693. *
  694. * Licensed under the Apache License, Version 2.0 (the "License");
  695. * you may not use this file except in compliance with the License.
  696. * You may obtain a copy of the License at
  697. *
  698. * http://www.apache.org/licenses/LICENSE-2.0
  699. *
  700. * Unless required by applicable law or agreed to in writing, software
  701. * distributed under the License is distributed on an "AS IS" BASIS,
  702. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  703. * See the License for the specific language governing permissions and
  704. * limitations under the License.
  705. */
  706. /**
  707. * A class that holds metadata about a Repo object
  708. */
  709. class RepoInfo {
  710. /**
  711. * @param host - Hostname portion of the url for the repo
  712. * @param secure - Whether or not this repo is accessed over ssl
  713. * @param namespace - The namespace represented by the repo
  714. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  715. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  716. * @param persistenceKey - Override the default session persistence storage key
  717. */
  718. constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false) {
  719. this.secure = secure;
  720. this.namespace = namespace;
  721. this.webSocketOnly = webSocketOnly;
  722. this.nodeAdmin = nodeAdmin;
  723. this.persistenceKey = persistenceKey;
  724. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  725. this._host = host.toLowerCase();
  726. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  727. this.internalHost =
  728. PersistentStorage.get('host:' + host) || this._host;
  729. }
  730. isCacheableHost() {
  731. return this.internalHost.substr(0, 2) === 's-';
  732. }
  733. isCustomHost() {
  734. return (this._domain !== 'firebaseio.com' &&
  735. this._domain !== 'firebaseio-demo.com');
  736. }
  737. get host() {
  738. return this._host;
  739. }
  740. set host(newHost) {
  741. if (newHost !== this.internalHost) {
  742. this.internalHost = newHost;
  743. if (this.isCacheableHost()) {
  744. PersistentStorage.set('host:' + this._host, this.internalHost);
  745. }
  746. }
  747. }
  748. toString() {
  749. let str = this.toURLString();
  750. if (this.persistenceKey) {
  751. str += '<' + this.persistenceKey + '>';
  752. }
  753. return str;
  754. }
  755. toURLString() {
  756. const protocol = this.secure ? 'https://' : 'http://';
  757. const query = this.includeNamespaceInQueryParams
  758. ? `?ns=${this.namespace}`
  759. : '';
  760. return `${protocol}${this.host}/${query}`;
  761. }
  762. }
  763. function repoInfoNeedsQueryParam(repoInfo) {
  764. return (repoInfo.host !== repoInfo.internalHost ||
  765. repoInfo.isCustomHost() ||
  766. repoInfo.includeNamespaceInQueryParams);
  767. }
  768. /**
  769. * Returns the websocket URL for this repo
  770. * @param repoInfo - RepoInfo object
  771. * @param type - of connection
  772. * @param params - list
  773. * @returns The URL for this repo
  774. */
  775. function repoInfoConnectionURL(repoInfo, type, params) {
  776. assert(typeof type === 'string', 'typeof type must == string');
  777. assert(typeof params === 'object', 'typeof params must == object');
  778. let connURL;
  779. if (type === WEBSOCKET) {
  780. connURL =
  781. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  782. }
  783. else if (type === LONG_POLLING) {
  784. connURL =
  785. (repoInfo.secure ? 'https://' : 'http://') +
  786. repoInfo.internalHost +
  787. '/.lp?';
  788. }
  789. else {
  790. throw new Error('Unknown connection type: ' + type);
  791. }
  792. if (repoInfoNeedsQueryParam(repoInfo)) {
  793. params['ns'] = repoInfo.namespace;
  794. }
  795. const pairs = [];
  796. each(params, (key, value) => {
  797. pairs.push(key + '=' + value);
  798. });
  799. return connURL + pairs.join('&');
  800. }
  801. /**
  802. * @license
  803. * Copyright 2017 Google LLC
  804. *
  805. * Licensed under the Apache License, Version 2.0 (the "License");
  806. * you may not use this file except in compliance with the License.
  807. * You may obtain a copy of the License at
  808. *
  809. * http://www.apache.org/licenses/LICENSE-2.0
  810. *
  811. * Unless required by applicable law or agreed to in writing, software
  812. * distributed under the License is distributed on an "AS IS" BASIS,
  813. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  814. * See the License for the specific language governing permissions and
  815. * limitations under the License.
  816. */
  817. /**
  818. * Tracks a collection of stats.
  819. */
  820. class StatsCollection {
  821. constructor() {
  822. this.counters_ = {};
  823. }
  824. incrementCounter(name, amount = 1) {
  825. if (!contains(this.counters_, name)) {
  826. this.counters_[name] = 0;
  827. }
  828. this.counters_[name] += amount;
  829. }
  830. get() {
  831. return deepCopy(this.counters_);
  832. }
  833. }
  834. /**
  835. * @license
  836. * Copyright 2017 Google LLC
  837. *
  838. * Licensed under the Apache License, Version 2.0 (the "License");
  839. * you may not use this file except in compliance with the License.
  840. * You may obtain a copy of the License at
  841. *
  842. * http://www.apache.org/licenses/LICENSE-2.0
  843. *
  844. * Unless required by applicable law or agreed to in writing, software
  845. * distributed under the License is distributed on an "AS IS" BASIS,
  846. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  847. * See the License for the specific language governing permissions and
  848. * limitations under the License.
  849. */
  850. const collections = {};
  851. const reporters = {};
  852. function statsManagerGetCollection(repoInfo) {
  853. const hashString = repoInfo.toString();
  854. if (!collections[hashString]) {
  855. collections[hashString] = new StatsCollection();
  856. }
  857. return collections[hashString];
  858. }
  859. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  860. const hashString = repoInfo.toString();
  861. if (!reporters[hashString]) {
  862. reporters[hashString] = creatorFunction();
  863. }
  864. return reporters[hashString];
  865. }
  866. /**
  867. * @license
  868. * Copyright 2019 Google LLC
  869. *
  870. * Licensed under the Apache License, Version 2.0 (the "License");
  871. * you may not use this file except in compliance with the License.
  872. * You may obtain a copy of the License at
  873. *
  874. * http://www.apache.org/licenses/LICENSE-2.0
  875. *
  876. * Unless required by applicable law or agreed to in writing, software
  877. * distributed under the License is distributed on an "AS IS" BASIS,
  878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  879. * See the License for the specific language governing permissions and
  880. * limitations under the License.
  881. */
  882. /** The semver (www.semver.org) version of the SDK. */
  883. let SDK_VERSION = '';
  884. /**
  885. * SDK_VERSION should be set before any database instance is created
  886. * @internal
  887. */
  888. function setSDKVersion(version) {
  889. SDK_VERSION = version;
  890. }
  891. /**
  892. * @license
  893. * Copyright 2017 Google LLC
  894. *
  895. * Licensed under the Apache License, Version 2.0 (the "License");
  896. * you may not use this file except in compliance with the License.
  897. * You may obtain a copy of the License at
  898. *
  899. * http://www.apache.org/licenses/LICENSE-2.0
  900. *
  901. * Unless required by applicable law or agreed to in writing, software
  902. * distributed under the License is distributed on an "AS IS" BASIS,
  903. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  904. * See the License for the specific language governing permissions and
  905. * limitations under the License.
  906. */
  907. const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  908. const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  909. let WebSocketImpl = null;
  910. if (typeof MozWebSocket !== 'undefined') {
  911. WebSocketImpl = MozWebSocket;
  912. }
  913. else if (typeof WebSocket !== 'undefined') {
  914. WebSocketImpl = WebSocket;
  915. }
  916. function setWebSocketImpl(impl) {
  917. WebSocketImpl = impl;
  918. }
  919. /**
  920. * Create a new websocket connection with the given callbacks.
  921. */
  922. class WebSocketConnection {
  923. /**
  924. * @param connId identifier for this transport
  925. * @param repoInfo The info for the websocket endpoint.
  926. * @param applicationId The Firebase App ID for this project.
  927. * @param appCheckToken The App Check Token for this client.
  928. * @param authToken The Auth Token for this client.
  929. * @param transportSessionId Optional transportSessionId if this is connecting
  930. * to an existing transport session
  931. * @param lastSessionId Optional lastSessionId if there was a previous
  932. * connection
  933. */
  934. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  935. this.connId = connId;
  936. this.applicationId = applicationId;
  937. this.appCheckToken = appCheckToken;
  938. this.authToken = authToken;
  939. this.keepaliveTimer = null;
  940. this.frames = null;
  941. this.totalFrames = 0;
  942. this.bytesSent = 0;
  943. this.bytesReceived = 0;
  944. this.log_ = logWrapper(this.connId);
  945. this.stats_ = statsManagerGetCollection(repoInfo);
  946. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  947. this.nodeAdmin = repoInfo.nodeAdmin;
  948. }
  949. /**
  950. * @param repoInfo - The info for the websocket endpoint.
  951. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  952. * session
  953. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  954. * @returns connection url
  955. */
  956. static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  957. const urlParams = {};
  958. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  959. if (!isNodeSdk() &&
  960. typeof location !== 'undefined' &&
  961. location.hostname &&
  962. FORGE_DOMAIN_RE.test(location.hostname)) {
  963. urlParams[REFERER_PARAM] = FORGE_REF;
  964. }
  965. if (transportSessionId) {
  966. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  967. }
  968. if (lastSessionId) {
  969. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  970. }
  971. if (appCheckToken) {
  972. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  973. }
  974. if (applicationId) {
  975. urlParams[APPLICATION_ID_PARAM] = applicationId;
  976. }
  977. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  978. }
  979. /**
  980. * @param onMessage - Callback when messages arrive
  981. * @param onDisconnect - Callback with connection lost.
  982. */
  983. open(onMessage, onDisconnect) {
  984. this.onDisconnect = onDisconnect;
  985. this.onMessage = onMessage;
  986. this.log_('Websocket connecting to ' + this.connURL);
  987. this.everConnected_ = false;
  988. // Assume failure until proven otherwise.
  989. PersistentStorage.set('previous_websocket_failure', true);
  990. try {
  991. let options;
  992. if (isNodeSdk()) {
  993. const device = this.nodeAdmin ? 'AdminNode' : 'Node';
  994. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  995. options = {
  996. headers: {
  997. 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
  998. 'X-Firebase-GMPID': this.applicationId || ''
  999. }
  1000. };
  1001. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1002. // Note that we send the credentials here even if they aren't admin credentials, which is
  1003. // not a problem.
  1004. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1005. // through the websocket connection once it is established.
  1006. if (this.authToken) {
  1007. options.headers['Authorization'] = `Bearer ${this.authToken}`;
  1008. }
  1009. if (this.appCheckToken) {
  1010. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1011. }
  1012. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1013. const env = process['env'];
  1014. const proxy = this.connURL.indexOf('wss://') === 0
  1015. ? env['HTTPS_PROXY'] || env['https_proxy']
  1016. : env['HTTP_PROXY'] || env['http_proxy'];
  1017. if (proxy) {
  1018. options['proxy'] = { origin: proxy };
  1019. }
  1020. }
  1021. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1022. }
  1023. catch (e) {
  1024. this.log_('Error instantiating WebSocket.');
  1025. const error = e.message || e.data;
  1026. if (error) {
  1027. this.log_(error);
  1028. }
  1029. this.onClosed_();
  1030. return;
  1031. }
  1032. this.mySock.onopen = () => {
  1033. this.log_('Websocket connected.');
  1034. this.everConnected_ = true;
  1035. };
  1036. this.mySock.onclose = () => {
  1037. this.log_('Websocket connection was disconnected.');
  1038. this.mySock = null;
  1039. this.onClosed_();
  1040. };
  1041. this.mySock.onmessage = m => {
  1042. this.handleIncomingFrame(m);
  1043. };
  1044. this.mySock.onerror = e => {
  1045. this.log_('WebSocket error. Closing connection.');
  1046. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1047. const error = e.message || e.data;
  1048. if (error) {
  1049. this.log_(error);
  1050. }
  1051. this.onClosed_();
  1052. };
  1053. }
  1054. /**
  1055. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1056. */
  1057. start() { }
  1058. static forceDisallow() {
  1059. WebSocketConnection.forceDisallow_ = true;
  1060. }
  1061. static isAvailable() {
  1062. let isOldAndroid = false;
  1063. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1064. const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1065. const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1066. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1067. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1068. isOldAndroid = true;
  1069. }
  1070. }
  1071. }
  1072. return (!isOldAndroid &&
  1073. WebSocketImpl !== null &&
  1074. !WebSocketConnection.forceDisallow_);
  1075. }
  1076. /**
  1077. * Returns true if we previously failed to connect with this transport.
  1078. */
  1079. static previouslyFailed() {
  1080. // If our persistent storage is actually only in-memory storage,
  1081. // we default to assuming that it previously failed to be safe.
  1082. return (PersistentStorage.isInMemoryStorage ||
  1083. PersistentStorage.get('previous_websocket_failure') === true);
  1084. }
  1085. markConnectionHealthy() {
  1086. PersistentStorage.remove('previous_websocket_failure');
  1087. }
  1088. appendFrame_(data) {
  1089. this.frames.push(data);
  1090. if (this.frames.length === this.totalFrames) {
  1091. const fullMess = this.frames.join('');
  1092. this.frames = null;
  1093. const jsonMess = jsonEval(fullMess);
  1094. //handle the message
  1095. this.onMessage(jsonMess);
  1096. }
  1097. }
  1098. /**
  1099. * @param frameCount - The number of frames we are expecting from the server
  1100. */
  1101. handleNewFrameCount_(frameCount) {
  1102. this.totalFrames = frameCount;
  1103. this.frames = [];
  1104. }
  1105. /**
  1106. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1107. * @returns Any remaining data to be process, or null if there is none
  1108. */
  1109. extractFrameCount_(data) {
  1110. assert(this.frames === null, 'We already have a frame buffer');
  1111. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1112. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1113. if (data.length <= 6) {
  1114. const frameCount = Number(data);
  1115. if (!isNaN(frameCount)) {
  1116. this.handleNewFrameCount_(frameCount);
  1117. return null;
  1118. }
  1119. }
  1120. this.handleNewFrameCount_(1);
  1121. return data;
  1122. }
  1123. /**
  1124. * Process a websocket frame that has arrived from the server.
  1125. * @param mess - The frame data
  1126. */
  1127. handleIncomingFrame(mess) {
  1128. if (this.mySock === null) {
  1129. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1130. }
  1131. const data = mess['data'];
  1132. this.bytesReceived += data.length;
  1133. this.stats_.incrementCounter('bytes_received', data.length);
  1134. this.resetKeepAlive();
  1135. if (this.frames !== null) {
  1136. // we're buffering
  1137. this.appendFrame_(data);
  1138. }
  1139. else {
  1140. // try to parse out a frame count, otherwise, assume 1 and process it
  1141. const remainingData = this.extractFrameCount_(data);
  1142. if (remainingData !== null) {
  1143. this.appendFrame_(remainingData);
  1144. }
  1145. }
  1146. }
  1147. /**
  1148. * Send a message to the server
  1149. * @param data - The JSON object to transmit
  1150. */
  1151. send(data) {
  1152. this.resetKeepAlive();
  1153. const dataStr = stringify(data);
  1154. this.bytesSent += dataStr.length;
  1155. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1156. //We can only fit a certain amount in each websocket frame, so we need to split this request
  1157. //up into multiple pieces if it doesn't fit in one request.
  1158. const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  1159. //Send the length header
  1160. if (dataSegs.length > 1) {
  1161. this.sendString_(String(dataSegs.length));
  1162. }
  1163. //Send the actual data in segments.
  1164. for (let i = 0; i < dataSegs.length; i++) {
  1165. this.sendString_(dataSegs[i]);
  1166. }
  1167. }
  1168. shutdown_() {
  1169. this.isClosed_ = true;
  1170. if (this.keepaliveTimer) {
  1171. clearInterval(this.keepaliveTimer);
  1172. this.keepaliveTimer = null;
  1173. }
  1174. if (this.mySock) {
  1175. this.mySock.close();
  1176. this.mySock = null;
  1177. }
  1178. }
  1179. onClosed_() {
  1180. if (!this.isClosed_) {
  1181. this.log_('WebSocket is closing itself');
  1182. this.shutdown_();
  1183. // since this is an internal close, trigger the close listener
  1184. if (this.onDisconnect) {
  1185. this.onDisconnect(this.everConnected_);
  1186. this.onDisconnect = null;
  1187. }
  1188. }
  1189. }
  1190. /**
  1191. * External-facing close handler.
  1192. * Close the websocket and kill the connection.
  1193. */
  1194. close() {
  1195. if (!this.isClosed_) {
  1196. this.log_('WebSocket is being closed');
  1197. this.shutdown_();
  1198. }
  1199. }
  1200. /**
  1201. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  1202. * the last activity.
  1203. */
  1204. resetKeepAlive() {
  1205. clearInterval(this.keepaliveTimer);
  1206. this.keepaliveTimer = setInterval(() => {
  1207. //If there has been no websocket activity for a while, send a no-op
  1208. if (this.mySock) {
  1209. this.sendString_('0');
  1210. }
  1211. this.resetKeepAlive();
  1212. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1213. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  1214. }
  1215. /**
  1216. * Send a string over the websocket.
  1217. *
  1218. * @param str - String to send.
  1219. */
  1220. sendString_(str) {
  1221. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  1222. // calls for some unknown reason. We treat these as an error and disconnect.
  1223. // See https://app.asana.com/0/58926111402292/68021340250410
  1224. try {
  1225. this.mySock.send(str);
  1226. }
  1227. catch (e) {
  1228. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  1229. setTimeout(this.onClosed_.bind(this), 0);
  1230. }
  1231. }
  1232. }
  1233. /**
  1234. * Number of response before we consider the connection "healthy."
  1235. */
  1236. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  1237. /**
  1238. * Time to wait for the connection te become healthy before giving up.
  1239. */
  1240. WebSocketConnection.healthyTimeout = 30000;
  1241. const name = "@firebase/database";
  1242. const version = "0.14.1";
  1243. /**
  1244. * @license
  1245. * Copyright 2021 Google LLC
  1246. *
  1247. * Licensed under the Apache License, Version 2.0 (the "License");
  1248. * you may not use this file except in compliance with the License.
  1249. * You may obtain a copy of the License at
  1250. *
  1251. * http://www.apache.org/licenses/LICENSE-2.0
  1252. *
  1253. * Unless required by applicable law or agreed to in writing, software
  1254. * distributed under the License is distributed on an "AS IS" BASIS,
  1255. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1256. * See the License for the specific language governing permissions and
  1257. * limitations under the License.
  1258. */
  1259. /**
  1260. * Abstraction around AppCheck's token fetching capabilities.
  1261. */
  1262. class AppCheckTokenProvider {
  1263. constructor(appName_, appCheckProvider) {
  1264. this.appName_ = appName_;
  1265. this.appCheckProvider = appCheckProvider;
  1266. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  1267. if (!this.appCheck) {
  1268. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
  1269. }
  1270. }
  1271. getToken(forceRefresh) {
  1272. if (!this.appCheck) {
  1273. return new Promise((resolve, reject) => {
  1274. // Support delayed initialization of FirebaseAppCheck. This allows our
  1275. // customers to initialize the RTDB SDK before initializing Firebase
  1276. // AppCheck and ensures that all requests are authenticated if a token
  1277. // becomes available before the timoeout below expires.
  1278. setTimeout(() => {
  1279. if (this.appCheck) {
  1280. this.getToken(forceRefresh).then(resolve, reject);
  1281. }
  1282. else {
  1283. resolve(null);
  1284. }
  1285. }, 0);
  1286. });
  1287. }
  1288. return this.appCheck.getToken(forceRefresh);
  1289. }
  1290. addTokenChangeListener(listener) {
  1291. var _a;
  1292. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
  1293. }
  1294. notifyForInvalidToken() {
  1295. warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
  1296. 'are invalid. This usually indicates your app was not initialized correctly.');
  1297. }
  1298. }
  1299. /**
  1300. * @license
  1301. * Copyright 2017 Google LLC
  1302. *
  1303. * Licensed under the Apache License, Version 2.0 (the "License");
  1304. * you may not use this file except in compliance with the License.
  1305. * You may obtain a copy of the License at
  1306. *
  1307. * http://www.apache.org/licenses/LICENSE-2.0
  1308. *
  1309. * Unless required by applicable law or agreed to in writing, software
  1310. * distributed under the License is distributed on an "AS IS" BASIS,
  1311. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1312. * See the License for the specific language governing permissions and
  1313. * limitations under the License.
  1314. */
  1315. /**
  1316. * Abstraction around FirebaseApp's token fetching capabilities.
  1317. */
  1318. class FirebaseAuthTokenProvider {
  1319. constructor(appName_, firebaseOptions_, authProvider_) {
  1320. this.appName_ = appName_;
  1321. this.firebaseOptions_ = firebaseOptions_;
  1322. this.authProvider_ = authProvider_;
  1323. this.auth_ = null;
  1324. this.auth_ = authProvider_.getImmediate({ optional: true });
  1325. if (!this.auth_) {
  1326. authProvider_.onInit(auth => (this.auth_ = auth));
  1327. }
  1328. }
  1329. getToken(forceRefresh) {
  1330. if (!this.auth_) {
  1331. return new Promise((resolve, reject) => {
  1332. // Support delayed initialization of FirebaseAuth. This allows our
  1333. // customers to initialize the RTDB SDK before initializing Firebase
  1334. // Auth and ensures that all requests are authenticated if a token
  1335. // becomes available before the timoeout below expires.
  1336. setTimeout(() => {
  1337. if (this.auth_) {
  1338. this.getToken(forceRefresh).then(resolve, reject);
  1339. }
  1340. else {
  1341. resolve(null);
  1342. }
  1343. }, 0);
  1344. });
  1345. }
  1346. return this.auth_.getToken(forceRefresh).catch(error => {
  1347. // TODO: Need to figure out all the cases this is raised and whether
  1348. // this makes sense.
  1349. if (error && error.code === 'auth/token-not-initialized') {
  1350. log('Got auth/token-not-initialized error. Treating as null token.');
  1351. return null;
  1352. }
  1353. else {
  1354. return Promise.reject(error);
  1355. }
  1356. });
  1357. }
  1358. addTokenChangeListener(listener) {
  1359. // TODO: We might want to wrap the listener and call it with no args to
  1360. // avoid a leaky abstraction, but that makes removing the listener harder.
  1361. if (this.auth_) {
  1362. this.auth_.addAuthTokenListener(listener);
  1363. }
  1364. else {
  1365. this.authProvider_
  1366. .get()
  1367. .then(auth => auth.addAuthTokenListener(listener));
  1368. }
  1369. }
  1370. removeTokenChangeListener(listener) {
  1371. this.authProvider_
  1372. .get()
  1373. .then(auth => auth.removeAuthTokenListener(listener));
  1374. }
  1375. notifyForInvalidToken() {
  1376. let errorMessage = 'Provided authentication credentials for the app named "' +
  1377. this.appName_ +
  1378. '" are invalid. This usually indicates your app was not ' +
  1379. 'initialized correctly. ';
  1380. if ('credential' in this.firebaseOptions_) {
  1381. errorMessage +=
  1382. 'Make sure the "credential" property provided to initializeApp() ' +
  1383. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1384. 'project.';
  1385. }
  1386. else if ('serviceAccount' in this.firebaseOptions_) {
  1387. errorMessage +=
  1388. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  1389. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1390. 'project.';
  1391. }
  1392. else {
  1393. errorMessage +=
  1394. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  1395. 'initializeApp() match the values provided for your app at ' +
  1396. 'https://console.firebase.google.com/.';
  1397. }
  1398. warn(errorMessage);
  1399. }
  1400. }
  1401. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  1402. class EmulatorTokenProvider {
  1403. constructor(accessToken) {
  1404. this.accessToken = accessToken;
  1405. }
  1406. getToken(forceRefresh) {
  1407. return Promise.resolve({
  1408. accessToken: this.accessToken
  1409. });
  1410. }
  1411. addTokenChangeListener(listener) {
  1412. // Invoke the listener immediately to match the behavior in Firebase Auth
  1413. // (see packages/auth/src/auth.js#L1807)
  1414. listener(this.accessToken);
  1415. }
  1416. removeTokenChangeListener(listener) { }
  1417. notifyForInvalidToken() { }
  1418. }
  1419. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  1420. EmulatorTokenProvider.OWNER = 'owner';
  1421. /**
  1422. * @license
  1423. * Copyright 2017 Google LLC
  1424. *
  1425. * Licensed under the Apache License, Version 2.0 (the "License");
  1426. * you may not use this file except in compliance with the License.
  1427. * You may obtain a copy of the License at
  1428. *
  1429. * http://www.apache.org/licenses/LICENSE-2.0
  1430. *
  1431. * Unless required by applicable law or agreed to in writing, software
  1432. * distributed under the License is distributed on an "AS IS" BASIS,
  1433. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1434. * See the License for the specific language governing permissions and
  1435. * limitations under the License.
  1436. */
  1437. /**
  1438. * This class ensures the packets from the server arrive in order
  1439. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1440. */
  1441. class PacketReceiver {
  1442. /**
  1443. * @param onMessage_
  1444. */
  1445. constructor(onMessage_) {
  1446. this.onMessage_ = onMessage_;
  1447. this.pendingResponses = [];
  1448. this.currentResponseNum = 0;
  1449. this.closeAfterResponse = -1;
  1450. this.onClose = null;
  1451. }
  1452. closeAfter(responseNum, callback) {
  1453. this.closeAfterResponse = responseNum;
  1454. this.onClose = callback;
  1455. if (this.closeAfterResponse < this.currentResponseNum) {
  1456. this.onClose();
  1457. this.onClose = null;
  1458. }
  1459. }
  1460. /**
  1461. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1462. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1463. * browsers will respond in the same order as the requests we sent
  1464. */
  1465. handleResponse(requestNum, data) {
  1466. this.pendingResponses[requestNum] = data;
  1467. while (this.pendingResponses[this.currentResponseNum]) {
  1468. const toProcess = this.pendingResponses[this.currentResponseNum];
  1469. delete this.pendingResponses[this.currentResponseNum];
  1470. for (let i = 0; i < toProcess.length; ++i) {
  1471. if (toProcess[i]) {
  1472. exceptionGuard(() => {
  1473. this.onMessage_(toProcess[i]);
  1474. });
  1475. }
  1476. }
  1477. if (this.currentResponseNum === this.closeAfterResponse) {
  1478. if (this.onClose) {
  1479. this.onClose();
  1480. this.onClose = null;
  1481. }
  1482. break;
  1483. }
  1484. this.currentResponseNum++;
  1485. }
  1486. }
  1487. }
  1488. /**
  1489. * @license
  1490. * Copyright 2017 Google LLC
  1491. *
  1492. * Licensed under the Apache License, Version 2.0 (the "License");
  1493. * you may not use this file except in compliance with the License.
  1494. * You may obtain a copy of the License at
  1495. *
  1496. * http://www.apache.org/licenses/LICENSE-2.0
  1497. *
  1498. * Unless required by applicable law or agreed to in writing, software
  1499. * distributed under the License is distributed on an "AS IS" BASIS,
  1500. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1501. * See the License for the specific language governing permissions and
  1502. * limitations under the License.
  1503. */
  1504. // URL query parameters associated with longpolling
  1505. const FIREBASE_LONGPOLL_START_PARAM = 'start';
  1506. const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1507. const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1508. const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1509. const FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1510. const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1511. const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1512. const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1513. const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1514. const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1515. const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1516. const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1517. //Data size constants.
  1518. //TODO: Perf: the maximum length actually differs from browser to browser.
  1519. // We should check what browser we're on and set accordingly.
  1520. const MAX_URL_DATA_SIZE = 1870;
  1521. const SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1522. const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1523. /**
  1524. * Keepalive period
  1525. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1526. * length of 30 seconds that we can't exceed.
  1527. */
  1528. const KEEPALIVE_REQUEST_INTERVAL = 25000;
  1529. /**
  1530. * How long to wait before aborting a long-polling connection attempt.
  1531. */
  1532. const LP_CONNECT_TIMEOUT = 30000;
  1533. /**
  1534. * This class manages a single long-polling connection.
  1535. */
  1536. class BrowserPollConnection {
  1537. /**
  1538. * @param connId An identifier for this connection, used for logging
  1539. * @param repoInfo The info for the endpoint to send data to.
  1540. * @param applicationId The Firebase App ID for this project.
  1541. * @param appCheckToken The AppCheck token for this client.
  1542. * @param authToken The AuthToken to use for this connection.
  1543. * @param transportSessionId Optional transportSessionid if we are
  1544. * reconnecting for an existing transport session
  1545. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1546. * already created a connection previously
  1547. */
  1548. constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1549. this.connId = connId;
  1550. this.repoInfo = repoInfo;
  1551. this.applicationId = applicationId;
  1552. this.appCheckToken = appCheckToken;
  1553. this.authToken = authToken;
  1554. this.transportSessionId = transportSessionId;
  1555. this.lastSessionId = lastSessionId;
  1556. this.bytesSent = 0;
  1557. this.bytesReceived = 0;
  1558. this.everConnected_ = false;
  1559. this.log_ = logWrapper(connId);
  1560. this.stats_ = statsManagerGetCollection(repoInfo);
  1561. this.urlFn = (params) => {
  1562. // Always add the token if we have one.
  1563. if (this.appCheckToken) {
  1564. params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1565. }
  1566. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1567. };
  1568. }
  1569. /**
  1570. * @param onMessage - Callback when messages arrive
  1571. * @param onDisconnect - Callback with connection lost.
  1572. */
  1573. open(onMessage, onDisconnect) {
  1574. this.curSegmentNum = 0;
  1575. this.onDisconnect_ = onDisconnect;
  1576. this.myPacketOrderer = new PacketReceiver(onMessage);
  1577. this.isClosed_ = false;
  1578. this.connectTimeoutTimer_ = setTimeout(() => {
  1579. this.log_('Timed out trying to connect.');
  1580. // Make sure we clear the host cache
  1581. this.onClosed_();
  1582. this.connectTimeoutTimer_ = null;
  1583. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1584. }, Math.floor(LP_CONNECT_TIMEOUT));
  1585. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1586. executeWhenDOMReady(() => {
  1587. if (this.isClosed_) {
  1588. return;
  1589. }
  1590. //Set up a callback that gets triggered once a connection is set up.
  1591. this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
  1592. const [command, arg1, arg2, arg3, arg4] = args;
  1593. this.incrementIncomingBytes_(args);
  1594. if (!this.scriptTagHolder) {
  1595. return; // we closed the connection.
  1596. }
  1597. if (this.connectTimeoutTimer_) {
  1598. clearTimeout(this.connectTimeoutTimer_);
  1599. this.connectTimeoutTimer_ = null;
  1600. }
  1601. this.everConnected_ = true;
  1602. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1603. this.id = arg1;
  1604. this.password = arg2;
  1605. }
  1606. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1607. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1608. if (arg1) {
  1609. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1610. // through our already open polls), so don't send any more.
  1611. this.scriptTagHolder.sendNewPolls = false;
  1612. // arg1 in this case is the last response number sent by the server. We should try to receive
  1613. // all of the responses up to this one before closing
  1614. this.myPacketOrderer.closeAfter(arg1, () => {
  1615. this.onClosed_();
  1616. });
  1617. }
  1618. else {
  1619. this.onClosed_();
  1620. }
  1621. }
  1622. else {
  1623. throw new Error('Unrecognized command received: ' + command);
  1624. }
  1625. }, (...args) => {
  1626. const [pN, data] = args;
  1627. this.incrementIncomingBytes_(args);
  1628. this.myPacketOrderer.handleResponse(pN, data);
  1629. }, () => {
  1630. this.onClosed_();
  1631. }, this.urlFn);
  1632. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1633. //from cache.
  1634. const urlParams = {};
  1635. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1636. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1637. if (this.scriptTagHolder.uniqueCallbackIdentifier) {
  1638. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1639. this.scriptTagHolder.uniqueCallbackIdentifier;
  1640. }
  1641. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1642. if (this.transportSessionId) {
  1643. urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
  1644. }
  1645. if (this.lastSessionId) {
  1646. urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
  1647. }
  1648. if (this.applicationId) {
  1649. urlParams[APPLICATION_ID_PARAM] = this.applicationId;
  1650. }
  1651. if (this.appCheckToken) {
  1652. urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
  1653. }
  1654. if (typeof location !== 'undefined' &&
  1655. location.hostname &&
  1656. FORGE_DOMAIN_RE.test(location.hostname)) {
  1657. urlParams[REFERER_PARAM] = FORGE_REF;
  1658. }
  1659. const connectURL = this.urlFn(urlParams);
  1660. this.log_('Connecting via long-poll to ' + connectURL);
  1661. this.scriptTagHolder.addTag(connectURL, () => {
  1662. /* do nothing */
  1663. });
  1664. });
  1665. }
  1666. /**
  1667. * Call this when a handshake has completed successfully and we want to consider the connection established
  1668. */
  1669. start() {
  1670. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1671. this.addDisconnectPingFrame(this.id, this.password);
  1672. }
  1673. /**
  1674. * Forces long polling to be considered as a potential transport
  1675. */
  1676. static forceAllow() {
  1677. BrowserPollConnection.forceAllow_ = true;
  1678. }
  1679. /**
  1680. * Forces longpolling to not be considered as a potential transport
  1681. */
  1682. static forceDisallow() {
  1683. BrowserPollConnection.forceDisallow_ = true;
  1684. }
  1685. // Static method, use string literal so it can be accessed in a generic way
  1686. static isAvailable() {
  1687. if (isNodeSdk()) {
  1688. return false;
  1689. }
  1690. else if (BrowserPollConnection.forceAllow_) {
  1691. return true;
  1692. }
  1693. else {
  1694. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1695. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1696. return (!BrowserPollConnection.forceDisallow_ &&
  1697. typeof document !== 'undefined' &&
  1698. document.createElement != null &&
  1699. !isChromeExtensionContentScript() &&
  1700. !isWindowsStoreApp());
  1701. }
  1702. }
  1703. /**
  1704. * No-op for polling
  1705. */
  1706. markConnectionHealthy() { }
  1707. /**
  1708. * Stops polling and cleans up the iframe
  1709. */
  1710. shutdown_() {
  1711. this.isClosed_ = true;
  1712. if (this.scriptTagHolder) {
  1713. this.scriptTagHolder.close();
  1714. this.scriptTagHolder = null;
  1715. }
  1716. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1717. if (this.myDisconnFrame) {
  1718. document.body.removeChild(this.myDisconnFrame);
  1719. this.myDisconnFrame = null;
  1720. }
  1721. if (this.connectTimeoutTimer_) {
  1722. clearTimeout(this.connectTimeoutTimer_);
  1723. this.connectTimeoutTimer_ = null;
  1724. }
  1725. }
  1726. /**
  1727. * Triggered when this transport is closed
  1728. */
  1729. onClosed_() {
  1730. if (!this.isClosed_) {
  1731. this.log_('Longpoll is closing itself');
  1732. this.shutdown_();
  1733. if (this.onDisconnect_) {
  1734. this.onDisconnect_(this.everConnected_);
  1735. this.onDisconnect_ = null;
  1736. }
  1737. }
  1738. }
  1739. /**
  1740. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1741. * that we've left.
  1742. */
  1743. close() {
  1744. if (!this.isClosed_) {
  1745. this.log_('Longpoll is being closed.');
  1746. this.shutdown_();
  1747. }
  1748. }
  1749. /**
  1750. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1751. * broken into chunks (since URLs have a small maximum length).
  1752. * @param data - The JSON data to transmit.
  1753. */
  1754. send(data) {
  1755. const dataStr = stringify(data);
  1756. this.bytesSent += dataStr.length;
  1757. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1758. //first, lets get the base64-encoded data
  1759. const base64data = base64Encode(dataStr);
  1760. //We can only fit a certain amount in each URL, so we need to split this request
  1761. //up into multiple pieces if it doesn't fit in one request.
  1762. const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1763. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1764. //of segments so that we can reassemble the packet on the server.
  1765. for (let i = 0; i < dataSegs.length; i++) {
  1766. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1767. this.curSegmentNum++;
  1768. }
  1769. }
  1770. /**
  1771. * This is how we notify the server that we're leaving.
  1772. * We aren't able to send requests with DHTML on a window close event, but we can
  1773. * trigger XHR requests in some browsers (everything but Opera basically).
  1774. */
  1775. addDisconnectPingFrame(id, pw) {
  1776. if (isNodeSdk()) {
  1777. return;
  1778. }
  1779. this.myDisconnFrame = document.createElement('iframe');
  1780. const urlParams = {};
  1781. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1782. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1783. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1784. this.myDisconnFrame.src = this.urlFn(urlParams);
  1785. this.myDisconnFrame.style.display = 'none';
  1786. document.body.appendChild(this.myDisconnFrame);
  1787. }
  1788. /**
  1789. * Used to track the bytes received by this client
  1790. */
  1791. incrementIncomingBytes_(args) {
  1792. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1793. const bytesReceived = stringify(args).length;
  1794. this.bytesReceived += bytesReceived;
  1795. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1796. }
  1797. }
  1798. /*********************************************************************************************
  1799. * A wrapper around an iframe that is used as a long-polling script holder.
  1800. *********************************************************************************************/
  1801. class FirebaseIFrameScriptHolder {
  1802. /**
  1803. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1804. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1805. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1806. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1807. */
  1808. constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
  1809. this.onDisconnect = onDisconnect;
  1810. this.urlFn = urlFn;
  1811. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1812. //problems in some browsers.
  1813. this.outstandingRequests = new Set();
  1814. //A queue of the pending segments waiting for transmission to the server.
  1815. this.pendingSegs = [];
  1816. //A serial number. We use this for two things:
  1817. // 1) A way to ensure the browser doesn't cache responses to polls
  1818. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1819. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1820. // JSONP code in the order it was added to the iframe.
  1821. this.currentSerial = Math.floor(Math.random() * 100000000);
  1822. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1823. // incoming data from the server that we're waiting for).
  1824. this.sendNewPolls = true;
  1825. if (!isNodeSdk()) {
  1826. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1827. //iframes where we put the long-polling script tags. We have two callbacks:
  1828. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1829. // 2) Message Callback - Triggered when new data arrives.
  1830. this.uniqueCallbackIdentifier = LUIDGenerator();
  1831. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1832. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1833. onMessageCB;
  1834. //Create an iframe for us to add script tags to.
  1835. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1836. // Set the iframe's contents.
  1837. let script = '';
  1838. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1839. // for ie9, but ie8 needs to do it again in the document itself.
  1840. if (this.myIFrame.src &&
  1841. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1842. const currentDomain = document.domain;
  1843. script = '<script>document.domain="' + currentDomain + '";</script>';
  1844. }
  1845. const iframeContents = '<html><body>' + script + '</body></html>';
  1846. try {
  1847. this.myIFrame.doc.open();
  1848. this.myIFrame.doc.write(iframeContents);
  1849. this.myIFrame.doc.close();
  1850. }
  1851. catch (e) {
  1852. log('frame writing exception');
  1853. if (e.stack) {
  1854. log(e.stack);
  1855. }
  1856. log(e);
  1857. }
  1858. }
  1859. else {
  1860. this.commandCB = commandCB;
  1861. this.onMessageCB = onMessageCB;
  1862. }
  1863. }
  1864. /**
  1865. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1866. * actually use.
  1867. */
  1868. static createIFrame_() {
  1869. const iframe = document.createElement('iframe');
  1870. iframe.style.display = 'none';
  1871. // This is necessary in order to initialize the document inside the iframe
  1872. if (document.body) {
  1873. document.body.appendChild(iframe);
  1874. try {
  1875. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1876. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1877. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1878. const a = iframe.contentWindow.document;
  1879. if (!a) {
  1880. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1881. log('No IE domain setting required');
  1882. }
  1883. }
  1884. catch (e) {
  1885. const domain = document.domain;
  1886. iframe.src =
  1887. "javascript:void((function(){document.open();document.domain='" +
  1888. domain +
  1889. "';document.close();})())";
  1890. }
  1891. }
  1892. else {
  1893. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1894. // never gets hit.
  1895. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1896. }
  1897. // Get the document of the iframe in a browser-specific way.
  1898. if (iframe.contentDocument) {
  1899. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1900. }
  1901. else if (iframe.contentWindow) {
  1902. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1903. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1904. }
  1905. else if (iframe.document) {
  1906. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1907. iframe.doc = iframe.document; //others?
  1908. }
  1909. return iframe;
  1910. }
  1911. /**
  1912. * Cancel all outstanding queries and remove the frame.
  1913. */
  1914. close() {
  1915. //Mark this iframe as dead, so no new requests are sent.
  1916. this.alive = false;
  1917. if (this.myIFrame) {
  1918. //We have to actually remove all of the html inside this iframe before removing it from the
  1919. //window, or IE will continue loading and executing the script tags we've already added, which
  1920. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1921. this.myIFrame.doc.body.textContent = '';
  1922. setTimeout(() => {
  1923. if (this.myIFrame !== null) {
  1924. document.body.removeChild(this.myIFrame);
  1925. this.myIFrame = null;
  1926. }
  1927. }, Math.floor(0));
  1928. }
  1929. // Protect from being called recursively.
  1930. const onDisconnect = this.onDisconnect;
  1931. if (onDisconnect) {
  1932. this.onDisconnect = null;
  1933. onDisconnect();
  1934. }
  1935. }
  1936. /**
  1937. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  1938. * @param id - The ID of this connection
  1939. * @param pw - The password for this connection
  1940. */
  1941. startLongPoll(id, pw) {
  1942. this.myID = id;
  1943. this.myPW = pw;
  1944. this.alive = true;
  1945. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  1946. while (this.newRequest_()) { }
  1947. }
  1948. /**
  1949. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  1950. * too many outstanding requests and we are still alive.
  1951. *
  1952. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  1953. * needed.
  1954. */
  1955. newRequest_() {
  1956. // We keep one outstanding request open all the time to receive data, but if we need to send data
  1957. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  1958. // close the old request.
  1959. if (this.alive &&
  1960. this.sendNewPolls &&
  1961. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  1962. //construct our url
  1963. this.currentSerial++;
  1964. const urlParams = {};
  1965. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  1966. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  1967. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  1968. let theURL = this.urlFn(urlParams);
  1969. //Now add as much data as we can.
  1970. let curDataString = '';
  1971. let i = 0;
  1972. while (this.pendingSegs.length > 0) {
  1973. //first, lets see if the next segment will fit.
  1974. const nextSeg = this.pendingSegs[0];
  1975. if (nextSeg.d.length +
  1976. SEG_HEADER_SIZE +
  1977. curDataString.length <=
  1978. MAX_URL_DATA_SIZE) {
  1979. //great, the segment will fit. Lets append it.
  1980. const theSeg = this.pendingSegs.shift();
  1981. curDataString =
  1982. curDataString +
  1983. '&' +
  1984. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  1985. i +
  1986. '=' +
  1987. theSeg.seg +
  1988. '&' +
  1989. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  1990. i +
  1991. '=' +
  1992. theSeg.ts +
  1993. '&' +
  1994. FIREBASE_LONGPOLL_DATA_PARAM +
  1995. i +
  1996. '=' +
  1997. theSeg.d;
  1998. i++;
  1999. }
  2000. else {
  2001. break;
  2002. }
  2003. }
  2004. theURL = theURL + curDataString;
  2005. this.addLongPollTag_(theURL, this.currentSerial);
  2006. return true;
  2007. }
  2008. else {
  2009. return false;
  2010. }
  2011. }
  2012. /**
  2013. * Queue a packet for transmission to the server.
  2014. * @param segnum - A sequential id for this packet segment used for reassembly
  2015. * @param totalsegs - The total number of segments in this packet
  2016. * @param data - The data for this segment.
  2017. */
  2018. enqueueSegment(segnum, totalsegs, data) {
  2019. //add this to the queue of segments to send.
  2020. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  2021. //send the data immediately if there isn't already data being transmitted, unless
  2022. //startLongPoll hasn't been called yet.
  2023. if (this.alive) {
  2024. this.newRequest_();
  2025. }
  2026. }
  2027. /**
  2028. * Add a script tag for a regular long-poll request.
  2029. * @param url - The URL of the script tag.
  2030. * @param serial - The serial number of the request.
  2031. */
  2032. addLongPollTag_(url, serial) {
  2033. //remember that we sent this request.
  2034. this.outstandingRequests.add(serial);
  2035. const doNewRequest = () => {
  2036. this.outstandingRequests.delete(serial);
  2037. this.newRequest_();
  2038. };
  2039. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  2040. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  2041. const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  2042. const readyStateCB = () => {
  2043. // Request completed. Cancel the keepalive.
  2044. clearTimeout(keepaliveTimeout);
  2045. // Trigger a new request so we can continue receiving data.
  2046. doNewRequest();
  2047. };
  2048. this.addTag(url, readyStateCB);
  2049. }
  2050. /**
  2051. * Add an arbitrary script tag to the iframe.
  2052. * @param url - The URL for the script tag source.
  2053. * @param loadCB - A callback to be triggered once the script has loaded.
  2054. */
  2055. addTag(url, loadCB) {
  2056. if (isNodeSdk()) {
  2057. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2058. this.doNodeLongPoll(url, loadCB);
  2059. }
  2060. else {
  2061. setTimeout(() => {
  2062. try {
  2063. // if we're already closed, don't add this poll
  2064. if (!this.sendNewPolls) {
  2065. return;
  2066. }
  2067. const newScript = this.myIFrame.doc.createElement('script');
  2068. newScript.type = 'text/javascript';
  2069. newScript.async = true;
  2070. newScript.src = url;
  2071. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2072. newScript.onload = newScript.onreadystatechange =
  2073. function () {
  2074. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2075. const rstate = newScript.readyState;
  2076. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  2077. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2078. newScript.onload = newScript.onreadystatechange = null;
  2079. if (newScript.parentNode) {
  2080. newScript.parentNode.removeChild(newScript);
  2081. }
  2082. loadCB();
  2083. }
  2084. };
  2085. newScript.onerror = () => {
  2086. log('Long-poll script failed to load: ' + url);
  2087. this.sendNewPolls = false;
  2088. this.close();
  2089. };
  2090. this.myIFrame.doc.body.appendChild(newScript);
  2091. }
  2092. catch (e) {
  2093. // TODO: we should make this error visible somehow
  2094. }
  2095. }, Math.floor(1));
  2096. }
  2097. }
  2098. }
  2099. /**
  2100. * @license
  2101. * Copyright 2017 Google LLC
  2102. *
  2103. * Licensed under the Apache License, Version 2.0 (the "License");
  2104. * you may not use this file except in compliance with the License.
  2105. * You may obtain a copy of the License at
  2106. *
  2107. * http://www.apache.org/licenses/LICENSE-2.0
  2108. *
  2109. * Unless required by applicable law or agreed to in writing, software
  2110. * distributed under the License is distributed on an "AS IS" BASIS,
  2111. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2112. * See the License for the specific language governing permissions and
  2113. * limitations under the License.
  2114. */
  2115. /**
  2116. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2117. * lifecycle.
  2118. *
  2119. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2120. * they are available.
  2121. */
  2122. class TransportManager {
  2123. /**
  2124. * @param repoInfo - Metadata around the namespace we're connecting to
  2125. */
  2126. constructor(repoInfo) {
  2127. this.initTransports_(repoInfo);
  2128. }
  2129. static get ALL_TRANSPORTS() {
  2130. return [BrowserPollConnection, WebSocketConnection];
  2131. }
  2132. /**
  2133. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2134. * TransportManager has already set up transports_
  2135. */
  2136. static get IS_TRANSPORT_INITIALIZED() {
  2137. return this.globalTransportInitialized_;
  2138. }
  2139. initTransports_(repoInfo) {
  2140. const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2141. let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2142. if (repoInfo.webSocketOnly) {
  2143. if (!isWebSocketsAvailable) {
  2144. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2145. }
  2146. isSkipPollConnection = true;
  2147. }
  2148. if (isSkipPollConnection) {
  2149. this.transports_ = [WebSocketConnection];
  2150. }
  2151. else {
  2152. const transports = (this.transports_ = []);
  2153. for (const transport of TransportManager.ALL_TRANSPORTS) {
  2154. if (transport && transport['isAvailable']()) {
  2155. transports.push(transport);
  2156. }
  2157. }
  2158. TransportManager.globalTransportInitialized_ = true;
  2159. }
  2160. }
  2161. /**
  2162. * @returns The constructor for the initial transport to use
  2163. */
  2164. initialTransport() {
  2165. if (this.transports_.length > 0) {
  2166. return this.transports_[0];
  2167. }
  2168. else {
  2169. throw new Error('No transports available');
  2170. }
  2171. }
  2172. /**
  2173. * @returns The constructor for the next transport, or null
  2174. */
  2175. upgradeTransport() {
  2176. if (this.transports_.length > 1) {
  2177. return this.transports_[1];
  2178. }
  2179. else {
  2180. return null;
  2181. }
  2182. }
  2183. }
  2184. // Keeps track of whether the TransportManager has already chosen a transport to use
  2185. TransportManager.globalTransportInitialized_ = false;
  2186. /**
  2187. * @license
  2188. * Copyright 2017 Google LLC
  2189. *
  2190. * Licensed under the Apache License, Version 2.0 (the "License");
  2191. * you may not use this file except in compliance with the License.
  2192. * You may obtain a copy of the License at
  2193. *
  2194. * http://www.apache.org/licenses/LICENSE-2.0
  2195. *
  2196. * Unless required by applicable law or agreed to in writing, software
  2197. * distributed under the License is distributed on an "AS IS" BASIS,
  2198. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2199. * See the License for the specific language governing permissions and
  2200. * limitations under the License.
  2201. */
  2202. // Abort upgrade attempt if it takes longer than 60s.
  2203. const UPGRADE_TIMEOUT = 60000;
  2204. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2205. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2206. const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2207. // 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)
  2208. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2209. // but we've sent/received enough bytes, we don't cancel the connection.
  2210. const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2211. const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2212. const MESSAGE_TYPE = 't';
  2213. const MESSAGE_DATA = 'd';
  2214. const CONTROL_SHUTDOWN = 's';
  2215. const CONTROL_RESET = 'r';
  2216. const CONTROL_ERROR = 'e';
  2217. const CONTROL_PONG = 'o';
  2218. const SWITCH_ACK = 'a';
  2219. const END_TRANSMISSION = 'n';
  2220. const PING = 'p';
  2221. const SERVER_HELLO = 'h';
  2222. /**
  2223. * Creates a new real-time connection to the server using whichever method works
  2224. * best in the current browser.
  2225. */
  2226. class Connection {
  2227. /**
  2228. * @param id - an id for this connection
  2229. * @param repoInfo_ - the info for the endpoint to connect to
  2230. * @param applicationId_ - the Firebase App ID for this project
  2231. * @param appCheckToken_ - The App Check Token for this device.
  2232. * @param authToken_ - The auth token for this session.
  2233. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2234. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2235. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2236. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2237. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2238. */
  2239. constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2240. this.id = id;
  2241. this.repoInfo_ = repoInfo_;
  2242. this.applicationId_ = applicationId_;
  2243. this.appCheckToken_ = appCheckToken_;
  2244. this.authToken_ = authToken_;
  2245. this.onMessage_ = onMessage_;
  2246. this.onReady_ = onReady_;
  2247. this.onDisconnect_ = onDisconnect_;
  2248. this.onKill_ = onKill_;
  2249. this.lastSessionId = lastSessionId;
  2250. this.connectionCount = 0;
  2251. this.pendingDataMessages = [];
  2252. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2253. this.log_ = logWrapper('c:' + this.id + ':');
  2254. this.transportManager_ = new TransportManager(repoInfo_);
  2255. this.log_('Connection created');
  2256. this.start_();
  2257. }
  2258. /**
  2259. * Starts a connection attempt
  2260. */
  2261. start_() {
  2262. const conn = this.transportManager_.initialTransport();
  2263. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2264. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2265. // can consider the transport healthy.
  2266. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2267. const onMessageReceived = this.connReceiver_(this.conn_);
  2268. const onConnectionLost = this.disconnReceiver_(this.conn_);
  2269. this.tx_ = this.conn_;
  2270. this.rx_ = this.conn_;
  2271. this.secondaryConn_ = null;
  2272. this.isHealthy_ = false;
  2273. /*
  2274. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2275. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2276. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2277. * still have the context of your originating frame.
  2278. */
  2279. setTimeout(() => {
  2280. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2281. this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
  2282. }, Math.floor(0));
  2283. const healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2284. if (healthyTimeoutMS > 0) {
  2285. this.healthyTimeout_ = setTimeoutNonBlocking(() => {
  2286. this.healthyTimeout_ = null;
  2287. if (!this.isHealthy_) {
  2288. if (this.conn_ &&
  2289. this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2290. this.log_('Connection exceeded healthy timeout but has received ' +
  2291. this.conn_.bytesReceived +
  2292. ' bytes. Marking connection healthy.');
  2293. this.isHealthy_ = true;
  2294. this.conn_.markConnectionHealthy();
  2295. }
  2296. else if (this.conn_ &&
  2297. this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2298. this.log_('Connection exceeded healthy timeout but has sent ' +
  2299. this.conn_.bytesSent +
  2300. ' bytes. Leaving connection alive.');
  2301. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2302. // the server.
  2303. }
  2304. else {
  2305. this.log_('Closing unhealthy connection after timeout.');
  2306. this.close();
  2307. }
  2308. }
  2309. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2310. }, Math.floor(healthyTimeoutMS));
  2311. }
  2312. }
  2313. nextTransportId_() {
  2314. return 'c:' + this.id + ':' + this.connectionCount++;
  2315. }
  2316. disconnReceiver_(conn) {
  2317. return everConnected => {
  2318. if (conn === this.conn_) {
  2319. this.onConnectionLost_(everConnected);
  2320. }
  2321. else if (conn === this.secondaryConn_) {
  2322. this.log_('Secondary connection lost.');
  2323. this.onSecondaryConnectionLost_();
  2324. }
  2325. else {
  2326. this.log_('closing an old connection');
  2327. }
  2328. };
  2329. }
  2330. connReceiver_(conn) {
  2331. return (message) => {
  2332. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2333. if (conn === this.rx_) {
  2334. this.onPrimaryMessageReceived_(message);
  2335. }
  2336. else if (conn === this.secondaryConn_) {
  2337. this.onSecondaryMessageReceived_(message);
  2338. }
  2339. else {
  2340. this.log_('message on old connection');
  2341. }
  2342. }
  2343. };
  2344. }
  2345. /**
  2346. * @param dataMsg - An arbitrary data message to be sent to the server
  2347. */
  2348. sendRequest(dataMsg) {
  2349. // wrap in a data message envelope and send it on
  2350. const msg = { t: 'd', d: dataMsg };
  2351. this.sendData_(msg);
  2352. }
  2353. tryCleanupConnection() {
  2354. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2355. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2356. this.conn_ = this.secondaryConn_;
  2357. this.secondaryConn_ = null;
  2358. // the server will shutdown the old connection
  2359. }
  2360. }
  2361. onSecondaryControl_(controlData) {
  2362. if (MESSAGE_TYPE in controlData) {
  2363. const cmd = controlData[MESSAGE_TYPE];
  2364. if (cmd === SWITCH_ACK) {
  2365. this.upgradeIfSecondaryHealthy_();
  2366. }
  2367. else if (cmd === CONTROL_RESET) {
  2368. // Most likely the session wasn't valid. Abandon the switch attempt
  2369. this.log_('Got a reset on secondary, closing it');
  2370. this.secondaryConn_.close();
  2371. // If we were already using this connection for something, than we need to fully close
  2372. if (this.tx_ === this.secondaryConn_ ||
  2373. this.rx_ === this.secondaryConn_) {
  2374. this.close();
  2375. }
  2376. }
  2377. else if (cmd === CONTROL_PONG) {
  2378. this.log_('got pong on secondary.');
  2379. this.secondaryResponsesRequired_--;
  2380. this.upgradeIfSecondaryHealthy_();
  2381. }
  2382. }
  2383. }
  2384. onSecondaryMessageReceived_(parsedData) {
  2385. const layer = requireKey('t', parsedData);
  2386. const data = requireKey('d', parsedData);
  2387. if (layer === 'c') {
  2388. this.onSecondaryControl_(data);
  2389. }
  2390. else if (layer === 'd') {
  2391. // got a data message, but we're still second connection. Need to buffer it up
  2392. this.pendingDataMessages.push(data);
  2393. }
  2394. else {
  2395. throw new Error('Unknown protocol layer: ' + layer);
  2396. }
  2397. }
  2398. upgradeIfSecondaryHealthy_() {
  2399. if (this.secondaryResponsesRequired_ <= 0) {
  2400. this.log_('Secondary connection is healthy.');
  2401. this.isHealthy_ = true;
  2402. this.secondaryConn_.markConnectionHealthy();
  2403. this.proceedWithUpgrade_();
  2404. }
  2405. else {
  2406. // Send a ping to make sure the connection is healthy.
  2407. this.log_('sending ping on secondary.');
  2408. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2409. }
  2410. }
  2411. proceedWithUpgrade_() {
  2412. // tell this connection to consider itself open
  2413. this.secondaryConn_.start();
  2414. // send ack
  2415. this.log_('sending client ack on secondary');
  2416. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2417. // send end packet on primary transport, switch to sending on this one
  2418. // can receive on this one, buffer responses until end received on primary transport
  2419. this.log_('Ending transmission on primary');
  2420. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2421. this.tx_ = this.secondaryConn_;
  2422. this.tryCleanupConnection();
  2423. }
  2424. onPrimaryMessageReceived_(parsedData) {
  2425. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2426. const layer = requireKey('t', parsedData);
  2427. const data = requireKey('d', parsedData);
  2428. if (layer === 'c') {
  2429. this.onControl_(data);
  2430. }
  2431. else if (layer === 'd') {
  2432. this.onDataMessage_(data);
  2433. }
  2434. }
  2435. onDataMessage_(message) {
  2436. this.onPrimaryResponse_();
  2437. // We don't do anything with data messages, just kick them up a level
  2438. this.onMessage_(message);
  2439. }
  2440. onPrimaryResponse_() {
  2441. if (!this.isHealthy_) {
  2442. this.primaryResponsesRequired_--;
  2443. if (this.primaryResponsesRequired_ <= 0) {
  2444. this.log_('Primary connection is healthy.');
  2445. this.isHealthy_ = true;
  2446. this.conn_.markConnectionHealthy();
  2447. }
  2448. }
  2449. }
  2450. onControl_(controlData) {
  2451. const cmd = requireKey(MESSAGE_TYPE, controlData);
  2452. if (MESSAGE_DATA in controlData) {
  2453. const payload = controlData[MESSAGE_DATA];
  2454. if (cmd === SERVER_HELLO) {
  2455. this.onHandshake_(payload);
  2456. }
  2457. else if (cmd === END_TRANSMISSION) {
  2458. this.log_('recvd end transmission on primary');
  2459. this.rx_ = this.secondaryConn_;
  2460. for (let i = 0; i < this.pendingDataMessages.length; ++i) {
  2461. this.onDataMessage_(this.pendingDataMessages[i]);
  2462. }
  2463. this.pendingDataMessages = [];
  2464. this.tryCleanupConnection();
  2465. }
  2466. else if (cmd === CONTROL_SHUTDOWN) {
  2467. // This was previously the 'onKill' callback passed to the lower-level connection
  2468. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2469. this.onConnectionShutdown_(payload);
  2470. }
  2471. else if (cmd === CONTROL_RESET) {
  2472. // payload in this case is the host we should contact
  2473. this.onReset_(payload);
  2474. }
  2475. else if (cmd === CONTROL_ERROR) {
  2476. error('Server Error: ' + payload);
  2477. }
  2478. else if (cmd === CONTROL_PONG) {
  2479. this.log_('got pong on primary.');
  2480. this.onPrimaryResponse_();
  2481. this.sendPingOnPrimaryIfNecessary_();
  2482. }
  2483. else {
  2484. error('Unknown control packet command: ' + cmd);
  2485. }
  2486. }
  2487. }
  2488. /**
  2489. * @param handshake - The handshake data returned from the server
  2490. */
  2491. onHandshake_(handshake) {
  2492. const timestamp = handshake.ts;
  2493. const version = handshake.v;
  2494. const host = handshake.h;
  2495. this.sessionId = handshake.s;
  2496. this.repoInfo_.host = host;
  2497. // if we've already closed the connection, then don't bother trying to progress further
  2498. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2499. this.conn_.start();
  2500. this.onConnectionEstablished_(this.conn_, timestamp);
  2501. if (PROTOCOL_VERSION !== version) {
  2502. warn('Protocol version mismatch detected');
  2503. }
  2504. // TODO: do we want to upgrade? when? maybe a delay?
  2505. this.tryStartUpgrade_();
  2506. }
  2507. }
  2508. tryStartUpgrade_() {
  2509. const conn = this.transportManager_.upgradeTransport();
  2510. if (conn) {
  2511. this.startUpgrade_(conn);
  2512. }
  2513. }
  2514. startUpgrade_(conn) {
  2515. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2516. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2517. // can consider the transport healthy.
  2518. this.secondaryResponsesRequired_ =
  2519. conn['responsesRequiredToBeHealthy'] || 0;
  2520. const onMessage = this.connReceiver_(this.secondaryConn_);
  2521. const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2522. this.secondaryConn_.open(onMessage, onDisconnect);
  2523. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2524. setTimeoutNonBlocking(() => {
  2525. if (this.secondaryConn_) {
  2526. this.log_('Timed out trying to upgrade.');
  2527. this.secondaryConn_.close();
  2528. }
  2529. }, Math.floor(UPGRADE_TIMEOUT));
  2530. }
  2531. onReset_(host) {
  2532. this.log_('Reset packet received. New host: ' + host);
  2533. this.repoInfo_.host = host;
  2534. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2535. // We don't currently support resets after the connection has already been established
  2536. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2537. this.close();
  2538. }
  2539. else {
  2540. // Close whatever connections we have open and start again.
  2541. this.closeConnections_();
  2542. this.start_();
  2543. }
  2544. }
  2545. onConnectionEstablished_(conn, timestamp) {
  2546. this.log_('Realtime connection established.');
  2547. this.conn_ = conn;
  2548. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2549. if (this.onReady_) {
  2550. this.onReady_(timestamp, this.sessionId);
  2551. this.onReady_ = null;
  2552. }
  2553. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2554. // send some pings.
  2555. if (this.primaryResponsesRequired_ === 0) {
  2556. this.log_('Primary connection is healthy.');
  2557. this.isHealthy_ = true;
  2558. }
  2559. else {
  2560. setTimeoutNonBlocking(() => {
  2561. this.sendPingOnPrimaryIfNecessary_();
  2562. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2563. }
  2564. }
  2565. sendPingOnPrimaryIfNecessary_() {
  2566. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2567. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2568. this.log_('sending ping on primary.');
  2569. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2570. }
  2571. }
  2572. onSecondaryConnectionLost_() {
  2573. const conn = this.secondaryConn_;
  2574. this.secondaryConn_ = null;
  2575. if (this.tx_ === conn || this.rx_ === conn) {
  2576. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2577. this.close();
  2578. }
  2579. }
  2580. /**
  2581. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2582. * we should flush the host cache
  2583. */
  2584. onConnectionLost_(everConnected) {
  2585. this.conn_ = null;
  2586. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2587. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2588. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2589. this.log_('Realtime connection failed.');
  2590. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2591. if (this.repoInfo_.isCacheableHost()) {
  2592. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2593. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2594. this.repoInfo_.internalHost = this.repoInfo_.host;
  2595. }
  2596. }
  2597. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2598. this.log_('Realtime connection lost.');
  2599. }
  2600. this.close();
  2601. }
  2602. onConnectionShutdown_(reason) {
  2603. this.log_('Connection shutdown command received. Shutting down...');
  2604. if (this.onKill_) {
  2605. this.onKill_(reason);
  2606. this.onKill_ = null;
  2607. }
  2608. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2609. // so clear the callback.
  2610. this.onDisconnect_ = null;
  2611. this.close();
  2612. }
  2613. sendData_(data) {
  2614. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2615. throw 'Connection is not connected';
  2616. }
  2617. else {
  2618. this.tx_.send(data);
  2619. }
  2620. }
  2621. /**
  2622. * Cleans up this connection, calling the appropriate callbacks
  2623. */
  2624. close() {
  2625. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2626. this.log_('Closing realtime connection.');
  2627. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2628. this.closeConnections_();
  2629. if (this.onDisconnect_) {
  2630. this.onDisconnect_();
  2631. this.onDisconnect_ = null;
  2632. }
  2633. }
  2634. }
  2635. closeConnections_() {
  2636. this.log_('Shutting down all connections');
  2637. if (this.conn_) {
  2638. this.conn_.close();
  2639. this.conn_ = null;
  2640. }
  2641. if (this.secondaryConn_) {
  2642. this.secondaryConn_.close();
  2643. this.secondaryConn_ = null;
  2644. }
  2645. if (this.healthyTimeout_) {
  2646. clearTimeout(this.healthyTimeout_);
  2647. this.healthyTimeout_ = null;
  2648. }
  2649. }
  2650. }
  2651. /**
  2652. * @license
  2653. * Copyright 2017 Google LLC
  2654. *
  2655. * Licensed under the Apache License, Version 2.0 (the "License");
  2656. * you may not use this file except in compliance with the License.
  2657. * You may obtain a copy of the License at
  2658. *
  2659. * http://www.apache.org/licenses/LICENSE-2.0
  2660. *
  2661. * Unless required by applicable law or agreed to in writing, software
  2662. * distributed under the License is distributed on an "AS IS" BASIS,
  2663. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2664. * See the License for the specific language governing permissions and
  2665. * limitations under the License.
  2666. */
  2667. /**
  2668. * Interface defining the set of actions that can be performed against the Firebase server
  2669. * (basically corresponds to our wire protocol).
  2670. *
  2671. * @interface
  2672. */
  2673. class ServerActions {
  2674. put(pathString, data, onComplete, hash) { }
  2675. merge(pathString, data, onComplete, hash) { }
  2676. /**
  2677. * Refreshes the auth token for the current connection.
  2678. * @param token - The authentication token
  2679. */
  2680. refreshAuthToken(token) { }
  2681. /**
  2682. * Refreshes the app check token for the current connection.
  2683. * @param token The app check token
  2684. */
  2685. refreshAppCheckToken(token) { }
  2686. onDisconnectPut(pathString, data, onComplete) { }
  2687. onDisconnectMerge(pathString, data, onComplete) { }
  2688. onDisconnectCancel(pathString, onComplete) { }
  2689. reportStats(stats) { }
  2690. }
  2691. /**
  2692. * @license
  2693. * Copyright 2017 Google LLC
  2694. *
  2695. * Licensed under the Apache License, Version 2.0 (the "License");
  2696. * you may not use this file except in compliance with the License.
  2697. * You may obtain a copy of the License at
  2698. *
  2699. * http://www.apache.org/licenses/LICENSE-2.0
  2700. *
  2701. * Unless required by applicable law or agreed to in writing, software
  2702. * distributed under the License is distributed on an "AS IS" BASIS,
  2703. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2704. * See the License for the specific language governing permissions and
  2705. * limitations under the License.
  2706. */
  2707. /**
  2708. * Base class to be used if you want to emit events. Call the constructor with
  2709. * the set of allowed event names.
  2710. */
  2711. class EventEmitter {
  2712. constructor(allowedEvents_) {
  2713. this.allowedEvents_ = allowedEvents_;
  2714. this.listeners_ = {};
  2715. assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2716. }
  2717. /**
  2718. * To be called by derived classes to trigger events.
  2719. */
  2720. trigger(eventType, ...varArgs) {
  2721. if (Array.isArray(this.listeners_[eventType])) {
  2722. // Clone the list, since callbacks could add/remove listeners.
  2723. const listeners = [...this.listeners_[eventType]];
  2724. for (let i = 0; i < listeners.length; i++) {
  2725. listeners[i].callback.apply(listeners[i].context, varArgs);
  2726. }
  2727. }
  2728. }
  2729. on(eventType, callback, context) {
  2730. this.validateEventType_(eventType);
  2731. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2732. this.listeners_[eventType].push({ callback, context });
  2733. const eventData = this.getInitialEvent(eventType);
  2734. if (eventData) {
  2735. callback.apply(context, eventData);
  2736. }
  2737. }
  2738. off(eventType, callback, context) {
  2739. this.validateEventType_(eventType);
  2740. const listeners = this.listeners_[eventType] || [];
  2741. for (let i = 0; i < listeners.length; i++) {
  2742. if (listeners[i].callback === callback &&
  2743. (!context || context === listeners[i].context)) {
  2744. listeners.splice(i, 1);
  2745. return;
  2746. }
  2747. }
  2748. }
  2749. validateEventType_(eventType) {
  2750. assert(this.allowedEvents_.find(et => {
  2751. return et === eventType;
  2752. }), 'Unknown event: ' + eventType);
  2753. }
  2754. }
  2755. /**
  2756. * @license
  2757. * Copyright 2017 Google LLC
  2758. *
  2759. * Licensed under the Apache License, Version 2.0 (the "License");
  2760. * you may not use this file except in compliance with the License.
  2761. * You may obtain a copy of the License at
  2762. *
  2763. * http://www.apache.org/licenses/LICENSE-2.0
  2764. *
  2765. * Unless required by applicable law or agreed to in writing, software
  2766. * distributed under the License is distributed on an "AS IS" BASIS,
  2767. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2768. * See the License for the specific language governing permissions and
  2769. * limitations under the License.
  2770. */
  2771. /**
  2772. * Monitors online state (as reported by window.online/offline events).
  2773. *
  2774. * The expectation is that this could have many false positives (thinks we are online
  2775. * when we're not), but no false negatives. So we can safely use it to determine when
  2776. * we definitely cannot reach the internet.
  2777. */
  2778. class OnlineMonitor extends EventEmitter {
  2779. constructor() {
  2780. super(['online']);
  2781. this.online_ = true;
  2782. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2783. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2784. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2785. // for Cordova.
  2786. if (typeof window !== 'undefined' &&
  2787. typeof window.addEventListener !== 'undefined' &&
  2788. !isMobileCordova()) {
  2789. window.addEventListener('online', () => {
  2790. if (!this.online_) {
  2791. this.online_ = true;
  2792. this.trigger('online', true);
  2793. }
  2794. }, false);
  2795. window.addEventListener('offline', () => {
  2796. if (this.online_) {
  2797. this.online_ = false;
  2798. this.trigger('online', false);
  2799. }
  2800. }, false);
  2801. }
  2802. }
  2803. static getInstance() {
  2804. return new OnlineMonitor();
  2805. }
  2806. getInitialEvent(eventType) {
  2807. assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2808. return [this.online_];
  2809. }
  2810. currentlyOnline() {
  2811. return this.online_;
  2812. }
  2813. }
  2814. /**
  2815. * @license
  2816. * Copyright 2017 Google LLC
  2817. *
  2818. * Licensed under the Apache License, Version 2.0 (the "License");
  2819. * you may not use this file except in compliance with the License.
  2820. * You may obtain a copy of the License at
  2821. *
  2822. * http://www.apache.org/licenses/LICENSE-2.0
  2823. *
  2824. * Unless required by applicable law or agreed to in writing, software
  2825. * distributed under the License is distributed on an "AS IS" BASIS,
  2826. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2827. * See the License for the specific language governing permissions and
  2828. * limitations under the License.
  2829. */
  2830. /** Maximum key depth. */
  2831. const MAX_PATH_DEPTH = 32;
  2832. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2833. const MAX_PATH_LENGTH_BYTES = 768;
  2834. /**
  2835. * An immutable object representing a parsed path. It's immutable so that you
  2836. * can pass them around to other functions without worrying about them changing
  2837. * it.
  2838. */
  2839. class Path {
  2840. /**
  2841. * @param pathOrString - Path string to parse, or another path, or the raw
  2842. * tokens array
  2843. */
  2844. constructor(pathOrString, pieceNum) {
  2845. if (pieceNum === void 0) {
  2846. this.pieces_ = pathOrString.split('/');
  2847. // Remove empty pieces.
  2848. let copyTo = 0;
  2849. for (let i = 0; i < this.pieces_.length; i++) {
  2850. if (this.pieces_[i].length > 0) {
  2851. this.pieces_[copyTo] = this.pieces_[i];
  2852. copyTo++;
  2853. }
  2854. }
  2855. this.pieces_.length = copyTo;
  2856. this.pieceNum_ = 0;
  2857. }
  2858. else {
  2859. this.pieces_ = pathOrString;
  2860. this.pieceNum_ = pieceNum;
  2861. }
  2862. }
  2863. toString() {
  2864. let pathString = '';
  2865. for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
  2866. if (this.pieces_[i] !== '') {
  2867. pathString += '/' + this.pieces_[i];
  2868. }
  2869. }
  2870. return pathString || '/';
  2871. }
  2872. }
  2873. function newEmptyPath() {
  2874. return new Path('');
  2875. }
  2876. function pathGetFront(path) {
  2877. if (path.pieceNum_ >= path.pieces_.length) {
  2878. return null;
  2879. }
  2880. return path.pieces_[path.pieceNum_];
  2881. }
  2882. /**
  2883. * @returns The number of segments in this path
  2884. */
  2885. function pathGetLength(path) {
  2886. return path.pieces_.length - path.pieceNum_;
  2887. }
  2888. function pathPopFront(path) {
  2889. let pieceNum = path.pieceNum_;
  2890. if (pieceNum < path.pieces_.length) {
  2891. pieceNum++;
  2892. }
  2893. return new Path(path.pieces_, pieceNum);
  2894. }
  2895. function pathGetBack(path) {
  2896. if (path.pieceNum_ < path.pieces_.length) {
  2897. return path.pieces_[path.pieces_.length - 1];
  2898. }
  2899. return null;
  2900. }
  2901. function pathToUrlEncodedString(path) {
  2902. let pathString = '';
  2903. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2904. if (path.pieces_[i] !== '') {
  2905. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  2906. }
  2907. }
  2908. return pathString || '/';
  2909. }
  2910. /**
  2911. * Shallow copy of the parts of the path.
  2912. *
  2913. */
  2914. function pathSlice(path, begin = 0) {
  2915. return path.pieces_.slice(path.pieceNum_ + begin);
  2916. }
  2917. function pathParent(path) {
  2918. if (path.pieceNum_ >= path.pieces_.length) {
  2919. return null;
  2920. }
  2921. const pieces = [];
  2922. for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  2923. pieces.push(path.pieces_[i]);
  2924. }
  2925. return new Path(pieces, 0);
  2926. }
  2927. function pathChild(path, childPathObj) {
  2928. const pieces = [];
  2929. for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
  2930. pieces.push(path.pieces_[i]);
  2931. }
  2932. if (childPathObj instanceof Path) {
  2933. for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  2934. pieces.push(childPathObj.pieces_[i]);
  2935. }
  2936. }
  2937. else {
  2938. const childPieces = childPathObj.split('/');
  2939. for (let i = 0; i < childPieces.length; i++) {
  2940. if (childPieces[i].length > 0) {
  2941. pieces.push(childPieces[i]);
  2942. }
  2943. }
  2944. }
  2945. return new Path(pieces, 0);
  2946. }
  2947. /**
  2948. * @returns True if there are no segments in this path
  2949. */
  2950. function pathIsEmpty(path) {
  2951. return path.pieceNum_ >= path.pieces_.length;
  2952. }
  2953. /**
  2954. * @returns The path from outerPath to innerPath
  2955. */
  2956. function newRelativePath(outerPath, innerPath) {
  2957. const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  2958. if (outer === null) {
  2959. return innerPath;
  2960. }
  2961. else if (outer === inner) {
  2962. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  2963. }
  2964. else {
  2965. throw new Error('INTERNAL ERROR: innerPath (' +
  2966. innerPath +
  2967. ') is not within ' +
  2968. 'outerPath (' +
  2969. outerPath +
  2970. ')');
  2971. }
  2972. }
  2973. /**
  2974. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  2975. */
  2976. function pathCompare(left, right) {
  2977. const leftKeys = pathSlice(left, 0);
  2978. const rightKeys = pathSlice(right, 0);
  2979. for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  2980. const cmp = nameCompare(leftKeys[i], rightKeys[i]);
  2981. if (cmp !== 0) {
  2982. return cmp;
  2983. }
  2984. }
  2985. if (leftKeys.length === rightKeys.length) {
  2986. return 0;
  2987. }
  2988. return leftKeys.length < rightKeys.length ? -1 : 1;
  2989. }
  2990. /**
  2991. * @returns true if paths are the same.
  2992. */
  2993. function pathEquals(path, other) {
  2994. if (pathGetLength(path) !== pathGetLength(other)) {
  2995. return false;
  2996. }
  2997. for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  2998. if (path.pieces_[i] !== other.pieces_[j]) {
  2999. return false;
  3000. }
  3001. }
  3002. return true;
  3003. }
  3004. /**
  3005. * @returns True if this path is a parent of (or the same as) other
  3006. */
  3007. function pathContains(path, other) {
  3008. let i = path.pieceNum_;
  3009. let j = other.pieceNum_;
  3010. if (pathGetLength(path) > pathGetLength(other)) {
  3011. return false;
  3012. }
  3013. while (i < path.pieces_.length) {
  3014. if (path.pieces_[i] !== other.pieces_[j]) {
  3015. return false;
  3016. }
  3017. ++i;
  3018. ++j;
  3019. }
  3020. return true;
  3021. }
  3022. /**
  3023. * Dynamic (mutable) path used to count path lengths.
  3024. *
  3025. * This class is used to efficiently check paths for valid
  3026. * length (in UTF8 bytes) and depth (used in path validation).
  3027. *
  3028. * Throws Error exception if path is ever invalid.
  3029. *
  3030. * The definition of a path always begins with '/'.
  3031. */
  3032. class ValidationPath {
  3033. /**
  3034. * @param path - Initial Path.
  3035. * @param errorPrefix_ - Prefix for any error messages.
  3036. */
  3037. constructor(path, errorPrefix_) {
  3038. this.errorPrefix_ = errorPrefix_;
  3039. this.parts_ = pathSlice(path, 0);
  3040. /** Initialize to number of '/' chars needed in path. */
  3041. this.byteLength_ = Math.max(1, this.parts_.length);
  3042. for (let i = 0; i < this.parts_.length; i++) {
  3043. this.byteLength_ += stringLength(this.parts_[i]);
  3044. }
  3045. validationPathCheckValid(this);
  3046. }
  3047. }
  3048. function validationPathPush(validationPath, child) {
  3049. // Count the needed '/'
  3050. if (validationPath.parts_.length > 0) {
  3051. validationPath.byteLength_ += 1;
  3052. }
  3053. validationPath.parts_.push(child);
  3054. validationPath.byteLength_ += stringLength(child);
  3055. validationPathCheckValid(validationPath);
  3056. }
  3057. function validationPathPop(validationPath) {
  3058. const last = validationPath.parts_.pop();
  3059. validationPath.byteLength_ -= stringLength(last);
  3060. // Un-count the previous '/'
  3061. if (validationPath.parts_.length > 0) {
  3062. validationPath.byteLength_ -= 1;
  3063. }
  3064. }
  3065. function validationPathCheckValid(validationPath) {
  3066. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3067. throw new Error(validationPath.errorPrefix_ +
  3068. 'has a key path longer than ' +
  3069. MAX_PATH_LENGTH_BYTES +
  3070. ' bytes (' +
  3071. validationPath.byteLength_ +
  3072. ').');
  3073. }
  3074. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3075. throw new Error(validationPath.errorPrefix_ +
  3076. 'path specified exceeds the maximum depth that can be written (' +
  3077. MAX_PATH_DEPTH +
  3078. ') or object contains a cycle ' +
  3079. validationPathToErrorString(validationPath));
  3080. }
  3081. }
  3082. /**
  3083. * String for use in error messages - uses '.' notation for path.
  3084. */
  3085. function validationPathToErrorString(validationPath) {
  3086. if (validationPath.parts_.length === 0) {
  3087. return '';
  3088. }
  3089. return "in property '" + validationPath.parts_.join('.') + "'";
  3090. }
  3091. /**
  3092. * @license
  3093. * Copyright 2017 Google LLC
  3094. *
  3095. * Licensed under the Apache License, Version 2.0 (the "License");
  3096. * you may not use this file except in compliance with the License.
  3097. * You may obtain a copy of the License at
  3098. *
  3099. * http://www.apache.org/licenses/LICENSE-2.0
  3100. *
  3101. * Unless required by applicable law or agreed to in writing, software
  3102. * distributed under the License is distributed on an "AS IS" BASIS,
  3103. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3104. * See the License for the specific language governing permissions and
  3105. * limitations under the License.
  3106. */
  3107. class VisibilityMonitor extends EventEmitter {
  3108. constructor() {
  3109. super(['visible']);
  3110. let hidden;
  3111. let visibilityChange;
  3112. if (typeof document !== 'undefined' &&
  3113. typeof document.addEventListener !== 'undefined') {
  3114. if (typeof document['hidden'] !== 'undefined') {
  3115. // Opera 12.10 and Firefox 18 and later support
  3116. visibilityChange = 'visibilitychange';
  3117. hidden = 'hidden';
  3118. }
  3119. else if (typeof document['mozHidden'] !== 'undefined') {
  3120. visibilityChange = 'mozvisibilitychange';
  3121. hidden = 'mozHidden';
  3122. }
  3123. else if (typeof document['msHidden'] !== 'undefined') {
  3124. visibilityChange = 'msvisibilitychange';
  3125. hidden = 'msHidden';
  3126. }
  3127. else if (typeof document['webkitHidden'] !== 'undefined') {
  3128. visibilityChange = 'webkitvisibilitychange';
  3129. hidden = 'webkitHidden';
  3130. }
  3131. }
  3132. // Initially, we always assume we are visible. This ensures that in browsers
  3133. // without page visibility support or in cases where we are never visible
  3134. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3135. // reconnects
  3136. this.visible_ = true;
  3137. if (visibilityChange) {
  3138. document.addEventListener(visibilityChange, () => {
  3139. const visible = !document[hidden];
  3140. if (visible !== this.visible_) {
  3141. this.visible_ = visible;
  3142. this.trigger('visible', visible);
  3143. }
  3144. }, false);
  3145. }
  3146. }
  3147. static getInstance() {
  3148. return new VisibilityMonitor();
  3149. }
  3150. getInitialEvent(eventType) {
  3151. assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3152. return [this.visible_];
  3153. }
  3154. }
  3155. /**
  3156. * @license
  3157. * Copyright 2017 Google LLC
  3158. *
  3159. * Licensed under the Apache License, Version 2.0 (the "License");
  3160. * you may not use this file except in compliance with the License.
  3161. * You may obtain a copy of the License at
  3162. *
  3163. * http://www.apache.org/licenses/LICENSE-2.0
  3164. *
  3165. * Unless required by applicable law or agreed to in writing, software
  3166. * distributed under the License is distributed on an "AS IS" BASIS,
  3167. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3168. * See the License for the specific language governing permissions and
  3169. * limitations under the License.
  3170. */
  3171. const RECONNECT_MIN_DELAY = 1000;
  3172. const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3173. const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3174. const RECONNECT_DELAY_MULTIPLIER = 1.3;
  3175. const RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3176. const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3177. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3178. const INVALID_TOKEN_THRESHOLD = 3;
  3179. /**
  3180. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3181. *
  3182. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3183. * in quotes to make sure the closure compiler does not minify them.
  3184. */
  3185. class PersistentConnection extends ServerActions {
  3186. /**
  3187. * @param repoInfo_ - Data about the namespace we are connecting to
  3188. * @param applicationId_ - The Firebase App ID for this project
  3189. * @param onDataUpdate_ - A callback for new data from the server
  3190. */
  3191. constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3192. super();
  3193. this.repoInfo_ = repoInfo_;
  3194. this.applicationId_ = applicationId_;
  3195. this.onDataUpdate_ = onDataUpdate_;
  3196. this.onConnectStatus_ = onConnectStatus_;
  3197. this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3198. this.authTokenProvider_ = authTokenProvider_;
  3199. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3200. this.authOverride_ = authOverride_;
  3201. // Used for diagnostic logging.
  3202. this.id = PersistentConnection.nextPersistentConnectionId_++;
  3203. this.log_ = logWrapper('p:' + this.id + ':');
  3204. this.interruptReasons_ = {};
  3205. this.listens = new Map();
  3206. this.outstandingPuts_ = [];
  3207. this.outstandingGets_ = [];
  3208. this.outstandingPutCount_ = 0;
  3209. this.outstandingGetCount_ = 0;
  3210. this.onDisconnectRequestQueue_ = [];
  3211. this.connected_ = false;
  3212. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3213. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3214. this.securityDebugCallback_ = null;
  3215. this.lastSessionId = null;
  3216. this.establishConnectionTimer_ = null;
  3217. this.visible_ = false;
  3218. // Before we get connected, we keep a queue of pending messages to send.
  3219. this.requestCBHash_ = {};
  3220. this.requestNumber_ = 0;
  3221. this.realtime_ = null;
  3222. this.authToken_ = null;
  3223. this.appCheckToken_ = null;
  3224. this.forceTokenRefresh_ = false;
  3225. this.invalidAuthTokenCount_ = 0;
  3226. this.invalidAppCheckTokenCount_ = 0;
  3227. this.firstConnection_ = true;
  3228. this.lastConnectionAttemptTime_ = null;
  3229. this.lastConnectionEstablishedTime_ = null;
  3230. if (authOverride_ && !isNodeSdk()) {
  3231. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3232. }
  3233. VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
  3234. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3235. OnlineMonitor.getInstance().on('online', this.onOnline_, this);
  3236. }
  3237. }
  3238. sendRequest(action, body, onResponse) {
  3239. const curReqNum = ++this.requestNumber_;
  3240. const msg = { r: curReqNum, a: action, b: body };
  3241. this.log_(stringify(msg));
  3242. assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3243. this.realtime_.sendRequest(msg);
  3244. if (onResponse) {
  3245. this.requestCBHash_[curReqNum] = onResponse;
  3246. }
  3247. }
  3248. get(query) {
  3249. this.initConnection_();
  3250. const deferred = new Deferred();
  3251. const request = {
  3252. p: query._path.toString(),
  3253. q: query._queryObject
  3254. };
  3255. const outstandingGet = {
  3256. action: 'g',
  3257. request,
  3258. onComplete: (message) => {
  3259. const payload = message['d'];
  3260. if (message['s'] === 'ok') {
  3261. deferred.resolve(payload);
  3262. }
  3263. else {
  3264. deferred.reject(payload);
  3265. }
  3266. }
  3267. };
  3268. this.outstandingGets_.push(outstandingGet);
  3269. this.outstandingGetCount_++;
  3270. const index = this.outstandingGets_.length - 1;
  3271. if (this.connected_) {
  3272. this.sendGet_(index);
  3273. }
  3274. return deferred.promise;
  3275. }
  3276. listen(query, currentHashFn, tag, onComplete) {
  3277. this.initConnection_();
  3278. const queryId = query._queryIdentifier;
  3279. const pathString = query._path.toString();
  3280. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3281. if (!this.listens.has(pathString)) {
  3282. this.listens.set(pathString, new Map());
  3283. }
  3284. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3285. assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
  3286. const listenSpec = {
  3287. onComplete,
  3288. hashFn: currentHashFn,
  3289. query,
  3290. tag
  3291. };
  3292. this.listens.get(pathString).set(queryId, listenSpec);
  3293. if (this.connected_) {
  3294. this.sendListen_(listenSpec);
  3295. }
  3296. }
  3297. sendGet_(index) {
  3298. const get = this.outstandingGets_[index];
  3299. this.sendRequest('g', get.request, (message) => {
  3300. delete this.outstandingGets_[index];
  3301. this.outstandingGetCount_--;
  3302. if (this.outstandingGetCount_ === 0) {
  3303. this.outstandingGets_ = [];
  3304. }
  3305. if (get.onComplete) {
  3306. get.onComplete(message);
  3307. }
  3308. });
  3309. }
  3310. sendListen_(listenSpec) {
  3311. const query = listenSpec.query;
  3312. const pathString = query._path.toString();
  3313. const queryId = query._queryIdentifier;
  3314. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3315. const req = { /*path*/ p: pathString };
  3316. const action = 'q';
  3317. // Only bother to send query if it's non-default.
  3318. if (listenSpec.tag) {
  3319. req['q'] = query._queryObject;
  3320. req['t'] = listenSpec.tag;
  3321. }
  3322. req[ /*hash*/'h'] = listenSpec.hashFn();
  3323. this.sendRequest(action, req, (message) => {
  3324. const payload = message[ /*data*/'d'];
  3325. const status = message[ /*status*/'s'];
  3326. // print warnings in any case...
  3327. PersistentConnection.warnOnListenWarnings_(payload, query);
  3328. const currentListenSpec = this.listens.get(pathString) &&
  3329. this.listens.get(pathString).get(queryId);
  3330. // only trigger actions if the listen hasn't been removed and readded
  3331. if (currentListenSpec === listenSpec) {
  3332. this.log_('listen response', message);
  3333. if (status !== 'ok') {
  3334. this.removeListen_(pathString, queryId);
  3335. }
  3336. if (listenSpec.onComplete) {
  3337. listenSpec.onComplete(status, payload);
  3338. }
  3339. }
  3340. });
  3341. }
  3342. static warnOnListenWarnings_(payload, query) {
  3343. if (payload && typeof payload === 'object' && contains(payload, 'w')) {
  3344. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3345. const warnings = safeGet(payload, 'w');
  3346. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3347. const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3348. const indexPath = query._path.toString();
  3349. warn(`Using an unspecified index. Your data will be downloaded and ` +
  3350. `filtered on the client. Consider adding ${indexSpec} at ` +
  3351. `${indexPath} to your security rules for better performance.`);
  3352. }
  3353. }
  3354. }
  3355. refreshAuthToken(token) {
  3356. this.authToken_ = token;
  3357. this.log_('Auth token refreshed');
  3358. if (this.authToken_) {
  3359. this.tryAuth();
  3360. }
  3361. else {
  3362. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3363. //the credential so we dont become authenticated next time we connect.
  3364. if (this.connected_) {
  3365. this.sendRequest('unauth', {}, () => { });
  3366. }
  3367. }
  3368. this.reduceReconnectDelayIfAdminCredential_(token);
  3369. }
  3370. reduceReconnectDelayIfAdminCredential_(credential) {
  3371. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3372. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3373. const isFirebaseSecret = credential && credential.length === 40;
  3374. if (isFirebaseSecret || isAdmin(credential)) {
  3375. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3376. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3377. }
  3378. }
  3379. refreshAppCheckToken(token) {
  3380. this.appCheckToken_ = token;
  3381. this.log_('App check token refreshed');
  3382. if (this.appCheckToken_) {
  3383. this.tryAppCheck();
  3384. }
  3385. else {
  3386. //If we're connected we want to let the server know to unauthenticate us.
  3387. //If we're not connected, simply delete the credential so we dont become
  3388. // authenticated next time we connect.
  3389. if (this.connected_) {
  3390. this.sendRequest('unappeck', {}, () => { });
  3391. }
  3392. }
  3393. }
  3394. /**
  3395. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3396. * a auth revoked (the connection is closed).
  3397. */
  3398. tryAuth() {
  3399. if (this.connected_ && this.authToken_) {
  3400. const token = this.authToken_;
  3401. const authMethod = isValidFormat(token) ? 'auth' : 'gauth';
  3402. const requestData = { cred: token };
  3403. if (this.authOverride_ === null) {
  3404. requestData['noauth'] = true;
  3405. }
  3406. else if (typeof this.authOverride_ === 'object') {
  3407. requestData['authvar'] = this.authOverride_;
  3408. }
  3409. this.sendRequest(authMethod, requestData, (res) => {
  3410. const status = res[ /*status*/'s'];
  3411. const data = res[ /*data*/'d'] || 'error';
  3412. if (this.authToken_ === token) {
  3413. if (status === 'ok') {
  3414. this.invalidAuthTokenCount_ = 0;
  3415. }
  3416. else {
  3417. // Triggers reconnect and force refresh for auth token
  3418. this.onAuthRevoked_(status, data);
  3419. }
  3420. }
  3421. });
  3422. }
  3423. }
  3424. /**
  3425. * Attempts to authenticate with the given token. If the authentication
  3426. * attempt fails, it's triggered like the token was revoked (the connection is
  3427. * closed).
  3428. */
  3429. tryAppCheck() {
  3430. if (this.connected_ && this.appCheckToken_) {
  3431. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
  3432. const status = res[ /*status*/'s'];
  3433. const data = res[ /*data*/'d'] || 'error';
  3434. if (status === 'ok') {
  3435. this.invalidAppCheckTokenCount_ = 0;
  3436. }
  3437. else {
  3438. this.onAppCheckRevoked_(status, data);
  3439. }
  3440. });
  3441. }
  3442. }
  3443. /**
  3444. * @inheritDoc
  3445. */
  3446. unlisten(query, tag) {
  3447. const pathString = query._path.toString();
  3448. const queryId = query._queryIdentifier;
  3449. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3450. assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3451. const listen = this.removeListen_(pathString, queryId);
  3452. if (listen && this.connected_) {
  3453. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3454. }
  3455. }
  3456. sendUnlisten_(pathString, queryId, queryObj, tag) {
  3457. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3458. const req = { /*path*/ p: pathString };
  3459. const action = 'n';
  3460. // Only bother sending queryId if it's non-default.
  3461. if (tag) {
  3462. req['q'] = queryObj;
  3463. req['t'] = tag;
  3464. }
  3465. this.sendRequest(action, req);
  3466. }
  3467. onDisconnectPut(pathString, data, onComplete) {
  3468. this.initConnection_();
  3469. if (this.connected_) {
  3470. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3471. }
  3472. else {
  3473. this.onDisconnectRequestQueue_.push({
  3474. pathString,
  3475. action: 'o',
  3476. data,
  3477. onComplete
  3478. });
  3479. }
  3480. }
  3481. onDisconnectMerge(pathString, data, onComplete) {
  3482. this.initConnection_();
  3483. if (this.connected_) {
  3484. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3485. }
  3486. else {
  3487. this.onDisconnectRequestQueue_.push({
  3488. pathString,
  3489. action: 'om',
  3490. data,
  3491. onComplete
  3492. });
  3493. }
  3494. }
  3495. onDisconnectCancel(pathString, onComplete) {
  3496. this.initConnection_();
  3497. if (this.connected_) {
  3498. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3499. }
  3500. else {
  3501. this.onDisconnectRequestQueue_.push({
  3502. pathString,
  3503. action: 'oc',
  3504. data: null,
  3505. onComplete
  3506. });
  3507. }
  3508. }
  3509. sendOnDisconnect_(action, pathString, data, onComplete) {
  3510. const request = { /*path*/ p: pathString, /*data*/ d: data };
  3511. this.log_('onDisconnect ' + action, request);
  3512. this.sendRequest(action, request, (response) => {
  3513. if (onComplete) {
  3514. setTimeout(() => {
  3515. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3516. }, Math.floor(0));
  3517. }
  3518. });
  3519. }
  3520. put(pathString, data, onComplete, hash) {
  3521. this.putInternal('p', pathString, data, onComplete, hash);
  3522. }
  3523. merge(pathString, data, onComplete, hash) {
  3524. this.putInternal('m', pathString, data, onComplete, hash);
  3525. }
  3526. putInternal(action, pathString, data, onComplete, hash) {
  3527. this.initConnection_();
  3528. const request = {
  3529. /*path*/ p: pathString,
  3530. /*data*/ d: data
  3531. };
  3532. if (hash !== undefined) {
  3533. request[ /*hash*/'h'] = hash;
  3534. }
  3535. // TODO: Only keep track of the most recent put for a given path?
  3536. this.outstandingPuts_.push({
  3537. action,
  3538. request,
  3539. onComplete
  3540. });
  3541. this.outstandingPutCount_++;
  3542. const index = this.outstandingPuts_.length - 1;
  3543. if (this.connected_) {
  3544. this.sendPut_(index);
  3545. }
  3546. else {
  3547. this.log_('Buffering put: ' + pathString);
  3548. }
  3549. }
  3550. sendPut_(index) {
  3551. const action = this.outstandingPuts_[index].action;
  3552. const request = this.outstandingPuts_[index].request;
  3553. const onComplete = this.outstandingPuts_[index].onComplete;
  3554. this.outstandingPuts_[index].queued = this.connected_;
  3555. this.sendRequest(action, request, (message) => {
  3556. this.log_(action + ' response', message);
  3557. delete this.outstandingPuts_[index];
  3558. this.outstandingPutCount_--;
  3559. // Clean up array occasionally.
  3560. if (this.outstandingPutCount_ === 0) {
  3561. this.outstandingPuts_ = [];
  3562. }
  3563. if (onComplete) {
  3564. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3565. }
  3566. });
  3567. }
  3568. reportStats(stats) {
  3569. // If we're not connected, we just drop the stats.
  3570. if (this.connected_) {
  3571. const request = { /*counters*/ c: stats };
  3572. this.log_('reportStats', request);
  3573. this.sendRequest(/*stats*/ 's', request, result => {
  3574. const status = result[ /*status*/'s'];
  3575. if (status !== 'ok') {
  3576. const errorReason = result[ /* data */'d'];
  3577. this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3578. }
  3579. });
  3580. }
  3581. }
  3582. onDataMessage_(message) {
  3583. if ('r' in message) {
  3584. // this is a response
  3585. this.log_('from server: ' + stringify(message));
  3586. const reqNum = message['r'];
  3587. const onResponse = this.requestCBHash_[reqNum];
  3588. if (onResponse) {
  3589. delete this.requestCBHash_[reqNum];
  3590. onResponse(message[ /*body*/'b']);
  3591. }
  3592. }
  3593. else if ('error' in message) {
  3594. throw 'A server-side error has occurred: ' + message['error'];
  3595. }
  3596. else if ('a' in message) {
  3597. // a and b are action and body, respectively
  3598. this.onDataPush_(message['a'], message['b']);
  3599. }
  3600. }
  3601. onDataPush_(action, body) {
  3602. this.log_('handleServerMessage', action, body);
  3603. if (action === 'd') {
  3604. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3605. /*isMerge*/ false, body['t']);
  3606. }
  3607. else if (action === 'm') {
  3608. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3609. /*isMerge=*/ true, body['t']);
  3610. }
  3611. else if (action === 'c') {
  3612. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3613. }
  3614. else if (action === 'ac') {
  3615. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3616. }
  3617. else if (action === 'apc') {
  3618. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3619. }
  3620. else if (action === 'sd') {
  3621. this.onSecurityDebugPacket_(body);
  3622. }
  3623. else {
  3624. error('Unrecognized action received from server: ' +
  3625. stringify(action) +
  3626. '\nAre you using the latest client?');
  3627. }
  3628. }
  3629. onReady_(timestamp, sessionId) {
  3630. this.log_('connection ready');
  3631. this.connected_ = true;
  3632. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3633. this.handleTimestamp_(timestamp);
  3634. this.lastSessionId = sessionId;
  3635. if (this.firstConnection_) {
  3636. this.sendConnectStats_();
  3637. }
  3638. this.restoreState_();
  3639. this.firstConnection_ = false;
  3640. this.onConnectStatus_(true);
  3641. }
  3642. scheduleConnect_(timeout) {
  3643. assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3644. if (this.establishConnectionTimer_) {
  3645. clearTimeout(this.establishConnectionTimer_);
  3646. }
  3647. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3648. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3649. this.establishConnectionTimer_ = setTimeout(() => {
  3650. this.establishConnectionTimer_ = null;
  3651. this.establishConnection_();
  3652. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3653. }, Math.floor(timeout));
  3654. }
  3655. initConnection_() {
  3656. if (!this.realtime_ && this.firstConnection_) {
  3657. this.scheduleConnect_(0);
  3658. }
  3659. }
  3660. onVisible_(visible) {
  3661. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3662. if (visible &&
  3663. !this.visible_ &&
  3664. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3665. this.log_('Window became visible. Reducing delay.');
  3666. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3667. if (!this.realtime_) {
  3668. this.scheduleConnect_(0);
  3669. }
  3670. }
  3671. this.visible_ = visible;
  3672. }
  3673. onOnline_(online) {
  3674. if (online) {
  3675. this.log_('Browser went online.');
  3676. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3677. if (!this.realtime_) {
  3678. this.scheduleConnect_(0);
  3679. }
  3680. }
  3681. else {
  3682. this.log_('Browser went offline. Killing connection.');
  3683. if (this.realtime_) {
  3684. this.realtime_.close();
  3685. }
  3686. }
  3687. }
  3688. onRealtimeDisconnect_() {
  3689. this.log_('data client disconnected');
  3690. this.connected_ = false;
  3691. this.realtime_ = null;
  3692. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3693. this.cancelSentTransactions_();
  3694. // Clear out the pending requests.
  3695. this.requestCBHash_ = {};
  3696. if (this.shouldReconnect_()) {
  3697. if (!this.visible_) {
  3698. this.log_("Window isn't visible. Delaying reconnect.");
  3699. this.reconnectDelay_ = this.maxReconnectDelay_;
  3700. this.lastConnectionAttemptTime_ = new Date().getTime();
  3701. }
  3702. else if (this.lastConnectionEstablishedTime_) {
  3703. // If we've been connected long enough, reset reconnect delay to minimum.
  3704. const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3705. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3706. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3707. }
  3708. this.lastConnectionEstablishedTime_ = null;
  3709. }
  3710. const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3711. let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3712. reconnectDelay = Math.random() * reconnectDelay;
  3713. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3714. this.scheduleConnect_(reconnectDelay);
  3715. // Adjust reconnect delay for next time.
  3716. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3717. }
  3718. this.onConnectStatus_(false);
  3719. }
  3720. async establishConnection_() {
  3721. if (this.shouldReconnect_()) {
  3722. this.log_('Making a connection attempt');
  3723. this.lastConnectionAttemptTime_ = new Date().getTime();
  3724. this.lastConnectionEstablishedTime_ = null;
  3725. const onDataMessage = this.onDataMessage_.bind(this);
  3726. const onReady = this.onReady_.bind(this);
  3727. const onDisconnect = this.onRealtimeDisconnect_.bind(this);
  3728. const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3729. const lastSessionId = this.lastSessionId;
  3730. let canceled = false;
  3731. let connection = null;
  3732. const closeFn = function () {
  3733. if (connection) {
  3734. connection.close();
  3735. }
  3736. else {
  3737. canceled = true;
  3738. onDisconnect();
  3739. }
  3740. };
  3741. const sendRequestFn = function (msg) {
  3742. assert(connection, "sendRequest call when we're not connected not allowed.");
  3743. connection.sendRequest(msg);
  3744. };
  3745. this.realtime_ = {
  3746. close: closeFn,
  3747. sendRequest: sendRequestFn
  3748. };
  3749. const forceRefresh = this.forceTokenRefresh_;
  3750. this.forceTokenRefresh_ = false;
  3751. try {
  3752. // First fetch auth and app check token, and establish connection after
  3753. // fetching the token was successful
  3754. const [authToken, appCheckToken] = await Promise.all([
  3755. this.authTokenProvider_.getToken(forceRefresh),
  3756. this.appCheckTokenProvider_.getToken(forceRefresh)
  3757. ]);
  3758. if (!canceled) {
  3759. log('getToken() completed. Creating connection.');
  3760. this.authToken_ = authToken && authToken.accessToken;
  3761. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3762. connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
  3763. /* onKill= */ reason => {
  3764. warn(reason + ' (' + this.repoInfo_.toString() + ')');
  3765. this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3766. }, lastSessionId);
  3767. }
  3768. else {
  3769. log('getToken() completed but was canceled');
  3770. }
  3771. }
  3772. catch (error) {
  3773. this.log_('Failed to get token: ' + error);
  3774. if (!canceled) {
  3775. if (this.repoInfo_.nodeAdmin) {
  3776. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3777. // But getToken() may also just have temporarily failed, so we still want to
  3778. // continue retrying.
  3779. warn(error);
  3780. }
  3781. closeFn();
  3782. }
  3783. }
  3784. }
  3785. }
  3786. interrupt(reason) {
  3787. log('Interrupting connection for reason: ' + reason);
  3788. this.interruptReasons_[reason] = true;
  3789. if (this.realtime_) {
  3790. this.realtime_.close();
  3791. }
  3792. else {
  3793. if (this.establishConnectionTimer_) {
  3794. clearTimeout(this.establishConnectionTimer_);
  3795. this.establishConnectionTimer_ = null;
  3796. }
  3797. if (this.connected_) {
  3798. this.onRealtimeDisconnect_();
  3799. }
  3800. }
  3801. }
  3802. resume(reason) {
  3803. log('Resuming connection for reason: ' + reason);
  3804. delete this.interruptReasons_[reason];
  3805. if (isEmpty(this.interruptReasons_)) {
  3806. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3807. if (!this.realtime_) {
  3808. this.scheduleConnect_(0);
  3809. }
  3810. }
  3811. }
  3812. handleTimestamp_(timestamp) {
  3813. const delta = timestamp - new Date().getTime();
  3814. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3815. }
  3816. cancelSentTransactions_() {
  3817. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3818. const put = this.outstandingPuts_[i];
  3819. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3820. if (put.onComplete) {
  3821. put.onComplete('disconnect');
  3822. }
  3823. delete this.outstandingPuts_[i];
  3824. this.outstandingPutCount_--;
  3825. }
  3826. }
  3827. // Clean up array occasionally.
  3828. if (this.outstandingPutCount_ === 0) {
  3829. this.outstandingPuts_ = [];
  3830. }
  3831. }
  3832. onListenRevoked_(pathString, query) {
  3833. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3834. let queryId;
  3835. if (!query) {
  3836. queryId = 'default';
  3837. }
  3838. else {
  3839. queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
  3840. }
  3841. const listen = this.removeListen_(pathString, queryId);
  3842. if (listen && listen.onComplete) {
  3843. listen.onComplete('permission_denied');
  3844. }
  3845. }
  3846. removeListen_(pathString, queryId) {
  3847. const normalizedPathString = new Path(pathString).toString(); // normalize path.
  3848. let listen;
  3849. if (this.listens.has(normalizedPathString)) {
  3850. const map = this.listens.get(normalizedPathString);
  3851. listen = map.get(queryId);
  3852. map.delete(queryId);
  3853. if (map.size === 0) {
  3854. this.listens.delete(normalizedPathString);
  3855. }
  3856. }
  3857. else {
  3858. // all listens for this path has already been removed
  3859. listen = undefined;
  3860. }
  3861. return listen;
  3862. }
  3863. onAuthRevoked_(statusCode, explanation) {
  3864. log('Auth token revoked: ' + statusCode + '/' + explanation);
  3865. this.authToken_ = null;
  3866. this.forceTokenRefresh_ = true;
  3867. this.realtime_.close();
  3868. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3869. // We'll wait a couple times before logging the warning / increasing the
  3870. // retry period since oauth tokens will report as "invalid" if they're
  3871. // just expired. Plus there may be transient issues that resolve themselves.
  3872. this.invalidAuthTokenCount_++;
  3873. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3874. // Set a long reconnect delay because recovery is unlikely
  3875. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3876. // Notify the auth token provider that the token is invalid, which will log
  3877. // a warning
  3878. this.authTokenProvider_.notifyForInvalidToken();
  3879. }
  3880. }
  3881. }
  3882. onAppCheckRevoked_(statusCode, explanation) {
  3883. log('App check token revoked: ' + statusCode + '/' + explanation);
  3884. this.appCheckToken_ = null;
  3885. this.forceTokenRefresh_ = true;
  3886. // Note: We don't close the connection as the developer may not have
  3887. // enforcement enabled. The backend closes connections with enforcements.
  3888. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  3889. // We'll wait a couple times before logging the warning / increasing the
  3890. // retry period since oauth tokens will report as "invalid" if they're
  3891. // just expired. Plus there may be transient issues that resolve themselves.
  3892. this.invalidAppCheckTokenCount_++;
  3893. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  3894. this.appCheckTokenProvider_.notifyForInvalidToken();
  3895. }
  3896. }
  3897. }
  3898. onSecurityDebugPacket_(body) {
  3899. if (this.securityDebugCallback_) {
  3900. this.securityDebugCallback_(body);
  3901. }
  3902. else {
  3903. if ('msg' in body) {
  3904. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  3905. }
  3906. }
  3907. }
  3908. restoreState_() {
  3909. //Re-authenticate ourselves if we have a credential stored.
  3910. this.tryAuth();
  3911. this.tryAppCheck();
  3912. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  3913. // make sure to send listens before puts.
  3914. for (const queries of this.listens.values()) {
  3915. for (const listenSpec of queries.values()) {
  3916. this.sendListen_(listenSpec);
  3917. }
  3918. }
  3919. for (let i = 0; i < this.outstandingPuts_.length; i++) {
  3920. if (this.outstandingPuts_[i]) {
  3921. this.sendPut_(i);
  3922. }
  3923. }
  3924. while (this.onDisconnectRequestQueue_.length) {
  3925. const request = this.onDisconnectRequestQueue_.shift();
  3926. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  3927. }
  3928. for (let i = 0; i < this.outstandingGets_.length; i++) {
  3929. if (this.outstandingGets_[i]) {
  3930. this.sendGet_(i);
  3931. }
  3932. }
  3933. }
  3934. /**
  3935. * Sends client stats for first connection
  3936. */
  3937. sendConnectStats_() {
  3938. const stats = {};
  3939. let clientName = 'js';
  3940. if (isNodeSdk()) {
  3941. if (this.repoInfo_.nodeAdmin) {
  3942. clientName = 'admin_node';
  3943. }
  3944. else {
  3945. clientName = 'node';
  3946. }
  3947. }
  3948. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  3949. if (isMobileCordova()) {
  3950. stats['framework.cordova'] = 1;
  3951. }
  3952. else if (isReactNative()) {
  3953. stats['framework.reactnative'] = 1;
  3954. }
  3955. this.reportStats(stats);
  3956. }
  3957. shouldReconnect_() {
  3958. const online = OnlineMonitor.getInstance().currentlyOnline();
  3959. return isEmpty(this.interruptReasons_) && online;
  3960. }
  3961. }
  3962. PersistentConnection.nextPersistentConnectionId_ = 0;
  3963. /**
  3964. * Counter for number of connections created. Mainly used for tagging in the logs
  3965. */
  3966. PersistentConnection.nextConnectionId_ = 0;
  3967. /**
  3968. * @license
  3969. * Copyright 2017 Google LLC
  3970. *
  3971. * Licensed under the Apache License, Version 2.0 (the "License");
  3972. * you may not use this file except in compliance with the License.
  3973. * You may obtain a copy of the License at
  3974. *
  3975. * http://www.apache.org/licenses/LICENSE-2.0
  3976. *
  3977. * Unless required by applicable law or agreed to in writing, software
  3978. * distributed under the License is distributed on an "AS IS" BASIS,
  3979. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3980. * See the License for the specific language governing permissions and
  3981. * limitations under the License.
  3982. */
  3983. class NamedNode {
  3984. constructor(name, node) {
  3985. this.name = name;
  3986. this.node = node;
  3987. }
  3988. static Wrap(name, node) {
  3989. return new NamedNode(name, node);
  3990. }
  3991. }
  3992. /**
  3993. * @license
  3994. * Copyright 2017 Google LLC
  3995. *
  3996. * Licensed under the Apache License, Version 2.0 (the "License");
  3997. * you may not use this file except in compliance with the License.
  3998. * You may obtain a copy of the License at
  3999. *
  4000. * http://www.apache.org/licenses/LICENSE-2.0
  4001. *
  4002. * Unless required by applicable law or agreed to in writing, software
  4003. * distributed under the License is distributed on an "AS IS" BASIS,
  4004. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4005. * See the License for the specific language governing permissions and
  4006. * limitations under the License.
  4007. */
  4008. class Index {
  4009. /**
  4010. * @returns A standalone comparison function for
  4011. * this index
  4012. */
  4013. getCompare() {
  4014. return this.compare.bind(this);
  4015. }
  4016. /**
  4017. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4018. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4019. *
  4020. *
  4021. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4022. */
  4023. indexedValueChanged(oldNode, newNode) {
  4024. const oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4025. const newWrapped = new NamedNode(MIN_NAME, newNode);
  4026. return this.compare(oldWrapped, newWrapped) !== 0;
  4027. }
  4028. /**
  4029. * @returns a node wrapper that will sort equal to or less than
  4030. * any other node wrapper, using this index
  4031. */
  4032. minPost() {
  4033. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4034. return NamedNode.MIN;
  4035. }
  4036. }
  4037. /**
  4038. * @license
  4039. * Copyright 2017 Google LLC
  4040. *
  4041. * Licensed under the Apache License, Version 2.0 (the "License");
  4042. * you may not use this file except in compliance with the License.
  4043. * You may obtain a copy of the License at
  4044. *
  4045. * http://www.apache.org/licenses/LICENSE-2.0
  4046. *
  4047. * Unless required by applicable law or agreed to in writing, software
  4048. * distributed under the License is distributed on an "AS IS" BASIS,
  4049. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4050. * See the License for the specific language governing permissions and
  4051. * limitations under the License.
  4052. */
  4053. let __EMPTY_NODE;
  4054. class KeyIndex extends Index {
  4055. static get __EMPTY_NODE() {
  4056. return __EMPTY_NODE;
  4057. }
  4058. static set __EMPTY_NODE(val) {
  4059. __EMPTY_NODE = val;
  4060. }
  4061. compare(a, b) {
  4062. return nameCompare(a.name, b.name);
  4063. }
  4064. isDefinedOn(node) {
  4065. // We could probably return true here (since every node has a key), but it's never called
  4066. // so just leaving unimplemented for now.
  4067. throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4068. }
  4069. indexedValueChanged(oldNode, newNode) {
  4070. return false; // The key for a node never changes.
  4071. }
  4072. minPost() {
  4073. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4074. return NamedNode.MIN;
  4075. }
  4076. maxPost() {
  4077. // TODO: This should really be created once and cached in a static property, but
  4078. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4079. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4080. }
  4081. makePost(indexValue, name) {
  4082. assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4083. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4084. return new NamedNode(indexValue, __EMPTY_NODE);
  4085. }
  4086. /**
  4087. * @returns String representation for inclusion in a query spec
  4088. */
  4089. toString() {
  4090. return '.key';
  4091. }
  4092. }
  4093. const KEY_INDEX = new KeyIndex();
  4094. /**
  4095. * @license
  4096. * Copyright 2017 Google LLC
  4097. *
  4098. * Licensed under the Apache License, Version 2.0 (the "License");
  4099. * you may not use this file except in compliance with the License.
  4100. * You may obtain a copy of the License at
  4101. *
  4102. * http://www.apache.org/licenses/LICENSE-2.0
  4103. *
  4104. * Unless required by applicable law or agreed to in writing, software
  4105. * distributed under the License is distributed on an "AS IS" BASIS,
  4106. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4107. * See the License for the specific language governing permissions and
  4108. * limitations under the License.
  4109. */
  4110. /**
  4111. * An iterator over an LLRBNode.
  4112. */
  4113. class SortedMapIterator {
  4114. /**
  4115. * @param node - Node to iterate.
  4116. * @param isReverse_ - Whether or not to iterate in reverse
  4117. */
  4118. constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
  4119. this.isReverse_ = isReverse_;
  4120. this.resultGenerator_ = resultGenerator_;
  4121. this.nodeStack_ = [];
  4122. let cmp = 1;
  4123. while (!node.isEmpty()) {
  4124. node = node;
  4125. cmp = startKey ? comparator(node.key, startKey) : 1;
  4126. // flip the comparison if we're going in reverse
  4127. if (isReverse_) {
  4128. cmp *= -1;
  4129. }
  4130. if (cmp < 0) {
  4131. // This node is less than our start key. ignore it
  4132. if (this.isReverse_) {
  4133. node = node.left;
  4134. }
  4135. else {
  4136. node = node.right;
  4137. }
  4138. }
  4139. else if (cmp === 0) {
  4140. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4141. this.nodeStack_.push(node);
  4142. break;
  4143. }
  4144. else {
  4145. // This node is greater than our start key, add it to the stack and move to the next one
  4146. this.nodeStack_.push(node);
  4147. if (this.isReverse_) {
  4148. node = node.right;
  4149. }
  4150. else {
  4151. node = node.left;
  4152. }
  4153. }
  4154. }
  4155. }
  4156. getNext() {
  4157. if (this.nodeStack_.length === 0) {
  4158. return null;
  4159. }
  4160. let node = this.nodeStack_.pop();
  4161. let result;
  4162. if (this.resultGenerator_) {
  4163. result = this.resultGenerator_(node.key, node.value);
  4164. }
  4165. else {
  4166. result = { key: node.key, value: node.value };
  4167. }
  4168. if (this.isReverse_) {
  4169. node = node.left;
  4170. while (!node.isEmpty()) {
  4171. this.nodeStack_.push(node);
  4172. node = node.right;
  4173. }
  4174. }
  4175. else {
  4176. node = node.right;
  4177. while (!node.isEmpty()) {
  4178. this.nodeStack_.push(node);
  4179. node = node.left;
  4180. }
  4181. }
  4182. return result;
  4183. }
  4184. hasNext() {
  4185. return this.nodeStack_.length > 0;
  4186. }
  4187. peek() {
  4188. if (this.nodeStack_.length === 0) {
  4189. return null;
  4190. }
  4191. const node = this.nodeStack_[this.nodeStack_.length - 1];
  4192. if (this.resultGenerator_) {
  4193. return this.resultGenerator_(node.key, node.value);
  4194. }
  4195. else {
  4196. return { key: node.key, value: node.value };
  4197. }
  4198. }
  4199. }
  4200. /**
  4201. * Represents a node in a Left-leaning Red-Black tree.
  4202. */
  4203. class LLRBNode {
  4204. /**
  4205. * @param key - Key associated with this node.
  4206. * @param value - Value associated with this node.
  4207. * @param color - Whether this node is red.
  4208. * @param left - Left child.
  4209. * @param right - Right child.
  4210. */
  4211. constructor(key, value, color, left, right) {
  4212. this.key = key;
  4213. this.value = value;
  4214. this.color = color != null ? color : LLRBNode.RED;
  4215. this.left =
  4216. left != null ? left : SortedMap.EMPTY_NODE;
  4217. this.right =
  4218. right != null ? right : SortedMap.EMPTY_NODE;
  4219. }
  4220. /**
  4221. * Returns a copy of the current node, optionally replacing pieces of it.
  4222. *
  4223. * @param key - New key for the node, or null.
  4224. * @param value - New value for the node, or null.
  4225. * @param color - New color for the node, or null.
  4226. * @param left - New left child for the node, or null.
  4227. * @param right - New right child for the node, or null.
  4228. * @returns The node copy.
  4229. */
  4230. copy(key, value, color, left, right) {
  4231. 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);
  4232. }
  4233. /**
  4234. * @returns The total number of nodes in the tree.
  4235. */
  4236. count() {
  4237. return this.left.count() + 1 + this.right.count();
  4238. }
  4239. /**
  4240. * @returns True if the tree is empty.
  4241. */
  4242. isEmpty() {
  4243. return false;
  4244. }
  4245. /**
  4246. * Traverses the tree in key order and calls the specified action function
  4247. * for each node.
  4248. *
  4249. * @param action - Callback function to be called for each
  4250. * node. If it returns true, traversal is aborted.
  4251. * @returns The first truthy value returned by action, or the last falsey
  4252. * value returned by action
  4253. */
  4254. inorderTraversal(action) {
  4255. return (this.left.inorderTraversal(action) ||
  4256. !!action(this.key, this.value) ||
  4257. this.right.inorderTraversal(action));
  4258. }
  4259. /**
  4260. * Traverses the tree in reverse key order and calls the specified action function
  4261. * for each node.
  4262. *
  4263. * @param action - Callback function to be called for each
  4264. * node. If it returns true, traversal is aborted.
  4265. * @returns True if traversal was aborted.
  4266. */
  4267. reverseTraversal(action) {
  4268. return (this.right.reverseTraversal(action) ||
  4269. action(this.key, this.value) ||
  4270. this.left.reverseTraversal(action));
  4271. }
  4272. /**
  4273. * @returns The minimum node in the tree.
  4274. */
  4275. min_() {
  4276. if (this.left.isEmpty()) {
  4277. return this;
  4278. }
  4279. else {
  4280. return this.left.min_();
  4281. }
  4282. }
  4283. /**
  4284. * @returns The maximum key in the tree.
  4285. */
  4286. minKey() {
  4287. return this.min_().key;
  4288. }
  4289. /**
  4290. * @returns The maximum key in the tree.
  4291. */
  4292. maxKey() {
  4293. if (this.right.isEmpty()) {
  4294. return this.key;
  4295. }
  4296. else {
  4297. return this.right.maxKey();
  4298. }
  4299. }
  4300. /**
  4301. * @param key - Key to insert.
  4302. * @param value - Value to insert.
  4303. * @param comparator - Comparator.
  4304. * @returns New tree, with the key/value added.
  4305. */
  4306. insert(key, value, comparator) {
  4307. let n = this;
  4308. const cmp = comparator(key, n.key);
  4309. if (cmp < 0) {
  4310. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4311. }
  4312. else if (cmp === 0) {
  4313. n = n.copy(null, value, null, null, null);
  4314. }
  4315. else {
  4316. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4317. }
  4318. return n.fixUp_();
  4319. }
  4320. /**
  4321. * @returns New tree, with the minimum key removed.
  4322. */
  4323. removeMin_() {
  4324. if (this.left.isEmpty()) {
  4325. return SortedMap.EMPTY_NODE;
  4326. }
  4327. let n = this;
  4328. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4329. n = n.moveRedLeft_();
  4330. }
  4331. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4332. return n.fixUp_();
  4333. }
  4334. /**
  4335. * @param key - The key of the item to remove.
  4336. * @param comparator - Comparator.
  4337. * @returns New tree, with the specified item removed.
  4338. */
  4339. remove(key, comparator) {
  4340. let n, smallest;
  4341. n = this;
  4342. if (comparator(key, n.key) < 0) {
  4343. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4344. n = n.moveRedLeft_();
  4345. }
  4346. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4347. }
  4348. else {
  4349. if (n.left.isRed_()) {
  4350. n = n.rotateRight_();
  4351. }
  4352. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4353. n = n.moveRedRight_();
  4354. }
  4355. if (comparator(key, n.key) === 0) {
  4356. if (n.right.isEmpty()) {
  4357. return SortedMap.EMPTY_NODE;
  4358. }
  4359. else {
  4360. smallest = n.right.min_();
  4361. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4362. }
  4363. }
  4364. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4365. }
  4366. return n.fixUp_();
  4367. }
  4368. /**
  4369. * @returns Whether this is a RED node.
  4370. */
  4371. isRed_() {
  4372. return this.color;
  4373. }
  4374. /**
  4375. * @returns New tree after performing any needed rotations.
  4376. */
  4377. fixUp_() {
  4378. let n = this;
  4379. if (n.right.isRed_() && !n.left.isRed_()) {
  4380. n = n.rotateLeft_();
  4381. }
  4382. if (n.left.isRed_() && n.left.left.isRed_()) {
  4383. n = n.rotateRight_();
  4384. }
  4385. if (n.left.isRed_() && n.right.isRed_()) {
  4386. n = n.colorFlip_();
  4387. }
  4388. return n;
  4389. }
  4390. /**
  4391. * @returns New tree, after moveRedLeft.
  4392. */
  4393. moveRedLeft_() {
  4394. let n = this.colorFlip_();
  4395. if (n.right.left.isRed_()) {
  4396. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4397. n = n.rotateLeft_();
  4398. n = n.colorFlip_();
  4399. }
  4400. return n;
  4401. }
  4402. /**
  4403. * @returns New tree, after moveRedRight.
  4404. */
  4405. moveRedRight_() {
  4406. let n = this.colorFlip_();
  4407. if (n.left.left.isRed_()) {
  4408. n = n.rotateRight_();
  4409. n = n.colorFlip_();
  4410. }
  4411. return n;
  4412. }
  4413. /**
  4414. * @returns New tree, after rotateLeft.
  4415. */
  4416. rotateLeft_() {
  4417. const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4418. return this.right.copy(null, null, this.color, nl, null);
  4419. }
  4420. /**
  4421. * @returns New tree, after rotateRight.
  4422. */
  4423. rotateRight_() {
  4424. const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4425. return this.left.copy(null, null, this.color, null, nr);
  4426. }
  4427. /**
  4428. * @returns Newt ree, after colorFlip.
  4429. */
  4430. colorFlip_() {
  4431. const left = this.left.copy(null, null, !this.left.color, null, null);
  4432. const right = this.right.copy(null, null, !this.right.color, null, null);
  4433. return this.copy(null, null, !this.color, left, right);
  4434. }
  4435. /**
  4436. * For testing.
  4437. *
  4438. * @returns True if all is well.
  4439. */
  4440. checkMaxDepth_() {
  4441. const blackDepth = this.check_();
  4442. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4443. }
  4444. check_() {
  4445. if (this.isRed_() && this.left.isRed_()) {
  4446. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4447. }
  4448. if (this.right.isRed_()) {
  4449. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4450. }
  4451. const blackDepth = this.left.check_();
  4452. if (blackDepth !== this.right.check_()) {
  4453. throw new Error('Black depths differ');
  4454. }
  4455. else {
  4456. return blackDepth + (this.isRed_() ? 0 : 1);
  4457. }
  4458. }
  4459. }
  4460. LLRBNode.RED = true;
  4461. LLRBNode.BLACK = false;
  4462. /**
  4463. * Represents an empty node (a leaf node in the Red-Black Tree).
  4464. */
  4465. class LLRBEmptyNode {
  4466. /**
  4467. * Returns a copy of the current node.
  4468. *
  4469. * @returns The node copy.
  4470. */
  4471. copy(key, value, color, left, right) {
  4472. return this;
  4473. }
  4474. /**
  4475. * Returns a copy of the tree, with the specified key/value added.
  4476. *
  4477. * @param key - Key to be added.
  4478. * @param value - Value to be added.
  4479. * @param comparator - Comparator.
  4480. * @returns New tree, with item added.
  4481. */
  4482. insert(key, value, comparator) {
  4483. return new LLRBNode(key, value, null);
  4484. }
  4485. /**
  4486. * Returns a copy of the tree, with the specified key removed.
  4487. *
  4488. * @param key - The key to remove.
  4489. * @param comparator - Comparator.
  4490. * @returns New tree, with item removed.
  4491. */
  4492. remove(key, comparator) {
  4493. return this;
  4494. }
  4495. /**
  4496. * @returns The total number of nodes in the tree.
  4497. */
  4498. count() {
  4499. return 0;
  4500. }
  4501. /**
  4502. * @returns True if the tree is empty.
  4503. */
  4504. isEmpty() {
  4505. return true;
  4506. }
  4507. /**
  4508. * Traverses the tree in key order and calls the specified action function
  4509. * for each node.
  4510. *
  4511. * @param action - Callback function to be called for each
  4512. * node. If it returns true, traversal is aborted.
  4513. * @returns True if traversal was aborted.
  4514. */
  4515. inorderTraversal(action) {
  4516. return false;
  4517. }
  4518. /**
  4519. * Traverses the tree in reverse key order and calls the specified action function
  4520. * for each node.
  4521. *
  4522. * @param action - Callback function to be called for each
  4523. * node. If it returns true, traversal is aborted.
  4524. * @returns True if traversal was aborted.
  4525. */
  4526. reverseTraversal(action) {
  4527. return false;
  4528. }
  4529. minKey() {
  4530. return null;
  4531. }
  4532. maxKey() {
  4533. return null;
  4534. }
  4535. check_() {
  4536. return 0;
  4537. }
  4538. /**
  4539. * @returns Whether this node is red.
  4540. */
  4541. isRed_() {
  4542. return false;
  4543. }
  4544. }
  4545. /**
  4546. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4547. * tree.
  4548. */
  4549. class SortedMap {
  4550. /**
  4551. * @param comparator_ - Key comparator.
  4552. * @param root_ - Optional root node for the map.
  4553. */
  4554. constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
  4555. this.comparator_ = comparator_;
  4556. this.root_ = root_;
  4557. }
  4558. /**
  4559. * Returns a copy of the map, with the specified key/value added or replaced.
  4560. * (TODO: We should perhaps rename this method to 'put')
  4561. *
  4562. * @param key - Key to be added.
  4563. * @param value - Value to be added.
  4564. * @returns New map, with item added.
  4565. */
  4566. insert(key, value) {
  4567. return new SortedMap(this.comparator_, this.root_
  4568. .insert(key, value, this.comparator_)
  4569. .copy(null, null, LLRBNode.BLACK, null, null));
  4570. }
  4571. /**
  4572. * Returns a copy of the map, with the specified key removed.
  4573. *
  4574. * @param key - The key to remove.
  4575. * @returns New map, with item removed.
  4576. */
  4577. remove(key) {
  4578. return new SortedMap(this.comparator_, this.root_
  4579. .remove(key, this.comparator_)
  4580. .copy(null, null, LLRBNode.BLACK, null, null));
  4581. }
  4582. /**
  4583. * Returns the value of the node with the given key, or null.
  4584. *
  4585. * @param key - The key to look up.
  4586. * @returns The value of the node with the given key, or null if the
  4587. * key doesn't exist.
  4588. */
  4589. get(key) {
  4590. let cmp;
  4591. let node = this.root_;
  4592. while (!node.isEmpty()) {
  4593. cmp = this.comparator_(key, node.key);
  4594. if (cmp === 0) {
  4595. return node.value;
  4596. }
  4597. else if (cmp < 0) {
  4598. node = node.left;
  4599. }
  4600. else if (cmp > 0) {
  4601. node = node.right;
  4602. }
  4603. }
  4604. return null;
  4605. }
  4606. /**
  4607. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4608. * @param key - The key to find the predecessor of
  4609. * @returns The predecessor key.
  4610. */
  4611. getPredecessorKey(key) {
  4612. let cmp, node = this.root_, rightParent = null;
  4613. while (!node.isEmpty()) {
  4614. cmp = this.comparator_(key, node.key);
  4615. if (cmp === 0) {
  4616. if (!node.left.isEmpty()) {
  4617. node = node.left;
  4618. while (!node.right.isEmpty()) {
  4619. node = node.right;
  4620. }
  4621. return node.key;
  4622. }
  4623. else if (rightParent) {
  4624. return rightParent.key;
  4625. }
  4626. else {
  4627. return null; // first item.
  4628. }
  4629. }
  4630. else if (cmp < 0) {
  4631. node = node.left;
  4632. }
  4633. else if (cmp > 0) {
  4634. rightParent = node;
  4635. node = node.right;
  4636. }
  4637. }
  4638. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4639. }
  4640. /**
  4641. * @returns True if the map is empty.
  4642. */
  4643. isEmpty() {
  4644. return this.root_.isEmpty();
  4645. }
  4646. /**
  4647. * @returns The total number of nodes in the map.
  4648. */
  4649. count() {
  4650. return this.root_.count();
  4651. }
  4652. /**
  4653. * @returns The minimum key in the map.
  4654. */
  4655. minKey() {
  4656. return this.root_.minKey();
  4657. }
  4658. /**
  4659. * @returns The maximum key in the map.
  4660. */
  4661. maxKey() {
  4662. return this.root_.maxKey();
  4663. }
  4664. /**
  4665. * Traverses the map in key order and calls the specified action function
  4666. * for each key/value pair.
  4667. *
  4668. * @param action - Callback function to be called
  4669. * for each key/value pair. If action returns true, traversal is aborted.
  4670. * @returns The first truthy value returned by action, or the last falsey
  4671. * value returned by action
  4672. */
  4673. inorderTraversal(action) {
  4674. return this.root_.inorderTraversal(action);
  4675. }
  4676. /**
  4677. * Traverses the map in reverse key order and calls the specified action function
  4678. * for each key/value pair.
  4679. *
  4680. * @param action - Callback function to be called
  4681. * for each key/value pair. If action returns true, traversal is aborted.
  4682. * @returns True if the traversal was aborted.
  4683. */
  4684. reverseTraversal(action) {
  4685. return this.root_.reverseTraversal(action);
  4686. }
  4687. /**
  4688. * Returns an iterator over the SortedMap.
  4689. * @returns The iterator.
  4690. */
  4691. getIterator(resultGenerator) {
  4692. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4693. }
  4694. getIteratorFrom(key, resultGenerator) {
  4695. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4696. }
  4697. getReverseIteratorFrom(key, resultGenerator) {
  4698. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4699. }
  4700. getReverseIterator(resultGenerator) {
  4701. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4702. }
  4703. }
  4704. /**
  4705. * Always use the same empty node, to reduce memory.
  4706. */
  4707. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4708. /**
  4709. * @license
  4710. * Copyright 2017 Google LLC
  4711. *
  4712. * Licensed under the Apache License, Version 2.0 (the "License");
  4713. * you may not use this file except in compliance with the License.
  4714. * You may obtain a copy of the License at
  4715. *
  4716. * http://www.apache.org/licenses/LICENSE-2.0
  4717. *
  4718. * Unless required by applicable law or agreed to in writing, software
  4719. * distributed under the License is distributed on an "AS IS" BASIS,
  4720. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4721. * See the License for the specific language governing permissions and
  4722. * limitations under the License.
  4723. */
  4724. function NAME_ONLY_COMPARATOR(left, right) {
  4725. return nameCompare(left.name, right.name);
  4726. }
  4727. function NAME_COMPARATOR(left, right) {
  4728. return nameCompare(left, right);
  4729. }
  4730. /**
  4731. * @license
  4732. * Copyright 2017 Google LLC
  4733. *
  4734. * Licensed under the Apache License, Version 2.0 (the "License");
  4735. * you may not use this file except in compliance with the License.
  4736. * You may obtain a copy of the License at
  4737. *
  4738. * http://www.apache.org/licenses/LICENSE-2.0
  4739. *
  4740. * Unless required by applicable law or agreed to in writing, software
  4741. * distributed under the License is distributed on an "AS IS" BASIS,
  4742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4743. * See the License for the specific language governing permissions and
  4744. * limitations under the License.
  4745. */
  4746. let MAX_NODE$2;
  4747. function setMaxNode$1(val) {
  4748. MAX_NODE$2 = val;
  4749. }
  4750. const priorityHashText = function (priority) {
  4751. if (typeof priority === 'number') {
  4752. return 'number:' + doubleToIEEE754String(priority);
  4753. }
  4754. else {
  4755. return 'string:' + priority;
  4756. }
  4757. };
  4758. /**
  4759. * Validates that a priority snapshot Node is valid.
  4760. */
  4761. const validatePriorityNode = function (priorityNode) {
  4762. if (priorityNode.isLeafNode()) {
  4763. const val = priorityNode.val();
  4764. assert(typeof val === 'string' ||
  4765. typeof val === 'number' ||
  4766. (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
  4767. }
  4768. else {
  4769. assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4770. }
  4771. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4772. assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4773. };
  4774. /**
  4775. * @license
  4776. * Copyright 2017 Google LLC
  4777. *
  4778. * Licensed under the Apache License, Version 2.0 (the "License");
  4779. * you may not use this file except in compliance with the License.
  4780. * You may obtain a copy of the License at
  4781. *
  4782. * http://www.apache.org/licenses/LICENSE-2.0
  4783. *
  4784. * Unless required by applicable law or agreed to in writing, software
  4785. * distributed under the License is distributed on an "AS IS" BASIS,
  4786. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4787. * See the License for the specific language governing permissions and
  4788. * limitations under the License.
  4789. */
  4790. let __childrenNodeConstructor;
  4791. /**
  4792. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4793. * implements Node and stores the value of the node (a string,
  4794. * number, or boolean) accessible via getValue().
  4795. */
  4796. class LeafNode {
  4797. /**
  4798. * @param value_ - The value to store in this leaf node. The object type is
  4799. * possible in the event of a deferred value
  4800. * @param priorityNode_ - The priority of this node.
  4801. */
  4802. constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4803. this.value_ = value_;
  4804. this.priorityNode_ = priorityNode_;
  4805. this.lazyHash_ = null;
  4806. assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4807. validatePriorityNode(this.priorityNode_);
  4808. }
  4809. static set __childrenNodeConstructor(val) {
  4810. __childrenNodeConstructor = val;
  4811. }
  4812. static get __childrenNodeConstructor() {
  4813. return __childrenNodeConstructor;
  4814. }
  4815. /** @inheritDoc */
  4816. isLeafNode() {
  4817. return true;
  4818. }
  4819. /** @inheritDoc */
  4820. getPriority() {
  4821. return this.priorityNode_;
  4822. }
  4823. /** @inheritDoc */
  4824. updatePriority(newPriorityNode) {
  4825. return new LeafNode(this.value_, newPriorityNode);
  4826. }
  4827. /** @inheritDoc */
  4828. getImmediateChild(childName) {
  4829. // Hack to treat priority as a regular child
  4830. if (childName === '.priority') {
  4831. return this.priorityNode_;
  4832. }
  4833. else {
  4834. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4835. }
  4836. }
  4837. /** @inheritDoc */
  4838. getChild(path) {
  4839. if (pathIsEmpty(path)) {
  4840. return this;
  4841. }
  4842. else if (pathGetFront(path) === '.priority') {
  4843. return this.priorityNode_;
  4844. }
  4845. else {
  4846. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  4847. }
  4848. }
  4849. hasChild() {
  4850. return false;
  4851. }
  4852. /** @inheritDoc */
  4853. getPredecessorChildName(childName, childNode) {
  4854. return null;
  4855. }
  4856. /** @inheritDoc */
  4857. updateImmediateChild(childName, newChildNode) {
  4858. if (childName === '.priority') {
  4859. return this.updatePriority(newChildNode);
  4860. }
  4861. else if (newChildNode.isEmpty() && childName !== '.priority') {
  4862. return this;
  4863. }
  4864. else {
  4865. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  4866. }
  4867. }
  4868. /** @inheritDoc */
  4869. updateChild(path, newChildNode) {
  4870. const front = pathGetFront(path);
  4871. if (front === null) {
  4872. return newChildNode;
  4873. }
  4874. else if (newChildNode.isEmpty() && front !== '.priority') {
  4875. return this;
  4876. }
  4877. else {
  4878. assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  4879. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  4880. }
  4881. }
  4882. /** @inheritDoc */
  4883. isEmpty() {
  4884. return false;
  4885. }
  4886. /** @inheritDoc */
  4887. numChildren() {
  4888. return 0;
  4889. }
  4890. /** @inheritDoc */
  4891. forEachChild(index, action) {
  4892. return false;
  4893. }
  4894. val(exportFormat) {
  4895. if (exportFormat && !this.getPriority().isEmpty()) {
  4896. return {
  4897. '.value': this.getValue(),
  4898. '.priority': this.getPriority().val()
  4899. };
  4900. }
  4901. else {
  4902. return this.getValue();
  4903. }
  4904. }
  4905. /** @inheritDoc */
  4906. hash() {
  4907. if (this.lazyHash_ === null) {
  4908. let toHash = '';
  4909. if (!this.priorityNode_.isEmpty()) {
  4910. toHash +=
  4911. 'priority:' +
  4912. priorityHashText(this.priorityNode_.val()) +
  4913. ':';
  4914. }
  4915. const type = typeof this.value_;
  4916. toHash += type + ':';
  4917. if (type === 'number') {
  4918. toHash += doubleToIEEE754String(this.value_);
  4919. }
  4920. else {
  4921. toHash += this.value_;
  4922. }
  4923. this.lazyHash_ = sha1(toHash);
  4924. }
  4925. return this.lazyHash_;
  4926. }
  4927. /**
  4928. * Returns the value of the leaf node.
  4929. * @returns The value of the node.
  4930. */
  4931. getValue() {
  4932. return this.value_;
  4933. }
  4934. compareTo(other) {
  4935. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  4936. return 1;
  4937. }
  4938. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  4939. return -1;
  4940. }
  4941. else {
  4942. assert(other.isLeafNode(), 'Unknown node type');
  4943. return this.compareToLeafNode_(other);
  4944. }
  4945. }
  4946. /**
  4947. * Comparison specifically for two leaf nodes
  4948. */
  4949. compareToLeafNode_(otherLeaf) {
  4950. const otherLeafType = typeof otherLeaf.value_;
  4951. const thisLeafType = typeof this.value_;
  4952. const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  4953. const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  4954. assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  4955. assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  4956. if (otherIndex === thisIndex) {
  4957. // Same type, compare values
  4958. if (thisLeafType === 'object') {
  4959. // Deferred value nodes are all equal, but we should also never get to this point...
  4960. return 0;
  4961. }
  4962. else {
  4963. // Note that this works because true > false, all others are number or string comparisons
  4964. if (this.value_ < otherLeaf.value_) {
  4965. return -1;
  4966. }
  4967. else if (this.value_ === otherLeaf.value_) {
  4968. return 0;
  4969. }
  4970. else {
  4971. return 1;
  4972. }
  4973. }
  4974. }
  4975. else {
  4976. return thisIndex - otherIndex;
  4977. }
  4978. }
  4979. withIndex() {
  4980. return this;
  4981. }
  4982. isIndexed() {
  4983. return true;
  4984. }
  4985. equals(other) {
  4986. if (other === this) {
  4987. return true;
  4988. }
  4989. else if (other.isLeafNode()) {
  4990. const otherLeaf = other;
  4991. return (this.value_ === otherLeaf.value_ &&
  4992. this.priorityNode_.equals(otherLeaf.priorityNode_));
  4993. }
  4994. else {
  4995. return false;
  4996. }
  4997. }
  4998. }
  4999. /**
  5000. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5001. * the same type, the comparison falls back to their value
  5002. */
  5003. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5004. /**
  5005. * @license
  5006. * Copyright 2017 Google LLC
  5007. *
  5008. * Licensed under the Apache License, Version 2.0 (the "License");
  5009. * you may not use this file except in compliance with the License.
  5010. * You may obtain a copy of the License at
  5011. *
  5012. * http://www.apache.org/licenses/LICENSE-2.0
  5013. *
  5014. * Unless required by applicable law or agreed to in writing, software
  5015. * distributed under the License is distributed on an "AS IS" BASIS,
  5016. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5017. * See the License for the specific language governing permissions and
  5018. * limitations under the License.
  5019. */
  5020. let nodeFromJSON$1;
  5021. let MAX_NODE$1;
  5022. function setNodeFromJSON(val) {
  5023. nodeFromJSON$1 = val;
  5024. }
  5025. function setMaxNode(val) {
  5026. MAX_NODE$1 = val;
  5027. }
  5028. class PriorityIndex extends Index {
  5029. compare(a, b) {
  5030. const aPriority = a.node.getPriority();
  5031. const bPriority = b.node.getPriority();
  5032. const indexCmp = aPriority.compareTo(bPriority);
  5033. if (indexCmp === 0) {
  5034. return nameCompare(a.name, b.name);
  5035. }
  5036. else {
  5037. return indexCmp;
  5038. }
  5039. }
  5040. isDefinedOn(node) {
  5041. return !node.getPriority().isEmpty();
  5042. }
  5043. indexedValueChanged(oldNode, newNode) {
  5044. return !oldNode.getPriority().equals(newNode.getPriority());
  5045. }
  5046. minPost() {
  5047. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5048. return NamedNode.MIN;
  5049. }
  5050. maxPost() {
  5051. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5052. }
  5053. makePost(indexValue, name) {
  5054. const priorityNode = nodeFromJSON$1(indexValue);
  5055. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5056. }
  5057. /**
  5058. * @returns String representation for inclusion in a query spec
  5059. */
  5060. toString() {
  5061. return '.priority';
  5062. }
  5063. }
  5064. const PRIORITY_INDEX = new PriorityIndex();
  5065. /**
  5066. * @license
  5067. * Copyright 2017 Google LLC
  5068. *
  5069. * Licensed under the Apache License, Version 2.0 (the "License");
  5070. * you may not use this file except in compliance with the License.
  5071. * You may obtain a copy of the License at
  5072. *
  5073. * http://www.apache.org/licenses/LICENSE-2.0
  5074. *
  5075. * Unless required by applicable law or agreed to in writing, software
  5076. * distributed under the License is distributed on an "AS IS" BASIS,
  5077. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5078. * See the License for the specific language governing permissions and
  5079. * limitations under the License.
  5080. */
  5081. const LOG_2 = Math.log(2);
  5082. class Base12Num {
  5083. constructor(length) {
  5084. const logBase2 = (num) =>
  5085. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5086. parseInt((Math.log(num) / LOG_2), 10);
  5087. const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
  5088. this.count = logBase2(length + 1);
  5089. this.current_ = this.count - 1;
  5090. const mask = bitMask(this.count);
  5091. this.bits_ = (length + 1) & mask;
  5092. }
  5093. nextBitIsOne() {
  5094. //noinspection JSBitwiseOperatorUsage
  5095. const result = !(this.bits_ & (0x1 << this.current_));
  5096. this.current_--;
  5097. return result;
  5098. }
  5099. }
  5100. /**
  5101. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5102. * function
  5103. *
  5104. * Uses the algorithm described in the paper linked here:
  5105. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5106. *
  5107. * @param childList - Unsorted list of children
  5108. * @param cmp - The comparison method to be used
  5109. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5110. * type is not NamedNode
  5111. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5112. */
  5113. const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5114. childList.sort(cmp);
  5115. const buildBalancedTree = function (low, high) {
  5116. const length = high - low;
  5117. let namedNode;
  5118. let key;
  5119. if (length === 0) {
  5120. return null;
  5121. }
  5122. else if (length === 1) {
  5123. namedNode = childList[low];
  5124. key = keyFn ? keyFn(namedNode) : namedNode;
  5125. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5126. }
  5127. else {
  5128. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5129. const middle = parseInt((length / 2), 10) + low;
  5130. const left = buildBalancedTree(low, middle);
  5131. const right = buildBalancedTree(middle + 1, high);
  5132. namedNode = childList[middle];
  5133. key = keyFn ? keyFn(namedNode) : namedNode;
  5134. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5135. }
  5136. };
  5137. const buildFrom12Array = function (base12) {
  5138. let node = null;
  5139. let root = null;
  5140. let index = childList.length;
  5141. const buildPennant = function (chunkSize, color) {
  5142. const low = index - chunkSize;
  5143. const high = index;
  5144. index -= chunkSize;
  5145. const childTree = buildBalancedTree(low + 1, high);
  5146. const namedNode = childList[low];
  5147. const key = keyFn ? keyFn(namedNode) : namedNode;
  5148. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5149. };
  5150. const attachPennant = function (pennant) {
  5151. if (node) {
  5152. node.left = pennant;
  5153. node = pennant;
  5154. }
  5155. else {
  5156. root = pennant;
  5157. node = pennant;
  5158. }
  5159. };
  5160. for (let i = 0; i < base12.count; ++i) {
  5161. const isOne = base12.nextBitIsOne();
  5162. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5163. const chunkSize = Math.pow(2, base12.count - (i + 1));
  5164. if (isOne) {
  5165. buildPennant(chunkSize, LLRBNode.BLACK);
  5166. }
  5167. else {
  5168. // current == 2
  5169. buildPennant(chunkSize, LLRBNode.BLACK);
  5170. buildPennant(chunkSize, LLRBNode.RED);
  5171. }
  5172. }
  5173. return root;
  5174. };
  5175. const base12 = new Base12Num(childList.length);
  5176. const root = buildFrom12Array(base12);
  5177. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5178. return new SortedMap(mapSortFn || cmp, root);
  5179. };
  5180. /**
  5181. * @license
  5182. * Copyright 2017 Google LLC
  5183. *
  5184. * Licensed under the Apache License, Version 2.0 (the "License");
  5185. * you may not use this file except in compliance with the License.
  5186. * You may obtain a copy of the License at
  5187. *
  5188. * http://www.apache.org/licenses/LICENSE-2.0
  5189. *
  5190. * Unless required by applicable law or agreed to in writing, software
  5191. * distributed under the License is distributed on an "AS IS" BASIS,
  5192. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5193. * See the License for the specific language governing permissions and
  5194. * limitations under the License.
  5195. */
  5196. let _defaultIndexMap;
  5197. const fallbackObject = {};
  5198. class IndexMap {
  5199. constructor(indexes_, indexSet_) {
  5200. this.indexes_ = indexes_;
  5201. this.indexSet_ = indexSet_;
  5202. }
  5203. /**
  5204. * The default IndexMap for nodes without a priority
  5205. */
  5206. static get Default() {
  5207. assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5208. _defaultIndexMap =
  5209. _defaultIndexMap ||
  5210. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5211. return _defaultIndexMap;
  5212. }
  5213. get(indexKey) {
  5214. const sortedMap = safeGet(this.indexes_, indexKey);
  5215. if (!sortedMap) {
  5216. throw new Error('No index defined for ' + indexKey);
  5217. }
  5218. if (sortedMap instanceof SortedMap) {
  5219. return sortedMap;
  5220. }
  5221. else {
  5222. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5223. // regular child map
  5224. return null;
  5225. }
  5226. }
  5227. hasIndex(indexDefinition) {
  5228. return contains(this.indexSet_, indexDefinition.toString());
  5229. }
  5230. addIndex(indexDefinition, existingChildren) {
  5231. assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5232. const childList = [];
  5233. let sawIndexedValue = false;
  5234. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5235. let next = iter.getNext();
  5236. while (next) {
  5237. sawIndexedValue =
  5238. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5239. childList.push(next);
  5240. next = iter.getNext();
  5241. }
  5242. let newIndex;
  5243. if (sawIndexedValue) {
  5244. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5245. }
  5246. else {
  5247. newIndex = fallbackObject;
  5248. }
  5249. const indexName = indexDefinition.toString();
  5250. const newIndexSet = Object.assign({}, this.indexSet_);
  5251. newIndexSet[indexName] = indexDefinition;
  5252. const newIndexes = Object.assign({}, this.indexes_);
  5253. newIndexes[indexName] = newIndex;
  5254. return new IndexMap(newIndexes, newIndexSet);
  5255. }
  5256. /**
  5257. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5258. */
  5259. addToIndexes(namedNode, existingChildren) {
  5260. const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {
  5261. const index = safeGet(this.indexSet_, indexName);
  5262. assert(index, 'Missing index implementation for ' + indexName);
  5263. if (indexedChildren === fallbackObject) {
  5264. // Check to see if we need to index everything
  5265. if (index.isDefinedOn(namedNode.node)) {
  5266. // We need to build this index
  5267. const childList = [];
  5268. const iter = existingChildren.getIterator(NamedNode.Wrap);
  5269. let next = iter.getNext();
  5270. while (next) {
  5271. if (next.name !== namedNode.name) {
  5272. childList.push(next);
  5273. }
  5274. next = iter.getNext();
  5275. }
  5276. childList.push(namedNode);
  5277. return buildChildSet(childList, index.getCompare());
  5278. }
  5279. else {
  5280. // No change, this remains a fallback
  5281. return fallbackObject;
  5282. }
  5283. }
  5284. else {
  5285. const existingSnap = existingChildren.get(namedNode.name);
  5286. let newChildren = indexedChildren;
  5287. if (existingSnap) {
  5288. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5289. }
  5290. return newChildren.insert(namedNode, namedNode.node);
  5291. }
  5292. });
  5293. return new IndexMap(newIndexes, this.indexSet_);
  5294. }
  5295. /**
  5296. * Create a new IndexMap instance with the given value removed
  5297. */
  5298. removeFromIndexes(namedNode, existingChildren) {
  5299. const newIndexes = map(this.indexes_, (indexedChildren) => {
  5300. if (indexedChildren === fallbackObject) {
  5301. // This is the fallback. Just return it, nothing to do in this case
  5302. return indexedChildren;
  5303. }
  5304. else {
  5305. const existingSnap = existingChildren.get(namedNode.name);
  5306. if (existingSnap) {
  5307. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5308. }
  5309. else {
  5310. // No record of this child
  5311. return indexedChildren;
  5312. }
  5313. }
  5314. });
  5315. return new IndexMap(newIndexes, this.indexSet_);
  5316. }
  5317. }
  5318. /**
  5319. * @license
  5320. * Copyright 2017 Google LLC
  5321. *
  5322. * Licensed under the Apache License, Version 2.0 (the "License");
  5323. * you may not use this file except in compliance with the License.
  5324. * You may obtain a copy of the License at
  5325. *
  5326. * http://www.apache.org/licenses/LICENSE-2.0
  5327. *
  5328. * Unless required by applicable law or agreed to in writing, software
  5329. * distributed under the License is distributed on an "AS IS" BASIS,
  5330. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5331. * See the License for the specific language governing permissions and
  5332. * limitations under the License.
  5333. */
  5334. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5335. let EMPTY_NODE;
  5336. /**
  5337. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5338. * (i.e. nodes with children). It implements Node and stores the
  5339. * list of children in the children property, sorted by child name.
  5340. */
  5341. class ChildrenNode {
  5342. /**
  5343. * @param children_ - List of children of this node..
  5344. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5345. */
  5346. constructor(children_, priorityNode_, indexMap_) {
  5347. this.children_ = children_;
  5348. this.priorityNode_ = priorityNode_;
  5349. this.indexMap_ = indexMap_;
  5350. this.lazyHash_ = null;
  5351. /**
  5352. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5353. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5354. * class instead of an empty ChildrenNode.
  5355. */
  5356. if (this.priorityNode_) {
  5357. validatePriorityNode(this.priorityNode_);
  5358. }
  5359. if (this.children_.isEmpty()) {
  5360. assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5361. }
  5362. }
  5363. static get EMPTY_NODE() {
  5364. return (EMPTY_NODE ||
  5365. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5366. }
  5367. /** @inheritDoc */
  5368. isLeafNode() {
  5369. return false;
  5370. }
  5371. /** @inheritDoc */
  5372. getPriority() {
  5373. return this.priorityNode_ || EMPTY_NODE;
  5374. }
  5375. /** @inheritDoc */
  5376. updatePriority(newPriorityNode) {
  5377. if (this.children_.isEmpty()) {
  5378. // Don't allow priorities on empty nodes
  5379. return this;
  5380. }
  5381. else {
  5382. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5383. }
  5384. }
  5385. /** @inheritDoc */
  5386. getImmediateChild(childName) {
  5387. // Hack to treat priority as a regular child
  5388. if (childName === '.priority') {
  5389. return this.getPriority();
  5390. }
  5391. else {
  5392. const child = this.children_.get(childName);
  5393. return child === null ? EMPTY_NODE : child;
  5394. }
  5395. }
  5396. /** @inheritDoc */
  5397. getChild(path) {
  5398. const front = pathGetFront(path);
  5399. if (front === null) {
  5400. return this;
  5401. }
  5402. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5403. }
  5404. /** @inheritDoc */
  5405. hasChild(childName) {
  5406. return this.children_.get(childName) !== null;
  5407. }
  5408. /** @inheritDoc */
  5409. updateImmediateChild(childName, newChildNode) {
  5410. assert(newChildNode, 'We should always be passing snapshot nodes');
  5411. if (childName === '.priority') {
  5412. return this.updatePriority(newChildNode);
  5413. }
  5414. else {
  5415. const namedNode = new NamedNode(childName, newChildNode);
  5416. let newChildren, newIndexMap;
  5417. if (newChildNode.isEmpty()) {
  5418. newChildren = this.children_.remove(childName);
  5419. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5420. }
  5421. else {
  5422. newChildren = this.children_.insert(childName, newChildNode);
  5423. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5424. }
  5425. const newPriority = newChildren.isEmpty()
  5426. ? EMPTY_NODE
  5427. : this.priorityNode_;
  5428. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5429. }
  5430. }
  5431. /** @inheritDoc */
  5432. updateChild(path, newChildNode) {
  5433. const front = pathGetFront(path);
  5434. if (front === null) {
  5435. return newChildNode;
  5436. }
  5437. else {
  5438. assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5439. const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5440. return this.updateImmediateChild(front, newImmediateChild);
  5441. }
  5442. }
  5443. /** @inheritDoc */
  5444. isEmpty() {
  5445. return this.children_.isEmpty();
  5446. }
  5447. /** @inheritDoc */
  5448. numChildren() {
  5449. return this.children_.count();
  5450. }
  5451. /** @inheritDoc */
  5452. val(exportFormat) {
  5453. if (this.isEmpty()) {
  5454. return null;
  5455. }
  5456. const obj = {};
  5457. let numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5458. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5459. obj[key] = childNode.val(exportFormat);
  5460. numKeys++;
  5461. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5462. maxKey = Math.max(maxKey, Number(key));
  5463. }
  5464. else {
  5465. allIntegerKeys = false;
  5466. }
  5467. });
  5468. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5469. // convert to array.
  5470. const array = [];
  5471. // eslint-disable-next-line guard-for-in
  5472. for (const key in obj) {
  5473. array[key] = obj[key];
  5474. }
  5475. return array;
  5476. }
  5477. else {
  5478. if (exportFormat && !this.getPriority().isEmpty()) {
  5479. obj['.priority'] = this.getPriority().val();
  5480. }
  5481. return obj;
  5482. }
  5483. }
  5484. /** @inheritDoc */
  5485. hash() {
  5486. if (this.lazyHash_ === null) {
  5487. let toHash = '';
  5488. if (!this.getPriority().isEmpty()) {
  5489. toHash +=
  5490. 'priority:' +
  5491. priorityHashText(this.getPriority().val()) +
  5492. ':';
  5493. }
  5494. this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  5495. const childHash = childNode.hash();
  5496. if (childHash !== '') {
  5497. toHash += ':' + key + ':' + childHash;
  5498. }
  5499. });
  5500. this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
  5501. }
  5502. return this.lazyHash_;
  5503. }
  5504. /** @inheritDoc */
  5505. getPredecessorChildName(childName, childNode, index) {
  5506. const idx = this.resolveIndex_(index);
  5507. if (idx) {
  5508. const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5509. return predecessor ? predecessor.name : null;
  5510. }
  5511. else {
  5512. return this.children_.getPredecessorKey(childName);
  5513. }
  5514. }
  5515. getFirstChildName(indexDefinition) {
  5516. const idx = this.resolveIndex_(indexDefinition);
  5517. if (idx) {
  5518. const minKey = idx.minKey();
  5519. return minKey && minKey.name;
  5520. }
  5521. else {
  5522. return this.children_.minKey();
  5523. }
  5524. }
  5525. getFirstChild(indexDefinition) {
  5526. const minKey = this.getFirstChildName(indexDefinition);
  5527. if (minKey) {
  5528. return new NamedNode(minKey, this.children_.get(minKey));
  5529. }
  5530. else {
  5531. return null;
  5532. }
  5533. }
  5534. /**
  5535. * Given an index, return the key name of the largest value we have, according to that index
  5536. */
  5537. getLastChildName(indexDefinition) {
  5538. const idx = this.resolveIndex_(indexDefinition);
  5539. if (idx) {
  5540. const maxKey = idx.maxKey();
  5541. return maxKey && maxKey.name;
  5542. }
  5543. else {
  5544. return this.children_.maxKey();
  5545. }
  5546. }
  5547. getLastChild(indexDefinition) {
  5548. const maxKey = this.getLastChildName(indexDefinition);
  5549. if (maxKey) {
  5550. return new NamedNode(maxKey, this.children_.get(maxKey));
  5551. }
  5552. else {
  5553. return null;
  5554. }
  5555. }
  5556. forEachChild(index, action) {
  5557. const idx = this.resolveIndex_(index);
  5558. if (idx) {
  5559. return idx.inorderTraversal(wrappedNode => {
  5560. return action(wrappedNode.name, wrappedNode.node);
  5561. });
  5562. }
  5563. else {
  5564. return this.children_.inorderTraversal(action);
  5565. }
  5566. }
  5567. getIterator(indexDefinition) {
  5568. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5569. }
  5570. getIteratorFrom(startPost, indexDefinition) {
  5571. const idx = this.resolveIndex_(indexDefinition);
  5572. if (idx) {
  5573. return idx.getIteratorFrom(startPost, key => key);
  5574. }
  5575. else {
  5576. const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5577. let next = iterator.peek();
  5578. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5579. iterator.getNext();
  5580. next = iterator.peek();
  5581. }
  5582. return iterator;
  5583. }
  5584. }
  5585. getReverseIterator(indexDefinition) {
  5586. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5587. }
  5588. getReverseIteratorFrom(endPost, indexDefinition) {
  5589. const idx = this.resolveIndex_(indexDefinition);
  5590. if (idx) {
  5591. return idx.getReverseIteratorFrom(endPost, key => {
  5592. return key;
  5593. });
  5594. }
  5595. else {
  5596. const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5597. let next = iterator.peek();
  5598. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5599. iterator.getNext();
  5600. next = iterator.peek();
  5601. }
  5602. return iterator;
  5603. }
  5604. }
  5605. compareTo(other) {
  5606. if (this.isEmpty()) {
  5607. if (other.isEmpty()) {
  5608. return 0;
  5609. }
  5610. else {
  5611. return -1;
  5612. }
  5613. }
  5614. else if (other.isLeafNode() || other.isEmpty()) {
  5615. return 1;
  5616. }
  5617. else if (other === MAX_NODE) {
  5618. return -1;
  5619. }
  5620. else {
  5621. // Must be another node with children.
  5622. return 0;
  5623. }
  5624. }
  5625. withIndex(indexDefinition) {
  5626. if (indexDefinition === KEY_INDEX ||
  5627. this.indexMap_.hasIndex(indexDefinition)) {
  5628. return this;
  5629. }
  5630. else {
  5631. const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5632. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5633. }
  5634. }
  5635. isIndexed(index) {
  5636. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5637. }
  5638. equals(other) {
  5639. if (other === this) {
  5640. return true;
  5641. }
  5642. else if (other.isLeafNode()) {
  5643. return false;
  5644. }
  5645. else {
  5646. const otherChildrenNode = other;
  5647. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5648. return false;
  5649. }
  5650. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5651. const thisIter = this.getIterator(PRIORITY_INDEX);
  5652. const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5653. let thisCurrent = thisIter.getNext();
  5654. let otherCurrent = otherIter.getNext();
  5655. while (thisCurrent && otherCurrent) {
  5656. if (thisCurrent.name !== otherCurrent.name ||
  5657. !thisCurrent.node.equals(otherCurrent.node)) {
  5658. return false;
  5659. }
  5660. thisCurrent = thisIter.getNext();
  5661. otherCurrent = otherIter.getNext();
  5662. }
  5663. return thisCurrent === null && otherCurrent === null;
  5664. }
  5665. else {
  5666. return false;
  5667. }
  5668. }
  5669. }
  5670. /**
  5671. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5672. * instead.
  5673. *
  5674. */
  5675. resolveIndex_(indexDefinition) {
  5676. if (indexDefinition === KEY_INDEX) {
  5677. return null;
  5678. }
  5679. else {
  5680. return this.indexMap_.get(indexDefinition.toString());
  5681. }
  5682. }
  5683. }
  5684. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5685. class MaxNode extends ChildrenNode {
  5686. constructor() {
  5687. super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
  5688. }
  5689. compareTo(other) {
  5690. if (other === this) {
  5691. return 0;
  5692. }
  5693. else {
  5694. return 1;
  5695. }
  5696. }
  5697. equals(other) {
  5698. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5699. return other === this;
  5700. }
  5701. getPriority() {
  5702. return this;
  5703. }
  5704. getImmediateChild(childName) {
  5705. return ChildrenNode.EMPTY_NODE;
  5706. }
  5707. isEmpty() {
  5708. return false;
  5709. }
  5710. }
  5711. /**
  5712. * Marker that will sort higher than any other snapshot.
  5713. */
  5714. const MAX_NODE = new MaxNode();
  5715. Object.defineProperties(NamedNode, {
  5716. MIN: {
  5717. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5718. },
  5719. MAX: {
  5720. value: new NamedNode(MAX_NAME, MAX_NODE)
  5721. }
  5722. });
  5723. /**
  5724. * Reference Extensions
  5725. */
  5726. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5727. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5728. setMaxNode$1(MAX_NODE);
  5729. setMaxNode(MAX_NODE);
  5730. /**
  5731. * @license
  5732. * Copyright 2017 Google LLC
  5733. *
  5734. * Licensed under the Apache License, Version 2.0 (the "License");
  5735. * you may not use this file except in compliance with the License.
  5736. * You may obtain a copy of the License at
  5737. *
  5738. * http://www.apache.org/licenses/LICENSE-2.0
  5739. *
  5740. * Unless required by applicable law or agreed to in writing, software
  5741. * distributed under the License is distributed on an "AS IS" BASIS,
  5742. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5743. * See the License for the specific language governing permissions and
  5744. * limitations under the License.
  5745. */
  5746. const USE_HINZE = true;
  5747. /**
  5748. * Constructs a snapshot node representing the passed JSON and returns it.
  5749. * @param json - JSON to create a node for.
  5750. * @param priority - Optional priority to use. This will be ignored if the
  5751. * passed JSON contains a .priority property.
  5752. */
  5753. function nodeFromJSON(json, priority = null) {
  5754. if (json === null) {
  5755. return ChildrenNode.EMPTY_NODE;
  5756. }
  5757. if (typeof json === 'object' && '.priority' in json) {
  5758. priority = json['.priority'];
  5759. }
  5760. assert(priority === null ||
  5761. typeof priority === 'string' ||
  5762. typeof priority === 'number' ||
  5763. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5764. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5765. json = json['.value'];
  5766. }
  5767. // Valid leaf nodes include non-objects or server-value wrapper objects
  5768. if (typeof json !== 'object' || '.sv' in json) {
  5769. const jsonLeaf = json;
  5770. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5771. }
  5772. if (!(json instanceof Array) && USE_HINZE) {
  5773. const children = [];
  5774. let childrenHavePriority = false;
  5775. const hinzeJsonObj = json;
  5776. each(hinzeJsonObj, (key, child) => {
  5777. if (key.substring(0, 1) !== '.') {
  5778. // Ignore metadata nodes
  5779. const childNode = nodeFromJSON(child);
  5780. if (!childNode.isEmpty()) {
  5781. childrenHavePriority =
  5782. childrenHavePriority || !childNode.getPriority().isEmpty();
  5783. children.push(new NamedNode(key, childNode));
  5784. }
  5785. }
  5786. });
  5787. if (children.length === 0) {
  5788. return ChildrenNode.EMPTY_NODE;
  5789. }
  5790. const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
  5791. if (childrenHavePriority) {
  5792. const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
  5793. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  5794. }
  5795. else {
  5796. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  5797. }
  5798. }
  5799. else {
  5800. let node = ChildrenNode.EMPTY_NODE;
  5801. each(json, (key, childData) => {
  5802. if (contains(json, key)) {
  5803. if (key.substring(0, 1) !== '.') {
  5804. // ignore metadata nodes.
  5805. const childNode = nodeFromJSON(childData);
  5806. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  5807. node = node.updateImmediateChild(key, childNode);
  5808. }
  5809. }
  5810. }
  5811. });
  5812. return node.updatePriority(nodeFromJSON(priority));
  5813. }
  5814. }
  5815. setNodeFromJSON(nodeFromJSON);
  5816. /**
  5817. * @license
  5818. * Copyright 2017 Google LLC
  5819. *
  5820. * Licensed under the Apache License, Version 2.0 (the "License");
  5821. * you may not use this file except in compliance with the License.
  5822. * You may obtain a copy of the License at
  5823. *
  5824. * http://www.apache.org/licenses/LICENSE-2.0
  5825. *
  5826. * Unless required by applicable law or agreed to in writing, software
  5827. * distributed under the License is distributed on an "AS IS" BASIS,
  5828. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5829. * See the License for the specific language governing permissions and
  5830. * limitations under the License.
  5831. */
  5832. class PathIndex extends Index {
  5833. constructor(indexPath_) {
  5834. super();
  5835. this.indexPath_ = indexPath_;
  5836. assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  5837. }
  5838. extractChild(snap) {
  5839. return snap.getChild(this.indexPath_);
  5840. }
  5841. isDefinedOn(node) {
  5842. return !node.getChild(this.indexPath_).isEmpty();
  5843. }
  5844. compare(a, b) {
  5845. const aChild = this.extractChild(a.node);
  5846. const bChild = this.extractChild(b.node);
  5847. const indexCmp = aChild.compareTo(bChild);
  5848. if (indexCmp === 0) {
  5849. return nameCompare(a.name, b.name);
  5850. }
  5851. else {
  5852. return indexCmp;
  5853. }
  5854. }
  5855. makePost(indexValue, name) {
  5856. const valueNode = nodeFromJSON(indexValue);
  5857. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  5858. return new NamedNode(name, node);
  5859. }
  5860. maxPost() {
  5861. const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  5862. return new NamedNode(MAX_NAME, node);
  5863. }
  5864. toString() {
  5865. return pathSlice(this.indexPath_, 0).join('/');
  5866. }
  5867. }
  5868. /**
  5869. * @license
  5870. * Copyright 2017 Google LLC
  5871. *
  5872. * Licensed under the Apache License, Version 2.0 (the "License");
  5873. * you may not use this file except in compliance with the License.
  5874. * You may obtain a copy of the License at
  5875. *
  5876. * http://www.apache.org/licenses/LICENSE-2.0
  5877. *
  5878. * Unless required by applicable law or agreed to in writing, software
  5879. * distributed under the License is distributed on an "AS IS" BASIS,
  5880. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5881. * See the License for the specific language governing permissions and
  5882. * limitations under the License.
  5883. */
  5884. class ValueIndex extends Index {
  5885. compare(a, b) {
  5886. const indexCmp = a.node.compareTo(b.node);
  5887. if (indexCmp === 0) {
  5888. return nameCompare(a.name, b.name);
  5889. }
  5890. else {
  5891. return indexCmp;
  5892. }
  5893. }
  5894. isDefinedOn(node) {
  5895. return true;
  5896. }
  5897. indexedValueChanged(oldNode, newNode) {
  5898. return !oldNode.equals(newNode);
  5899. }
  5900. minPost() {
  5901. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5902. return NamedNode.MIN;
  5903. }
  5904. maxPost() {
  5905. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5906. return NamedNode.MAX;
  5907. }
  5908. makePost(indexValue, name) {
  5909. const valueNode = nodeFromJSON(indexValue);
  5910. return new NamedNode(name, valueNode);
  5911. }
  5912. /**
  5913. * @returns String representation for inclusion in a query spec
  5914. */
  5915. toString() {
  5916. return '.value';
  5917. }
  5918. }
  5919. const VALUE_INDEX = new ValueIndex();
  5920. /**
  5921. * @license
  5922. * Copyright 2017 Google LLC
  5923. *
  5924. * Licensed under the Apache License, Version 2.0 (the "License");
  5925. * you may not use this file except in compliance with the License.
  5926. * You may obtain a copy of the License at
  5927. *
  5928. * http://www.apache.org/licenses/LICENSE-2.0
  5929. *
  5930. * Unless required by applicable law or agreed to in writing, software
  5931. * distributed under the License is distributed on an "AS IS" BASIS,
  5932. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5933. * See the License for the specific language governing permissions and
  5934. * limitations under the License.
  5935. */
  5936. function changeValue(snapshotNode) {
  5937. return { type: "value" /* ChangeType.VALUE */, snapshotNode };
  5938. }
  5939. function changeChildAdded(childName, snapshotNode) {
  5940. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };
  5941. }
  5942. function changeChildRemoved(childName, snapshotNode) {
  5943. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };
  5944. }
  5945. function changeChildChanged(childName, snapshotNode, oldSnap) {
  5946. return {
  5947. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  5948. snapshotNode,
  5949. childName,
  5950. oldSnap
  5951. };
  5952. }
  5953. function changeChildMoved(childName, snapshotNode) {
  5954. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };
  5955. }
  5956. /**
  5957. * @license
  5958. * Copyright 2017 Google LLC
  5959. *
  5960. * Licensed under the Apache License, Version 2.0 (the "License");
  5961. * you may not use this file except in compliance with the License.
  5962. * You may obtain a copy of the License at
  5963. *
  5964. * http://www.apache.org/licenses/LICENSE-2.0
  5965. *
  5966. * Unless required by applicable law or agreed to in writing, software
  5967. * distributed under the License is distributed on an "AS IS" BASIS,
  5968. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5969. * See the License for the specific language governing permissions and
  5970. * limitations under the License.
  5971. */
  5972. /**
  5973. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  5974. */
  5975. class IndexedFilter {
  5976. constructor(index_) {
  5977. this.index_ = index_;
  5978. }
  5979. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  5980. assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  5981. const oldChild = snap.getImmediateChild(key);
  5982. // Check if anything actually changed.
  5983. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  5984. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  5985. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  5986. // to avoid treating these cases as "nothing changed."
  5987. if (oldChild.isEmpty() === newChild.isEmpty()) {
  5988. // Nothing changed.
  5989. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  5990. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  5991. return snap;
  5992. }
  5993. }
  5994. if (optChangeAccumulator != null) {
  5995. if (newChild.isEmpty()) {
  5996. if (snap.hasChild(key)) {
  5997. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  5998. }
  5999. else {
  6000. assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6001. }
  6002. }
  6003. else if (oldChild.isEmpty()) {
  6004. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6005. }
  6006. else {
  6007. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6008. }
  6009. }
  6010. if (snap.isLeafNode() && newChild.isEmpty()) {
  6011. return snap;
  6012. }
  6013. else {
  6014. // Make sure the node is indexed
  6015. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6016. }
  6017. }
  6018. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6019. if (optChangeAccumulator != null) {
  6020. if (!oldSnap.isLeafNode()) {
  6021. oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6022. if (!newSnap.hasChild(key)) {
  6023. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6024. }
  6025. });
  6026. }
  6027. if (!newSnap.isLeafNode()) {
  6028. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6029. if (oldSnap.hasChild(key)) {
  6030. const oldChild = oldSnap.getImmediateChild(key);
  6031. if (!oldChild.equals(childNode)) {
  6032. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6033. }
  6034. }
  6035. else {
  6036. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6037. }
  6038. });
  6039. }
  6040. }
  6041. return newSnap.withIndex(this.index_);
  6042. }
  6043. updatePriority(oldSnap, newPriority) {
  6044. if (oldSnap.isEmpty()) {
  6045. return ChildrenNode.EMPTY_NODE;
  6046. }
  6047. else {
  6048. return oldSnap.updatePriority(newPriority);
  6049. }
  6050. }
  6051. filtersNodes() {
  6052. return false;
  6053. }
  6054. getIndexedFilter() {
  6055. return this;
  6056. }
  6057. getIndex() {
  6058. return this.index_;
  6059. }
  6060. }
  6061. /**
  6062. * @license
  6063. * Copyright 2017 Google LLC
  6064. *
  6065. * Licensed under the Apache License, Version 2.0 (the "License");
  6066. * you may not use this file except in compliance with the License.
  6067. * You may obtain a copy of the License at
  6068. *
  6069. * http://www.apache.org/licenses/LICENSE-2.0
  6070. *
  6071. * Unless required by applicable law or agreed to in writing, software
  6072. * distributed under the License is distributed on an "AS IS" BASIS,
  6073. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6074. * See the License for the specific language governing permissions and
  6075. * limitations under the License.
  6076. */
  6077. /**
  6078. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6079. */
  6080. class RangedFilter {
  6081. constructor(params) {
  6082. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6083. this.index_ = params.getIndex();
  6084. this.startPost_ = RangedFilter.getStartPost_(params);
  6085. this.endPost_ = RangedFilter.getEndPost_(params);
  6086. this.startIsInclusive_ = !params.startAfterSet_;
  6087. this.endIsInclusive_ = !params.endBeforeSet_;
  6088. }
  6089. getStartPost() {
  6090. return this.startPost_;
  6091. }
  6092. getEndPost() {
  6093. return this.endPost_;
  6094. }
  6095. matches(node) {
  6096. const isWithinStart = this.startIsInclusive_
  6097. ? this.index_.compare(this.getStartPost(), node) <= 0
  6098. : this.index_.compare(this.getStartPost(), node) < 0;
  6099. const isWithinEnd = this.endIsInclusive_
  6100. ? this.index_.compare(node, this.getEndPost()) <= 0
  6101. : this.index_.compare(node, this.getEndPost()) < 0;
  6102. return isWithinStart && isWithinEnd;
  6103. }
  6104. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6105. if (!this.matches(new NamedNode(key, newChild))) {
  6106. newChild = ChildrenNode.EMPTY_NODE;
  6107. }
  6108. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6109. }
  6110. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6111. if (newSnap.isLeafNode()) {
  6112. // Make sure we have a children node with the correct index, not a leaf node;
  6113. newSnap = ChildrenNode.EMPTY_NODE;
  6114. }
  6115. let filtered = newSnap.withIndex(this.index_);
  6116. // Don't support priorities on queries
  6117. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6118. const self = this;
  6119. newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  6120. if (!self.matches(new NamedNode(key, childNode))) {
  6121. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6122. }
  6123. });
  6124. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6125. }
  6126. updatePriority(oldSnap, newPriority) {
  6127. // Don't support priorities on queries
  6128. return oldSnap;
  6129. }
  6130. filtersNodes() {
  6131. return true;
  6132. }
  6133. getIndexedFilter() {
  6134. return this.indexedFilter_;
  6135. }
  6136. getIndex() {
  6137. return this.index_;
  6138. }
  6139. static getStartPost_(params) {
  6140. if (params.hasStart()) {
  6141. const startName = params.getIndexStartName();
  6142. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6143. }
  6144. else {
  6145. return params.getIndex().minPost();
  6146. }
  6147. }
  6148. static getEndPost_(params) {
  6149. if (params.hasEnd()) {
  6150. const endName = params.getIndexEndName();
  6151. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6152. }
  6153. else {
  6154. return params.getIndex().maxPost();
  6155. }
  6156. }
  6157. }
  6158. /**
  6159. * @license
  6160. * Copyright 2017 Google LLC
  6161. *
  6162. * Licensed under the Apache License, Version 2.0 (the "License");
  6163. * you may not use this file except in compliance with the License.
  6164. * You may obtain a copy of the License at
  6165. *
  6166. * http://www.apache.org/licenses/LICENSE-2.0
  6167. *
  6168. * Unless required by applicable law or agreed to in writing, software
  6169. * distributed under the License is distributed on an "AS IS" BASIS,
  6170. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6171. * See the License for the specific language governing permissions and
  6172. * limitations under the License.
  6173. */
  6174. /**
  6175. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6176. */
  6177. class LimitedFilter {
  6178. constructor(params) {
  6179. this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
  6180. this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
  6181. this.withinStartPost = (node) => {
  6182. const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
  6183. return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6184. };
  6185. this.withinEndPost = (node) => {
  6186. const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
  6187. return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6188. };
  6189. this.rangedFilter_ = new RangedFilter(params);
  6190. this.index_ = params.getIndex();
  6191. this.limit_ = params.getLimit();
  6192. this.reverse_ = !params.isViewFromLeft();
  6193. this.startIsInclusive_ = !params.startAfterSet_;
  6194. this.endIsInclusive_ = !params.endBeforeSet_;
  6195. }
  6196. updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6197. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6198. newChild = ChildrenNode.EMPTY_NODE;
  6199. }
  6200. if (snap.getImmediateChild(key).equals(newChild)) {
  6201. // No change
  6202. return snap;
  6203. }
  6204. else if (snap.numChildren() < this.limit_) {
  6205. return this.rangedFilter_
  6206. .getIndexedFilter()
  6207. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6208. }
  6209. else {
  6210. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6211. }
  6212. }
  6213. updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
  6214. let filtered;
  6215. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6216. // Make sure we have a children node with the correct index, not a leaf node;
  6217. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6218. }
  6219. else {
  6220. if (this.limit_ * 2 < newSnap.numChildren() &&
  6221. newSnap.isIndexed(this.index_)) {
  6222. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6223. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6224. // anchor to the startPost, endPost, or last element as appropriate
  6225. let iterator;
  6226. if (this.reverse_) {
  6227. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6228. }
  6229. else {
  6230. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6231. }
  6232. let count = 0;
  6233. while (iterator.hasNext() && count < this.limit_) {
  6234. const next = iterator.getNext();
  6235. if (!this.withinDirectionalStart(next)) {
  6236. // if we have not reached the start, skip to the next element
  6237. continue;
  6238. }
  6239. else if (!this.withinDirectionalEnd(next)) {
  6240. // if we have reached the end, stop adding elements
  6241. break;
  6242. }
  6243. else {
  6244. filtered = filtered.updateImmediateChild(next.name, next.node);
  6245. count++;
  6246. }
  6247. }
  6248. }
  6249. else {
  6250. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6251. filtered = newSnap.withIndex(this.index_);
  6252. // Don't support priorities on queries
  6253. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6254. let iterator;
  6255. if (this.reverse_) {
  6256. iterator = filtered.getReverseIterator(this.index_);
  6257. }
  6258. else {
  6259. iterator = filtered.getIterator(this.index_);
  6260. }
  6261. let count = 0;
  6262. while (iterator.hasNext()) {
  6263. const next = iterator.getNext();
  6264. const inRange = count < this.limit_ &&
  6265. this.withinDirectionalStart(next) &&
  6266. this.withinDirectionalEnd(next);
  6267. if (inRange) {
  6268. count++;
  6269. }
  6270. else {
  6271. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6272. }
  6273. }
  6274. }
  6275. }
  6276. return this.rangedFilter_
  6277. .getIndexedFilter()
  6278. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6279. }
  6280. updatePriority(oldSnap, newPriority) {
  6281. // Don't support priorities on queries
  6282. return oldSnap;
  6283. }
  6284. filtersNodes() {
  6285. return true;
  6286. }
  6287. getIndexedFilter() {
  6288. return this.rangedFilter_.getIndexedFilter();
  6289. }
  6290. getIndex() {
  6291. return this.index_;
  6292. }
  6293. fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
  6294. // TODO: rename all cache stuff etc to general snap terminology
  6295. let cmp;
  6296. if (this.reverse_) {
  6297. const indexCmp = this.index_.getCompare();
  6298. cmp = (a, b) => indexCmp(b, a);
  6299. }
  6300. else {
  6301. cmp = this.index_.getCompare();
  6302. }
  6303. const oldEventCache = snap;
  6304. assert(oldEventCache.numChildren() === this.limit_, '');
  6305. const newChildNamedNode = new NamedNode(childKey, childSnap);
  6306. const windowBoundary = this.reverse_
  6307. ? oldEventCache.getFirstChild(this.index_)
  6308. : oldEventCache.getLastChild(this.index_);
  6309. const inRange = this.rangedFilter_.matches(newChildNamedNode);
  6310. if (oldEventCache.hasChild(childKey)) {
  6311. const oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6312. let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6313. while (nextChild != null &&
  6314. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6315. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6316. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6317. // the limited filter...
  6318. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6319. }
  6320. const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6321. const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6322. if (remainsInWindow) {
  6323. if (changeAccumulator != null) {
  6324. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6325. }
  6326. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6327. }
  6328. else {
  6329. if (changeAccumulator != null) {
  6330. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6331. }
  6332. const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6333. const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6334. if (nextChildInRange) {
  6335. if (changeAccumulator != null) {
  6336. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6337. }
  6338. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6339. }
  6340. else {
  6341. return newEventCache;
  6342. }
  6343. }
  6344. }
  6345. else if (childSnap.isEmpty()) {
  6346. // we're deleting a node, but it was not in the window, so ignore it
  6347. return snap;
  6348. }
  6349. else if (inRange) {
  6350. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6351. if (changeAccumulator != null) {
  6352. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6353. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6354. }
  6355. return oldEventCache
  6356. .updateImmediateChild(childKey, childSnap)
  6357. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6358. }
  6359. else {
  6360. return snap;
  6361. }
  6362. }
  6363. else {
  6364. return snap;
  6365. }
  6366. }
  6367. }
  6368. /**
  6369. * @license
  6370. * Copyright 2017 Google LLC
  6371. *
  6372. * Licensed under the Apache License, Version 2.0 (the "License");
  6373. * you may not use this file except in compliance with the License.
  6374. * You may obtain a copy of the License at
  6375. *
  6376. * http://www.apache.org/licenses/LICENSE-2.0
  6377. *
  6378. * Unless required by applicable law or agreed to in writing, software
  6379. * distributed under the License is distributed on an "AS IS" BASIS,
  6380. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6381. * See the License for the specific language governing permissions and
  6382. * limitations under the License.
  6383. */
  6384. /**
  6385. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6386. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6387. * user-facing API level, so it is not done here.
  6388. *
  6389. * @internal
  6390. */
  6391. class QueryParams {
  6392. constructor() {
  6393. this.limitSet_ = false;
  6394. this.startSet_ = false;
  6395. this.startNameSet_ = false;
  6396. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6397. this.endSet_ = false;
  6398. this.endNameSet_ = false;
  6399. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6400. this.limit_ = 0;
  6401. this.viewFrom_ = '';
  6402. this.indexStartValue_ = null;
  6403. this.indexStartName_ = '';
  6404. this.indexEndValue_ = null;
  6405. this.indexEndName_ = '';
  6406. this.index_ = PRIORITY_INDEX;
  6407. }
  6408. hasStart() {
  6409. return this.startSet_;
  6410. }
  6411. /**
  6412. * @returns True if it would return from left.
  6413. */
  6414. isViewFromLeft() {
  6415. if (this.viewFrom_ === '') {
  6416. // limit(), rather than limitToFirst or limitToLast was called.
  6417. // This means that only one of startSet_ and endSet_ is true. Use them
  6418. // to calculate which side of the view to anchor to. If neither is set,
  6419. // anchor to the end.
  6420. return this.startSet_;
  6421. }
  6422. else {
  6423. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6424. }
  6425. }
  6426. /**
  6427. * Only valid to call if hasStart() returns true
  6428. */
  6429. getIndexStartValue() {
  6430. assert(this.startSet_, 'Only valid if start has been set');
  6431. return this.indexStartValue_;
  6432. }
  6433. /**
  6434. * Only valid to call if hasStart() returns true.
  6435. * Returns the starting key name for the range defined by these query parameters
  6436. */
  6437. getIndexStartName() {
  6438. assert(this.startSet_, 'Only valid if start has been set');
  6439. if (this.startNameSet_) {
  6440. return this.indexStartName_;
  6441. }
  6442. else {
  6443. return MIN_NAME;
  6444. }
  6445. }
  6446. hasEnd() {
  6447. return this.endSet_;
  6448. }
  6449. /**
  6450. * Only valid to call if hasEnd() returns true.
  6451. */
  6452. getIndexEndValue() {
  6453. assert(this.endSet_, 'Only valid if end has been set');
  6454. return this.indexEndValue_;
  6455. }
  6456. /**
  6457. * Only valid to call if hasEnd() returns true.
  6458. * Returns the end key name for the range defined by these query parameters
  6459. */
  6460. getIndexEndName() {
  6461. assert(this.endSet_, 'Only valid if end has been set');
  6462. if (this.endNameSet_) {
  6463. return this.indexEndName_;
  6464. }
  6465. else {
  6466. return MAX_NAME;
  6467. }
  6468. }
  6469. hasLimit() {
  6470. return this.limitSet_;
  6471. }
  6472. /**
  6473. * @returns True if a limit has been set and it has been explicitly anchored
  6474. */
  6475. hasAnchoredLimit() {
  6476. return this.limitSet_ && this.viewFrom_ !== '';
  6477. }
  6478. /**
  6479. * Only valid to call if hasLimit() returns true
  6480. */
  6481. getLimit() {
  6482. assert(this.limitSet_, 'Only valid if limit has been set');
  6483. return this.limit_;
  6484. }
  6485. getIndex() {
  6486. return this.index_;
  6487. }
  6488. loadsAllData() {
  6489. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6490. }
  6491. isDefault() {
  6492. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6493. }
  6494. copy() {
  6495. const copy = new QueryParams();
  6496. copy.limitSet_ = this.limitSet_;
  6497. copy.limit_ = this.limit_;
  6498. copy.startSet_ = this.startSet_;
  6499. copy.startAfterSet_ = this.startAfterSet_;
  6500. copy.indexStartValue_ = this.indexStartValue_;
  6501. copy.startNameSet_ = this.startNameSet_;
  6502. copy.indexStartName_ = this.indexStartName_;
  6503. copy.endSet_ = this.endSet_;
  6504. copy.endBeforeSet_ = this.endBeforeSet_;
  6505. copy.indexEndValue_ = this.indexEndValue_;
  6506. copy.endNameSet_ = this.endNameSet_;
  6507. copy.indexEndName_ = this.indexEndName_;
  6508. copy.index_ = this.index_;
  6509. copy.viewFrom_ = this.viewFrom_;
  6510. return copy;
  6511. }
  6512. }
  6513. function queryParamsGetNodeFilter(queryParams) {
  6514. if (queryParams.loadsAllData()) {
  6515. return new IndexedFilter(queryParams.getIndex());
  6516. }
  6517. else if (queryParams.hasLimit()) {
  6518. return new LimitedFilter(queryParams);
  6519. }
  6520. else {
  6521. return new RangedFilter(queryParams);
  6522. }
  6523. }
  6524. function queryParamsLimitToFirst(queryParams, newLimit) {
  6525. const newParams = queryParams.copy();
  6526. newParams.limitSet_ = true;
  6527. newParams.limit_ = newLimit;
  6528. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6529. return newParams;
  6530. }
  6531. function queryParamsLimitToLast(queryParams, newLimit) {
  6532. const newParams = queryParams.copy();
  6533. newParams.limitSet_ = true;
  6534. newParams.limit_ = newLimit;
  6535. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6536. return newParams;
  6537. }
  6538. function queryParamsStartAt(queryParams, indexValue, key) {
  6539. const newParams = queryParams.copy();
  6540. newParams.startSet_ = true;
  6541. if (indexValue === undefined) {
  6542. indexValue = null;
  6543. }
  6544. newParams.indexStartValue_ = indexValue;
  6545. if (key != null) {
  6546. newParams.startNameSet_ = true;
  6547. newParams.indexStartName_ = key;
  6548. }
  6549. else {
  6550. newParams.startNameSet_ = false;
  6551. newParams.indexStartName_ = '';
  6552. }
  6553. return newParams;
  6554. }
  6555. function queryParamsStartAfter(queryParams, indexValue, key) {
  6556. let params;
  6557. if (queryParams.index_ === KEY_INDEX || !!key) {
  6558. params = queryParamsStartAt(queryParams, indexValue, key);
  6559. }
  6560. else {
  6561. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6562. }
  6563. params.startAfterSet_ = true;
  6564. return params;
  6565. }
  6566. function queryParamsEndAt(queryParams, indexValue, key) {
  6567. const newParams = queryParams.copy();
  6568. newParams.endSet_ = true;
  6569. if (indexValue === undefined) {
  6570. indexValue = null;
  6571. }
  6572. newParams.indexEndValue_ = indexValue;
  6573. if (key !== undefined) {
  6574. newParams.endNameSet_ = true;
  6575. newParams.indexEndName_ = key;
  6576. }
  6577. else {
  6578. newParams.endNameSet_ = false;
  6579. newParams.indexEndName_ = '';
  6580. }
  6581. return newParams;
  6582. }
  6583. function queryParamsEndBefore(queryParams, indexValue, key) {
  6584. let params;
  6585. if (queryParams.index_ === KEY_INDEX || !!key) {
  6586. params = queryParamsEndAt(queryParams, indexValue, key);
  6587. }
  6588. else {
  6589. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6590. }
  6591. params.endBeforeSet_ = true;
  6592. return params;
  6593. }
  6594. function queryParamsOrderBy(queryParams, index) {
  6595. const newParams = queryParams.copy();
  6596. newParams.index_ = index;
  6597. return newParams;
  6598. }
  6599. /**
  6600. * Returns a set of REST query string parameters representing this query.
  6601. *
  6602. * @returns query string parameters
  6603. */
  6604. function queryParamsToRestQueryStringParameters(queryParams) {
  6605. const qs = {};
  6606. if (queryParams.isDefault()) {
  6607. return qs;
  6608. }
  6609. let orderBy;
  6610. if (queryParams.index_ === PRIORITY_INDEX) {
  6611. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6612. }
  6613. else if (queryParams.index_ === VALUE_INDEX) {
  6614. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6615. }
  6616. else if (queryParams.index_ === KEY_INDEX) {
  6617. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6618. }
  6619. else {
  6620. assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6621. orderBy = queryParams.index_.toString();
  6622. }
  6623. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);
  6624. if (queryParams.startSet_) {
  6625. const startParam = queryParams.startAfterSet_
  6626. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6627. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6628. qs[startParam] = stringify(queryParams.indexStartValue_);
  6629. if (queryParams.startNameSet_) {
  6630. qs[startParam] += ',' + stringify(queryParams.indexStartName_);
  6631. }
  6632. }
  6633. if (queryParams.endSet_) {
  6634. const endParam = queryParams.endBeforeSet_
  6635. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6636. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6637. qs[endParam] = stringify(queryParams.indexEndValue_);
  6638. if (queryParams.endNameSet_) {
  6639. qs[endParam] += ',' + stringify(queryParams.indexEndName_);
  6640. }
  6641. }
  6642. if (queryParams.limitSet_) {
  6643. if (queryParams.isViewFromLeft()) {
  6644. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6645. }
  6646. else {
  6647. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6648. }
  6649. }
  6650. return qs;
  6651. }
  6652. function queryParamsGetQueryObject(queryParams) {
  6653. const obj = {};
  6654. if (queryParams.startSet_) {
  6655. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6656. queryParams.indexStartValue_;
  6657. if (queryParams.startNameSet_) {
  6658. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6659. queryParams.indexStartName_;
  6660. }
  6661. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6662. !queryParams.startAfterSet_;
  6663. }
  6664. if (queryParams.endSet_) {
  6665. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6666. if (queryParams.endNameSet_) {
  6667. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6668. }
  6669. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6670. !queryParams.endBeforeSet_;
  6671. }
  6672. if (queryParams.limitSet_) {
  6673. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6674. let viewFrom = queryParams.viewFrom_;
  6675. if (viewFrom === '') {
  6676. if (queryParams.isViewFromLeft()) {
  6677. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6678. }
  6679. else {
  6680. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6681. }
  6682. }
  6683. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6684. }
  6685. // For now, priority index is the default, so we only specify if it's some other index
  6686. if (queryParams.index_ !== PRIORITY_INDEX) {
  6687. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6688. }
  6689. return obj;
  6690. }
  6691. /**
  6692. * @license
  6693. * Copyright 2017 Google LLC
  6694. *
  6695. * Licensed under the Apache License, Version 2.0 (the "License");
  6696. * you may not use this file except in compliance with the License.
  6697. * You may obtain a copy of the License at
  6698. *
  6699. * http://www.apache.org/licenses/LICENSE-2.0
  6700. *
  6701. * Unless required by applicable law or agreed to in writing, software
  6702. * distributed under the License is distributed on an "AS IS" BASIS,
  6703. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6704. * See the License for the specific language governing permissions and
  6705. * limitations under the License.
  6706. */
  6707. /**
  6708. * An implementation of ServerActions that communicates with the server via REST requests.
  6709. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6710. * persistent connection (using WebSockets or long-polling)
  6711. */
  6712. class ReadonlyRestClient extends ServerActions {
  6713. /**
  6714. * @param repoInfo_ - Data about the namespace we are connecting to
  6715. * @param onDataUpdate_ - A callback for new data from the server
  6716. */
  6717. constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6718. super();
  6719. this.repoInfo_ = repoInfo_;
  6720. this.onDataUpdate_ = onDataUpdate_;
  6721. this.authTokenProvider_ = authTokenProvider_;
  6722. this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6723. /** @private {function(...[*])} */
  6724. this.log_ = logWrapper('p:rest:');
  6725. /**
  6726. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6727. * that's been removed. :-/
  6728. */
  6729. this.listens_ = {};
  6730. }
  6731. reportStats(stats) {
  6732. throw new Error('Method not implemented.');
  6733. }
  6734. static getListenId_(query, tag) {
  6735. if (tag !== undefined) {
  6736. return 'tag$' + tag;
  6737. }
  6738. else {
  6739. assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6740. return query._path.toString();
  6741. }
  6742. }
  6743. /** @inheritDoc */
  6744. listen(query, currentHashFn, tag, onComplete) {
  6745. const pathString = query._path.toString();
  6746. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6747. // Mark this listener so we can tell if it's removed.
  6748. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6749. const thisListen = {};
  6750. this.listens_[listenId] = thisListen;
  6751. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6752. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6753. let data = result;
  6754. if (error === 404) {
  6755. data = null;
  6756. error = null;
  6757. }
  6758. if (error === null) {
  6759. this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6760. }
  6761. if (safeGet(this.listens_, listenId) === thisListen) {
  6762. let status;
  6763. if (!error) {
  6764. status = 'ok';
  6765. }
  6766. else if (error === 401) {
  6767. status = 'permission_denied';
  6768. }
  6769. else {
  6770. status = 'rest_error:' + error;
  6771. }
  6772. onComplete(status, null);
  6773. }
  6774. });
  6775. }
  6776. /** @inheritDoc */
  6777. unlisten(query, tag) {
  6778. const listenId = ReadonlyRestClient.getListenId_(query, tag);
  6779. delete this.listens_[listenId];
  6780. }
  6781. get(query) {
  6782. const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6783. const pathString = query._path.toString();
  6784. const deferred = new Deferred();
  6785. this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
  6786. let data = result;
  6787. if (error === 404) {
  6788. data = null;
  6789. error = null;
  6790. }
  6791. if (error === null) {
  6792. this.onDataUpdate_(pathString, data,
  6793. /*isMerge=*/ false,
  6794. /*tag=*/ null);
  6795. deferred.resolve(data);
  6796. }
  6797. else {
  6798. deferred.reject(new Error(data));
  6799. }
  6800. });
  6801. return deferred.promise;
  6802. }
  6803. /** @inheritDoc */
  6804. refreshAuthToken(token) {
  6805. // no-op since we just always call getToken.
  6806. }
  6807. /**
  6808. * Performs a REST request to the given path, with the provided query string parameters,
  6809. * and any auth credentials we have.
  6810. */
  6811. restRequest_(pathString, queryStringParameters = {}, callback) {
  6812. queryStringParameters['format'] = 'export';
  6813. return Promise.all([
  6814. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  6815. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  6816. ]).then(([authToken, appCheckToken]) => {
  6817. if (authToken && authToken.accessToken) {
  6818. queryStringParameters['auth'] = authToken.accessToken;
  6819. }
  6820. if (appCheckToken && appCheckToken.token) {
  6821. queryStringParameters['ac'] = appCheckToken.token;
  6822. }
  6823. const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
  6824. this.repoInfo_.host +
  6825. pathString +
  6826. '?' +
  6827. 'ns=' +
  6828. this.repoInfo_.namespace +
  6829. querystring(queryStringParameters);
  6830. this.log_('Sending REST request for ' + url);
  6831. const xhr = new XMLHttpRequest();
  6832. xhr.onreadystatechange = () => {
  6833. if (callback && xhr.readyState === 4) {
  6834. this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  6835. let res = null;
  6836. if (xhr.status >= 200 && xhr.status < 300) {
  6837. try {
  6838. res = jsonEval(xhr.responseText);
  6839. }
  6840. catch (e) {
  6841. warn('Failed to parse JSON response for ' +
  6842. url +
  6843. ': ' +
  6844. xhr.responseText);
  6845. }
  6846. callback(null, res);
  6847. }
  6848. else {
  6849. // 401 and 404 are expected.
  6850. if (xhr.status !== 401 && xhr.status !== 404) {
  6851. warn('Got unsuccessful REST response for ' +
  6852. url +
  6853. ' Status: ' +
  6854. xhr.status);
  6855. }
  6856. callback(xhr.status);
  6857. }
  6858. callback = null;
  6859. }
  6860. };
  6861. xhr.open('GET', url, /*asynchronous=*/ true);
  6862. xhr.send();
  6863. });
  6864. }
  6865. }
  6866. /**
  6867. * @license
  6868. * Copyright 2017 Google LLC
  6869. *
  6870. * Licensed under the Apache License, Version 2.0 (the "License");
  6871. * you may not use this file except in compliance with the License.
  6872. * You may obtain a copy of the License at
  6873. *
  6874. * http://www.apache.org/licenses/LICENSE-2.0
  6875. *
  6876. * Unless required by applicable law or agreed to in writing, software
  6877. * distributed under the License is distributed on an "AS IS" BASIS,
  6878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6879. * See the License for the specific language governing permissions and
  6880. * limitations under the License.
  6881. */
  6882. /**
  6883. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  6884. */
  6885. class SnapshotHolder {
  6886. constructor() {
  6887. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  6888. }
  6889. getNode(path) {
  6890. return this.rootNode_.getChild(path);
  6891. }
  6892. updateSnapshot(path, newSnapshotNode) {
  6893. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  6894. }
  6895. }
  6896. /**
  6897. * @license
  6898. * Copyright 2017 Google LLC
  6899. *
  6900. * Licensed under the Apache License, Version 2.0 (the "License");
  6901. * you may not use this file except in compliance with the License.
  6902. * You may obtain a copy of the License at
  6903. *
  6904. * http://www.apache.org/licenses/LICENSE-2.0
  6905. *
  6906. * Unless required by applicable law or agreed to in writing, software
  6907. * distributed under the License is distributed on an "AS IS" BASIS,
  6908. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6909. * See the License for the specific language governing permissions and
  6910. * limitations under the License.
  6911. */
  6912. function newSparseSnapshotTree() {
  6913. return {
  6914. value: null,
  6915. children: new Map()
  6916. };
  6917. }
  6918. /**
  6919. * Stores the given node at the specified path. If there is already a node
  6920. * at a shallower path, it merges the new data into that snapshot node.
  6921. *
  6922. * @param path - Path to look up snapshot for.
  6923. * @param data - The new data, or null.
  6924. */
  6925. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  6926. if (pathIsEmpty(path)) {
  6927. sparseSnapshotTree.value = data;
  6928. sparseSnapshotTree.children.clear();
  6929. }
  6930. else if (sparseSnapshotTree.value !== null) {
  6931. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  6932. }
  6933. else {
  6934. const childKey = pathGetFront(path);
  6935. if (!sparseSnapshotTree.children.has(childKey)) {
  6936. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  6937. }
  6938. const child = sparseSnapshotTree.children.get(childKey);
  6939. path = pathPopFront(path);
  6940. sparseSnapshotTreeRemember(child, path, data);
  6941. }
  6942. }
  6943. /**
  6944. * Purge the data at path from the cache.
  6945. *
  6946. * @param path - Path to look up snapshot for.
  6947. * @returns True if this node should now be removed.
  6948. */
  6949. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  6950. if (pathIsEmpty(path)) {
  6951. sparseSnapshotTree.value = null;
  6952. sparseSnapshotTree.children.clear();
  6953. return true;
  6954. }
  6955. else {
  6956. if (sparseSnapshotTree.value !== null) {
  6957. if (sparseSnapshotTree.value.isLeafNode()) {
  6958. // We're trying to forget a node that doesn't exist
  6959. return false;
  6960. }
  6961. else {
  6962. const value = sparseSnapshotTree.value;
  6963. sparseSnapshotTree.value = null;
  6964. value.forEachChild(PRIORITY_INDEX, (key, tree) => {
  6965. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  6966. });
  6967. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  6968. }
  6969. }
  6970. else if (sparseSnapshotTree.children.size > 0) {
  6971. const childKey = pathGetFront(path);
  6972. path = pathPopFront(path);
  6973. if (sparseSnapshotTree.children.has(childKey)) {
  6974. const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  6975. if (safeToRemove) {
  6976. sparseSnapshotTree.children.delete(childKey);
  6977. }
  6978. }
  6979. return sparseSnapshotTree.children.size === 0;
  6980. }
  6981. else {
  6982. return true;
  6983. }
  6984. }
  6985. }
  6986. /**
  6987. * Recursively iterates through all of the stored tree and calls the
  6988. * callback on each one.
  6989. *
  6990. * @param prefixPath - Path to look up node for.
  6991. * @param func - The function to invoke for each tree.
  6992. */
  6993. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  6994. if (sparseSnapshotTree.value !== null) {
  6995. func(prefixPath, sparseSnapshotTree.value);
  6996. }
  6997. else {
  6998. sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
  6999. const path = new Path(prefixPath.toString() + '/' + key);
  7000. sparseSnapshotTreeForEachTree(tree, path, func);
  7001. });
  7002. }
  7003. }
  7004. /**
  7005. * Iterates through each immediate child and triggers the callback.
  7006. * Only seems to be used in tests.
  7007. *
  7008. * @param func - The function to invoke for each child.
  7009. */
  7010. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7011. sparseSnapshotTree.children.forEach((tree, key) => {
  7012. func(key, tree);
  7013. });
  7014. }
  7015. /**
  7016. * @license
  7017. * Copyright 2017 Google LLC
  7018. *
  7019. * Licensed under the Apache License, Version 2.0 (the "License");
  7020. * you may not use this file except in compliance with the License.
  7021. * You may obtain a copy of the License at
  7022. *
  7023. * http://www.apache.org/licenses/LICENSE-2.0
  7024. *
  7025. * Unless required by applicable law or agreed to in writing, software
  7026. * distributed under the License is distributed on an "AS IS" BASIS,
  7027. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7028. * See the License for the specific language governing permissions and
  7029. * limitations under the License.
  7030. */
  7031. /**
  7032. * Returns the delta from the previous call to get stats.
  7033. *
  7034. * @param collection_ - The collection to "listen" to.
  7035. */
  7036. class StatsListener {
  7037. constructor(collection_) {
  7038. this.collection_ = collection_;
  7039. this.last_ = null;
  7040. }
  7041. get() {
  7042. const newStats = this.collection_.get();
  7043. const delta = Object.assign({}, newStats);
  7044. if (this.last_) {
  7045. each(this.last_, (stat, value) => {
  7046. delta[stat] = delta[stat] - value;
  7047. });
  7048. }
  7049. this.last_ = newStats;
  7050. return delta;
  7051. }
  7052. }
  7053. /**
  7054. * @license
  7055. * Copyright 2017 Google LLC
  7056. *
  7057. * Licensed under the Apache License, Version 2.0 (the "License");
  7058. * you may not use this file except in compliance with the License.
  7059. * You may obtain a copy of the License at
  7060. *
  7061. * http://www.apache.org/licenses/LICENSE-2.0
  7062. *
  7063. * Unless required by applicable law or agreed to in writing, software
  7064. * distributed under the License is distributed on an "AS IS" BASIS,
  7065. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7066. * See the License for the specific language governing permissions and
  7067. * limitations under the License.
  7068. */
  7069. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7070. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7071. // seconds to try to ensure the Firebase connection is established / settled.
  7072. const FIRST_STATS_MIN_TIME = 10 * 1000;
  7073. const FIRST_STATS_MAX_TIME = 30 * 1000;
  7074. // We'll continue to report stats on average every 5 minutes.
  7075. const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7076. class StatsReporter {
  7077. constructor(collection, server_) {
  7078. this.server_ = server_;
  7079. this.statsToReport_ = {};
  7080. this.statsListener_ = new StatsListener(collection);
  7081. const timeout = FIRST_STATS_MIN_TIME +
  7082. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7083. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7084. }
  7085. reportStats_() {
  7086. const stats = this.statsListener_.get();
  7087. const reportedStats = {};
  7088. let haveStatsToReport = false;
  7089. each(stats, (stat, value) => {
  7090. if (value > 0 && contains(this.statsToReport_, stat)) {
  7091. reportedStats[stat] = value;
  7092. haveStatsToReport = true;
  7093. }
  7094. });
  7095. if (haveStatsToReport) {
  7096. this.server_.reportStats(reportedStats);
  7097. }
  7098. // queue our next run.
  7099. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7100. }
  7101. }
  7102. /**
  7103. * @license
  7104. * Copyright 2017 Google LLC
  7105. *
  7106. * Licensed under the Apache License, Version 2.0 (the "License");
  7107. * you may not use this file except in compliance with the License.
  7108. * You may obtain a copy of the License at
  7109. *
  7110. * http://www.apache.org/licenses/LICENSE-2.0
  7111. *
  7112. * Unless required by applicable law or agreed to in writing, software
  7113. * distributed under the License is distributed on an "AS IS" BASIS,
  7114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7115. * See the License for the specific language governing permissions and
  7116. * limitations under the License.
  7117. */
  7118. /**
  7119. *
  7120. * @enum
  7121. */
  7122. var OperationType;
  7123. (function (OperationType) {
  7124. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7125. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7126. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7127. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7128. })(OperationType || (OperationType = {}));
  7129. function newOperationSourceUser() {
  7130. return {
  7131. fromUser: true,
  7132. fromServer: false,
  7133. queryId: null,
  7134. tagged: false
  7135. };
  7136. }
  7137. function newOperationSourceServer() {
  7138. return {
  7139. fromUser: false,
  7140. fromServer: true,
  7141. queryId: null,
  7142. tagged: false
  7143. };
  7144. }
  7145. function newOperationSourceServerTaggedQuery(queryId) {
  7146. return {
  7147. fromUser: false,
  7148. fromServer: true,
  7149. queryId,
  7150. tagged: true
  7151. };
  7152. }
  7153. /**
  7154. * @license
  7155. * Copyright 2017 Google LLC
  7156. *
  7157. * Licensed under the Apache License, Version 2.0 (the "License");
  7158. * you may not use this file except in compliance with the License.
  7159. * You may obtain a copy of the License at
  7160. *
  7161. * http://www.apache.org/licenses/LICENSE-2.0
  7162. *
  7163. * Unless required by applicable law or agreed to in writing, software
  7164. * distributed under the License is distributed on an "AS IS" BASIS,
  7165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7166. * See the License for the specific language governing permissions and
  7167. * limitations under the License.
  7168. */
  7169. class AckUserWrite {
  7170. /**
  7171. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7172. */
  7173. constructor(
  7174. /** @inheritDoc */ path,
  7175. /** @inheritDoc */ affectedTree,
  7176. /** @inheritDoc */ revert) {
  7177. this.path = path;
  7178. this.affectedTree = affectedTree;
  7179. this.revert = revert;
  7180. /** @inheritDoc */
  7181. this.type = OperationType.ACK_USER_WRITE;
  7182. /** @inheritDoc */
  7183. this.source = newOperationSourceUser();
  7184. }
  7185. operationForChild(childName) {
  7186. if (!pathIsEmpty(this.path)) {
  7187. assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7188. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7189. }
  7190. else if (this.affectedTree.value != null) {
  7191. assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7192. // All child locations are affected as well; just return same operation.
  7193. return this;
  7194. }
  7195. else {
  7196. const childTree = this.affectedTree.subtree(new Path(childName));
  7197. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7198. }
  7199. }
  7200. }
  7201. /**
  7202. * @license
  7203. * Copyright 2017 Google LLC
  7204. *
  7205. * Licensed under the Apache License, Version 2.0 (the "License");
  7206. * you may not use this file except in compliance with the License.
  7207. * You may obtain a copy of the License at
  7208. *
  7209. * http://www.apache.org/licenses/LICENSE-2.0
  7210. *
  7211. * Unless required by applicable law or agreed to in writing, software
  7212. * distributed under the License is distributed on an "AS IS" BASIS,
  7213. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7214. * See the License for the specific language governing permissions and
  7215. * limitations under the License.
  7216. */
  7217. class ListenComplete {
  7218. constructor(source, path) {
  7219. this.source = source;
  7220. this.path = path;
  7221. /** @inheritDoc */
  7222. this.type = OperationType.LISTEN_COMPLETE;
  7223. }
  7224. operationForChild(childName) {
  7225. if (pathIsEmpty(this.path)) {
  7226. return new ListenComplete(this.source, newEmptyPath());
  7227. }
  7228. else {
  7229. return new ListenComplete(this.source, pathPopFront(this.path));
  7230. }
  7231. }
  7232. }
  7233. /**
  7234. * @license
  7235. * Copyright 2017 Google LLC
  7236. *
  7237. * Licensed under the Apache License, Version 2.0 (the "License");
  7238. * you may not use this file except in compliance with the License.
  7239. * You may obtain a copy of the License at
  7240. *
  7241. * http://www.apache.org/licenses/LICENSE-2.0
  7242. *
  7243. * Unless required by applicable law or agreed to in writing, software
  7244. * distributed under the License is distributed on an "AS IS" BASIS,
  7245. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7246. * See the License for the specific language governing permissions and
  7247. * limitations under the License.
  7248. */
  7249. class Overwrite {
  7250. constructor(source, path, snap) {
  7251. this.source = source;
  7252. this.path = path;
  7253. this.snap = snap;
  7254. /** @inheritDoc */
  7255. this.type = OperationType.OVERWRITE;
  7256. }
  7257. operationForChild(childName) {
  7258. if (pathIsEmpty(this.path)) {
  7259. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7260. }
  7261. else {
  7262. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7263. }
  7264. }
  7265. }
  7266. /**
  7267. * @license
  7268. * Copyright 2017 Google LLC
  7269. *
  7270. * Licensed under the Apache License, Version 2.0 (the "License");
  7271. * you may not use this file except in compliance with the License.
  7272. * You may obtain a copy of the License at
  7273. *
  7274. * http://www.apache.org/licenses/LICENSE-2.0
  7275. *
  7276. * Unless required by applicable law or agreed to in writing, software
  7277. * distributed under the License is distributed on an "AS IS" BASIS,
  7278. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7279. * See the License for the specific language governing permissions and
  7280. * limitations under the License.
  7281. */
  7282. class Merge {
  7283. constructor(
  7284. /** @inheritDoc */ source,
  7285. /** @inheritDoc */ path,
  7286. /** @inheritDoc */ children) {
  7287. this.source = source;
  7288. this.path = path;
  7289. this.children = children;
  7290. /** @inheritDoc */
  7291. this.type = OperationType.MERGE;
  7292. }
  7293. operationForChild(childName) {
  7294. if (pathIsEmpty(this.path)) {
  7295. const childTree = this.children.subtree(new Path(childName));
  7296. if (childTree.isEmpty()) {
  7297. // This child is unaffected
  7298. return null;
  7299. }
  7300. else if (childTree.value) {
  7301. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7302. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7303. }
  7304. else {
  7305. // This is a merge at a deeper level
  7306. return new Merge(this.source, newEmptyPath(), childTree);
  7307. }
  7308. }
  7309. else {
  7310. assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7311. return new Merge(this.source, pathPopFront(this.path), this.children);
  7312. }
  7313. }
  7314. toString() {
  7315. return ('Operation(' +
  7316. this.path +
  7317. ': ' +
  7318. this.source.toString() +
  7319. ' merge: ' +
  7320. this.children.toString() +
  7321. ')');
  7322. }
  7323. }
  7324. /**
  7325. * @license
  7326. * Copyright 2017 Google LLC
  7327. *
  7328. * Licensed under the Apache License, Version 2.0 (the "License");
  7329. * you may not use this file except in compliance with the License.
  7330. * You may obtain a copy of the License at
  7331. *
  7332. * http://www.apache.org/licenses/LICENSE-2.0
  7333. *
  7334. * Unless required by applicable law or agreed to in writing, software
  7335. * distributed under the License is distributed on an "AS IS" BASIS,
  7336. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7337. * See the License for the specific language governing permissions and
  7338. * limitations under the License.
  7339. */
  7340. /**
  7341. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7342. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7343. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7344. * whether a node potentially had children removed due to a filter.
  7345. */
  7346. class CacheNode {
  7347. constructor(node_, fullyInitialized_, filtered_) {
  7348. this.node_ = node_;
  7349. this.fullyInitialized_ = fullyInitialized_;
  7350. this.filtered_ = filtered_;
  7351. }
  7352. /**
  7353. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7354. */
  7355. isFullyInitialized() {
  7356. return this.fullyInitialized_;
  7357. }
  7358. /**
  7359. * Returns whether this node is potentially missing children due to a filter applied to the node
  7360. */
  7361. isFiltered() {
  7362. return this.filtered_;
  7363. }
  7364. isCompleteForPath(path) {
  7365. if (pathIsEmpty(path)) {
  7366. return this.isFullyInitialized() && !this.filtered_;
  7367. }
  7368. const childKey = pathGetFront(path);
  7369. return this.isCompleteForChild(childKey);
  7370. }
  7371. isCompleteForChild(key) {
  7372. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7373. }
  7374. getNode() {
  7375. return this.node_;
  7376. }
  7377. }
  7378. /**
  7379. * @license
  7380. * Copyright 2017 Google LLC
  7381. *
  7382. * Licensed under the Apache License, Version 2.0 (the "License");
  7383. * you may not use this file except in compliance with the License.
  7384. * You may obtain a copy of the License at
  7385. *
  7386. * http://www.apache.org/licenses/LICENSE-2.0
  7387. *
  7388. * Unless required by applicable law or agreed to in writing, software
  7389. * distributed under the License is distributed on an "AS IS" BASIS,
  7390. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7391. * See the License for the specific language governing permissions and
  7392. * limitations under the License.
  7393. */
  7394. /**
  7395. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7396. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7397. * for details.
  7398. *
  7399. */
  7400. class EventGenerator {
  7401. constructor(query_) {
  7402. this.query_ = query_;
  7403. this.index_ = this.query_._queryParams.getIndex();
  7404. }
  7405. }
  7406. /**
  7407. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7408. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7409. *
  7410. * Notes:
  7411. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7412. * our index.
  7413. * - prevName will be calculated based on the index ordering.
  7414. */
  7415. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7416. const events = [];
  7417. const moves = [];
  7418. changes.forEach(change => {
  7419. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7420. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7421. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7422. }
  7423. });
  7424. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7425. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7426. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7427. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7428. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7429. return events;
  7430. }
  7431. /**
  7432. * Given changes of a single change type, generate the corresponding events.
  7433. */
  7434. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7435. const filteredChanges = changes.filter(change => change.type === eventType);
  7436. filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
  7437. filteredChanges.forEach(change => {
  7438. const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7439. registrations.forEach(registration => {
  7440. if (registration.respondsTo(change.type)) {
  7441. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7442. }
  7443. });
  7444. });
  7445. }
  7446. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7447. if (change.type === 'value' || change.type === 'child_removed') {
  7448. return change;
  7449. }
  7450. else {
  7451. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7452. return change;
  7453. }
  7454. }
  7455. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7456. if (a.childName == null || b.childName == null) {
  7457. throw assertionError('Should only compare child_ events.');
  7458. }
  7459. const aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7460. const bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7461. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7462. }
  7463. /**
  7464. * @license
  7465. * Copyright 2017 Google LLC
  7466. *
  7467. * Licensed under the Apache License, Version 2.0 (the "License");
  7468. * you may not use this file except in compliance with the License.
  7469. * You may obtain a copy of the License at
  7470. *
  7471. * http://www.apache.org/licenses/LICENSE-2.0
  7472. *
  7473. * Unless required by applicable law or agreed to in writing, software
  7474. * distributed under the License is distributed on an "AS IS" BASIS,
  7475. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7476. * See the License for the specific language governing permissions and
  7477. * limitations under the License.
  7478. */
  7479. function newViewCache(eventCache, serverCache) {
  7480. return { eventCache, serverCache };
  7481. }
  7482. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7483. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7484. }
  7485. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7486. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7487. }
  7488. function viewCacheGetCompleteEventSnap(viewCache) {
  7489. return viewCache.eventCache.isFullyInitialized()
  7490. ? viewCache.eventCache.getNode()
  7491. : null;
  7492. }
  7493. function viewCacheGetCompleteServerSnap(viewCache) {
  7494. return viewCache.serverCache.isFullyInitialized()
  7495. ? viewCache.serverCache.getNode()
  7496. : null;
  7497. }
  7498. /**
  7499. * @license
  7500. * Copyright 2017 Google LLC
  7501. *
  7502. * Licensed under the Apache License, Version 2.0 (the "License");
  7503. * you may not use this file except in compliance with the License.
  7504. * You may obtain a copy of the License at
  7505. *
  7506. * http://www.apache.org/licenses/LICENSE-2.0
  7507. *
  7508. * Unless required by applicable law or agreed to in writing, software
  7509. * distributed under the License is distributed on an "AS IS" BASIS,
  7510. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7511. * See the License for the specific language governing permissions and
  7512. * limitations under the License.
  7513. */
  7514. let emptyChildrenSingleton;
  7515. /**
  7516. * Singleton empty children collection.
  7517. *
  7518. */
  7519. const EmptyChildren = () => {
  7520. if (!emptyChildrenSingleton) {
  7521. emptyChildrenSingleton = new SortedMap(stringCompare);
  7522. }
  7523. return emptyChildrenSingleton;
  7524. };
  7525. /**
  7526. * A tree with immutable elements.
  7527. */
  7528. class ImmutableTree {
  7529. constructor(value, children = EmptyChildren()) {
  7530. this.value = value;
  7531. this.children = children;
  7532. }
  7533. static fromObject(obj) {
  7534. let tree = new ImmutableTree(null);
  7535. each(obj, (childPath, childSnap) => {
  7536. tree = tree.set(new Path(childPath), childSnap);
  7537. });
  7538. return tree;
  7539. }
  7540. /**
  7541. * True if the value is empty and there are no children
  7542. */
  7543. isEmpty() {
  7544. return this.value === null && this.children.isEmpty();
  7545. }
  7546. /**
  7547. * Given a path and predicate, return the first node and the path to that node
  7548. * where the predicate returns true.
  7549. *
  7550. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7551. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7552. *
  7553. * @param relativePath - The remainder of the path
  7554. * @param predicate - The predicate to satisfy to return a node
  7555. */
  7556. findRootMostMatchingPathAndValue(relativePath, predicate) {
  7557. if (this.value != null && predicate(this.value)) {
  7558. return { path: newEmptyPath(), value: this.value };
  7559. }
  7560. else {
  7561. if (pathIsEmpty(relativePath)) {
  7562. return null;
  7563. }
  7564. else {
  7565. const front = pathGetFront(relativePath);
  7566. const child = this.children.get(front);
  7567. if (child !== null) {
  7568. const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7569. if (childExistingPathAndValue != null) {
  7570. const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7571. return { path: fullPath, value: childExistingPathAndValue.value };
  7572. }
  7573. else {
  7574. return null;
  7575. }
  7576. }
  7577. else {
  7578. return null;
  7579. }
  7580. }
  7581. }
  7582. }
  7583. /**
  7584. * Find, if it exists, the shortest subpath of the given path that points a defined
  7585. * value in the tree
  7586. */
  7587. findRootMostValueAndPath(relativePath) {
  7588. return this.findRootMostMatchingPathAndValue(relativePath, () => true);
  7589. }
  7590. /**
  7591. * @returns The subtree at the given path
  7592. */
  7593. subtree(relativePath) {
  7594. if (pathIsEmpty(relativePath)) {
  7595. return this;
  7596. }
  7597. else {
  7598. const front = pathGetFront(relativePath);
  7599. const childTree = this.children.get(front);
  7600. if (childTree !== null) {
  7601. return childTree.subtree(pathPopFront(relativePath));
  7602. }
  7603. else {
  7604. return new ImmutableTree(null);
  7605. }
  7606. }
  7607. }
  7608. /**
  7609. * Sets a value at the specified path.
  7610. *
  7611. * @param relativePath - Path to set value at.
  7612. * @param toSet - Value to set.
  7613. * @returns Resulting tree.
  7614. */
  7615. set(relativePath, toSet) {
  7616. if (pathIsEmpty(relativePath)) {
  7617. return new ImmutableTree(toSet, this.children);
  7618. }
  7619. else {
  7620. const front = pathGetFront(relativePath);
  7621. const child = this.children.get(front) || new ImmutableTree(null);
  7622. const newChild = child.set(pathPopFront(relativePath), toSet);
  7623. const newChildren = this.children.insert(front, newChild);
  7624. return new ImmutableTree(this.value, newChildren);
  7625. }
  7626. }
  7627. /**
  7628. * Removes the value at the specified path.
  7629. *
  7630. * @param relativePath - Path to value to remove.
  7631. * @returns Resulting tree.
  7632. */
  7633. remove(relativePath) {
  7634. if (pathIsEmpty(relativePath)) {
  7635. if (this.children.isEmpty()) {
  7636. return new ImmutableTree(null);
  7637. }
  7638. else {
  7639. return new ImmutableTree(null, this.children);
  7640. }
  7641. }
  7642. else {
  7643. const front = pathGetFront(relativePath);
  7644. const child = this.children.get(front);
  7645. if (child) {
  7646. const newChild = child.remove(pathPopFront(relativePath));
  7647. let newChildren;
  7648. if (newChild.isEmpty()) {
  7649. newChildren = this.children.remove(front);
  7650. }
  7651. else {
  7652. newChildren = this.children.insert(front, newChild);
  7653. }
  7654. if (this.value === null && newChildren.isEmpty()) {
  7655. return new ImmutableTree(null);
  7656. }
  7657. else {
  7658. return new ImmutableTree(this.value, newChildren);
  7659. }
  7660. }
  7661. else {
  7662. return this;
  7663. }
  7664. }
  7665. }
  7666. /**
  7667. * Gets a value from the tree.
  7668. *
  7669. * @param relativePath - Path to get value for.
  7670. * @returns Value at path, or null.
  7671. */
  7672. get(relativePath) {
  7673. if (pathIsEmpty(relativePath)) {
  7674. return this.value;
  7675. }
  7676. else {
  7677. const front = pathGetFront(relativePath);
  7678. const child = this.children.get(front);
  7679. if (child) {
  7680. return child.get(pathPopFront(relativePath));
  7681. }
  7682. else {
  7683. return null;
  7684. }
  7685. }
  7686. }
  7687. /**
  7688. * Replace the subtree at the specified path with the given new tree.
  7689. *
  7690. * @param relativePath - Path to replace subtree for.
  7691. * @param newTree - New tree.
  7692. * @returns Resulting tree.
  7693. */
  7694. setTree(relativePath, newTree) {
  7695. if (pathIsEmpty(relativePath)) {
  7696. return newTree;
  7697. }
  7698. else {
  7699. const front = pathGetFront(relativePath);
  7700. const child = this.children.get(front) || new ImmutableTree(null);
  7701. const newChild = child.setTree(pathPopFront(relativePath), newTree);
  7702. let newChildren;
  7703. if (newChild.isEmpty()) {
  7704. newChildren = this.children.remove(front);
  7705. }
  7706. else {
  7707. newChildren = this.children.insert(front, newChild);
  7708. }
  7709. return new ImmutableTree(this.value, newChildren);
  7710. }
  7711. }
  7712. /**
  7713. * Performs a depth first fold on this tree. Transforms a tree into a single
  7714. * value, given a function that operates on the path to a node, an optional
  7715. * current value, and a map of child names to folded subtrees
  7716. */
  7717. fold(fn) {
  7718. return this.fold_(newEmptyPath(), fn);
  7719. }
  7720. /**
  7721. * Recursive helper for public-facing fold() method
  7722. */
  7723. fold_(pathSoFar, fn) {
  7724. const accum = {};
  7725. this.children.inorderTraversal((childKey, childTree) => {
  7726. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7727. });
  7728. return fn(pathSoFar, this.value, accum);
  7729. }
  7730. /**
  7731. * Find the first matching value on the given path. Return the result of applying f to it.
  7732. */
  7733. findOnPath(path, f) {
  7734. return this.findOnPath_(path, newEmptyPath(), f);
  7735. }
  7736. findOnPath_(pathToFollow, pathSoFar, f) {
  7737. const result = this.value ? f(pathSoFar, this.value) : false;
  7738. if (result) {
  7739. return result;
  7740. }
  7741. else {
  7742. if (pathIsEmpty(pathToFollow)) {
  7743. return null;
  7744. }
  7745. else {
  7746. const front = pathGetFront(pathToFollow);
  7747. const nextChild = this.children.get(front);
  7748. if (nextChild) {
  7749. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7750. }
  7751. else {
  7752. return null;
  7753. }
  7754. }
  7755. }
  7756. }
  7757. foreachOnPath(path, f) {
  7758. return this.foreachOnPath_(path, newEmptyPath(), f);
  7759. }
  7760. foreachOnPath_(pathToFollow, currentRelativePath, f) {
  7761. if (pathIsEmpty(pathToFollow)) {
  7762. return this;
  7763. }
  7764. else {
  7765. if (this.value) {
  7766. f(currentRelativePath, this.value);
  7767. }
  7768. const front = pathGetFront(pathToFollow);
  7769. const nextChild = this.children.get(front);
  7770. if (nextChild) {
  7771. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  7772. }
  7773. else {
  7774. return new ImmutableTree(null);
  7775. }
  7776. }
  7777. }
  7778. /**
  7779. * Calls the given function for each node in the tree that has a value.
  7780. *
  7781. * @param f - A function to be called with the path from the root of the tree to
  7782. * a node, and the value at that node. Called in depth-first order.
  7783. */
  7784. foreach(f) {
  7785. this.foreach_(newEmptyPath(), f);
  7786. }
  7787. foreach_(currentRelativePath, f) {
  7788. this.children.inorderTraversal((childName, childTree) => {
  7789. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  7790. });
  7791. if (this.value) {
  7792. f(currentRelativePath, this.value);
  7793. }
  7794. }
  7795. foreachChild(f) {
  7796. this.children.inorderTraversal((childName, childTree) => {
  7797. if (childTree.value) {
  7798. f(childName, childTree.value);
  7799. }
  7800. });
  7801. }
  7802. }
  7803. /**
  7804. * @license
  7805. * Copyright 2017 Google LLC
  7806. *
  7807. * Licensed under the Apache License, Version 2.0 (the "License");
  7808. * you may not use this file except in compliance with the License.
  7809. * You may obtain a copy of the License at
  7810. *
  7811. * http://www.apache.org/licenses/LICENSE-2.0
  7812. *
  7813. * Unless required by applicable law or agreed to in writing, software
  7814. * distributed under the License is distributed on an "AS IS" BASIS,
  7815. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7816. * See the License for the specific language governing permissions and
  7817. * limitations under the License.
  7818. */
  7819. /**
  7820. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  7821. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  7822. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  7823. * to reflect the write added.
  7824. */
  7825. class CompoundWrite {
  7826. constructor(writeTree_) {
  7827. this.writeTree_ = writeTree_;
  7828. }
  7829. static empty() {
  7830. return new CompoundWrite(new ImmutableTree(null));
  7831. }
  7832. }
  7833. function compoundWriteAddWrite(compoundWrite, path, node) {
  7834. if (pathIsEmpty(path)) {
  7835. return new CompoundWrite(new ImmutableTree(node));
  7836. }
  7837. else {
  7838. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7839. if (rootmost != null) {
  7840. const rootMostPath = rootmost.path;
  7841. let value = rootmost.value;
  7842. const relativePath = newRelativePath(rootMostPath, path);
  7843. value = value.updateChild(relativePath, node);
  7844. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  7845. }
  7846. else {
  7847. const subtree = new ImmutableTree(node);
  7848. const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  7849. return new CompoundWrite(newWriteTree);
  7850. }
  7851. }
  7852. }
  7853. function compoundWriteAddWrites(compoundWrite, path, updates) {
  7854. let newWrite = compoundWrite;
  7855. each(updates, (childKey, node) => {
  7856. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  7857. });
  7858. return newWrite;
  7859. }
  7860. /**
  7861. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  7862. * location, which must be removed by calling this method with that path.
  7863. *
  7864. * @param compoundWrite - The CompoundWrite to remove.
  7865. * @param path - The path at which a write and all deeper writes should be removed
  7866. * @returns The new CompoundWrite with the removed path
  7867. */
  7868. function compoundWriteRemoveWrite(compoundWrite, path) {
  7869. if (pathIsEmpty(path)) {
  7870. return CompoundWrite.empty();
  7871. }
  7872. else {
  7873. const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  7874. return new CompoundWrite(newWriteTree);
  7875. }
  7876. }
  7877. /**
  7878. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  7879. * considered "complete".
  7880. *
  7881. * @param compoundWrite - The CompoundWrite to check.
  7882. * @param path - The path to check for
  7883. * @returns Whether there is a complete write at that path
  7884. */
  7885. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  7886. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  7887. }
  7888. /**
  7889. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  7890. * writes from deeper paths, but will return child nodes from a more shallow path.
  7891. *
  7892. * @param compoundWrite - The CompoundWrite to get the node from.
  7893. * @param path - The path to get a complete write
  7894. * @returns The node if complete at that path, or null otherwise.
  7895. */
  7896. function compoundWriteGetCompleteNode(compoundWrite, path) {
  7897. const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  7898. if (rootmost != null) {
  7899. return compoundWrite.writeTree_
  7900. .get(rootmost.path)
  7901. .getChild(newRelativePath(rootmost.path, path));
  7902. }
  7903. else {
  7904. return null;
  7905. }
  7906. }
  7907. /**
  7908. * Returns all children that are guaranteed to be a complete overwrite.
  7909. *
  7910. * @param compoundWrite - The CompoundWrite to get children from.
  7911. * @returns A list of all complete children.
  7912. */
  7913. function compoundWriteGetCompleteChildren(compoundWrite) {
  7914. const children = [];
  7915. const node = compoundWrite.writeTree_.value;
  7916. if (node != null) {
  7917. // If it's a leaf node, it has no children; so nothing to do.
  7918. if (!node.isLeafNode()) {
  7919. node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  7920. children.push(new NamedNode(childName, childNode));
  7921. });
  7922. }
  7923. }
  7924. else {
  7925. compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
  7926. if (childTree.value != null) {
  7927. children.push(new NamedNode(childName, childTree.value));
  7928. }
  7929. });
  7930. }
  7931. return children;
  7932. }
  7933. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  7934. if (pathIsEmpty(path)) {
  7935. return compoundWrite;
  7936. }
  7937. else {
  7938. const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  7939. if (shadowingNode != null) {
  7940. return new CompoundWrite(new ImmutableTree(shadowingNode));
  7941. }
  7942. else {
  7943. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  7944. }
  7945. }
  7946. }
  7947. /**
  7948. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  7949. * @returns Whether this CompoundWrite is empty
  7950. */
  7951. function compoundWriteIsEmpty(compoundWrite) {
  7952. return compoundWrite.writeTree_.isEmpty();
  7953. }
  7954. /**
  7955. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  7956. * node
  7957. * @param node - The node to apply this CompoundWrite to
  7958. * @returns The node with all writes applied
  7959. */
  7960. function compoundWriteApply(compoundWrite, node) {
  7961. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  7962. }
  7963. function applySubtreeWrite(relativePath, writeTree, node) {
  7964. if (writeTree.value != null) {
  7965. // Since there a write is always a leaf, we're done here
  7966. return node.updateChild(relativePath, writeTree.value);
  7967. }
  7968. else {
  7969. let priorityWrite = null;
  7970. writeTree.children.inorderTraversal((childKey, childTree) => {
  7971. if (childKey === '.priority') {
  7972. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  7973. // to apply priorities to empty nodes that are later filled
  7974. assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  7975. priorityWrite = childTree.value;
  7976. }
  7977. else {
  7978. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  7979. }
  7980. });
  7981. // If there was a priority write, we only apply it if the node is not empty
  7982. if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
  7983. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
  7984. }
  7985. return node;
  7986. }
  7987. }
  7988. /**
  7989. * @license
  7990. * Copyright 2017 Google LLC
  7991. *
  7992. * Licensed under the Apache License, Version 2.0 (the "License");
  7993. * you may not use this file except in compliance with the License.
  7994. * You may obtain a copy of the License at
  7995. *
  7996. * http://www.apache.org/licenses/LICENSE-2.0
  7997. *
  7998. * Unless required by applicable law or agreed to in writing, software
  7999. * distributed under the License is distributed on an "AS IS" BASIS,
  8000. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8001. * See the License for the specific language governing permissions and
  8002. * limitations under the License.
  8003. */
  8004. /**
  8005. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8006. *
  8007. */
  8008. function writeTreeChildWrites(writeTree, path) {
  8009. return newWriteTreeRef(path, writeTree);
  8010. }
  8011. /**
  8012. * Record a new overwrite from user code.
  8013. *
  8014. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8015. */
  8016. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8017. assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8018. if (visible === undefined) {
  8019. visible = true;
  8020. }
  8021. writeTree.allWrites.push({
  8022. path,
  8023. snap,
  8024. writeId,
  8025. visible
  8026. });
  8027. if (visible) {
  8028. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8029. }
  8030. writeTree.lastWriteId = writeId;
  8031. }
  8032. /**
  8033. * Record a new merge from user code.
  8034. */
  8035. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8036. assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8037. writeTree.allWrites.push({
  8038. path,
  8039. children: changedChildren,
  8040. writeId,
  8041. visible: true
  8042. });
  8043. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8044. writeTree.lastWriteId = writeId;
  8045. }
  8046. function writeTreeGetWrite(writeTree, writeId) {
  8047. for (let i = 0; i < writeTree.allWrites.length; i++) {
  8048. const record = writeTree.allWrites[i];
  8049. if (record.writeId === writeId) {
  8050. return record;
  8051. }
  8052. }
  8053. return null;
  8054. }
  8055. /**
  8056. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8057. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8058. *
  8059. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8060. * events as a result).
  8061. */
  8062. function writeTreeRemoveWrite(writeTree, writeId) {
  8063. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8064. // out of order.
  8065. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8066. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8067. const idx = writeTree.allWrites.findIndex(s => {
  8068. return s.writeId === writeId;
  8069. });
  8070. assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8071. const writeToRemove = writeTree.allWrites[idx];
  8072. writeTree.allWrites.splice(idx, 1);
  8073. let removedWriteWasVisible = writeToRemove.visible;
  8074. let removedWriteOverlapsWithOtherWrites = false;
  8075. let i = writeTree.allWrites.length - 1;
  8076. while (removedWriteWasVisible && i >= 0) {
  8077. const currentWrite = writeTree.allWrites[i];
  8078. if (currentWrite.visible) {
  8079. if (i >= idx &&
  8080. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8081. // The removed write was completely shadowed by a subsequent write.
  8082. removedWriteWasVisible = false;
  8083. }
  8084. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8085. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8086. removedWriteOverlapsWithOtherWrites = true;
  8087. }
  8088. }
  8089. i--;
  8090. }
  8091. if (!removedWriteWasVisible) {
  8092. return false;
  8093. }
  8094. else if (removedWriteOverlapsWithOtherWrites) {
  8095. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8096. writeTreeResetTree_(writeTree);
  8097. return true;
  8098. }
  8099. else {
  8100. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8101. if (writeToRemove.snap) {
  8102. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8103. }
  8104. else {
  8105. const children = writeToRemove.children;
  8106. each(children, (childName) => {
  8107. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8108. });
  8109. }
  8110. return true;
  8111. }
  8112. }
  8113. function writeTreeRecordContainsPath_(writeRecord, path) {
  8114. if (writeRecord.snap) {
  8115. return pathContains(writeRecord.path, path);
  8116. }
  8117. else {
  8118. for (const childName in writeRecord.children) {
  8119. if (writeRecord.children.hasOwnProperty(childName) &&
  8120. pathContains(pathChild(writeRecord.path, childName), path)) {
  8121. return true;
  8122. }
  8123. }
  8124. return false;
  8125. }
  8126. }
  8127. /**
  8128. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8129. */
  8130. function writeTreeResetTree_(writeTree) {
  8131. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8132. if (writeTree.allWrites.length > 0) {
  8133. writeTree.lastWriteId =
  8134. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8135. }
  8136. else {
  8137. writeTree.lastWriteId = -1;
  8138. }
  8139. }
  8140. /**
  8141. * The default filter used when constructing the tree. Keep everything that's visible.
  8142. */
  8143. function writeTreeDefaultFilter_(write) {
  8144. return write.visible;
  8145. }
  8146. /**
  8147. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8148. * event data at that path.
  8149. */
  8150. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8151. let compoundWrite = CompoundWrite.empty();
  8152. for (let i = 0; i < writes.length; ++i) {
  8153. const write = writes[i];
  8154. // Theory, a later set will either:
  8155. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8156. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8157. if (filter(write)) {
  8158. const writePath = write.path;
  8159. let relativePath;
  8160. if (write.snap) {
  8161. if (pathContains(treeRoot, writePath)) {
  8162. relativePath = newRelativePath(treeRoot, writePath);
  8163. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8164. }
  8165. else if (pathContains(writePath, treeRoot)) {
  8166. relativePath = newRelativePath(writePath, treeRoot);
  8167. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8168. }
  8169. else ;
  8170. }
  8171. else if (write.children) {
  8172. if (pathContains(treeRoot, writePath)) {
  8173. relativePath = newRelativePath(treeRoot, writePath);
  8174. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8175. }
  8176. else if (pathContains(writePath, treeRoot)) {
  8177. relativePath = newRelativePath(writePath, treeRoot);
  8178. if (pathIsEmpty(relativePath)) {
  8179. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8180. }
  8181. else {
  8182. const child = safeGet(write.children, pathGetFront(relativePath));
  8183. if (child) {
  8184. // There exists a child in this node that matches the root path
  8185. const deepNode = child.getChild(pathPopFront(relativePath));
  8186. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8187. }
  8188. }
  8189. }
  8190. else ;
  8191. }
  8192. else {
  8193. throw assertionError('WriteRecord should have .snap or .children');
  8194. }
  8195. }
  8196. }
  8197. return compoundWrite;
  8198. }
  8199. /**
  8200. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8201. * writes), attempt to calculate a complete snapshot for the given path
  8202. *
  8203. * @param writeIdsToExclude - An optional set to be excluded
  8204. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8205. */
  8206. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8207. if (!writeIdsToExclude && !includeHiddenWrites) {
  8208. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8209. if (shadowingNode != null) {
  8210. return shadowingNode;
  8211. }
  8212. else {
  8213. const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8214. if (compoundWriteIsEmpty(subMerge)) {
  8215. return completeServerCache;
  8216. }
  8217. else if (completeServerCache == null &&
  8218. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8219. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8220. return null;
  8221. }
  8222. else {
  8223. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8224. return compoundWriteApply(subMerge, layeredCache);
  8225. }
  8226. }
  8227. }
  8228. else {
  8229. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8230. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8231. return completeServerCache;
  8232. }
  8233. else {
  8234. // If the server cache is null, and we don't have a complete cache, we need to return null
  8235. if (!includeHiddenWrites &&
  8236. completeServerCache == null &&
  8237. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8238. return null;
  8239. }
  8240. else {
  8241. const filter = function (write) {
  8242. return ((write.visible || includeHiddenWrites) &&
  8243. (!writeIdsToExclude ||
  8244. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8245. (pathContains(write.path, treePath) ||
  8246. pathContains(treePath, write.path)));
  8247. };
  8248. const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8249. const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8250. return compoundWriteApply(mergeAtPath, layeredCache);
  8251. }
  8252. }
  8253. }
  8254. }
  8255. /**
  8256. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8257. * Used when creating new views, to pre-fill their complete event children snapshot.
  8258. */
  8259. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8260. let completeChildren = ChildrenNode.EMPTY_NODE;
  8261. const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8262. if (topLevelSet) {
  8263. if (!topLevelSet.isLeafNode()) {
  8264. // we're shadowing everything. Return the children.
  8265. topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
  8266. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8267. });
  8268. }
  8269. return completeChildren;
  8270. }
  8271. else if (completeServerChildren) {
  8272. // Layer any children we have on top of this
  8273. // We know we don't have a top-level set, so just enumerate existing children
  8274. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8275. completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  8276. const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
  8277. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8278. });
  8279. // Add any complete children we have from the set
  8280. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8281. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8282. });
  8283. return completeChildren;
  8284. }
  8285. else {
  8286. // We don't have anything to layer on top of. Layer on any children we have
  8287. // Note that we can return an empty snap if we have a defined delete
  8288. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8289. compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
  8290. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8291. });
  8292. return completeChildren;
  8293. }
  8294. }
  8295. /**
  8296. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8297. * applied to the event cache.
  8298. *
  8299. * Possibilities:
  8300. *
  8301. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8302. *
  8303. * 2. Some write is completely shadowing. No events to be raised
  8304. *
  8305. * 3. Is partially shadowed. Events
  8306. *
  8307. * Either existingEventSnap or existingServerSnap must exist
  8308. */
  8309. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8310. assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8311. const path = pathChild(treePath, childPath);
  8312. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8313. // At this point we can probably guarantee that we're in case 2, meaning no events
  8314. // May need to check visibility while doing the findRootMostValueAndPath call
  8315. return null;
  8316. }
  8317. else {
  8318. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8319. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8320. if (compoundWriteIsEmpty(childMerge)) {
  8321. // We're not shadowing at all. Case 1
  8322. return existingServerSnap.getChild(childPath);
  8323. }
  8324. else {
  8325. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8326. // However this is tricky to find out, since user updates don't necessary change the server
  8327. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8328. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8329. // only check if the updates change the serverNode.
  8330. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8331. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8332. }
  8333. }
  8334. }
  8335. /**
  8336. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8337. * complete child for this ChildKey.
  8338. */
  8339. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8340. const path = pathChild(treePath, childKey);
  8341. const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8342. if (shadowingNode != null) {
  8343. return shadowingNode;
  8344. }
  8345. else {
  8346. if (existingServerSnap.isCompleteForChild(childKey)) {
  8347. const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8348. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8349. }
  8350. else {
  8351. return null;
  8352. }
  8353. }
  8354. }
  8355. /**
  8356. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8357. * a higher path, this will return the child of that write relative to the write and this path.
  8358. * Returns null if there is no write at this path.
  8359. */
  8360. function writeTreeShadowingWrite(writeTree, path) {
  8361. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8362. }
  8363. /**
  8364. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8365. * the window, but may now be in the window.
  8366. */
  8367. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8368. let toIterate;
  8369. const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8370. const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8371. if (shadowingNode != null) {
  8372. toIterate = shadowingNode;
  8373. }
  8374. else if (completeServerData != null) {
  8375. toIterate = compoundWriteApply(merge, completeServerData);
  8376. }
  8377. else {
  8378. // no children to iterate on
  8379. return [];
  8380. }
  8381. toIterate = toIterate.withIndex(index);
  8382. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8383. const nodes = [];
  8384. const cmp = index.getCompare();
  8385. const iter = reverse
  8386. ? toIterate.getReverseIteratorFrom(startPost, index)
  8387. : toIterate.getIteratorFrom(startPost, index);
  8388. let next = iter.getNext();
  8389. while (next && nodes.length < count) {
  8390. if (cmp(next, startPost) !== 0) {
  8391. nodes.push(next);
  8392. }
  8393. next = iter.getNext();
  8394. }
  8395. return nodes;
  8396. }
  8397. else {
  8398. return [];
  8399. }
  8400. }
  8401. function newWriteTree() {
  8402. return {
  8403. visibleWrites: CompoundWrite.empty(),
  8404. allWrites: [],
  8405. lastWriteId: -1
  8406. };
  8407. }
  8408. /**
  8409. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8410. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8411. * can lead to a more expensive calculation.
  8412. *
  8413. * @param writeIdsToExclude - Optional writes to exclude.
  8414. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8415. */
  8416. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8417. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8418. }
  8419. /**
  8420. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8421. * mix of the given server data and write data.
  8422. *
  8423. */
  8424. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8425. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8426. }
  8427. /**
  8428. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8429. * if anything, needs to be applied to the event cache.
  8430. *
  8431. * Possibilities:
  8432. *
  8433. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8434. *
  8435. * 2. Some write is completely shadowing. No events to be raised
  8436. *
  8437. * 3. Is partially shadowed. Events should be raised
  8438. *
  8439. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8440. *
  8441. *
  8442. */
  8443. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8444. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8445. }
  8446. /**
  8447. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8448. * a higher path, this will return the child of that write relative to the write and this path.
  8449. * Returns null if there is no write at this path.
  8450. *
  8451. */
  8452. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8453. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8454. }
  8455. /**
  8456. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8457. * the window, but may now be in the window
  8458. */
  8459. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8460. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8461. }
  8462. /**
  8463. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8464. * complete child for this ChildKey.
  8465. */
  8466. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8467. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8468. }
  8469. /**
  8470. * Return a WriteTreeRef for a child.
  8471. */
  8472. function writeTreeRefChild(writeTreeRef, childName) {
  8473. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8474. }
  8475. function newWriteTreeRef(path, writeTree) {
  8476. return {
  8477. treePath: path,
  8478. writeTree
  8479. };
  8480. }
  8481. /**
  8482. * @license
  8483. * Copyright 2017 Google LLC
  8484. *
  8485. * Licensed under the Apache License, Version 2.0 (the "License");
  8486. * you may not use this file except in compliance with the License.
  8487. * You may obtain a copy of the License at
  8488. *
  8489. * http://www.apache.org/licenses/LICENSE-2.0
  8490. *
  8491. * Unless required by applicable law or agreed to in writing, software
  8492. * distributed under the License is distributed on an "AS IS" BASIS,
  8493. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8494. * See the License for the specific language governing permissions and
  8495. * limitations under the License.
  8496. */
  8497. class ChildChangeAccumulator {
  8498. constructor() {
  8499. this.changeMap = new Map();
  8500. }
  8501. trackChildChange(change) {
  8502. const type = change.type;
  8503. const childKey = change.childName;
  8504. assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8505. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8506. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8507. assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8508. const oldChange = this.changeMap.get(childKey);
  8509. if (oldChange) {
  8510. const oldType = oldChange.type;
  8511. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8512. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8513. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8514. }
  8515. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8516. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8517. this.changeMap.delete(childKey);
  8518. }
  8519. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8520. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8521. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8522. }
  8523. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8524. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8525. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8526. }
  8527. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8528. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8529. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8530. }
  8531. else {
  8532. throw assertionError('Illegal combination of changes: ' +
  8533. change +
  8534. ' occurred after ' +
  8535. oldChange);
  8536. }
  8537. }
  8538. else {
  8539. this.changeMap.set(childKey, change);
  8540. }
  8541. }
  8542. getChanges() {
  8543. return Array.from(this.changeMap.values());
  8544. }
  8545. }
  8546. /**
  8547. * @license
  8548. * Copyright 2017 Google LLC
  8549. *
  8550. * Licensed under the Apache License, Version 2.0 (the "License");
  8551. * you may not use this file except in compliance with the License.
  8552. * You may obtain a copy of the License at
  8553. *
  8554. * http://www.apache.org/licenses/LICENSE-2.0
  8555. *
  8556. * Unless required by applicable law or agreed to in writing, software
  8557. * distributed under the License is distributed on an "AS IS" BASIS,
  8558. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8559. * See the License for the specific language governing permissions and
  8560. * limitations under the License.
  8561. */
  8562. /**
  8563. * An implementation of CompleteChildSource that never returns any additional children
  8564. */
  8565. // eslint-disable-next-line @typescript-eslint/naming-convention
  8566. class NoCompleteChildSource_ {
  8567. getCompleteChild(childKey) {
  8568. return null;
  8569. }
  8570. getChildAfterChild(index, child, reverse) {
  8571. return null;
  8572. }
  8573. }
  8574. /**
  8575. * Singleton instance.
  8576. */
  8577. const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8578. /**
  8579. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8580. * old event caches available to calculate complete children.
  8581. */
  8582. class WriteTreeCompleteChildSource {
  8583. constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
  8584. this.writes_ = writes_;
  8585. this.viewCache_ = viewCache_;
  8586. this.optCompleteServerCache_ = optCompleteServerCache_;
  8587. }
  8588. getCompleteChild(childKey) {
  8589. const node = this.viewCache_.eventCache;
  8590. if (node.isCompleteForChild(childKey)) {
  8591. return node.getNode().getImmediateChild(childKey);
  8592. }
  8593. else {
  8594. const serverNode = this.optCompleteServerCache_ != null
  8595. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8596. : this.viewCache_.serverCache;
  8597. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8598. }
  8599. }
  8600. getChildAfterChild(index, child, reverse) {
  8601. const completeServerData = this.optCompleteServerCache_ != null
  8602. ? this.optCompleteServerCache_
  8603. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8604. const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8605. if (nodes.length === 0) {
  8606. return null;
  8607. }
  8608. else {
  8609. return nodes[0];
  8610. }
  8611. }
  8612. }
  8613. /**
  8614. * @license
  8615. * Copyright 2017 Google LLC
  8616. *
  8617. * Licensed under the Apache License, Version 2.0 (the "License");
  8618. * you may not use this file except in compliance with the License.
  8619. * You may obtain a copy of the License at
  8620. *
  8621. * http://www.apache.org/licenses/LICENSE-2.0
  8622. *
  8623. * Unless required by applicable law or agreed to in writing, software
  8624. * distributed under the License is distributed on an "AS IS" BASIS,
  8625. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8626. * See the License for the specific language governing permissions and
  8627. * limitations under the License.
  8628. */
  8629. function newViewProcessor(filter) {
  8630. return { filter };
  8631. }
  8632. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8633. assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8634. assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8635. }
  8636. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8637. const accumulator = new ChildChangeAccumulator();
  8638. let newViewCache, filterServerNode;
  8639. if (operation.type === OperationType.OVERWRITE) {
  8640. const overwrite = operation;
  8641. if (overwrite.source.fromUser) {
  8642. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8643. }
  8644. else {
  8645. assert(overwrite.source.fromServer, 'Unknown source.');
  8646. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8647. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8648. // again
  8649. filterServerNode =
  8650. overwrite.source.tagged ||
  8651. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8652. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8653. }
  8654. }
  8655. else if (operation.type === OperationType.MERGE) {
  8656. const merge = operation;
  8657. if (merge.source.fromUser) {
  8658. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8659. }
  8660. else {
  8661. assert(merge.source.fromServer, 'Unknown source.');
  8662. // We filter the node if it's a tagged update or the node has been previously filtered
  8663. filterServerNode =
  8664. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8665. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8666. }
  8667. }
  8668. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8669. const ackUserWrite = operation;
  8670. if (!ackUserWrite.revert) {
  8671. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8672. }
  8673. else {
  8674. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8675. }
  8676. }
  8677. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8678. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8679. }
  8680. else {
  8681. throw assertionError('Unknown operation type: ' + operation.type);
  8682. }
  8683. const changes = accumulator.getChanges();
  8684. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8685. return { viewCache: newViewCache, changes };
  8686. }
  8687. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8688. const eventSnap = newViewCache.eventCache;
  8689. if (eventSnap.isFullyInitialized()) {
  8690. const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8691. const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8692. if (accumulator.length > 0 ||
  8693. !oldViewCache.eventCache.isFullyInitialized() ||
  8694. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8695. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8696. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8697. }
  8698. }
  8699. }
  8700. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8701. const oldEventSnap = viewCache.eventCache;
  8702. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8703. // we have a shadowing write, ignore changes
  8704. return viewCache;
  8705. }
  8706. else {
  8707. let newEventCache, serverNode;
  8708. if (pathIsEmpty(changePath)) {
  8709. // TODO: figure out how this plays with "sliding ack windows"
  8710. assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8711. if (viewCache.serverCache.isFiltered()) {
  8712. // We need to special case this, because we need to only apply writes to complete children, or
  8713. // we might end up raising events for incomplete children. If the server data is filtered deep
  8714. // writes cannot be guaranteed to be complete
  8715. const serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8716. const completeChildren = serverCache instanceof ChildrenNode
  8717. ? serverCache
  8718. : ChildrenNode.EMPTY_NODE;
  8719. const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8720. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8721. }
  8722. else {
  8723. const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8724. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8725. }
  8726. }
  8727. else {
  8728. const childKey = pathGetFront(changePath);
  8729. if (childKey === '.priority') {
  8730. assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8731. const oldEventNode = oldEventSnap.getNode();
  8732. serverNode = viewCache.serverCache.getNode();
  8733. // we might have overwrites for this priority
  8734. const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8735. if (updatedPriority != null) {
  8736. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8737. }
  8738. else {
  8739. // priority didn't change, keep old node
  8740. newEventCache = oldEventSnap.getNode();
  8741. }
  8742. }
  8743. else {
  8744. const childChangePath = pathPopFront(changePath);
  8745. // update child
  8746. let newEventChild;
  8747. if (oldEventSnap.isCompleteForChild(childKey)) {
  8748. serverNode = viewCache.serverCache.getNode();
  8749. const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  8750. if (eventChildUpdate != null) {
  8751. newEventChild = oldEventSnap
  8752. .getNode()
  8753. .getImmediateChild(childKey)
  8754. .updateChild(childChangePath, eventChildUpdate);
  8755. }
  8756. else {
  8757. // Nothing changed, just keep the old child
  8758. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8759. }
  8760. }
  8761. else {
  8762. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  8763. }
  8764. if (newEventChild != null) {
  8765. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  8766. }
  8767. else {
  8768. // no complete child available or no change
  8769. newEventCache = oldEventSnap.getNode();
  8770. }
  8771. }
  8772. }
  8773. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  8774. }
  8775. }
  8776. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  8777. const oldServerSnap = oldViewCache.serverCache;
  8778. let newServerCache;
  8779. const serverFilter = filterServerNode
  8780. ? viewProcessor.filter
  8781. : viewProcessor.filter.getIndexedFilter();
  8782. if (pathIsEmpty(changePath)) {
  8783. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  8784. }
  8785. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  8786. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  8787. const newServerNode = oldServerSnap
  8788. .getNode()
  8789. .updateChild(changePath, changedSnap);
  8790. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  8791. }
  8792. else {
  8793. const childKey = pathGetFront(changePath);
  8794. if (!oldServerSnap.isCompleteForPath(changePath) &&
  8795. pathGetLength(changePath) > 1) {
  8796. // We don't update incomplete nodes with updates intended for other listeners
  8797. return oldViewCache;
  8798. }
  8799. const childChangePath = pathPopFront(changePath);
  8800. const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  8801. const newChildNode = childNode.updateChild(childChangePath, changedSnap);
  8802. if (childKey === '.priority') {
  8803. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  8804. }
  8805. else {
  8806. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  8807. }
  8808. }
  8809. const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  8810. const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  8811. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  8812. }
  8813. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  8814. const oldEventSnap = oldViewCache.eventCache;
  8815. let newViewCache, newEventCache;
  8816. const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  8817. if (pathIsEmpty(changePath)) {
  8818. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  8819. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  8820. }
  8821. else {
  8822. const childKey = pathGetFront(changePath);
  8823. if (childKey === '.priority') {
  8824. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  8825. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  8826. }
  8827. else {
  8828. const childChangePath = pathPopFront(changePath);
  8829. const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  8830. let newChild;
  8831. if (pathIsEmpty(childChangePath)) {
  8832. // Child overwrite, we can replace the child
  8833. newChild = changedSnap;
  8834. }
  8835. else {
  8836. const childNode = source.getCompleteChild(childKey);
  8837. if (childNode != null) {
  8838. if (pathGetBack(childChangePath) === '.priority' &&
  8839. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  8840. // This is a priority update on an empty node. If this node exists on the server, the
  8841. // server will send down the priority in the update, so ignore for now
  8842. newChild = childNode;
  8843. }
  8844. else {
  8845. newChild = childNode.updateChild(childChangePath, changedSnap);
  8846. }
  8847. }
  8848. else {
  8849. // There is no complete child node available
  8850. newChild = ChildrenNode.EMPTY_NODE;
  8851. }
  8852. }
  8853. if (!oldChild.equals(newChild)) {
  8854. const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  8855. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  8856. }
  8857. else {
  8858. newViewCache = oldViewCache;
  8859. }
  8860. }
  8861. }
  8862. return newViewCache;
  8863. }
  8864. function viewProcessorCacheHasChild(viewCache, childKey) {
  8865. return viewCache.eventCache.isCompleteForChild(childKey);
  8866. }
  8867. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  8868. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8869. // window leaving room for new items. It's important we process these changes first, so we
  8870. // iterate the changes twice, first processing any that affect items currently in view.
  8871. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8872. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8873. // not the other.
  8874. let curViewCache = viewCache;
  8875. changedChildren.foreach((relativePath, childNode) => {
  8876. const writePath = pathChild(path, relativePath);
  8877. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8878. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8879. }
  8880. });
  8881. changedChildren.foreach((relativePath, childNode) => {
  8882. const writePath = pathChild(path, relativePath);
  8883. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  8884. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  8885. }
  8886. });
  8887. return curViewCache;
  8888. }
  8889. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  8890. merge.foreach((relativePath, childNode) => {
  8891. node = node.updateChild(relativePath, childNode);
  8892. });
  8893. return node;
  8894. }
  8895. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  8896. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  8897. // wait for the complete data update coming soon.
  8898. if (viewCache.serverCache.getNode().isEmpty() &&
  8899. !viewCache.serverCache.isFullyInitialized()) {
  8900. return viewCache;
  8901. }
  8902. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  8903. // window leaving room for new items. It's important we process these changes first, so we
  8904. // iterate the changes twice, first processing any that affect items currently in view.
  8905. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  8906. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  8907. // not the other.
  8908. let curViewCache = viewCache;
  8909. let viewMergeTree;
  8910. if (pathIsEmpty(path)) {
  8911. viewMergeTree = changedChildren;
  8912. }
  8913. else {
  8914. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  8915. }
  8916. const serverNode = viewCache.serverCache.getNode();
  8917. viewMergeTree.children.inorderTraversal((childKey, childTree) => {
  8918. if (serverNode.hasChild(childKey)) {
  8919. const serverChild = viewCache.serverCache
  8920. .getNode()
  8921. .getImmediateChild(childKey);
  8922. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  8923. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8924. }
  8925. });
  8926. viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
  8927. const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  8928. childMergeTree.value === null;
  8929. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  8930. const serverChild = viewCache.serverCache
  8931. .getNode()
  8932. .getImmediateChild(childKey);
  8933. const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  8934. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  8935. }
  8936. });
  8937. return curViewCache;
  8938. }
  8939. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  8940. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  8941. return viewCache;
  8942. }
  8943. // Only filter server node if it is currently filtered
  8944. const filterServerNode = viewCache.serverCache.isFiltered();
  8945. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  8946. // now that it won't be shadowed.
  8947. const serverCache = viewCache.serverCache;
  8948. if (affectedTree.value != null) {
  8949. // This is an overwrite.
  8950. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  8951. serverCache.isCompleteForPath(ackPath)) {
  8952. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  8953. }
  8954. else if (pathIsEmpty(ackPath)) {
  8955. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  8956. // should just re-apply whatever we have in our cache as a merge.
  8957. let changedChildren = new ImmutableTree(null);
  8958. serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
  8959. changedChildren = changedChildren.set(new Path(name), node);
  8960. });
  8961. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8962. }
  8963. else {
  8964. return viewCache;
  8965. }
  8966. }
  8967. else {
  8968. // This is a merge.
  8969. let changedChildren = new ImmutableTree(null);
  8970. affectedTree.foreach((mergePath, value) => {
  8971. const serverCachePath = pathChild(ackPath, mergePath);
  8972. if (serverCache.isCompleteForPath(serverCachePath)) {
  8973. changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  8974. }
  8975. });
  8976. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
  8977. }
  8978. }
  8979. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  8980. const oldServerNode = viewCache.serverCache;
  8981. const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  8982. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  8983. }
  8984. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  8985. let complete;
  8986. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  8987. return viewCache;
  8988. }
  8989. else {
  8990. const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  8991. const oldEventCache = viewCache.eventCache.getNode();
  8992. let newEventCache;
  8993. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  8994. let newNode;
  8995. if (viewCache.serverCache.isFullyInitialized()) {
  8996. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8997. }
  8998. else {
  8999. const serverChildren = viewCache.serverCache.getNode();
  9000. assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9001. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9002. }
  9003. newNode = newNode;
  9004. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9005. }
  9006. else {
  9007. const childKey = pathGetFront(path);
  9008. let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9009. if (newChild == null &&
  9010. viewCache.serverCache.isCompleteForChild(childKey)) {
  9011. newChild = oldEventCache.getImmediateChild(childKey);
  9012. }
  9013. if (newChild != null) {
  9014. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9015. }
  9016. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9017. // No complete child available, delete the existing one, if any
  9018. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9019. }
  9020. else {
  9021. newEventCache = oldEventCache;
  9022. }
  9023. if (newEventCache.isEmpty() &&
  9024. viewCache.serverCache.isFullyInitialized()) {
  9025. // We might have reverted all child writes. Maybe the old event was a leaf node
  9026. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9027. if (complete.isLeafNode()) {
  9028. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9029. }
  9030. }
  9031. }
  9032. complete =
  9033. viewCache.serverCache.isFullyInitialized() ||
  9034. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9035. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9036. }
  9037. }
  9038. /**
  9039. * @license
  9040. * Copyright 2017 Google LLC
  9041. *
  9042. * Licensed under the Apache License, Version 2.0 (the "License");
  9043. * you may not use this file except in compliance with the License.
  9044. * You may obtain a copy of the License at
  9045. *
  9046. * http://www.apache.org/licenses/LICENSE-2.0
  9047. *
  9048. * Unless required by applicable law or agreed to in writing, software
  9049. * distributed under the License is distributed on an "AS IS" BASIS,
  9050. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9051. * See the License for the specific language governing permissions and
  9052. * limitations under the License.
  9053. */
  9054. /**
  9055. * A view represents a specific location and query that has 1 or more event registrations.
  9056. *
  9057. * It does several things:
  9058. * - Maintains the list of event registrations for this location/query.
  9059. * - Maintains a cache of the data visible for this location/query.
  9060. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9061. * registrations returns the set of events to be raised.
  9062. */
  9063. class View {
  9064. constructor(query_, initialViewCache) {
  9065. this.query_ = query_;
  9066. this.eventRegistrations_ = [];
  9067. const params = this.query_._queryParams;
  9068. const indexFilter = new IndexedFilter(params.getIndex());
  9069. const filter = queryParamsGetNodeFilter(params);
  9070. this.processor_ = newViewProcessor(filter);
  9071. const initialServerCache = initialViewCache.serverCache;
  9072. const initialEventCache = initialViewCache.eventCache;
  9073. // Don't filter server node with other filter than index, wait for tagged listen
  9074. const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9075. const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9076. const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9077. const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9078. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9079. this.eventGenerator_ = new EventGenerator(this.query_);
  9080. }
  9081. get query() {
  9082. return this.query_;
  9083. }
  9084. }
  9085. function viewGetServerCache(view) {
  9086. return view.viewCache_.serverCache.getNode();
  9087. }
  9088. function viewGetCompleteNode(view) {
  9089. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9090. }
  9091. function viewGetCompleteServerCache(view, path) {
  9092. const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9093. if (cache) {
  9094. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9095. // we need to see if it contains the child we're interested in.
  9096. if (view.query._queryParams.loadsAllData() ||
  9097. (!pathIsEmpty(path) &&
  9098. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9099. return cache.getChild(path);
  9100. }
  9101. }
  9102. return null;
  9103. }
  9104. function viewIsEmpty(view) {
  9105. return view.eventRegistrations_.length === 0;
  9106. }
  9107. function viewAddEventRegistration(view, eventRegistration) {
  9108. view.eventRegistrations_.push(eventRegistration);
  9109. }
  9110. /**
  9111. * @param eventRegistration - If null, remove all callbacks.
  9112. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9113. * @returns Cancel events, if cancelError was provided.
  9114. */
  9115. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9116. const cancelEvents = [];
  9117. if (cancelError) {
  9118. assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9119. const path = view.query._path;
  9120. view.eventRegistrations_.forEach(registration => {
  9121. const maybeEvent = registration.createCancelEvent(cancelError, path);
  9122. if (maybeEvent) {
  9123. cancelEvents.push(maybeEvent);
  9124. }
  9125. });
  9126. }
  9127. if (eventRegistration) {
  9128. let remaining = [];
  9129. for (let i = 0; i < view.eventRegistrations_.length; ++i) {
  9130. const existing = view.eventRegistrations_[i];
  9131. if (!existing.matches(eventRegistration)) {
  9132. remaining.push(existing);
  9133. }
  9134. else if (eventRegistration.hasAnyCallback()) {
  9135. // We're removing just this one
  9136. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9137. break;
  9138. }
  9139. }
  9140. view.eventRegistrations_ = remaining;
  9141. }
  9142. else {
  9143. view.eventRegistrations_ = [];
  9144. }
  9145. return cancelEvents;
  9146. }
  9147. /**
  9148. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9149. */
  9150. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9151. if (operation.type === OperationType.MERGE &&
  9152. operation.source.queryId !== null) {
  9153. assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9154. assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9155. }
  9156. const oldViewCache = view.viewCache_;
  9157. const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9158. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9159. assert(result.viewCache.serverCache.isFullyInitialized() ||
  9160. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9161. view.viewCache_ = result.viewCache;
  9162. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9163. }
  9164. function viewGetInitialEvents(view, registration) {
  9165. const eventSnap = view.viewCache_.eventCache;
  9166. const initialChanges = [];
  9167. if (!eventSnap.getNode().isLeafNode()) {
  9168. const eventNode = eventSnap.getNode();
  9169. eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
  9170. initialChanges.push(changeChildAdded(key, childNode));
  9171. });
  9172. }
  9173. if (eventSnap.isFullyInitialized()) {
  9174. initialChanges.push(changeValue(eventSnap.getNode()));
  9175. }
  9176. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9177. }
  9178. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9179. const registrations = eventRegistration
  9180. ? [eventRegistration]
  9181. : view.eventRegistrations_;
  9182. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9183. }
  9184. /**
  9185. * @license
  9186. * Copyright 2017 Google LLC
  9187. *
  9188. * Licensed under the Apache License, Version 2.0 (the "License");
  9189. * you may not use this file except in compliance with the License.
  9190. * You may obtain a copy of the License at
  9191. *
  9192. * http://www.apache.org/licenses/LICENSE-2.0
  9193. *
  9194. * Unless required by applicable law or agreed to in writing, software
  9195. * distributed under the License is distributed on an "AS IS" BASIS,
  9196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9197. * See the License for the specific language governing permissions and
  9198. * limitations under the License.
  9199. */
  9200. let referenceConstructor$1;
  9201. /**
  9202. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9203. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9204. * and user writes (set, transaction, update).
  9205. *
  9206. * It's responsible for:
  9207. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9208. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9209. * applyUserOverwrite, etc.)
  9210. */
  9211. class SyncPoint {
  9212. constructor() {
  9213. /**
  9214. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9215. * queryId and the value is the View for that query.
  9216. *
  9217. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9218. */
  9219. this.views = new Map();
  9220. }
  9221. }
  9222. function syncPointSetReferenceConstructor(val) {
  9223. assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9224. referenceConstructor$1 = val;
  9225. }
  9226. function syncPointGetReferenceConstructor() {
  9227. assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9228. return referenceConstructor$1;
  9229. }
  9230. function syncPointIsEmpty(syncPoint) {
  9231. return syncPoint.views.size === 0;
  9232. }
  9233. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9234. const queryId = operation.source.queryId;
  9235. if (queryId !== null) {
  9236. const view = syncPoint.views.get(queryId);
  9237. assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9238. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9239. }
  9240. else {
  9241. let events = [];
  9242. for (const view of syncPoint.views.values()) {
  9243. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9244. }
  9245. return events;
  9246. }
  9247. }
  9248. /**
  9249. * Get a view for the specified query.
  9250. *
  9251. * @param query - The query to return a view for
  9252. * @param writesCache
  9253. * @param serverCache
  9254. * @param serverCacheComplete
  9255. * @returns Events to raise.
  9256. */
  9257. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9258. const queryId = query._queryIdentifier;
  9259. const view = syncPoint.views.get(queryId);
  9260. if (!view) {
  9261. // TODO: make writesCache take flag for complete server node
  9262. let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9263. let eventCacheComplete = false;
  9264. if (eventCache) {
  9265. eventCacheComplete = true;
  9266. }
  9267. else if (serverCache instanceof ChildrenNode) {
  9268. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9269. eventCacheComplete = false;
  9270. }
  9271. else {
  9272. eventCache = ChildrenNode.EMPTY_NODE;
  9273. eventCacheComplete = false;
  9274. }
  9275. const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9276. return new View(query, viewCache);
  9277. }
  9278. return view;
  9279. }
  9280. /**
  9281. * Add an event callback for the specified query.
  9282. *
  9283. * @param query
  9284. * @param eventRegistration
  9285. * @param writesCache
  9286. * @param serverCache - Complete server cache, if we have it.
  9287. * @param serverCacheComplete
  9288. * @returns Events to raise.
  9289. */
  9290. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9291. const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9292. if (!syncPoint.views.has(query._queryIdentifier)) {
  9293. syncPoint.views.set(query._queryIdentifier, view);
  9294. }
  9295. // This is guaranteed to exist now, we just created anything that was missing
  9296. viewAddEventRegistration(view, eventRegistration);
  9297. return viewGetInitialEvents(view, eventRegistration);
  9298. }
  9299. /**
  9300. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9301. *
  9302. * If query is the default query, we'll check all views for the specified eventRegistration.
  9303. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9304. *
  9305. * @param eventRegistration - If null, remove all callbacks.
  9306. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9307. * @returns removed queries and any cancel events
  9308. */
  9309. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9310. const queryId = query._queryIdentifier;
  9311. const removed = [];
  9312. let cancelEvents = [];
  9313. const hadCompleteView = syncPointHasCompleteView(syncPoint);
  9314. if (queryId === 'default') {
  9315. // When you do ref.off(...), we search all views for the registration to remove.
  9316. for (const [viewQueryId, view] of syncPoint.views.entries()) {
  9317. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9318. if (viewIsEmpty(view)) {
  9319. syncPoint.views.delete(viewQueryId);
  9320. // We'll deal with complete views later.
  9321. if (!view.query._queryParams.loadsAllData()) {
  9322. removed.push(view.query);
  9323. }
  9324. }
  9325. }
  9326. }
  9327. else {
  9328. // remove the callback from the specific view.
  9329. const view = syncPoint.views.get(queryId);
  9330. if (view) {
  9331. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9332. if (viewIsEmpty(view)) {
  9333. syncPoint.views.delete(queryId);
  9334. // We'll deal with complete views later.
  9335. if (!view.query._queryParams.loadsAllData()) {
  9336. removed.push(view.query);
  9337. }
  9338. }
  9339. }
  9340. }
  9341. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9342. // We removed our last complete view.
  9343. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9344. }
  9345. return { removed, events: cancelEvents };
  9346. }
  9347. function syncPointGetQueryViews(syncPoint) {
  9348. const result = [];
  9349. for (const view of syncPoint.views.values()) {
  9350. if (!view.query._queryParams.loadsAllData()) {
  9351. result.push(view);
  9352. }
  9353. }
  9354. return result;
  9355. }
  9356. /**
  9357. * @param path - The path to the desired complete snapshot
  9358. * @returns A complete cache, if it exists
  9359. */
  9360. function syncPointGetCompleteServerCache(syncPoint, path) {
  9361. let serverCache = null;
  9362. for (const view of syncPoint.views.values()) {
  9363. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9364. }
  9365. return serverCache;
  9366. }
  9367. function syncPointViewForQuery(syncPoint, query) {
  9368. const params = query._queryParams;
  9369. if (params.loadsAllData()) {
  9370. return syncPointGetCompleteView(syncPoint);
  9371. }
  9372. else {
  9373. const queryId = query._queryIdentifier;
  9374. return syncPoint.views.get(queryId);
  9375. }
  9376. }
  9377. function syncPointViewExistsForQuery(syncPoint, query) {
  9378. return syncPointViewForQuery(syncPoint, query) != null;
  9379. }
  9380. function syncPointHasCompleteView(syncPoint) {
  9381. return syncPointGetCompleteView(syncPoint) != null;
  9382. }
  9383. function syncPointGetCompleteView(syncPoint) {
  9384. for (const view of syncPoint.views.values()) {
  9385. if (view.query._queryParams.loadsAllData()) {
  9386. return view;
  9387. }
  9388. }
  9389. return null;
  9390. }
  9391. /**
  9392. * @license
  9393. * Copyright 2017 Google LLC
  9394. *
  9395. * Licensed under the Apache License, Version 2.0 (the "License");
  9396. * you may not use this file except in compliance with the License.
  9397. * You may obtain a copy of the License at
  9398. *
  9399. * http://www.apache.org/licenses/LICENSE-2.0
  9400. *
  9401. * Unless required by applicable law or agreed to in writing, software
  9402. * distributed under the License is distributed on an "AS IS" BASIS,
  9403. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9404. * See the License for the specific language governing permissions and
  9405. * limitations under the License.
  9406. */
  9407. let referenceConstructor;
  9408. function syncTreeSetReferenceConstructor(val) {
  9409. assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9410. referenceConstructor = val;
  9411. }
  9412. function syncTreeGetReferenceConstructor() {
  9413. assert(referenceConstructor, 'Reference.ts has not been loaded');
  9414. return referenceConstructor;
  9415. }
  9416. /**
  9417. * Static tracker for next query tag.
  9418. */
  9419. let syncTreeNextQueryTag_ = 1;
  9420. /**
  9421. * SyncTree is the central class for managing event callback registration, data caching, views
  9422. * (query processing), and event generation. There are typically two SyncTree instances for
  9423. * each Repo, one for the normal Firebase data, and one for the .info data.
  9424. *
  9425. * It has a number of responsibilities, including:
  9426. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9427. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9428. * (applyUserOverwrite(), applyUserMerge()).
  9429. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9430. * applyServerMerge()).
  9431. * - Generating user-facing events for server and user changes (all of the apply* methods
  9432. * return the set of events that need to be raised as a result).
  9433. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9434. * to the correct set of paths and queries to satisfy the current set of user event
  9435. * callbacks (listens are started/stopped using the provided listenProvider).
  9436. *
  9437. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9438. * events are returned to the caller rather than raised synchronously.
  9439. *
  9440. */
  9441. class SyncTree {
  9442. /**
  9443. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9444. * to server data.
  9445. */
  9446. constructor(listenProvider_) {
  9447. this.listenProvider_ = listenProvider_;
  9448. /**
  9449. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9450. */
  9451. this.syncPointTree_ = new ImmutableTree(null);
  9452. /**
  9453. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9454. */
  9455. this.pendingWriteTree_ = newWriteTree();
  9456. this.tagToQueryMap = new Map();
  9457. this.queryToTagMap = new Map();
  9458. }
  9459. }
  9460. /**
  9461. * Apply the data changes for a user-generated set() or transaction() call.
  9462. *
  9463. * @returns Events to raise.
  9464. */
  9465. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9466. // Record pending write.
  9467. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9468. if (!visible) {
  9469. return [];
  9470. }
  9471. else {
  9472. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9473. }
  9474. }
  9475. /**
  9476. * Apply the data from a user-generated update() call
  9477. *
  9478. * @returns Events to raise.
  9479. */
  9480. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9481. // Record pending merge.
  9482. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9483. const changeTree = ImmutableTree.fromObject(changedChildren);
  9484. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9485. }
  9486. /**
  9487. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9488. *
  9489. * @param revert - True if the given write failed and needs to be reverted
  9490. * @returns Events to raise.
  9491. */
  9492. function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
  9493. const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9494. const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9495. if (!needToReevaluate) {
  9496. return [];
  9497. }
  9498. else {
  9499. let affectedTree = new ImmutableTree(null);
  9500. if (write.snap != null) {
  9501. // overwrite
  9502. affectedTree = affectedTree.set(newEmptyPath(), true);
  9503. }
  9504. else {
  9505. each(write.children, (pathString) => {
  9506. affectedTree = affectedTree.set(new Path(pathString), true);
  9507. });
  9508. }
  9509. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
  9510. }
  9511. }
  9512. /**
  9513. * Apply new server data for the specified path..
  9514. *
  9515. * @returns Events to raise.
  9516. */
  9517. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9518. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9519. }
  9520. /**
  9521. * Apply new server data to be merged in at the specified path.
  9522. *
  9523. * @returns Events to raise.
  9524. */
  9525. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9526. const changeTree = ImmutableTree.fromObject(changedChildren);
  9527. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9528. }
  9529. /**
  9530. * Apply a listen complete for a query
  9531. *
  9532. * @returns Events to raise.
  9533. */
  9534. function syncTreeApplyListenComplete(syncTree, path) {
  9535. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9536. }
  9537. /**
  9538. * Apply a listen complete for a tagged query
  9539. *
  9540. * @returns Events to raise.
  9541. */
  9542. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9543. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9544. if (queryKey) {
  9545. const r = syncTreeParseQueryKey_(queryKey);
  9546. const queryPath = r.path, queryId = r.queryId;
  9547. const relativePath = newRelativePath(queryPath, path);
  9548. const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9549. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9550. }
  9551. else {
  9552. // We've already removed the query. No big deal, ignore the update
  9553. return [];
  9554. }
  9555. }
  9556. /**
  9557. * Remove event callback(s).
  9558. *
  9559. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9560. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9561. *
  9562. * @param eventRegistration - If null, all callbacks are removed.
  9563. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9564. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9565. * deduping needs to take place. This flag allows toggling of that behavior
  9566. * @returns Cancel events, if cancelError was provided.
  9567. */
  9568. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
  9569. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9570. const path = query._path;
  9571. const maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9572. let cancelEvents = [];
  9573. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9574. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9575. // not loadsAllData().
  9576. if (maybeSyncPoint &&
  9577. (query._queryIdentifier === 'default' ||
  9578. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9579. const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9580. if (syncPointIsEmpty(maybeSyncPoint)) {
  9581. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9582. }
  9583. const removed = removedAndEvents.removed;
  9584. cancelEvents = removedAndEvents.events;
  9585. if (!skipListenerDedup) {
  9586. /**
  9587. * We may have just removed one of many listeners and can short-circuit this whole process
  9588. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9589. * properly set up.
  9590. */
  9591. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9592. // queryId === 'default'
  9593. const removingDefault = -1 !==
  9594. removed.findIndex(query => {
  9595. return query._queryParams.loadsAllData();
  9596. });
  9597. const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
  9598. if (removingDefault && !covered) {
  9599. const subtree = syncTree.syncPointTree_.subtree(path);
  9600. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9601. // removal
  9602. if (!subtree.isEmpty()) {
  9603. // We need to fold over our subtree and collect the listeners to send
  9604. const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9605. // Ok, we've collected all the listens we need. Set them up.
  9606. for (let i = 0; i < newViews.length; ++i) {
  9607. const view = newViews[i], newQuery = view.query;
  9608. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9609. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9610. }
  9611. }
  9612. // Otherwise there's nothing below us, so nothing we need to start listening on
  9613. }
  9614. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9615. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9616. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9617. if (!covered && removed.length > 0 && !cancelError) {
  9618. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9619. // default. Otherwise, we need to iterate through and cancel each individual query
  9620. if (removingDefault) {
  9621. // We don't tag default listeners
  9622. const defaultTag = null;
  9623. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9624. }
  9625. else {
  9626. removed.forEach((queryToRemove) => {
  9627. const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9628. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9629. });
  9630. }
  9631. }
  9632. }
  9633. // Now, clear all of the tags we're tracking for the removed listens
  9634. syncTreeRemoveTags_(syncTree, removed);
  9635. }
  9636. return cancelEvents;
  9637. }
  9638. /**
  9639. * Apply new server data for the specified tagged query.
  9640. *
  9641. * @returns Events to raise.
  9642. */
  9643. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9644. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9645. if (queryKey != null) {
  9646. const r = syncTreeParseQueryKey_(queryKey);
  9647. const queryPath = r.path, queryId = r.queryId;
  9648. const relativePath = newRelativePath(queryPath, path);
  9649. const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9650. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9651. }
  9652. else {
  9653. // Query must have been removed already
  9654. return [];
  9655. }
  9656. }
  9657. /**
  9658. * Apply server data to be merged in for the specified tagged query.
  9659. *
  9660. * @returns Events to raise.
  9661. */
  9662. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9663. const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9664. if (queryKey) {
  9665. const r = syncTreeParseQueryKey_(queryKey);
  9666. const queryPath = r.path, queryId = r.queryId;
  9667. const relativePath = newRelativePath(queryPath, path);
  9668. const changeTree = ImmutableTree.fromObject(changedChildren);
  9669. const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9670. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9671. }
  9672. else {
  9673. // We've already removed the query. No big deal, ignore the update
  9674. return [];
  9675. }
  9676. }
  9677. /**
  9678. * Add an event callback for the specified query.
  9679. *
  9680. * @returns Events to raise.
  9681. */
  9682. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
  9683. const path = query._path;
  9684. let serverCache = null;
  9685. let foundAncestorDefaultView = false;
  9686. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9687. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9688. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9689. const relativePath = newRelativePath(pathToSyncPoint, path);
  9690. serverCache =
  9691. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9692. foundAncestorDefaultView =
  9693. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  9694. });
  9695. let syncPoint = syncTree.syncPointTree_.get(path);
  9696. if (!syncPoint) {
  9697. syncPoint = new SyncPoint();
  9698. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9699. }
  9700. else {
  9701. foundAncestorDefaultView =
  9702. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  9703. serverCache =
  9704. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9705. }
  9706. let serverCacheComplete;
  9707. if (serverCache != null) {
  9708. serverCacheComplete = true;
  9709. }
  9710. else {
  9711. serverCacheComplete = false;
  9712. serverCache = ChildrenNode.EMPTY_NODE;
  9713. const subtree = syncTree.syncPointTree_.subtree(path);
  9714. subtree.foreachChild((childName, childSyncPoint) => {
  9715. const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  9716. if (completeCache) {
  9717. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  9718. }
  9719. });
  9720. }
  9721. const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  9722. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  9723. // We need to track a tag for this query
  9724. const queryKey = syncTreeMakeQueryKey_(query);
  9725. assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  9726. const tag = syncTreeGetNextQueryTag_();
  9727. syncTree.queryToTagMap.set(queryKey, tag);
  9728. syncTree.tagToQueryMap.set(tag, queryKey);
  9729. }
  9730. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  9731. let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  9732. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  9733. const view = syncPointViewForQuery(syncPoint, query);
  9734. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  9735. }
  9736. return events;
  9737. }
  9738. /**
  9739. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  9740. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  9741. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  9742. * <incremented total> as the write is applied locally and then acknowledged at the server.
  9743. *
  9744. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  9745. *
  9746. * @param path - The path to the data we want
  9747. * @param writeIdsToExclude - A specific set to be excluded
  9748. */
  9749. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  9750. const includeHiddenSets = true;
  9751. const writeTree = syncTree.pendingWriteTree_;
  9752. const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
  9753. const relativePath = newRelativePath(pathSoFar, path);
  9754. const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  9755. if (serverCache) {
  9756. return serverCache;
  9757. }
  9758. });
  9759. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  9760. }
  9761. function syncTreeGetServerValue(syncTree, query) {
  9762. const path = query._path;
  9763. let serverCache = null;
  9764. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  9765. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  9766. syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
  9767. const relativePath = newRelativePath(pathToSyncPoint, path);
  9768. serverCache =
  9769. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  9770. });
  9771. let syncPoint = syncTree.syncPointTree_.get(path);
  9772. if (!syncPoint) {
  9773. syncPoint = new SyncPoint();
  9774. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  9775. }
  9776. else {
  9777. serverCache =
  9778. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9779. }
  9780. const serverCacheComplete = serverCache != null;
  9781. const serverCacheNode = serverCacheComplete
  9782. ? new CacheNode(serverCache, true, false)
  9783. : null;
  9784. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  9785. const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  9786. return viewGetCompleteNode(view);
  9787. }
  9788. /**
  9789. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  9790. *
  9791. * NOTES:
  9792. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  9793. *
  9794. * - We call applyOperation() on each SyncPoint passing three things:
  9795. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  9796. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  9797. * 3. A snapshot Node with cached server data, if we have it.
  9798. *
  9799. * - We concatenate all of the events returned by each SyncPoint and return the result.
  9800. */
  9801. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  9802. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  9803. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  9804. }
  9805. /**
  9806. * Recursive helper for applyOperationToSyncPoints_
  9807. */
  9808. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  9809. if (pathIsEmpty(operation.path)) {
  9810. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  9811. }
  9812. else {
  9813. const syncPoint = syncPointTree.get(newEmptyPath());
  9814. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9815. if (serverCache == null && syncPoint != null) {
  9816. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9817. }
  9818. let events = [];
  9819. const childName = pathGetFront(operation.path);
  9820. const childOperation = operation.operationForChild(childName);
  9821. const childTree = syncPointTree.children.get(childName);
  9822. if (childTree && childOperation) {
  9823. const childServerCache = serverCache
  9824. ? serverCache.getImmediateChild(childName)
  9825. : null;
  9826. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9827. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9828. }
  9829. if (syncPoint) {
  9830. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9831. }
  9832. return events;
  9833. }
  9834. }
  9835. /**
  9836. * Recursive helper for applyOperationToSyncPoints_
  9837. */
  9838. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  9839. const syncPoint = syncPointTree.get(newEmptyPath());
  9840. // If we don't have cached server data, see if we can get it from this SyncPoint.
  9841. if (serverCache == null && syncPoint != null) {
  9842. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  9843. }
  9844. let events = [];
  9845. syncPointTree.children.inorderTraversal((childName, childTree) => {
  9846. const childServerCache = serverCache
  9847. ? serverCache.getImmediateChild(childName)
  9848. : null;
  9849. const childWritesCache = writeTreeRefChild(writesCache, childName);
  9850. const childOperation = operation.operationForChild(childName);
  9851. if (childOperation) {
  9852. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  9853. }
  9854. });
  9855. if (syncPoint) {
  9856. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  9857. }
  9858. return events;
  9859. }
  9860. function syncTreeCreateListenerForView_(syncTree, view) {
  9861. const query = view.query;
  9862. const tag = syncTreeTagForQuery(syncTree, query);
  9863. return {
  9864. hashFn: () => {
  9865. const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  9866. return cache.hash();
  9867. },
  9868. onComplete: (status) => {
  9869. if (status === 'ok') {
  9870. if (tag) {
  9871. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  9872. }
  9873. else {
  9874. return syncTreeApplyListenComplete(syncTree, query._path);
  9875. }
  9876. }
  9877. else {
  9878. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  9879. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  9880. const error = errorForServerCode(status, query);
  9881. return syncTreeRemoveEventRegistration(syncTree, query,
  9882. /*eventRegistration*/ null, error);
  9883. }
  9884. }
  9885. };
  9886. }
  9887. /**
  9888. * Return the tag associated with the given query.
  9889. */
  9890. function syncTreeTagForQuery(syncTree, query) {
  9891. const queryKey = syncTreeMakeQueryKey_(query);
  9892. return syncTree.queryToTagMap.get(queryKey);
  9893. }
  9894. /**
  9895. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  9896. */
  9897. function syncTreeMakeQueryKey_(query) {
  9898. return query._path.toString() + '$' + query._queryIdentifier;
  9899. }
  9900. /**
  9901. * Return the query associated with the given tag, if we have one
  9902. */
  9903. function syncTreeQueryKeyForTag_(syncTree, tag) {
  9904. return syncTree.tagToQueryMap.get(tag);
  9905. }
  9906. /**
  9907. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  9908. */
  9909. function syncTreeParseQueryKey_(queryKey) {
  9910. const splitIndex = queryKey.indexOf('$');
  9911. assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  9912. return {
  9913. queryId: queryKey.substr(splitIndex + 1),
  9914. path: new Path(queryKey.substr(0, splitIndex))
  9915. };
  9916. }
  9917. /**
  9918. * A helper method to apply tagged operations
  9919. */
  9920. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  9921. const syncPoint = syncTree.syncPointTree_.get(queryPath);
  9922. assert(syncPoint, "Missing sync point for query tag that we're tracking");
  9923. const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  9924. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  9925. }
  9926. /**
  9927. * This collapses multiple unfiltered views into a single view, since we only need a single
  9928. * listener for them.
  9929. */
  9930. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  9931. return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  9932. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  9933. const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  9934. return [completeView];
  9935. }
  9936. else {
  9937. // No complete view here, flatten any deeper listens into an array
  9938. let views = [];
  9939. if (maybeChildSyncPoint) {
  9940. views = syncPointGetQueryViews(maybeChildSyncPoint);
  9941. }
  9942. each(childMap, (_key, childViews) => {
  9943. views = views.concat(childViews);
  9944. });
  9945. return views;
  9946. }
  9947. });
  9948. }
  9949. /**
  9950. * Normalizes a query to a query we send the server for listening
  9951. *
  9952. * @returns The normalized query
  9953. */
  9954. function syncTreeQueryForListening_(query) {
  9955. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  9956. // We treat queries that load all data as default queries
  9957. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  9958. // from Query
  9959. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  9960. }
  9961. else {
  9962. return query;
  9963. }
  9964. }
  9965. function syncTreeRemoveTags_(syncTree, queries) {
  9966. for (let j = 0; j < queries.length; ++j) {
  9967. const removedQuery = queries[j];
  9968. if (!removedQuery._queryParams.loadsAllData()) {
  9969. // We should have a tag for this
  9970. const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  9971. const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  9972. syncTree.queryToTagMap.delete(removedQueryKey);
  9973. syncTree.tagToQueryMap.delete(removedQueryTag);
  9974. }
  9975. }
  9976. }
  9977. /**
  9978. * Static accessor for query tags.
  9979. */
  9980. function syncTreeGetNextQueryTag_() {
  9981. return syncTreeNextQueryTag_++;
  9982. }
  9983. /**
  9984. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  9985. *
  9986. * @returns This method can return events to support synchronous data sources
  9987. */
  9988. function syncTreeSetupListener_(syncTree, query, view) {
  9989. const path = query._path;
  9990. const tag = syncTreeTagForQuery(syncTree, query);
  9991. const listener = syncTreeCreateListenerForView_(syncTree, view);
  9992. const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  9993. const subtree = syncTree.syncPointTree_.subtree(path);
  9994. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  9995. // may need to shadow other listens as well.
  9996. if (tag) {
  9997. assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  9998. }
  9999. else {
  10000. // Shadow everything at or below this location, this is a default listener.
  10001. const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
  10002. if (!pathIsEmpty(relativePath) &&
  10003. maybeChildSyncPoint &&
  10004. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10005. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10006. }
  10007. else {
  10008. // No default listener here, flatten any deeper queries into an array
  10009. let queries = [];
  10010. if (maybeChildSyncPoint) {
  10011. queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
  10012. }
  10013. each(childMap, (_key, childQueries) => {
  10014. queries = queries.concat(childQueries);
  10015. });
  10016. return queries;
  10017. }
  10018. });
  10019. for (let i = 0; i < queriesToStop.length; ++i) {
  10020. const queryToStop = queriesToStop[i];
  10021. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10022. }
  10023. }
  10024. return events;
  10025. }
  10026. /**
  10027. * @license
  10028. * Copyright 2017 Google LLC
  10029. *
  10030. * Licensed under the Apache License, Version 2.0 (the "License");
  10031. * you may not use this file except in compliance with the License.
  10032. * You may obtain a copy of the License at
  10033. *
  10034. * http://www.apache.org/licenses/LICENSE-2.0
  10035. *
  10036. * Unless required by applicable law or agreed to in writing, software
  10037. * distributed under the License is distributed on an "AS IS" BASIS,
  10038. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10039. * See the License for the specific language governing permissions and
  10040. * limitations under the License.
  10041. */
  10042. class ExistingValueProvider {
  10043. constructor(node_) {
  10044. this.node_ = node_;
  10045. }
  10046. getImmediateChild(childName) {
  10047. const child = this.node_.getImmediateChild(childName);
  10048. return new ExistingValueProvider(child);
  10049. }
  10050. node() {
  10051. return this.node_;
  10052. }
  10053. }
  10054. class DeferredValueProvider {
  10055. constructor(syncTree, path) {
  10056. this.syncTree_ = syncTree;
  10057. this.path_ = path;
  10058. }
  10059. getImmediateChild(childName) {
  10060. const childPath = pathChild(this.path_, childName);
  10061. return new DeferredValueProvider(this.syncTree_, childPath);
  10062. }
  10063. node() {
  10064. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10065. }
  10066. }
  10067. /**
  10068. * Generate placeholders for deferred values.
  10069. */
  10070. const generateWithValues = function (values) {
  10071. values = values || {};
  10072. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10073. return values;
  10074. };
  10075. /**
  10076. * Value to use when firing local events. When writing server values, fire
  10077. * local events with an approximate value, otherwise return value as-is.
  10078. */
  10079. const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10080. if (!value || typeof value !== 'object') {
  10081. return value;
  10082. }
  10083. assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10084. if (typeof value['.sv'] === 'string') {
  10085. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10086. }
  10087. else if (typeof value['.sv'] === 'object') {
  10088. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10089. }
  10090. else {
  10091. assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10092. }
  10093. };
  10094. const resolveScalarDeferredValue = function (op, existing, serverValues) {
  10095. switch (op) {
  10096. case 'timestamp':
  10097. return serverValues['timestamp'];
  10098. default:
  10099. assert(false, 'Unexpected server value: ' + op);
  10100. }
  10101. };
  10102. const resolveComplexDeferredValue = function (op, existing, unused) {
  10103. if (!op.hasOwnProperty('increment')) {
  10104. assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10105. }
  10106. const delta = op['increment'];
  10107. if (typeof delta !== 'number') {
  10108. assert(false, 'Unexpected increment value: ' + delta);
  10109. }
  10110. const existingNode = existing.node();
  10111. assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10112. // Incrementing a non-number sets the value to the incremented amount
  10113. if (!existingNode.isLeafNode()) {
  10114. return delta;
  10115. }
  10116. const leaf = existingNode;
  10117. const existingVal = leaf.getValue();
  10118. if (typeof existingVal !== 'number') {
  10119. return delta;
  10120. }
  10121. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10122. return existingVal + delta;
  10123. };
  10124. /**
  10125. * Recursively replace all deferred values and priorities in the tree with the
  10126. * specified generated replacement values.
  10127. * @param path - path to which write is relative
  10128. * @param node - new data written at path
  10129. * @param syncTree - current data
  10130. */
  10131. const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10132. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10133. };
  10134. /**
  10135. * Recursively replace all deferred values and priorities in the node with the
  10136. * specified generated replacement values. If there are no server values in the node,
  10137. * it'll be returned as-is.
  10138. */
  10139. const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10140. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10141. };
  10142. function resolveDeferredValue(node, existingVal, serverValues) {
  10143. const rawPri = node.getPriority().val();
  10144. const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10145. let newNode;
  10146. if (node.isLeafNode()) {
  10147. const leafNode = node;
  10148. const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10149. if (value !== leafNode.getValue() ||
  10150. priority !== leafNode.getPriority().val()) {
  10151. return new LeafNode(value, nodeFromJSON(priority));
  10152. }
  10153. else {
  10154. return node;
  10155. }
  10156. }
  10157. else {
  10158. const childrenNode = node;
  10159. newNode = childrenNode;
  10160. if (priority !== childrenNode.getPriority().val()) {
  10161. newNode = newNode.updatePriority(new LeafNode(priority));
  10162. }
  10163. childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
  10164. const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10165. if (newChildNode !== childNode) {
  10166. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10167. }
  10168. });
  10169. return newNode;
  10170. }
  10171. }
  10172. /**
  10173. * @license
  10174. * Copyright 2017 Google LLC
  10175. *
  10176. * Licensed under the Apache License, Version 2.0 (the "License");
  10177. * you may not use this file except in compliance with the License.
  10178. * You may obtain a copy of the License at
  10179. *
  10180. * http://www.apache.org/licenses/LICENSE-2.0
  10181. *
  10182. * Unless required by applicable law or agreed to in writing, software
  10183. * distributed under the License is distributed on an "AS IS" BASIS,
  10184. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10185. * See the License for the specific language governing permissions and
  10186. * limitations under the License.
  10187. */
  10188. /**
  10189. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10190. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10191. * children.
  10192. */
  10193. class Tree {
  10194. /**
  10195. * @param name - Optional name of the node.
  10196. * @param parent - Optional parent node.
  10197. * @param node - Optional node to wrap.
  10198. */
  10199. constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
  10200. this.name = name;
  10201. this.parent = parent;
  10202. this.node = node;
  10203. }
  10204. }
  10205. /**
  10206. * Returns a sub-Tree for the given path.
  10207. *
  10208. * @param pathObj - Path to look up.
  10209. * @returns Tree for path.
  10210. */
  10211. function treeSubTree(tree, pathObj) {
  10212. // TODO: Require pathObj to be Path?
  10213. let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10214. let child = tree, next = pathGetFront(path);
  10215. while (next !== null) {
  10216. const childNode = safeGet(child.node.children, next) || {
  10217. children: {},
  10218. childCount: 0
  10219. };
  10220. child = new Tree(next, child, childNode);
  10221. path = pathPopFront(path);
  10222. next = pathGetFront(path);
  10223. }
  10224. return child;
  10225. }
  10226. /**
  10227. * Returns the data associated with this tree node.
  10228. *
  10229. * @returns The data or null if no data exists.
  10230. */
  10231. function treeGetValue(tree) {
  10232. return tree.node.value;
  10233. }
  10234. /**
  10235. * Sets data to this tree node.
  10236. *
  10237. * @param value - Value to set.
  10238. */
  10239. function treeSetValue(tree, value) {
  10240. tree.node.value = value;
  10241. treeUpdateParents(tree);
  10242. }
  10243. /**
  10244. * @returns Whether the tree has any children.
  10245. */
  10246. function treeHasChildren(tree) {
  10247. return tree.node.childCount > 0;
  10248. }
  10249. /**
  10250. * @returns Whethe rthe tree is empty (no value or children).
  10251. */
  10252. function treeIsEmpty(tree) {
  10253. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10254. }
  10255. /**
  10256. * Calls action for each child of this tree node.
  10257. *
  10258. * @param action - Action to be called for each child.
  10259. */
  10260. function treeForEachChild(tree, action) {
  10261. each(tree.node.children, (child, childTree) => {
  10262. action(new Tree(child, tree, childTree));
  10263. });
  10264. }
  10265. /**
  10266. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10267. *
  10268. * @param action - Action to be called for each child.
  10269. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10270. * false.
  10271. * @param childrenFirst - Whether to call action on children before calling it on
  10272. * parent.
  10273. */
  10274. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10275. if (includeSelf && !childrenFirst) {
  10276. action(tree);
  10277. }
  10278. treeForEachChild(tree, child => {
  10279. treeForEachDescendant(child, action, true, childrenFirst);
  10280. });
  10281. if (includeSelf && childrenFirst) {
  10282. action(tree);
  10283. }
  10284. }
  10285. /**
  10286. * Calls action on each ancestor node.
  10287. *
  10288. * @param action - Action to be called on each parent; return
  10289. * true to abort.
  10290. * @param includeSelf - Whether to call action on this node as well.
  10291. * @returns true if the action callback returned true.
  10292. */
  10293. function treeForEachAncestor(tree, action, includeSelf) {
  10294. let node = includeSelf ? tree : tree.parent;
  10295. while (node !== null) {
  10296. if (action(node)) {
  10297. return true;
  10298. }
  10299. node = node.parent;
  10300. }
  10301. return false;
  10302. }
  10303. /**
  10304. * @returns The path of this tree node, as a Path.
  10305. */
  10306. function treeGetPath(tree) {
  10307. return new Path(tree.parent === null
  10308. ? tree.name
  10309. : treeGetPath(tree.parent) + '/' + tree.name);
  10310. }
  10311. /**
  10312. * Adds or removes this child from its parent based on whether it's empty or not.
  10313. */
  10314. function treeUpdateParents(tree) {
  10315. if (tree.parent !== null) {
  10316. treeUpdateChild(tree.parent, tree.name, tree);
  10317. }
  10318. }
  10319. /**
  10320. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10321. *
  10322. * @param childName - The name of the child to update.
  10323. * @param child - The child to update.
  10324. */
  10325. function treeUpdateChild(tree, childName, child) {
  10326. const childEmpty = treeIsEmpty(child);
  10327. const childExists = contains(tree.node.children, childName);
  10328. if (childEmpty && childExists) {
  10329. delete tree.node.children[childName];
  10330. tree.node.childCount--;
  10331. treeUpdateParents(tree);
  10332. }
  10333. else if (!childEmpty && !childExists) {
  10334. tree.node.children[childName] = child.node;
  10335. tree.node.childCount++;
  10336. treeUpdateParents(tree);
  10337. }
  10338. }
  10339. /**
  10340. * @license
  10341. * Copyright 2017 Google LLC
  10342. *
  10343. * Licensed under the Apache License, Version 2.0 (the "License");
  10344. * you may not use this file except in compliance with the License.
  10345. * You may obtain a copy of the License at
  10346. *
  10347. * http://www.apache.org/licenses/LICENSE-2.0
  10348. *
  10349. * Unless required by applicable law or agreed to in writing, software
  10350. * distributed under the License is distributed on an "AS IS" BASIS,
  10351. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10352. * See the License for the specific language governing permissions and
  10353. * limitations under the License.
  10354. */
  10355. /**
  10356. * True for invalid Firebase keys
  10357. */
  10358. const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10359. /**
  10360. * True for invalid Firebase paths.
  10361. * Allows '/' in paths.
  10362. */
  10363. const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10364. /**
  10365. * Maximum number of characters to allow in leaf value
  10366. */
  10367. const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10368. const isValidKey = function (key) {
  10369. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10370. };
  10371. const isValidPathString = function (pathString) {
  10372. return (typeof pathString === 'string' &&
  10373. pathString.length !== 0 &&
  10374. !INVALID_PATH_REGEX_.test(pathString));
  10375. };
  10376. const isValidRootPathString = function (pathString) {
  10377. if (pathString) {
  10378. // Allow '/.info/' at the beginning.
  10379. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10380. }
  10381. return isValidPathString(pathString);
  10382. };
  10383. const isValidPriority = function (priority) {
  10384. return (priority === null ||
  10385. typeof priority === 'string' ||
  10386. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10387. (priority &&
  10388. typeof priority === 'object' &&
  10389. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10390. contains(priority, '.sv')));
  10391. };
  10392. /**
  10393. * Pre-validate a datum passed as an argument to Firebase function.
  10394. */
  10395. const validateFirebaseDataArg = function (fnName, value, path, optional) {
  10396. if (optional && value === undefined) {
  10397. return;
  10398. }
  10399. validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
  10400. };
  10401. /**
  10402. * Validate a data object client-side before sending to server.
  10403. */
  10404. const validateFirebaseData = function (errorPrefix, data, path_) {
  10405. const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10406. if (data === undefined) {
  10407. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10408. }
  10409. if (typeof data === 'function') {
  10410. throw new Error(errorPrefix +
  10411. 'contains a function ' +
  10412. validationPathToErrorString(path) +
  10413. ' with contents = ' +
  10414. data.toString());
  10415. }
  10416. if (isInvalidJSONNumber(data)) {
  10417. throw new Error(errorPrefix +
  10418. 'contains ' +
  10419. data.toString() +
  10420. ' ' +
  10421. validationPathToErrorString(path));
  10422. }
  10423. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10424. if (typeof data === 'string' &&
  10425. data.length > MAX_LEAF_SIZE_ / 3 &&
  10426. stringLength(data) > MAX_LEAF_SIZE_) {
  10427. throw new Error(errorPrefix +
  10428. 'contains a string greater than ' +
  10429. MAX_LEAF_SIZE_ +
  10430. ' utf8 bytes ' +
  10431. validationPathToErrorString(path) +
  10432. " ('" +
  10433. data.substring(0, 50) +
  10434. "...')");
  10435. }
  10436. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10437. // to save extra walking of large objects.
  10438. if (data && typeof data === 'object') {
  10439. let hasDotValue = false;
  10440. let hasActualChild = false;
  10441. each(data, (key, value) => {
  10442. if (key === '.value') {
  10443. hasDotValue = true;
  10444. }
  10445. else if (key !== '.priority' && key !== '.sv') {
  10446. hasActualChild = true;
  10447. if (!isValidKey(key)) {
  10448. throw new Error(errorPrefix +
  10449. ' contains an invalid key (' +
  10450. key +
  10451. ') ' +
  10452. validationPathToErrorString(path) +
  10453. '. Keys must be non-empty strings ' +
  10454. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10455. }
  10456. }
  10457. validationPathPush(path, key);
  10458. validateFirebaseData(errorPrefix, value, path);
  10459. validationPathPop(path);
  10460. });
  10461. if (hasDotValue && hasActualChild) {
  10462. throw new Error(errorPrefix +
  10463. ' contains ".value" child ' +
  10464. validationPathToErrorString(path) +
  10465. ' in addition to actual children.');
  10466. }
  10467. }
  10468. };
  10469. /**
  10470. * Pre-validate paths passed in the firebase function.
  10471. */
  10472. const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10473. let i, curPath;
  10474. for (i = 0; i < mergePaths.length; i++) {
  10475. curPath = mergePaths[i];
  10476. const keys = pathSlice(curPath);
  10477. for (let j = 0; j < keys.length; j++) {
  10478. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10479. else if (!isValidKey(keys[j])) {
  10480. throw new Error(errorPrefix +
  10481. 'contains an invalid key (' +
  10482. keys[j] +
  10483. ') in path ' +
  10484. curPath.toString() +
  10485. '. Keys must be non-empty strings ' +
  10486. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10487. }
  10488. }
  10489. }
  10490. // Check that update keys are not descendants of each other.
  10491. // We rely on the property that sorting guarantees that ancestors come
  10492. // right before descendants.
  10493. mergePaths.sort(pathCompare);
  10494. let prevPath = null;
  10495. for (i = 0; i < mergePaths.length; i++) {
  10496. curPath = mergePaths[i];
  10497. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10498. throw new Error(errorPrefix +
  10499. 'contains a path ' +
  10500. prevPath.toString() +
  10501. ' that is ancestor of another path ' +
  10502. curPath.toString());
  10503. }
  10504. prevPath = curPath;
  10505. }
  10506. };
  10507. /**
  10508. * pre-validate an object passed as an argument to firebase function (
  10509. * must be an object - e.g. for firebase.update()).
  10510. */
  10511. const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10512. if (optional && data === undefined) {
  10513. return;
  10514. }
  10515. const errorPrefix$1 = errorPrefix(fnName, 'values');
  10516. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10517. throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
  10518. }
  10519. const mergePaths = [];
  10520. each(data, (key, value) => {
  10521. const curPath = new Path(key);
  10522. validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
  10523. if (pathGetBack(curPath) === '.priority') {
  10524. if (!isValidPriority(value)) {
  10525. throw new Error(errorPrefix$1 +
  10526. "contains an invalid value for '" +
  10527. curPath.toString() +
  10528. "', which must be a valid " +
  10529. 'Firebase priority (a string, finite number, server value, or null).');
  10530. }
  10531. }
  10532. mergePaths.push(curPath);
  10533. });
  10534. validateFirebaseMergePaths(errorPrefix$1, mergePaths);
  10535. };
  10536. const validatePriority = function (fnName, priority, optional) {
  10537. if (optional && priority === undefined) {
  10538. return;
  10539. }
  10540. if (isInvalidJSONNumber(priority)) {
  10541. throw new Error(errorPrefix(fnName, 'priority') +
  10542. 'is ' +
  10543. priority.toString() +
  10544. ', but must be a valid Firebase priority (a string, finite number, ' +
  10545. 'server value, or null).');
  10546. }
  10547. // Special case to allow importing data with a .sv.
  10548. if (!isValidPriority(priority)) {
  10549. throw new Error(errorPrefix(fnName, 'priority') +
  10550. 'must be a valid Firebase priority ' +
  10551. '(a string, finite number, server value, or null).');
  10552. }
  10553. };
  10554. const validateKey = function (fnName, argumentName, key, optional) {
  10555. if (optional && key === undefined) {
  10556. return;
  10557. }
  10558. if (!isValidKey(key)) {
  10559. throw new Error(errorPrefix(fnName, argumentName) +
  10560. 'was an invalid key = "' +
  10561. key +
  10562. '". Firebase keys must be non-empty strings and ' +
  10563. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10564. }
  10565. };
  10566. /**
  10567. * @internal
  10568. */
  10569. const validatePathString = function (fnName, argumentName, pathString, optional) {
  10570. if (optional && pathString === undefined) {
  10571. return;
  10572. }
  10573. if (!isValidPathString(pathString)) {
  10574. throw new Error(errorPrefix(fnName, argumentName) +
  10575. 'was an invalid path = "' +
  10576. pathString +
  10577. '". Paths must be non-empty strings and ' +
  10578. 'can\'t contain ".", "#", "$", "[", or "]"');
  10579. }
  10580. };
  10581. const validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10582. if (pathString) {
  10583. // Allow '/.info/' at the beginning.
  10584. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10585. }
  10586. validatePathString(fnName, argumentName, pathString, optional);
  10587. };
  10588. /**
  10589. * @internal
  10590. */
  10591. const validateWritablePath = function (fnName, path) {
  10592. if (pathGetFront(path) === '.info') {
  10593. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10594. }
  10595. };
  10596. const validateUrl = function (fnName, parsedUrl) {
  10597. // TODO = Validate server better.
  10598. const pathString = parsedUrl.path.toString();
  10599. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10600. parsedUrl.repoInfo.host.length === 0 ||
  10601. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10602. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10603. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10604. throw new Error(errorPrefix(fnName, 'url') +
  10605. 'must be a valid firebase URL and ' +
  10606. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10607. }
  10608. };
  10609. /**
  10610. * @license
  10611. * Copyright 2017 Google LLC
  10612. *
  10613. * Licensed under the Apache License, Version 2.0 (the "License");
  10614. * you may not use this file except in compliance with the License.
  10615. * You may obtain a copy of the License at
  10616. *
  10617. * http://www.apache.org/licenses/LICENSE-2.0
  10618. *
  10619. * Unless required by applicable law or agreed to in writing, software
  10620. * distributed under the License is distributed on an "AS IS" BASIS,
  10621. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10622. * See the License for the specific language governing permissions and
  10623. * limitations under the License.
  10624. */
  10625. /**
  10626. * The event queue serves a few purposes:
  10627. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10628. * events being queued.
  10629. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10630. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10631. * left off, ensuring that the events are still raised synchronously and in order.
  10632. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10633. * events are raised synchronously.
  10634. *
  10635. * NOTE: This can all go away if/when we move to async events.
  10636. *
  10637. */
  10638. class EventQueue {
  10639. constructor() {
  10640. this.eventLists_ = [];
  10641. /**
  10642. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10643. */
  10644. this.recursionDepth_ = 0;
  10645. }
  10646. }
  10647. /**
  10648. * @param eventDataList - The new events to queue.
  10649. */
  10650. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10651. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10652. let currList = null;
  10653. for (let i = 0; i < eventDataList.length; i++) {
  10654. const data = eventDataList[i];
  10655. const path = data.getPath();
  10656. if (currList !== null && !pathEquals(path, currList.path)) {
  10657. eventQueue.eventLists_.push(currList);
  10658. currList = null;
  10659. }
  10660. if (currList === null) {
  10661. currList = { events: [], path };
  10662. }
  10663. currList.events.push(data);
  10664. }
  10665. if (currList) {
  10666. eventQueue.eventLists_.push(currList);
  10667. }
  10668. }
  10669. /**
  10670. * Queues the specified events and synchronously raises all events (including previously queued ones)
  10671. * for the specified path.
  10672. *
  10673. * It is assumed that the new events are all for the specified path.
  10674. *
  10675. * @param path - The path to raise events for.
  10676. * @param eventDataList - The new events to raise.
  10677. */
  10678. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  10679. eventQueueQueueEvents(eventQueue, eventDataList);
  10680. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
  10681. }
  10682. /**
  10683. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  10684. * locations related to the specified change path (i.e. all ancestors and descendants).
  10685. *
  10686. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  10687. *
  10688. * @param changedPath - The path to raise events for.
  10689. * @param eventDataList - The events to raise
  10690. */
  10691. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  10692. eventQueueQueueEvents(eventQueue, eventDataList);
  10693. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
  10694. pathContains(changedPath, eventPath));
  10695. }
  10696. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  10697. eventQueue.recursionDepth_++;
  10698. let sentAll = true;
  10699. for (let i = 0; i < eventQueue.eventLists_.length; i++) {
  10700. const eventList = eventQueue.eventLists_[i];
  10701. if (eventList) {
  10702. const eventPath = eventList.path;
  10703. if (predicate(eventPath)) {
  10704. eventListRaise(eventQueue.eventLists_[i]);
  10705. eventQueue.eventLists_[i] = null;
  10706. }
  10707. else {
  10708. sentAll = false;
  10709. }
  10710. }
  10711. }
  10712. if (sentAll) {
  10713. eventQueue.eventLists_ = [];
  10714. }
  10715. eventQueue.recursionDepth_--;
  10716. }
  10717. /**
  10718. * Iterates through the list and raises each event
  10719. */
  10720. function eventListRaise(eventList) {
  10721. for (let i = 0; i < eventList.events.length; i++) {
  10722. const eventData = eventList.events[i];
  10723. if (eventData !== null) {
  10724. eventList.events[i] = null;
  10725. const eventFn = eventData.getEventRunner();
  10726. if (logger) {
  10727. log('event: ' + eventData.toString());
  10728. }
  10729. exceptionGuard(eventFn);
  10730. }
  10731. }
  10732. }
  10733. /**
  10734. * @license
  10735. * Copyright 2017 Google LLC
  10736. *
  10737. * Licensed under the Apache License, Version 2.0 (the "License");
  10738. * you may not use this file except in compliance with the License.
  10739. * You may obtain a copy of the License at
  10740. *
  10741. * http://www.apache.org/licenses/LICENSE-2.0
  10742. *
  10743. * Unless required by applicable law or agreed to in writing, software
  10744. * distributed under the License is distributed on an "AS IS" BASIS,
  10745. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10746. * See the License for the specific language governing permissions and
  10747. * limitations under the License.
  10748. */
  10749. const INTERRUPT_REASON = 'repo_interrupt';
  10750. /**
  10751. * If a transaction does not succeed after 25 retries, we abort it. Among other
  10752. * things this ensure that if there's ever a bug causing a mismatch between
  10753. * client / server hashes for some data, we won't retry indefinitely.
  10754. */
  10755. const MAX_TRANSACTION_RETRIES = 25;
  10756. /**
  10757. * A connection to a single data repository.
  10758. */
  10759. class Repo {
  10760. constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  10761. this.repoInfo_ = repoInfo_;
  10762. this.forceRestClient_ = forceRestClient_;
  10763. this.authTokenProvider_ = authTokenProvider_;
  10764. this.appCheckProvider_ = appCheckProvider_;
  10765. this.dataUpdateCount = 0;
  10766. this.statsListener_ = null;
  10767. this.eventQueue_ = new EventQueue();
  10768. this.nextWriteId_ = 1;
  10769. this.interceptServerDataCallback_ = null;
  10770. /** A list of data pieces and paths to be set when this client disconnects. */
  10771. this.onDisconnect_ = newSparseSnapshotTree();
  10772. /** Stores queues of outstanding transactions for Firebase locations. */
  10773. this.transactionQueueTree_ = new Tree();
  10774. // TODO: This should be @private but it's used by test_access.js and internal.js
  10775. this.persistentConnection_ = null;
  10776. // This key is intentionally not updated if RepoInfo is later changed or replaced
  10777. this.key = this.repoInfo_.toURLString();
  10778. }
  10779. /**
  10780. * @returns The URL corresponding to the root of this Firebase.
  10781. */
  10782. toString() {
  10783. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  10784. }
  10785. }
  10786. function repoStart(repo, appId, authOverride) {
  10787. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  10788. if (repo.forceRestClient_ || beingCrawled()) {
  10789. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
  10790. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10791. }, repo.authTokenProvider_, repo.appCheckProvider_);
  10792. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  10793. setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);
  10794. }
  10795. else {
  10796. // Validate authOverride
  10797. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  10798. if (typeof authOverride !== 'object') {
  10799. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  10800. }
  10801. try {
  10802. stringify(authOverride);
  10803. }
  10804. catch (e) {
  10805. throw new Error('Invalid authOverride provided: ' + e);
  10806. }
  10807. }
  10808. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
  10809. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  10810. }, (connectStatus) => {
  10811. repoOnConnectStatus(repo, connectStatus);
  10812. }, (updates) => {
  10813. repoOnServerInfoUpdate(repo, updates);
  10814. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  10815. repo.server_ = repo.persistentConnection_;
  10816. }
  10817. repo.authTokenProvider_.addTokenChangeListener(token => {
  10818. repo.server_.refreshAuthToken(token);
  10819. });
  10820. repo.appCheckProvider_.addTokenChangeListener(result => {
  10821. repo.server_.refreshAppCheckToken(result.token);
  10822. });
  10823. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  10824. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  10825. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
  10826. // Used for .info.
  10827. repo.infoData_ = new SnapshotHolder();
  10828. repo.infoSyncTree_ = new SyncTree({
  10829. startListening: (query, tag, currentHashFn, onComplete) => {
  10830. let infoEvents = [];
  10831. const node = repo.infoData_.getNode(query._path);
  10832. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  10833. // on initial data...
  10834. if (!node.isEmpty()) {
  10835. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  10836. setTimeout(() => {
  10837. onComplete('ok');
  10838. }, 0);
  10839. }
  10840. return infoEvents;
  10841. },
  10842. stopListening: () => { }
  10843. });
  10844. repoUpdateInfo(repo, 'connected', false);
  10845. repo.serverSyncTree_ = new SyncTree({
  10846. startListening: (query, tag, currentHashFn, onComplete) => {
  10847. repo.server_.listen(query, currentHashFn, tag, (status, data) => {
  10848. const events = onComplete(status, data);
  10849. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10850. });
  10851. // No synchronous events for network-backed sync trees
  10852. return [];
  10853. },
  10854. stopListening: (query, tag) => {
  10855. repo.server_.unlisten(query, tag);
  10856. }
  10857. });
  10858. }
  10859. /**
  10860. * @returns The time in milliseconds, taking the server offset into account if we have one.
  10861. */
  10862. function repoServerTime(repo) {
  10863. const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  10864. const offset = offsetNode.val() || 0;
  10865. return new Date().getTime() + offset;
  10866. }
  10867. /**
  10868. * Generate ServerValues using some variables from the repo object.
  10869. */
  10870. function repoGenerateServerValues(repo) {
  10871. return generateWithValues({
  10872. timestamp: repoServerTime(repo)
  10873. });
  10874. }
  10875. /**
  10876. * Called by realtime when we get new messages from the server.
  10877. */
  10878. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  10879. // For testing.
  10880. repo.dataUpdateCount++;
  10881. const path = new Path(pathString);
  10882. data = repo.interceptServerDataCallback_
  10883. ? repo.interceptServerDataCallback_(pathString, data)
  10884. : data;
  10885. let events = [];
  10886. if (tag) {
  10887. if (isMerge) {
  10888. const taggedChildren = map(data, (raw) => nodeFromJSON(raw));
  10889. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  10890. }
  10891. else {
  10892. const taggedSnap = nodeFromJSON(data);
  10893. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  10894. }
  10895. }
  10896. else if (isMerge) {
  10897. const changedChildren = map(data, (raw) => nodeFromJSON(raw));
  10898. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  10899. }
  10900. else {
  10901. const snap = nodeFromJSON(data);
  10902. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  10903. }
  10904. let affectedPath = path;
  10905. if (events.length > 0) {
  10906. // Since we have a listener outstanding for each transaction, receiving any events
  10907. // is a proxy for some change having occurred.
  10908. affectedPath = repoRerunTransactions(repo, path);
  10909. }
  10910. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  10911. }
  10912. function repoOnConnectStatus(repo, connectStatus) {
  10913. repoUpdateInfo(repo, 'connected', connectStatus);
  10914. if (connectStatus === false) {
  10915. repoRunOnDisconnectEvents(repo);
  10916. }
  10917. }
  10918. function repoOnServerInfoUpdate(repo, updates) {
  10919. each(updates, (key, value) => {
  10920. repoUpdateInfo(repo, key, value);
  10921. });
  10922. }
  10923. function repoUpdateInfo(repo, pathString, value) {
  10924. const path = new Path('/.info/' + pathString);
  10925. const newNode = nodeFromJSON(value);
  10926. repo.infoData_.updateSnapshot(path, newNode);
  10927. const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  10928. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  10929. }
  10930. function repoGetNextWriteId(repo) {
  10931. return repo.nextWriteId_++;
  10932. }
  10933. /**
  10934. * The purpose of `getValue` is to return the latest known value
  10935. * satisfying `query`.
  10936. *
  10937. * This method will first check for in-memory cached values
  10938. * belonging to active listeners. If they are found, such values
  10939. * are considered to be the most up-to-date.
  10940. *
  10941. * If the client is not connected, this method will wait until the
  10942. * repo has established a connection and then request the value for `query`.
  10943. * If the client is not able to retrieve the query result for another reason,
  10944. * it reports an error.
  10945. *
  10946. * @param query - The query to surface a value for.
  10947. */
  10948. function repoGetValue(repo, query, eventRegistration) {
  10949. // Only active queries are cached. There is no persisted cache.
  10950. const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  10951. if (cached != null) {
  10952. return Promise.resolve(cached);
  10953. }
  10954. return repo.server_.get(query).then(payload => {
  10955. const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  10956. /**
  10957. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  10958. * Add an event registration,
  10959. * Update data at the path,
  10960. * Raise any events,
  10961. * Cleanup the SyncTree
  10962. */
  10963. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  10964. let events;
  10965. if (query._queryParams.loadsAllData()) {
  10966. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  10967. }
  10968. else {
  10969. const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  10970. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  10971. }
  10972. /*
  10973. * We need to raise events in the scenario where `get()` is called at a parent path, and
  10974. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  10975. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  10976. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  10977. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  10978. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  10979. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  10980. * ensure the corresponding child events will get fired.
  10981. */
  10982. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  10983. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  10984. return node;
  10985. }, err => {
  10986. repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
  10987. return Promise.reject(new Error(err));
  10988. });
  10989. }
  10990. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  10991. repoLog(repo, 'set', {
  10992. path: path.toString(),
  10993. value: newVal,
  10994. priority: newPriority
  10995. });
  10996. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  10997. // (b) store unresolved paths on JSON parse
  10998. const serverValues = repoGenerateServerValues(repo);
  10999. const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11000. const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11001. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11002. const writeId = repoGetNextWriteId(repo);
  11003. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11004. eventQueueQueueEvents(repo.eventQueue_, events);
  11005. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {
  11006. const success = status === 'ok';
  11007. if (!success) {
  11008. warn('set at ' + path + ' failed: ' + status);
  11009. }
  11010. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11011. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11012. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11013. });
  11014. const affectedPath = repoAbortTransactions(repo, path);
  11015. repoRerunTransactions(repo, affectedPath);
  11016. // We queued the events above, so just flush the queue here
  11017. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11018. }
  11019. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11020. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11021. // Start with our existing data and merge each child into it.
  11022. let empty = true;
  11023. const serverValues = repoGenerateServerValues(repo);
  11024. const changedChildren = {};
  11025. each(childrenToMerge, (changedKey, changedValue) => {
  11026. empty = false;
  11027. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11028. });
  11029. if (!empty) {
  11030. const writeId = repoGetNextWriteId(repo);
  11031. const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
  11032. eventQueueQueueEvents(repo.eventQueue_, events);
  11033. repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
  11034. const success = status === 'ok';
  11035. if (!success) {
  11036. warn('update at ' + path + ' failed: ' + status);
  11037. }
  11038. const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11039. const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11040. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11041. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11042. });
  11043. each(childrenToMerge, (changedPath) => {
  11044. const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11045. repoRerunTransactions(repo, affectedPath);
  11046. });
  11047. // We queued the events above, so just flush the queue here
  11048. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11049. }
  11050. else {
  11051. log("update() called with empty data. Don't do anything.");
  11052. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11053. }
  11054. }
  11055. /**
  11056. * Applies all of the changes stored up in the onDisconnect_ tree.
  11057. */
  11058. function repoRunOnDisconnectEvents(repo) {
  11059. repoLog(repo, 'onDisconnectEvents');
  11060. const serverValues = repoGenerateServerValues(repo);
  11061. const resolvedOnDisconnectTree = newSparseSnapshotTree();
  11062. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
  11063. const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11064. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11065. });
  11066. let events = [];
  11067. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
  11068. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11069. const affectedPath = repoAbortTransactions(repo, path);
  11070. repoRerunTransactions(repo, affectedPath);
  11071. });
  11072. repo.onDisconnect_ = newSparseSnapshotTree();
  11073. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11074. }
  11075. function repoOnDisconnectCancel(repo, path, onComplete) {
  11076. repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
  11077. if (status === 'ok') {
  11078. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11079. }
  11080. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11081. });
  11082. }
  11083. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11084. const newNode = nodeFromJSON(value);
  11085. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11086. if (status === 'ok') {
  11087. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11088. }
  11089. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11090. });
  11091. }
  11092. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11093. const newNode = nodeFromJSON(value, priority);
  11094. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {
  11095. if (status === 'ok') {
  11096. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11097. }
  11098. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11099. });
  11100. }
  11101. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11102. if (isEmpty(childrenToMerge)) {
  11103. log("onDisconnect().update() called with empty data. Don't do anything.");
  11104. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11105. return;
  11106. }
  11107. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
  11108. if (status === 'ok') {
  11109. each(childrenToMerge, (childName, childNode) => {
  11110. const newChildNode = nodeFromJSON(childNode);
  11111. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11112. });
  11113. }
  11114. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11115. });
  11116. }
  11117. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11118. let events;
  11119. if (pathGetFront(query._path) === '.info') {
  11120. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11121. }
  11122. else {
  11123. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11124. }
  11125. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11126. }
  11127. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11128. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11129. // a little bit by handling the return values anyways.
  11130. let events;
  11131. if (pathGetFront(query._path) === '.info') {
  11132. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11133. }
  11134. else {
  11135. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11136. }
  11137. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11138. }
  11139. function repoInterrupt(repo) {
  11140. if (repo.persistentConnection_) {
  11141. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11142. }
  11143. }
  11144. function repoResume(repo) {
  11145. if (repo.persistentConnection_) {
  11146. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11147. }
  11148. }
  11149. function repoLog(repo, ...varArgs) {
  11150. let prefix = '';
  11151. if (repo.persistentConnection_) {
  11152. prefix = repo.persistentConnection_.id + ':';
  11153. }
  11154. log(prefix, ...varArgs);
  11155. }
  11156. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11157. if (callback) {
  11158. exceptionGuard(() => {
  11159. if (status === 'ok') {
  11160. callback(null);
  11161. }
  11162. else {
  11163. const code = (status || 'error').toUpperCase();
  11164. let message = code;
  11165. if (errorReason) {
  11166. message += ': ' + errorReason;
  11167. }
  11168. const error = new Error(message);
  11169. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11170. error.code = code;
  11171. callback(error);
  11172. }
  11173. });
  11174. }
  11175. }
  11176. /**
  11177. * Creates a new transaction, adds it to the transactions we're tracking, and
  11178. * sends it to the server if possible.
  11179. *
  11180. * @param path - Path at which to do transaction.
  11181. * @param transactionUpdate - Update callback.
  11182. * @param onComplete - Completion callback.
  11183. * @param unwatcher - Function that will be called when the transaction no longer
  11184. * need data updates for `path`.
  11185. * @param applyLocally - Whether or not to make intermediate results visible
  11186. */
  11187. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11188. repoLog(repo, 'transaction on ' + path);
  11189. // Initialize transaction.
  11190. const transaction = {
  11191. path,
  11192. update: transactionUpdate,
  11193. onComplete,
  11194. // One of TransactionStatus enums.
  11195. status: null,
  11196. // Used when combining transactions at different locations to figure out
  11197. // which one goes first.
  11198. order: LUIDGenerator(),
  11199. // Whether to raise local events for this transaction.
  11200. applyLocally,
  11201. // Count of how many times we've retried the transaction.
  11202. retryCount: 0,
  11203. // Function to call to clean up our .on() listener.
  11204. unwatcher,
  11205. // Stores why a transaction was aborted.
  11206. abortReason: null,
  11207. currentWriteId: null,
  11208. currentInputSnapshot: null,
  11209. currentOutputSnapshotRaw: null,
  11210. currentOutputSnapshotResolved: null
  11211. };
  11212. // Run transaction initially.
  11213. const currentState = repoGetLatestState(repo, path, undefined);
  11214. transaction.currentInputSnapshot = currentState;
  11215. const newVal = transaction.update(currentState.val());
  11216. if (newVal === undefined) {
  11217. // Abort transaction.
  11218. transaction.unwatcher();
  11219. transaction.currentOutputSnapshotRaw = null;
  11220. transaction.currentOutputSnapshotResolved = null;
  11221. if (transaction.onComplete) {
  11222. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11223. }
  11224. }
  11225. else {
  11226. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11227. // Mark as run and add to our queue.
  11228. transaction.status = 0 /* TransactionStatus.RUN */;
  11229. const queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11230. const nodeQueue = treeGetValue(queueNode) || [];
  11231. nodeQueue.push(transaction);
  11232. treeSetValue(queueNode, nodeQueue);
  11233. // Update visibleData and raise events
  11234. // Note: We intentionally raise events after updating all of our
  11235. // transaction state, since the user could start new transactions from the
  11236. // event callbacks.
  11237. let priorityForNode;
  11238. if (typeof newVal === 'object' &&
  11239. newVal !== null &&
  11240. contains(newVal, '.priority')) {
  11241. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11242. priorityForNode = safeGet(newVal, '.priority');
  11243. assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11244. 'Priority must be a valid string, finite number, server value, or null.');
  11245. }
  11246. else {
  11247. const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11248. ChildrenNode.EMPTY_NODE;
  11249. priorityForNode = currentNode.getPriority().val();
  11250. }
  11251. const serverValues = repoGenerateServerValues(repo);
  11252. const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11253. const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11254. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11255. transaction.currentOutputSnapshotResolved = newNode;
  11256. transaction.currentWriteId = repoGetNextWriteId(repo);
  11257. const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11258. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11259. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11260. }
  11261. }
  11262. /**
  11263. * @param excludeSets - A specific set to exclude
  11264. */
  11265. function repoGetLatestState(repo, path, excludeSets) {
  11266. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11267. ChildrenNode.EMPTY_NODE);
  11268. }
  11269. /**
  11270. * Sends any already-run transactions that aren't waiting for outstanding
  11271. * transactions to complete.
  11272. *
  11273. * Externally it's called with no arguments, but it calls itself recursively
  11274. * with a particular transactionQueueTree node to recurse through the tree.
  11275. *
  11276. * @param node - transactionQueueTree node to start at.
  11277. */
  11278. function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
  11279. // Before recursing, make sure any completed transactions are removed.
  11280. if (!node) {
  11281. repoPruneCompletedTransactionsBelowNode(repo, node);
  11282. }
  11283. if (treeGetValue(node)) {
  11284. const queue = repoBuildTransactionQueue(repo, node);
  11285. assert(queue.length > 0, 'Sending zero length transaction queue');
  11286. const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);
  11287. // If they're all run (and not sent), we can send them. Else, we must wait.
  11288. if (allRun) {
  11289. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11290. }
  11291. }
  11292. else if (treeHasChildren(node)) {
  11293. treeForEachChild(node, childNode => {
  11294. repoSendReadyTransactions(repo, childNode);
  11295. });
  11296. }
  11297. }
  11298. /**
  11299. * Given a list of run transactions, send them to the server and then handle
  11300. * the result (success or failure).
  11301. *
  11302. * @param path - The location of the queue.
  11303. * @param queue - Queue of transactions under the specified location.
  11304. */
  11305. function repoSendTransactionQueue(repo, path, queue) {
  11306. // Mark transactions as sent and increment retry count!
  11307. const setsToIgnore = queue.map(txn => {
  11308. return txn.currentWriteId;
  11309. });
  11310. const latestState = repoGetLatestState(repo, path, setsToIgnore);
  11311. let snapToSend = latestState;
  11312. const latestHash = latestState.hash();
  11313. for (let i = 0; i < queue.length; i++) {
  11314. const txn = queue[i];
  11315. assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11316. txn.status = 1 /* TransactionStatus.SENT */;
  11317. txn.retryCount++;
  11318. const relativePath = newRelativePath(path, txn.path);
  11319. // If we've gotten to this point, the output snapshot must be defined.
  11320. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11321. }
  11322. const dataToSend = snapToSend.val(true);
  11323. const pathToSend = path;
  11324. // Send the put.
  11325. repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
  11326. repoLog(repo, 'transaction put response', {
  11327. path: pathToSend.toString(),
  11328. status
  11329. });
  11330. let events = [];
  11331. if (status === 'ok') {
  11332. // Queue up the callbacks and fire them after cleaning up all of our
  11333. // transaction state, since the callback could trigger more
  11334. // transactions or sets.
  11335. const callbacks = [];
  11336. for (let i = 0; i < queue.length; i++) {
  11337. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11338. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11339. if (queue[i].onComplete) {
  11340. // We never unset the output snapshot, and given that this
  11341. // transaction is complete, it should be set
  11342. callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
  11343. }
  11344. queue[i].unwatcher();
  11345. }
  11346. // Now remove the completed transactions.
  11347. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11348. // There may be pending transactions that we can now send.
  11349. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11350. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11351. // Finally, trigger onComplete callbacks.
  11352. for (let i = 0; i < callbacks.length; i++) {
  11353. exceptionGuard(callbacks[i]);
  11354. }
  11355. }
  11356. else {
  11357. // transactions are no longer sent. Update their status appropriately.
  11358. if (status === 'datastale') {
  11359. for (let i = 0; i < queue.length; i++) {
  11360. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11361. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11362. }
  11363. else {
  11364. queue[i].status = 0 /* TransactionStatus.RUN */;
  11365. }
  11366. }
  11367. }
  11368. else {
  11369. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11370. for (let i = 0; i < queue.length; i++) {
  11371. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11372. queue[i].abortReason = status;
  11373. }
  11374. }
  11375. repoRerunTransactions(repo, path);
  11376. }
  11377. }, latestHash);
  11378. }
  11379. /**
  11380. * Finds all transactions dependent on the data at changedPath and reruns them.
  11381. *
  11382. * Should be called any time cached data changes.
  11383. *
  11384. * Return the highest path that was affected by rerunning transactions. This
  11385. * is the path at which events need to be raised for.
  11386. *
  11387. * @param changedPath - The path in mergedData that changed.
  11388. * @returns The rootmost path that was affected by rerunning transactions.
  11389. */
  11390. function repoRerunTransactions(repo, changedPath) {
  11391. const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11392. const path = treeGetPath(rootMostTransactionNode);
  11393. const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11394. repoRerunTransactionQueue(repo, queue, path);
  11395. return path;
  11396. }
  11397. /**
  11398. * Does all the work of rerunning transactions (as well as cleans up aborted
  11399. * transactions and whatnot).
  11400. *
  11401. * @param queue - The queue of transactions to run.
  11402. * @param path - The path the queue is for.
  11403. */
  11404. function repoRerunTransactionQueue(repo, queue, path) {
  11405. if (queue.length === 0) {
  11406. return; // Nothing to do!
  11407. }
  11408. // Queue up the callbacks and fire them after cleaning up all of our
  11409. // transaction state, since the callback could trigger more transactions or
  11410. // sets.
  11411. const callbacks = [];
  11412. let events = [];
  11413. // Ignore all of the sets we're going to re-run.
  11414. const txnsToRerun = queue.filter(q => {
  11415. return q.status === 0 /* TransactionStatus.RUN */;
  11416. });
  11417. const setsToIgnore = txnsToRerun.map(q => {
  11418. return q.currentWriteId;
  11419. });
  11420. for (let i = 0; i < queue.length; i++) {
  11421. const transaction = queue[i];
  11422. const relativePath = newRelativePath(path, transaction.path);
  11423. let abortTransaction = false, abortReason;
  11424. assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11425. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11426. abortTransaction = true;
  11427. abortReason = transaction.abortReason;
  11428. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11429. }
  11430. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11431. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11432. abortTransaction = true;
  11433. abortReason = 'maxretry';
  11434. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11435. }
  11436. else {
  11437. // This code reruns a transaction
  11438. const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11439. transaction.currentInputSnapshot = currentNode;
  11440. const newData = queue[i].update(currentNode.val());
  11441. if (newData !== undefined) {
  11442. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11443. let newDataNode = nodeFromJSON(newData);
  11444. const hasExplicitPriority = typeof newData === 'object' &&
  11445. newData != null &&
  11446. contains(newData, '.priority');
  11447. if (!hasExplicitPriority) {
  11448. // Keep the old priority if there wasn't a priority explicitly specified.
  11449. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11450. }
  11451. const oldWriteId = transaction.currentWriteId;
  11452. const serverValues = repoGenerateServerValues(repo);
  11453. const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11454. transaction.currentOutputSnapshotRaw = newDataNode;
  11455. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11456. transaction.currentWriteId = repoGetNextWriteId(repo);
  11457. // Mutates setsToIgnore in place
  11458. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11459. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11460. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11461. }
  11462. else {
  11463. abortTransaction = true;
  11464. abortReason = 'nodata';
  11465. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11466. }
  11467. }
  11468. }
  11469. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11470. events = [];
  11471. if (abortTransaction) {
  11472. // Abort.
  11473. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11474. // Removing a listener can trigger pruning which can muck with
  11475. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11476. // until we're done.
  11477. (function (unwatcher) {
  11478. setTimeout(unwatcher, Math.floor(0));
  11479. })(queue[i].unwatcher);
  11480. if (queue[i].onComplete) {
  11481. if (abortReason === 'nodata') {
  11482. callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
  11483. }
  11484. else {
  11485. callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
  11486. }
  11487. }
  11488. }
  11489. }
  11490. // Clean up completed transactions.
  11491. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11492. // Now fire callbacks, now that we're in a good, known state.
  11493. for (let i = 0; i < callbacks.length; i++) {
  11494. exceptionGuard(callbacks[i]);
  11495. }
  11496. // Try to send the transaction result to the server.
  11497. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11498. }
  11499. /**
  11500. * Returns the rootmost ancestor node of the specified path that has a pending
  11501. * transaction on it, or just returns the node for the given path if there are
  11502. * no pending transactions on any ancestor.
  11503. *
  11504. * @param path - The location to start at.
  11505. * @returns The rootmost node with a transaction.
  11506. */
  11507. function repoGetAncestorTransactionNode(repo, path) {
  11508. let front;
  11509. // Start at the root and walk deeper into the tree towards path until we
  11510. // find a node with pending transactions.
  11511. let transactionNode = repo.transactionQueueTree_;
  11512. front = pathGetFront(path);
  11513. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11514. transactionNode = treeSubTree(transactionNode, front);
  11515. path = pathPopFront(path);
  11516. front = pathGetFront(path);
  11517. }
  11518. return transactionNode;
  11519. }
  11520. /**
  11521. * Builds the queue of all transactions at or below the specified
  11522. * transactionNode.
  11523. *
  11524. * @param transactionNode
  11525. * @returns The generated queue.
  11526. */
  11527. function repoBuildTransactionQueue(repo, transactionNode) {
  11528. // Walk any child transaction queues and aggregate them into a single queue.
  11529. const transactionQueue = [];
  11530. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11531. // Sort them by the order the transactions were created.
  11532. transactionQueue.sort((a, b) => a.order - b.order);
  11533. return transactionQueue;
  11534. }
  11535. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11536. const nodeQueue = treeGetValue(node);
  11537. if (nodeQueue) {
  11538. for (let i = 0; i < nodeQueue.length; i++) {
  11539. queue.push(nodeQueue[i]);
  11540. }
  11541. }
  11542. treeForEachChild(node, child => {
  11543. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11544. });
  11545. }
  11546. /**
  11547. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11548. */
  11549. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11550. const queue = treeGetValue(node);
  11551. if (queue) {
  11552. let to = 0;
  11553. for (let from = 0; from < queue.length; from++) {
  11554. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11555. queue[to] = queue[from];
  11556. to++;
  11557. }
  11558. }
  11559. queue.length = to;
  11560. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11561. }
  11562. treeForEachChild(node, childNode => {
  11563. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11564. });
  11565. }
  11566. /**
  11567. * Aborts all transactions on ancestors or descendants of the specified path.
  11568. * Called when doing a set() or update() since we consider them incompatible
  11569. * with transactions.
  11570. *
  11571. * @param path - Path for which we want to abort related transactions.
  11572. */
  11573. function repoAbortTransactions(repo, path) {
  11574. const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11575. const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11576. treeForEachAncestor(transactionNode, (node) => {
  11577. repoAbortTransactionsOnNode(repo, node);
  11578. });
  11579. repoAbortTransactionsOnNode(repo, transactionNode);
  11580. treeForEachDescendant(transactionNode, (node) => {
  11581. repoAbortTransactionsOnNode(repo, node);
  11582. });
  11583. return affectedPath;
  11584. }
  11585. /**
  11586. * Abort transactions stored in this transaction queue node.
  11587. *
  11588. * @param node - Node to abort transactions for.
  11589. */
  11590. function repoAbortTransactionsOnNode(repo, node) {
  11591. const queue = treeGetValue(node);
  11592. if (queue) {
  11593. // Queue up the callbacks and fire them after cleaning up all of our
  11594. // transaction state, since the callback could trigger more transactions
  11595. // or sets.
  11596. const callbacks = [];
  11597. // Go through queue. Any already-sent transactions must be marked for
  11598. // abort, while the unsent ones can be immediately aborted and removed.
  11599. let events = [];
  11600. let lastSent = -1;
  11601. for (let i = 0; i < queue.length; i++) {
  11602. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11603. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11604. assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11605. lastSent = i;
  11606. // Mark transaction for abort when it comes back.
  11607. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11608. queue[i].abortReason = 'set';
  11609. }
  11610. else {
  11611. assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11612. // We can abort it immediately.
  11613. queue[i].unwatcher();
  11614. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11615. if (queue[i].onComplete) {
  11616. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11617. }
  11618. }
  11619. }
  11620. if (lastSent === -1) {
  11621. // We're not waiting for any sent transactions. We can clear the queue.
  11622. treeSetValue(node, undefined);
  11623. }
  11624. else {
  11625. // Remove the transactions we aborted.
  11626. queue.length = lastSent + 1;
  11627. }
  11628. // Now fire the callbacks.
  11629. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11630. for (let i = 0; i < callbacks.length; i++) {
  11631. exceptionGuard(callbacks[i]);
  11632. }
  11633. }
  11634. }
  11635. /**
  11636. * @license
  11637. * Copyright 2017 Google LLC
  11638. *
  11639. * Licensed under the Apache License, Version 2.0 (the "License");
  11640. * you may not use this file except in compliance with the License.
  11641. * You may obtain a copy of the License at
  11642. *
  11643. * http://www.apache.org/licenses/LICENSE-2.0
  11644. *
  11645. * Unless required by applicable law or agreed to in writing, software
  11646. * distributed under the License is distributed on an "AS IS" BASIS,
  11647. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11648. * See the License for the specific language governing permissions and
  11649. * limitations under the License.
  11650. */
  11651. function decodePath(pathString) {
  11652. let pathStringDecoded = '';
  11653. const pieces = pathString.split('/');
  11654. for (let i = 0; i < pieces.length; i++) {
  11655. if (pieces[i].length > 0) {
  11656. let piece = pieces[i];
  11657. try {
  11658. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  11659. }
  11660. catch (e) { }
  11661. pathStringDecoded += '/' + piece;
  11662. }
  11663. }
  11664. return pathStringDecoded;
  11665. }
  11666. /**
  11667. * @returns key value hash
  11668. */
  11669. function decodeQuery(queryString) {
  11670. const results = {};
  11671. if (queryString.charAt(0) === '?') {
  11672. queryString = queryString.substring(1);
  11673. }
  11674. for (const segment of queryString.split('&')) {
  11675. if (segment.length === 0) {
  11676. continue;
  11677. }
  11678. const kv = segment.split('=');
  11679. if (kv.length === 2) {
  11680. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  11681. }
  11682. else {
  11683. warn(`Invalid query segment '${segment}' in query '${queryString}'`);
  11684. }
  11685. }
  11686. return results;
  11687. }
  11688. const parseRepoInfo = function (dataURL, nodeAdmin) {
  11689. const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  11690. if (parsedUrl.domain === 'firebase.com') {
  11691. fatal(parsedUrl.host +
  11692. ' is no longer supported. ' +
  11693. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  11694. }
  11695. // Catch common error of uninitialized namespace value.
  11696. if ((!namespace || namespace === 'undefined') &&
  11697. parsedUrl.domain !== 'localhost') {
  11698. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  11699. }
  11700. if (!parsedUrl.secure) {
  11701. warnIfPageIsSecure();
  11702. }
  11703. const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  11704. return {
  11705. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  11706. /*persistenceKey=*/ '',
  11707. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  11708. path: new Path(parsedUrl.pathString)
  11709. };
  11710. };
  11711. const parseDatabaseURL = function (dataURL) {
  11712. // Default to empty strings in the event of a malformed string.
  11713. let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  11714. // Always default to SSL, unless otherwise specified.
  11715. let secure = true, scheme = 'https', port = 443;
  11716. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  11717. if (typeof dataURL === 'string') {
  11718. // Parse scheme.
  11719. let colonInd = dataURL.indexOf('//');
  11720. if (colonInd >= 0) {
  11721. scheme = dataURL.substring(0, colonInd - 1);
  11722. dataURL = dataURL.substring(colonInd + 2);
  11723. }
  11724. // Parse host, path, and query string.
  11725. let slashInd = dataURL.indexOf('/');
  11726. if (slashInd === -1) {
  11727. slashInd = dataURL.length;
  11728. }
  11729. let questionMarkInd = dataURL.indexOf('?');
  11730. if (questionMarkInd === -1) {
  11731. questionMarkInd = dataURL.length;
  11732. }
  11733. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  11734. if (slashInd < questionMarkInd) {
  11735. // For pathString, questionMarkInd will always come after slashInd
  11736. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  11737. }
  11738. const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  11739. // If we have a port, use scheme for determining if it's secure.
  11740. colonInd = host.indexOf(':');
  11741. if (colonInd >= 0) {
  11742. secure = scheme === 'https' || scheme === 'wss';
  11743. port = parseInt(host.substring(colonInd + 1), 10);
  11744. }
  11745. else {
  11746. colonInd = host.length;
  11747. }
  11748. const hostWithoutPort = host.slice(0, colonInd);
  11749. if (hostWithoutPort.toLowerCase() === 'localhost') {
  11750. domain = 'localhost';
  11751. }
  11752. else if (hostWithoutPort.split('.').length <= 2) {
  11753. domain = hostWithoutPort;
  11754. }
  11755. else {
  11756. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  11757. const dotInd = host.indexOf('.');
  11758. subdomain = host.substring(0, dotInd).toLowerCase();
  11759. domain = host.substring(dotInd + 1);
  11760. // Normalize namespaces to lowercase to share storage / connection.
  11761. namespace = subdomain;
  11762. }
  11763. // Always treat the value of the `ns` as the namespace name if it is present.
  11764. if ('ns' in queryParams) {
  11765. namespace = queryParams['ns'];
  11766. }
  11767. }
  11768. return {
  11769. host,
  11770. port,
  11771. domain,
  11772. subdomain,
  11773. secure,
  11774. scheme,
  11775. pathString,
  11776. namespace
  11777. };
  11778. };
  11779. /**
  11780. * @license
  11781. * Copyright 2017 Google LLC
  11782. *
  11783. * Licensed under the Apache License, Version 2.0 (the "License");
  11784. * you may not use this file except in compliance with the License.
  11785. * You may obtain a copy of the License at
  11786. *
  11787. * http://www.apache.org/licenses/LICENSE-2.0
  11788. *
  11789. * Unless required by applicable law or agreed to in writing, software
  11790. * distributed under the License is distributed on an "AS IS" BASIS,
  11791. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11792. * See the License for the specific language governing permissions and
  11793. * limitations under the License.
  11794. */
  11795. // Modeled after base64 web-safe chars, but ordered by ASCII.
  11796. const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  11797. /**
  11798. * Fancy ID generator that creates 20-character string identifiers with the
  11799. * following properties:
  11800. *
  11801. * 1. They're based on timestamp so that they sort *after* any existing ids.
  11802. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  11803. * collide with other clients' IDs.
  11804. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  11805. * that will sort properly).
  11806. * 4. They're monotonically increasing. Even if you generate more than one in
  11807. * the same timestamp, the latter ones will sort after the former ones. We do
  11808. * this by using the previous random bits but "incrementing" them by 1 (only
  11809. * in the case of a timestamp collision).
  11810. */
  11811. const nextPushId = (function () {
  11812. // Timestamp of last push, used to prevent local collisions if you push twice
  11813. // in one ms.
  11814. let lastPushTime = 0;
  11815. // We generate 72-bits of randomness which get turned into 12 characters and
  11816. // appended to the timestamp to prevent collisions with other clients. We
  11817. // store the last characters we generated because in the event of a collision,
  11818. // we'll use those same characters except "incremented" by one.
  11819. const lastRandChars = [];
  11820. return function (now) {
  11821. const duplicateTime = now === lastPushTime;
  11822. lastPushTime = now;
  11823. let i;
  11824. const timeStampChars = new Array(8);
  11825. for (i = 7; i >= 0; i--) {
  11826. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  11827. // NOTE: Can't use << here because javascript will convert to int and lose
  11828. // the upper bits.
  11829. now = Math.floor(now / 64);
  11830. }
  11831. assert(now === 0, 'Cannot push at time == 0');
  11832. let id = timeStampChars.join('');
  11833. if (!duplicateTime) {
  11834. for (i = 0; i < 12; i++) {
  11835. lastRandChars[i] = Math.floor(Math.random() * 64);
  11836. }
  11837. }
  11838. else {
  11839. // If the timestamp hasn't changed since last push, use the same random
  11840. // number, except incremented by 1.
  11841. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  11842. lastRandChars[i] = 0;
  11843. }
  11844. lastRandChars[i]++;
  11845. }
  11846. for (i = 0; i < 12; i++) {
  11847. id += PUSH_CHARS.charAt(lastRandChars[i]);
  11848. }
  11849. assert(id.length === 20, 'nextPushId: Length should be 20.');
  11850. return id;
  11851. };
  11852. })();
  11853. /**
  11854. * @license
  11855. * Copyright 2017 Google LLC
  11856. *
  11857. * Licensed under the Apache License, Version 2.0 (the "License");
  11858. * you may not use this file except in compliance with the License.
  11859. * You may obtain a copy of the License at
  11860. *
  11861. * http://www.apache.org/licenses/LICENSE-2.0
  11862. *
  11863. * Unless required by applicable law or agreed to in writing, software
  11864. * distributed under the License is distributed on an "AS IS" BASIS,
  11865. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11866. * See the License for the specific language governing permissions and
  11867. * limitations under the License.
  11868. */
  11869. /**
  11870. * Encapsulates the data needed to raise an event
  11871. */
  11872. class DataEvent {
  11873. /**
  11874. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  11875. * @param eventRegistration - The function to call to with the event data. User provided
  11876. * @param snapshot - The data backing the event
  11877. * @param prevName - Optional, the name of the previous child for child_* events.
  11878. */
  11879. constructor(eventType, eventRegistration, snapshot, prevName) {
  11880. this.eventType = eventType;
  11881. this.eventRegistration = eventRegistration;
  11882. this.snapshot = snapshot;
  11883. this.prevName = prevName;
  11884. }
  11885. getPath() {
  11886. const ref = this.snapshot.ref;
  11887. if (this.eventType === 'value') {
  11888. return ref._path;
  11889. }
  11890. else {
  11891. return ref.parent._path;
  11892. }
  11893. }
  11894. getEventType() {
  11895. return this.eventType;
  11896. }
  11897. getEventRunner() {
  11898. return this.eventRegistration.getEventRunner(this);
  11899. }
  11900. toString() {
  11901. return (this.getPath().toString() +
  11902. ':' +
  11903. this.eventType +
  11904. ':' +
  11905. stringify(this.snapshot.exportVal()));
  11906. }
  11907. }
  11908. class CancelEvent {
  11909. constructor(eventRegistration, error, path) {
  11910. this.eventRegistration = eventRegistration;
  11911. this.error = error;
  11912. this.path = path;
  11913. }
  11914. getPath() {
  11915. return this.path;
  11916. }
  11917. getEventType() {
  11918. return 'cancel';
  11919. }
  11920. getEventRunner() {
  11921. return this.eventRegistration.getEventRunner(this);
  11922. }
  11923. toString() {
  11924. return this.path.toString() + ':cancel';
  11925. }
  11926. }
  11927. /**
  11928. * @license
  11929. * Copyright 2017 Google LLC
  11930. *
  11931. * Licensed under the Apache License, Version 2.0 (the "License");
  11932. * you may not use this file except in compliance with the License.
  11933. * You may obtain a copy of the License at
  11934. *
  11935. * http://www.apache.org/licenses/LICENSE-2.0
  11936. *
  11937. * Unless required by applicable law or agreed to in writing, software
  11938. * distributed under the License is distributed on an "AS IS" BASIS,
  11939. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11940. * See the License for the specific language governing permissions and
  11941. * limitations under the License.
  11942. */
  11943. /**
  11944. * A wrapper class that converts events from the database@exp SDK to the legacy
  11945. * Database SDK. Events are not converted directly as event registration relies
  11946. * on reference comparison of the original user callback (see `matches()`) and
  11947. * relies on equality of the legacy SDK's `context` object.
  11948. */
  11949. class CallbackContext {
  11950. constructor(snapshotCallback, cancelCallback) {
  11951. this.snapshotCallback = snapshotCallback;
  11952. this.cancelCallback = cancelCallback;
  11953. }
  11954. onValue(expDataSnapshot, previousChildName) {
  11955. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  11956. }
  11957. onCancel(error) {
  11958. assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  11959. return this.cancelCallback.call(null, error);
  11960. }
  11961. get hasCancelCallback() {
  11962. return !!this.cancelCallback;
  11963. }
  11964. matches(other) {
  11965. return (this.snapshotCallback === other.snapshotCallback ||
  11966. (this.snapshotCallback.userCallback !== undefined &&
  11967. this.snapshotCallback.userCallback ===
  11968. other.snapshotCallback.userCallback &&
  11969. this.snapshotCallback.context === other.snapshotCallback.context));
  11970. }
  11971. }
  11972. /**
  11973. * @license
  11974. * Copyright 2021 Google LLC
  11975. *
  11976. * Licensed under the Apache License, Version 2.0 (the "License");
  11977. * you may not use this file except in compliance with the License.
  11978. * You may obtain a copy of the License at
  11979. *
  11980. * http://www.apache.org/licenses/LICENSE-2.0
  11981. *
  11982. * Unless required by applicable law or agreed to in writing, software
  11983. * distributed under the License is distributed on an "AS IS" BASIS,
  11984. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11985. * See the License for the specific language governing permissions and
  11986. * limitations under the License.
  11987. */
  11988. /**
  11989. * The `onDisconnect` class allows you to write or clear data when your client
  11990. * disconnects from the Database server. These updates occur whether your
  11991. * client disconnects cleanly or not, so you can rely on them to clean up data
  11992. * even if a connection is dropped or a client crashes.
  11993. *
  11994. * The `onDisconnect` class is most commonly used to manage presence in
  11995. * applications where it is useful to detect how many clients are connected and
  11996. * when other clients disconnect. See
  11997. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  11998. * for more information.
  11999. *
  12000. * To avoid problems when a connection is dropped before the requests can be
  12001. * transferred to the Database server, these functions should be called before
  12002. * writing any data.
  12003. *
  12004. * Note that `onDisconnect` operations are only triggered once. If you want an
  12005. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12006. * the `onDisconnect` operations each time you reconnect.
  12007. */
  12008. class OnDisconnect {
  12009. /** @hideconstructor */
  12010. constructor(_repo, _path) {
  12011. this._repo = _repo;
  12012. this._path = _path;
  12013. }
  12014. /**
  12015. * Cancels all previously queued `onDisconnect()` set or update events for this
  12016. * location and all children.
  12017. *
  12018. * If a write has been queued for this location via a `set()` or `update()` at a
  12019. * parent location, the write at this location will be canceled, though writes
  12020. * to sibling locations will still occur.
  12021. *
  12022. * @returns Resolves when synchronization to the server is complete.
  12023. */
  12024. cancel() {
  12025. const deferred = new Deferred();
  12026. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
  12027. return deferred.promise;
  12028. }
  12029. /**
  12030. * Ensures the data at this location is deleted when the client is disconnected
  12031. * (due to closing the browser, navigating to a new page, or network issues).
  12032. *
  12033. * @returns Resolves when synchronization to the server is complete.
  12034. */
  12035. remove() {
  12036. validateWritablePath('OnDisconnect.remove', this._path);
  12037. const deferred = new Deferred();
  12038. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
  12039. return deferred.promise;
  12040. }
  12041. /**
  12042. * Ensures the data at this location is set to the specified value when the
  12043. * client is disconnected (due to closing the browser, navigating to a new page,
  12044. * or network issues).
  12045. *
  12046. * `set()` is especially useful for implementing "presence" systems, where a
  12047. * value should be changed or cleared when a user disconnects so that they
  12048. * appear "offline" to other users. See
  12049. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12050. * for more information.
  12051. *
  12052. * Note that `onDisconnect` operations are only triggered once. If you want an
  12053. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12054. * the `onDisconnect` operations each time.
  12055. *
  12056. * @param value - The value to be written to this location on disconnect (can
  12057. * be an object, array, string, number, boolean, or null).
  12058. * @returns Resolves when synchronization to the Database is complete.
  12059. */
  12060. set(value) {
  12061. validateWritablePath('OnDisconnect.set', this._path);
  12062. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12063. const deferred = new Deferred();
  12064. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
  12065. return deferred.promise;
  12066. }
  12067. /**
  12068. * Ensures the data at this location is set to the specified value and priority
  12069. * when the client is disconnected (due to closing the browser, navigating to a
  12070. * new page, or network issues).
  12071. *
  12072. * @param value - The value to be written to this location on disconnect (can
  12073. * be an object, array, string, number, boolean, or null).
  12074. * @param priority - The priority to be written (string, number, or null).
  12075. * @returns Resolves when synchronization to the Database is complete.
  12076. */
  12077. setWithPriority(value, priority) {
  12078. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12079. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12080. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12081. const deferred = new Deferred();
  12082. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
  12083. return deferred.promise;
  12084. }
  12085. /**
  12086. * Writes multiple values at this location when the client is disconnected (due
  12087. * to closing the browser, navigating to a new page, or network issues).
  12088. *
  12089. * The `values` argument contains multiple property-value pairs that will be
  12090. * written to the Database together. Each child property can either be a simple
  12091. * property (for example, "name") or a relative path (for example, "name/first")
  12092. * from the current location to the data to update.
  12093. *
  12094. * As opposed to the `set()` method, `update()` can be use to selectively update
  12095. * only the referenced properties at the current location (instead of replacing
  12096. * all the child properties at the current location).
  12097. *
  12098. * @param values - Object containing multiple values.
  12099. * @returns Resolves when synchronization to the Database is complete.
  12100. */
  12101. update(values) {
  12102. validateWritablePath('OnDisconnect.update', this._path);
  12103. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12104. const deferred = new Deferred();
  12105. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
  12106. return deferred.promise;
  12107. }
  12108. }
  12109. /**
  12110. * @license
  12111. * Copyright 2020 Google LLC
  12112. *
  12113. * Licensed under the Apache License, Version 2.0 (the "License");
  12114. * you may not use this file except in compliance with the License.
  12115. * You may obtain a copy of the License at
  12116. *
  12117. * http://www.apache.org/licenses/LICENSE-2.0
  12118. *
  12119. * Unless required by applicable law or agreed to in writing, software
  12120. * distributed under the License is distributed on an "AS IS" BASIS,
  12121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12122. * See the License for the specific language governing permissions and
  12123. * limitations under the License.
  12124. */
  12125. /**
  12126. * @internal
  12127. */
  12128. class QueryImpl {
  12129. /**
  12130. * @hideconstructor
  12131. */
  12132. constructor(_repo, _path, _queryParams, _orderByCalled) {
  12133. this._repo = _repo;
  12134. this._path = _path;
  12135. this._queryParams = _queryParams;
  12136. this._orderByCalled = _orderByCalled;
  12137. }
  12138. get key() {
  12139. if (pathIsEmpty(this._path)) {
  12140. return null;
  12141. }
  12142. else {
  12143. return pathGetBack(this._path);
  12144. }
  12145. }
  12146. get ref() {
  12147. return new ReferenceImpl(this._repo, this._path);
  12148. }
  12149. get _queryIdentifier() {
  12150. const obj = queryParamsGetQueryObject(this._queryParams);
  12151. const id = ObjectToUniqueKey(obj);
  12152. return id === '{}' ? 'default' : id;
  12153. }
  12154. /**
  12155. * An object representation of the query parameters used by this Query.
  12156. */
  12157. get _queryObject() {
  12158. return queryParamsGetQueryObject(this._queryParams);
  12159. }
  12160. isEqual(other) {
  12161. other = getModularInstance(other);
  12162. if (!(other instanceof QueryImpl)) {
  12163. return false;
  12164. }
  12165. const sameRepo = this._repo === other._repo;
  12166. const samePath = pathEquals(this._path, other._path);
  12167. const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12168. return sameRepo && samePath && sameQueryIdentifier;
  12169. }
  12170. toJSON() {
  12171. return this.toString();
  12172. }
  12173. toString() {
  12174. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12175. }
  12176. }
  12177. /**
  12178. * Validates that no other order by call has been made
  12179. */
  12180. function validateNoPreviousOrderByCall(query, fnName) {
  12181. if (query._orderByCalled === true) {
  12182. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12183. }
  12184. }
  12185. /**
  12186. * Validates start/end values for queries.
  12187. */
  12188. function validateQueryEndpoints(params) {
  12189. let startNode = null;
  12190. let endNode = null;
  12191. if (params.hasStart()) {
  12192. startNode = params.getIndexStartValue();
  12193. }
  12194. if (params.hasEnd()) {
  12195. endNode = params.getIndexEndValue();
  12196. }
  12197. if (params.getIndex() === KEY_INDEX) {
  12198. const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12199. 'startAt(), endAt(), or equalTo().';
  12200. const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12201. 'endAt(), endBefore(), or equalTo() must be a string.';
  12202. if (params.hasStart()) {
  12203. const startName = params.getIndexStartName();
  12204. if (startName !== MIN_NAME) {
  12205. throw new Error(tooManyArgsError);
  12206. }
  12207. else if (typeof startNode !== 'string') {
  12208. throw new Error(wrongArgTypeError);
  12209. }
  12210. }
  12211. if (params.hasEnd()) {
  12212. const endName = params.getIndexEndName();
  12213. if (endName !== MAX_NAME) {
  12214. throw new Error(tooManyArgsError);
  12215. }
  12216. else if (typeof endNode !== 'string') {
  12217. throw new Error(wrongArgTypeError);
  12218. }
  12219. }
  12220. }
  12221. else if (params.getIndex() === PRIORITY_INDEX) {
  12222. if ((startNode != null && !isValidPriority(startNode)) ||
  12223. (endNode != null && !isValidPriority(endNode))) {
  12224. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12225. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12226. '(null, a number, or a string).');
  12227. }
  12228. }
  12229. else {
  12230. assert(params.getIndex() instanceof PathIndex ||
  12231. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12232. if ((startNode != null && typeof startNode === 'object') ||
  12233. (endNode != null && typeof endNode === 'object')) {
  12234. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12235. 'equalTo() cannot be an object.');
  12236. }
  12237. }
  12238. }
  12239. /**
  12240. * Validates that limit* has been called with the correct combination of parameters
  12241. */
  12242. function validateLimit(params) {
  12243. if (params.hasStart() &&
  12244. params.hasEnd() &&
  12245. params.hasLimit() &&
  12246. !params.hasAnchoredLimit()) {
  12247. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12248. 'limitToFirst() or limitToLast() instead.');
  12249. }
  12250. }
  12251. /**
  12252. * @internal
  12253. */
  12254. class ReferenceImpl extends QueryImpl {
  12255. /** @hideconstructor */
  12256. constructor(repo, path) {
  12257. super(repo, path, new QueryParams(), false);
  12258. }
  12259. get parent() {
  12260. const parentPath = pathParent(this._path);
  12261. return parentPath === null
  12262. ? null
  12263. : new ReferenceImpl(this._repo, parentPath);
  12264. }
  12265. get root() {
  12266. let ref = this;
  12267. while (ref.parent !== null) {
  12268. ref = ref.parent;
  12269. }
  12270. return ref;
  12271. }
  12272. }
  12273. /**
  12274. * A `DataSnapshot` contains data from a Database location.
  12275. *
  12276. * Any time you read data from the Database, you receive the data as a
  12277. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12278. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12279. * JavaScript object by calling the `val()` method. Alternatively, you can
  12280. * traverse into the snapshot by calling `child()` to return child snapshots
  12281. * (which you could then call `val()` on).
  12282. *
  12283. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12284. * a Database location. It cannot be modified and will never change (to modify
  12285. * data, you always call the `set()` method on a `Reference` directly).
  12286. */
  12287. class DataSnapshot {
  12288. /**
  12289. * @param _node - A SnapshotNode to wrap.
  12290. * @param ref - The location this snapshot came from.
  12291. * @param _index - The iteration order for this snapshot
  12292. * @hideconstructor
  12293. */
  12294. constructor(_node,
  12295. /**
  12296. * The location of this DataSnapshot.
  12297. */
  12298. ref, _index) {
  12299. this._node = _node;
  12300. this.ref = ref;
  12301. this._index = _index;
  12302. }
  12303. /**
  12304. * Gets the priority value of the data in this `DataSnapshot`.
  12305. *
  12306. * Applications need not use priority but can order collections by
  12307. * ordinary properties (see
  12308. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12309. * ).
  12310. */
  12311. get priority() {
  12312. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12313. return this._node.getPriority().val();
  12314. }
  12315. /**
  12316. * The key (last part of the path) of the location of this `DataSnapshot`.
  12317. *
  12318. * The last token in a Database location is considered its key. For example,
  12319. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12320. * `DataSnapshot` will return the key for the location that generated it.
  12321. * However, accessing the key on the root URL of a Database will return
  12322. * `null`.
  12323. */
  12324. get key() {
  12325. return this.ref.key;
  12326. }
  12327. /** Returns the number of child properties of this `DataSnapshot`. */
  12328. get size() {
  12329. return this._node.numChildren();
  12330. }
  12331. /**
  12332. * Gets another `DataSnapshot` for the location at the specified relative path.
  12333. *
  12334. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12335. * another `DataSnapshot` for the location at the specified relative path. The
  12336. * relative path can either be a simple child name (for example, "ada") or a
  12337. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12338. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12339. * whose value is `null`) is returned.
  12340. *
  12341. * @param path - A relative path to the location of child data.
  12342. */
  12343. child(path) {
  12344. const childPath = new Path(path);
  12345. const childRef = child(this.ref, path);
  12346. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12347. }
  12348. /**
  12349. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12350. * efficient than using `snapshot.val() !== null`.
  12351. */
  12352. exists() {
  12353. return !this._node.isEmpty();
  12354. }
  12355. /**
  12356. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12357. *
  12358. * The `exportVal()` method is similar to `val()`, except priority information
  12359. * is included (if available), making it suitable for backing up your data.
  12360. *
  12361. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12362. * Array, string, number, boolean, or `null`).
  12363. */
  12364. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12365. exportVal() {
  12366. return this._node.val(true);
  12367. }
  12368. /**
  12369. * Enumerates the top-level children in the `DataSnapshot`.
  12370. *
  12371. * Because of the way JavaScript objects work, the ordering of data in the
  12372. * JavaScript object returned by `val()` is not guaranteed to match the
  12373. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12374. * where `forEach()` comes in handy. It guarantees the children of a
  12375. * `DataSnapshot` will be iterated in their query order.
  12376. *
  12377. * If no explicit `orderBy*()` method is used, results are returned
  12378. * ordered by key (unless priorities are used, in which case, results are
  12379. * returned by priority).
  12380. *
  12381. * @param action - A function that will be called for each child DataSnapshot.
  12382. * The callback can return true to cancel further enumeration.
  12383. * @returns true if enumeration was canceled due to your callback returning
  12384. * true.
  12385. */
  12386. forEach(action) {
  12387. if (this._node.isLeafNode()) {
  12388. return false;
  12389. }
  12390. const childrenNode = this._node;
  12391. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12392. return !!childrenNode.forEachChild(this._index, (key, node) => {
  12393. return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
  12394. });
  12395. }
  12396. /**
  12397. * Returns true if the specified child path has (non-null) data.
  12398. *
  12399. * @param path - A relative path to the location of a potential child.
  12400. * @returns `true` if data exists at the specified child path; else
  12401. * `false`.
  12402. */
  12403. hasChild(path) {
  12404. const childPath = new Path(path);
  12405. return !this._node.getChild(childPath).isEmpty();
  12406. }
  12407. /**
  12408. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12409. * properties.
  12410. *
  12411. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12412. * children. If it does, you can enumerate them using `forEach()`. If it
  12413. * doesn't, then either this snapshot contains a primitive value (which can be
  12414. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12415. * `null`).
  12416. *
  12417. * @returns true if this snapshot has any children; else false.
  12418. */
  12419. hasChildren() {
  12420. if (this._node.isLeafNode()) {
  12421. return false;
  12422. }
  12423. else {
  12424. return !this._node.isEmpty();
  12425. }
  12426. }
  12427. /**
  12428. * Returns a JSON-serializable representation of this object.
  12429. */
  12430. toJSON() {
  12431. return this.exportVal();
  12432. }
  12433. /**
  12434. * Extracts a JavaScript value from a `DataSnapshot`.
  12435. *
  12436. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12437. * scalar type (string, number, or boolean), an array, or an object. It may
  12438. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12439. * data).
  12440. *
  12441. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12442. * Array, string, number, boolean, or `null`).
  12443. */
  12444. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12445. val() {
  12446. return this._node.val();
  12447. }
  12448. }
  12449. /**
  12450. *
  12451. * Returns a `Reference` representing the location in the Database
  12452. * corresponding to the provided path. If no path is provided, the `Reference`
  12453. * will point to the root of the Database.
  12454. *
  12455. * @param db - The database instance to obtain a reference for.
  12456. * @param path - Optional path representing the location the returned
  12457. * `Reference` will point. If not provided, the returned `Reference` will
  12458. * point to the root of the Database.
  12459. * @returns If a path is provided, a `Reference`
  12460. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12461. * root of the Database.
  12462. */
  12463. function ref(db, path) {
  12464. db = getModularInstance(db);
  12465. db._checkNotDeleted('ref');
  12466. return path !== undefined ? child(db._root, path) : db._root;
  12467. }
  12468. /**
  12469. * Returns a `Reference` representing the location in the Database
  12470. * corresponding to the provided Firebase URL.
  12471. *
  12472. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12473. * has a different domain than the current `Database` instance.
  12474. *
  12475. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12476. * and are not applied to the returned `Reference`.
  12477. *
  12478. * @param db - The database instance to obtain a reference for.
  12479. * @param url - The Firebase URL at which the returned `Reference` will
  12480. * point.
  12481. * @returns A `Reference` pointing to the provided
  12482. * Firebase URL.
  12483. */
  12484. function refFromURL(db, url) {
  12485. db = getModularInstance(db);
  12486. db._checkNotDeleted('refFromURL');
  12487. const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12488. validateUrl('refFromURL', parsedURL);
  12489. const repoInfo = parsedURL.repoInfo;
  12490. if (!db._repo.repoInfo_.isCustomHost() &&
  12491. repoInfo.host !== db._repo.repoInfo_.host) {
  12492. fatal('refFromURL' +
  12493. ': Host name does not match the current database: ' +
  12494. '(found ' +
  12495. repoInfo.host +
  12496. ' but expected ' +
  12497. db._repo.repoInfo_.host +
  12498. ')');
  12499. }
  12500. return ref(db, parsedURL.path.toString());
  12501. }
  12502. /**
  12503. * Gets a `Reference` for the location at the specified relative path.
  12504. *
  12505. * The relative path can either be a simple child name (for example, "ada") or
  12506. * a deeper slash-separated path (for example, "ada/name/first").
  12507. *
  12508. * @param parent - The parent location.
  12509. * @param path - A relative path from this location to the desired child
  12510. * location.
  12511. * @returns The specified child location.
  12512. */
  12513. function child(parent, path) {
  12514. parent = getModularInstance(parent);
  12515. if (pathGetFront(parent._path) === null) {
  12516. validateRootPathString('child', 'path', path, false);
  12517. }
  12518. else {
  12519. validatePathString('child', 'path', path, false);
  12520. }
  12521. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12522. }
  12523. /**
  12524. * Returns an `OnDisconnect` object - see
  12525. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12526. * for more information on how to use it.
  12527. *
  12528. * @param ref - The reference to add OnDisconnect triggers for.
  12529. */
  12530. function onDisconnect(ref) {
  12531. ref = getModularInstance(ref);
  12532. return new OnDisconnect(ref._repo, ref._path);
  12533. }
  12534. /**
  12535. * Generates a new child location using a unique key and returns its
  12536. * `Reference`.
  12537. *
  12538. * This is the most common pattern for adding data to a collection of items.
  12539. *
  12540. * If you provide a value to `push()`, the value is written to the
  12541. * generated location. If you don't pass a value, nothing is written to the
  12542. * database and the child remains empty (but you can use the `Reference`
  12543. * elsewhere).
  12544. *
  12545. * The unique keys generated by `push()` are ordered by the current time, so the
  12546. * resulting list of items is chronologically sorted. The keys are also
  12547. * designed to be unguessable (they contain 72 random bits of entropy).
  12548. *
  12549. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12550. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12551. *
  12552. * @param parent - The parent location.
  12553. * @param value - Optional value to be written at the generated location.
  12554. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12555. * but can be used immediately as the `Reference` to the child location.
  12556. */
  12557. function push(parent, value) {
  12558. parent = getModularInstance(parent);
  12559. validateWritablePath('push', parent._path);
  12560. validateFirebaseDataArg('push', value, parent._path, true);
  12561. const now = repoServerTime(parent._repo);
  12562. const name = nextPushId(now);
  12563. // push() returns a ThennableReference whose promise is fulfilled with a
  12564. // regular Reference. We use child() to create handles to two different
  12565. // references. The first is turned into a ThennableReference below by adding
  12566. // then() and catch() methods and is used as the return value of push(). The
  12567. // second remains a regular Reference and is used as the fulfilled value of
  12568. // the first ThennableReference.
  12569. const thennablePushRef = child(parent, name);
  12570. const pushRef = child(parent, name);
  12571. let promise;
  12572. if (value != null) {
  12573. promise = set(pushRef, value).then(() => pushRef);
  12574. }
  12575. else {
  12576. promise = Promise.resolve(pushRef);
  12577. }
  12578. thennablePushRef.then = promise.then.bind(promise);
  12579. thennablePushRef.catch = promise.then.bind(promise, undefined);
  12580. return thennablePushRef;
  12581. }
  12582. /**
  12583. * Removes the data at this Database location.
  12584. *
  12585. * Any data at child locations will also be deleted.
  12586. *
  12587. * The effect of the remove will be visible immediately and the corresponding
  12588. * event 'value' will be triggered. Synchronization of the remove to the
  12589. * Firebase servers will also be started, and the returned Promise will resolve
  12590. * when complete. If provided, the onComplete callback will be called
  12591. * asynchronously after synchronization has finished.
  12592. *
  12593. * @param ref - The location to remove.
  12594. * @returns Resolves when remove on server is complete.
  12595. */
  12596. function remove(ref) {
  12597. validateWritablePath('remove', ref._path);
  12598. return set(ref, null);
  12599. }
  12600. /**
  12601. * Writes data to this Database location.
  12602. *
  12603. * This will overwrite any data at this location and all child locations.
  12604. *
  12605. * The effect of the write will be visible immediately, and the corresponding
  12606. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  12607. * the data to the Firebase servers will also be started, and the returned
  12608. * Promise will resolve when complete. If provided, the `onComplete` callback
  12609. * will be called asynchronously after synchronization has finished.
  12610. *
  12611. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  12612. * all data at this location and all child locations will be deleted.
  12613. *
  12614. * `set()` will remove any priority stored at this location, so if priority is
  12615. * meant to be preserved, you need to use `setWithPriority()` instead.
  12616. *
  12617. * Note that modifying data with `set()` will cancel any pending transactions
  12618. * at that location, so extreme care should be taken if mixing `set()` and
  12619. * `transaction()` to modify the same data.
  12620. *
  12621. * A single `set()` will generate a single "value" event at the location where
  12622. * the `set()` was performed.
  12623. *
  12624. * @param ref - The location to write to.
  12625. * @param value - The value to be written (string, number, boolean, object,
  12626. * array, or null).
  12627. * @returns Resolves when write to server is complete.
  12628. */
  12629. function set(ref, value) {
  12630. ref = getModularInstance(ref);
  12631. validateWritablePath('set', ref._path);
  12632. validateFirebaseDataArg('set', value, ref._path, false);
  12633. const deferred = new Deferred();
  12634. repoSetWithPriority(ref._repo, ref._path, value,
  12635. /*priority=*/ null, deferred.wrapCallback(() => { }));
  12636. return deferred.promise;
  12637. }
  12638. /**
  12639. * Sets a priority for the data at this Database location.
  12640. *
  12641. * Applications need not use priority but can order collections by
  12642. * ordinary properties (see
  12643. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12644. * ).
  12645. *
  12646. * @param ref - The location to write to.
  12647. * @param priority - The priority to be written (string, number, or null).
  12648. * @returns Resolves when write to server is complete.
  12649. */
  12650. function setPriority(ref, priority) {
  12651. ref = getModularInstance(ref);
  12652. validateWritablePath('setPriority', ref._path);
  12653. validatePriority('setPriority', priority, false);
  12654. const deferred = new Deferred();
  12655. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
  12656. return deferred.promise;
  12657. }
  12658. /**
  12659. * Writes data the Database location. Like `set()` but also specifies the
  12660. * priority for that data.
  12661. *
  12662. * Applications need not use priority but can order collections by
  12663. * ordinary properties (see
  12664. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  12665. * ).
  12666. *
  12667. * @param ref - The location to write to.
  12668. * @param value - The value to be written (string, number, boolean, object,
  12669. * array, or null).
  12670. * @param priority - The priority to be written (string, number, or null).
  12671. * @returns Resolves when write to server is complete.
  12672. */
  12673. function setWithPriority(ref, value, priority) {
  12674. validateWritablePath('setWithPriority', ref._path);
  12675. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  12676. validatePriority('setWithPriority', priority, false);
  12677. if (ref.key === '.length' || ref.key === '.keys') {
  12678. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  12679. }
  12680. const deferred = new Deferred();
  12681. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
  12682. return deferred.promise;
  12683. }
  12684. /**
  12685. * Writes multiple values to the Database at once.
  12686. *
  12687. * The `values` argument contains multiple property-value pairs that will be
  12688. * written to the Database together. Each child property can either be a simple
  12689. * property (for example, "name") or a relative path (for example,
  12690. * "name/first") from the current location to the data to update.
  12691. *
  12692. * As opposed to the `set()` method, `update()` can be use to selectively update
  12693. * only the referenced properties at the current location (instead of replacing
  12694. * all the child properties at the current location).
  12695. *
  12696. * The effect of the write will be visible immediately, and the corresponding
  12697. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  12698. * the data to the Firebase servers will also be started, and the returned
  12699. * Promise will resolve when complete. If provided, the `onComplete` callback
  12700. * will be called asynchronously after synchronization has finished.
  12701. *
  12702. * A single `update()` will generate a single "value" event at the location
  12703. * where the `update()` was performed, regardless of how many children were
  12704. * modified.
  12705. *
  12706. * Note that modifying data with `update()` will cancel any pending
  12707. * transactions at that location, so extreme care should be taken if mixing
  12708. * `update()` and `transaction()` to modify the same data.
  12709. *
  12710. * Passing `null` to `update()` will remove the data at this location.
  12711. *
  12712. * See
  12713. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  12714. *
  12715. * @param ref - The location to write to.
  12716. * @param values - Object containing multiple values.
  12717. * @returns Resolves when update on server is complete.
  12718. */
  12719. function update(ref, values) {
  12720. validateFirebaseMergeDataArg('update', values, ref._path, false);
  12721. const deferred = new Deferred();
  12722. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
  12723. return deferred.promise;
  12724. }
  12725. /**
  12726. * Gets the most up-to-date result for this query.
  12727. *
  12728. * @param query - The query to run.
  12729. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  12730. * available, or rejects if the client is unable to return a value (e.g., if the
  12731. * server is unreachable and there is nothing cached).
  12732. */
  12733. function get(query) {
  12734. query = getModularInstance(query);
  12735. const callbackContext = new CallbackContext(() => { });
  12736. const container = new ValueEventRegistration(callbackContext);
  12737. return repoGetValue(query._repo, query, container).then(node => {
  12738. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  12739. });
  12740. }
  12741. /**
  12742. * Represents registration for 'value' events.
  12743. */
  12744. class ValueEventRegistration {
  12745. constructor(callbackContext) {
  12746. this.callbackContext = callbackContext;
  12747. }
  12748. respondsTo(eventType) {
  12749. return eventType === 'value';
  12750. }
  12751. createEvent(change, query) {
  12752. const index = query._queryParams.getIndex();
  12753. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  12754. }
  12755. getEventRunner(eventData) {
  12756. if (eventData.getEventType() === 'cancel') {
  12757. return () => this.callbackContext.onCancel(eventData.error);
  12758. }
  12759. else {
  12760. return () => this.callbackContext.onValue(eventData.snapshot, null);
  12761. }
  12762. }
  12763. createCancelEvent(error, path) {
  12764. if (this.callbackContext.hasCancelCallback) {
  12765. return new CancelEvent(this, error, path);
  12766. }
  12767. else {
  12768. return null;
  12769. }
  12770. }
  12771. matches(other) {
  12772. if (!(other instanceof ValueEventRegistration)) {
  12773. return false;
  12774. }
  12775. else if (!other.callbackContext || !this.callbackContext) {
  12776. // If no callback specified, we consider it to match any callback.
  12777. return true;
  12778. }
  12779. else {
  12780. return other.callbackContext.matches(this.callbackContext);
  12781. }
  12782. }
  12783. hasAnyCallback() {
  12784. return this.callbackContext !== null;
  12785. }
  12786. }
  12787. /**
  12788. * Represents the registration of a child_x event.
  12789. */
  12790. class ChildEventRegistration {
  12791. constructor(eventType, callbackContext) {
  12792. this.eventType = eventType;
  12793. this.callbackContext = callbackContext;
  12794. }
  12795. respondsTo(eventType) {
  12796. let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  12797. eventToCheck =
  12798. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  12799. return this.eventType === eventToCheck;
  12800. }
  12801. createCancelEvent(error, path) {
  12802. if (this.callbackContext.hasCancelCallback) {
  12803. return new CancelEvent(this, error, path);
  12804. }
  12805. else {
  12806. return null;
  12807. }
  12808. }
  12809. createEvent(change, query) {
  12810. assert(change.childName != null, 'Child events should have a childName.');
  12811. const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  12812. const index = query._queryParams.getIndex();
  12813. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  12814. }
  12815. getEventRunner(eventData) {
  12816. if (eventData.getEventType() === 'cancel') {
  12817. return () => this.callbackContext.onCancel(eventData.error);
  12818. }
  12819. else {
  12820. return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  12821. }
  12822. }
  12823. matches(other) {
  12824. if (other instanceof ChildEventRegistration) {
  12825. return (this.eventType === other.eventType &&
  12826. (!this.callbackContext ||
  12827. !other.callbackContext ||
  12828. this.callbackContext.matches(other.callbackContext)));
  12829. }
  12830. return false;
  12831. }
  12832. hasAnyCallback() {
  12833. return !!this.callbackContext;
  12834. }
  12835. }
  12836. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  12837. let cancelCallback;
  12838. if (typeof cancelCallbackOrListenOptions === 'object') {
  12839. cancelCallback = undefined;
  12840. options = cancelCallbackOrListenOptions;
  12841. }
  12842. if (typeof cancelCallbackOrListenOptions === 'function') {
  12843. cancelCallback = cancelCallbackOrListenOptions;
  12844. }
  12845. if (options && options.onlyOnce) {
  12846. const userCallback = callback;
  12847. const onceCallback = (dataSnapshot, previousChildName) => {
  12848. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12849. userCallback(dataSnapshot, previousChildName);
  12850. };
  12851. onceCallback.userCallback = callback.userCallback;
  12852. onceCallback.context = callback.context;
  12853. callback = onceCallback;
  12854. }
  12855. const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  12856. const container = eventType === 'value'
  12857. ? new ValueEventRegistration(callbackContext)
  12858. : new ChildEventRegistration(eventType, callbackContext);
  12859. repoAddEventCallbackForQuery(query._repo, query, container);
  12860. return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  12861. }
  12862. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  12863. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  12864. }
  12865. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  12866. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  12867. }
  12868. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  12869. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  12870. }
  12871. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  12872. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  12873. }
  12874. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  12875. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  12876. }
  12877. /**
  12878. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  12879. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  12880. * the respective `on*` callbacks.
  12881. *
  12882. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  12883. * will not automatically remove listeners registered on child nodes, `off()`
  12884. * must also be called on any child listeners to remove the callback.
  12885. *
  12886. * If a callback is not specified, all callbacks for the specified eventType
  12887. * will be removed. Similarly, if no eventType is specified, all callbacks
  12888. * for the `Reference` will be removed.
  12889. *
  12890. * Individual listeners can also be removed by invoking their unsubscribe
  12891. * callbacks.
  12892. *
  12893. * @param query - The query that the listener was registered with.
  12894. * @param eventType - One of the following strings: "value", "child_added",
  12895. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  12896. * for the `Reference` will be removed.
  12897. * @param callback - The callback function that was passed to `on()` or
  12898. * `undefined` to remove all callbacks.
  12899. */
  12900. function off(query, eventType, callback) {
  12901. let container = null;
  12902. const expCallback = callback ? new CallbackContext(callback) : null;
  12903. if (eventType === 'value') {
  12904. container = new ValueEventRegistration(expCallback);
  12905. }
  12906. else if (eventType) {
  12907. container = new ChildEventRegistration(eventType, expCallback);
  12908. }
  12909. repoRemoveEventCallbackForQuery(query._repo, query, container);
  12910. }
  12911. /**
  12912. * A `QueryConstraint` is used to narrow the set of documents returned by a
  12913. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  12914. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  12915. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  12916. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  12917. * {@link orderByValue} or {@link equalTo} and
  12918. * can then be passed to {@link query} to create a new query instance that
  12919. * also contains this `QueryConstraint`.
  12920. */
  12921. class QueryConstraint {
  12922. }
  12923. class QueryEndAtConstraint extends QueryConstraint {
  12924. constructor(_value, _key) {
  12925. super();
  12926. this._value = _value;
  12927. this._key = _key;
  12928. }
  12929. _apply(query) {
  12930. validateFirebaseDataArg('endAt', this._value, query._path, true);
  12931. const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  12932. validateLimit(newParams);
  12933. validateQueryEndpoints(newParams);
  12934. if (query._queryParams.hasEnd()) {
  12935. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  12936. 'endBefore or equalTo).');
  12937. }
  12938. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12939. }
  12940. }
  12941. /**
  12942. * Creates a `QueryConstraint` with the specified ending point.
  12943. *
  12944. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12945. * allows you to choose arbitrary starting and ending points for your queries.
  12946. *
  12947. * The ending point is inclusive, so children with exactly the specified value
  12948. * will be included in the query. The optional key argument can be used to
  12949. * further limit the range of the query. If it is specified, then children that
  12950. * have exactly the specified value must also have a key name less than or equal
  12951. * to the specified key.
  12952. *
  12953. * You can read more about `endAt()` in
  12954. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  12955. *
  12956. * @param value - The value to end at. The argument type depends on which
  12957. * `orderBy*()` function was used in this query. Specify a value that matches
  12958. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  12959. * value must be a string.
  12960. * @param key - The child key to end at, among the children with the previously
  12961. * specified priority. This argument is only allowed if ordering by child,
  12962. * value, or priority.
  12963. */
  12964. function endAt(value, key) {
  12965. validateKey('endAt', 'key', key, true);
  12966. return new QueryEndAtConstraint(value, key);
  12967. }
  12968. class QueryEndBeforeConstraint extends QueryConstraint {
  12969. constructor(_value, _key) {
  12970. super();
  12971. this._value = _value;
  12972. this._key = _key;
  12973. }
  12974. _apply(query) {
  12975. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  12976. const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  12977. validateLimit(newParams);
  12978. validateQueryEndpoints(newParams);
  12979. if (query._queryParams.hasEnd()) {
  12980. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  12981. 'endBefore or equalTo).');
  12982. }
  12983. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  12984. }
  12985. }
  12986. /**
  12987. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  12988. *
  12989. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  12990. * allows you to choose arbitrary starting and ending points for your queries.
  12991. *
  12992. * The ending point is exclusive. If only a value is provided, children
  12993. * with a value less than the specified value will be included in the query.
  12994. * If a key is specified, then children must have a value less than or equal
  12995. * to the specified value and a key name less than the specified key.
  12996. *
  12997. * @param value - The value to end before. The argument type depends on which
  12998. * `orderBy*()` function was used in this query. Specify a value that matches
  12999. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13000. * value must be a string.
  13001. * @param key - The child key to end before, among the children with the
  13002. * previously specified priority. This argument is only allowed if ordering by
  13003. * child, value, or priority.
  13004. */
  13005. function endBefore(value, key) {
  13006. validateKey('endBefore', 'key', key, true);
  13007. return new QueryEndBeforeConstraint(value, key);
  13008. }
  13009. class QueryStartAtConstraint extends QueryConstraint {
  13010. constructor(_value, _key) {
  13011. super();
  13012. this._value = _value;
  13013. this._key = _key;
  13014. }
  13015. _apply(query) {
  13016. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13017. const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13018. validateLimit(newParams);
  13019. validateQueryEndpoints(newParams);
  13020. if (query._queryParams.hasStart()) {
  13021. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13022. 'startBefore or equalTo).');
  13023. }
  13024. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13025. }
  13026. }
  13027. /**
  13028. * Creates a `QueryConstraint` with the specified starting point.
  13029. *
  13030. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13031. * allows you to choose arbitrary starting and ending points for your queries.
  13032. *
  13033. * The starting point is inclusive, so children with exactly the specified value
  13034. * will be included in the query. The optional key argument can be used to
  13035. * further limit the range of the query. If it is specified, then children that
  13036. * have exactly the specified value must also have a key name greater than or
  13037. * equal to the specified key.
  13038. *
  13039. * You can read more about `startAt()` in
  13040. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13041. *
  13042. * @param value - The value to start at. The argument type depends on which
  13043. * `orderBy*()` function was used in this query. Specify a value that matches
  13044. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13045. * value must be a string.
  13046. * @param key - The child key to start at. This argument is only allowed if
  13047. * ordering by child, value, or priority.
  13048. */
  13049. function startAt(value = null, key) {
  13050. validateKey('startAt', 'key', key, true);
  13051. return new QueryStartAtConstraint(value, key);
  13052. }
  13053. class QueryStartAfterConstraint extends QueryConstraint {
  13054. constructor(_value, _key) {
  13055. super();
  13056. this._value = _value;
  13057. this._key = _key;
  13058. }
  13059. _apply(query) {
  13060. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13061. const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13062. validateLimit(newParams);
  13063. validateQueryEndpoints(newParams);
  13064. if (query._queryParams.hasStart()) {
  13065. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13066. 'startAfter, or equalTo).');
  13067. }
  13068. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13069. }
  13070. }
  13071. /**
  13072. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13073. *
  13074. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13075. * allows you to choose arbitrary starting and ending points for your queries.
  13076. *
  13077. * The starting point is exclusive. If only a value is provided, children
  13078. * with a value greater than the specified value will be included in the query.
  13079. * If a key is specified, then children must have a value greater than or equal
  13080. * to the specified value and a a key name greater than the specified key.
  13081. *
  13082. * @param value - The value to start after. The argument type depends on which
  13083. * `orderBy*()` function was used in this query. Specify a value that matches
  13084. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13085. * value must be a string.
  13086. * @param key - The child key to start after. This argument is only allowed if
  13087. * ordering by child, value, or priority.
  13088. */
  13089. function startAfter(value, key) {
  13090. validateKey('startAfter', 'key', key, true);
  13091. return new QueryStartAfterConstraint(value, key);
  13092. }
  13093. class QueryLimitToFirstConstraint extends QueryConstraint {
  13094. constructor(_limit) {
  13095. super();
  13096. this._limit = _limit;
  13097. }
  13098. _apply(query) {
  13099. if (query._queryParams.hasLimit()) {
  13100. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13101. 'or limitToLast).');
  13102. }
  13103. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13104. }
  13105. }
  13106. /**
  13107. * Creates a new `QueryConstraint` that if limited to the first specific number
  13108. * of children.
  13109. *
  13110. * The `limitToFirst()` method is used to set a maximum number of children to be
  13111. * synced for a given callback. If we set a limit of 100, we will initially only
  13112. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13113. * stored in our Database, a `child_added` event will fire for each message.
  13114. * However, if we have over 100 messages, we will only receive a `child_added`
  13115. * event for the first 100 ordered messages. As items change, we will receive
  13116. * `child_removed` events for each item that drops out of the active list so
  13117. * that the total number stays at 100.
  13118. *
  13119. * You can read more about `limitToFirst()` in
  13120. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13121. *
  13122. * @param limit - The maximum number of nodes to include in this query.
  13123. */
  13124. function limitToFirst(limit) {
  13125. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13126. throw new Error('limitToFirst: First argument must be a positive integer.');
  13127. }
  13128. return new QueryLimitToFirstConstraint(limit);
  13129. }
  13130. class QueryLimitToLastConstraint extends QueryConstraint {
  13131. constructor(_limit) {
  13132. super();
  13133. this._limit = _limit;
  13134. }
  13135. _apply(query) {
  13136. if (query._queryParams.hasLimit()) {
  13137. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13138. 'or limitToLast).');
  13139. }
  13140. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13141. }
  13142. }
  13143. /**
  13144. * Creates a new `QueryConstraint` that is limited to return only the last
  13145. * specified number of children.
  13146. *
  13147. * The `limitToLast()` method is used to set a maximum number of children to be
  13148. * synced for a given callback. If we set a limit of 100, we will initially only
  13149. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13150. * stored in our Database, a `child_added` event will fire for each message.
  13151. * However, if we have over 100 messages, we will only receive a `child_added`
  13152. * event for the last 100 ordered messages. As items change, we will receive
  13153. * `child_removed` events for each item that drops out of the active list so
  13154. * that the total number stays at 100.
  13155. *
  13156. * You can read more about `limitToLast()` in
  13157. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13158. *
  13159. * @param limit - The maximum number of nodes to include in this query.
  13160. */
  13161. function limitToLast(limit) {
  13162. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13163. throw new Error('limitToLast: First argument must be a positive integer.');
  13164. }
  13165. return new QueryLimitToLastConstraint(limit);
  13166. }
  13167. class QueryOrderByChildConstraint extends QueryConstraint {
  13168. constructor(_path) {
  13169. super();
  13170. this._path = _path;
  13171. }
  13172. _apply(query) {
  13173. validateNoPreviousOrderByCall(query, 'orderByChild');
  13174. const parsedPath = new Path(this._path);
  13175. if (pathIsEmpty(parsedPath)) {
  13176. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13177. }
  13178. const index = new PathIndex(parsedPath);
  13179. const newParams = queryParamsOrderBy(query._queryParams, index);
  13180. validateQueryEndpoints(newParams);
  13181. return new QueryImpl(query._repo, query._path, newParams,
  13182. /*orderByCalled=*/ true);
  13183. }
  13184. }
  13185. /**
  13186. * Creates a new `QueryConstraint` that orders by the specified child key.
  13187. *
  13188. * Queries can only order by one key at a time. Calling `orderByChild()`
  13189. * multiple times on the same query is an error.
  13190. *
  13191. * Firebase queries allow you to order your data by any child key on the fly.
  13192. * However, if you know in advance what your indexes will be, you can define
  13193. * them via the .indexOn rule in your Security Rules for better performance. See
  13194. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13195. * rule for more information.
  13196. *
  13197. * You can read more about `orderByChild()` in
  13198. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13199. *
  13200. * @param path - The path to order by.
  13201. */
  13202. function orderByChild(path) {
  13203. if (path === '$key') {
  13204. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13205. }
  13206. else if (path === '$priority') {
  13207. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13208. }
  13209. else if (path === '$value') {
  13210. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13211. }
  13212. validatePathString('orderByChild', 'path', path, false);
  13213. return new QueryOrderByChildConstraint(path);
  13214. }
  13215. class QueryOrderByKeyConstraint extends QueryConstraint {
  13216. _apply(query) {
  13217. validateNoPreviousOrderByCall(query, 'orderByKey');
  13218. const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13219. validateQueryEndpoints(newParams);
  13220. return new QueryImpl(query._repo, query._path, newParams,
  13221. /*orderByCalled=*/ true);
  13222. }
  13223. }
  13224. /**
  13225. * Creates a new `QueryConstraint` that orders by the key.
  13226. *
  13227. * Sorts the results of a query by their (ascending) key values.
  13228. *
  13229. * You can read more about `orderByKey()` in
  13230. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13231. */
  13232. function orderByKey() {
  13233. return new QueryOrderByKeyConstraint();
  13234. }
  13235. class QueryOrderByPriorityConstraint extends QueryConstraint {
  13236. _apply(query) {
  13237. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13238. const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13239. validateQueryEndpoints(newParams);
  13240. return new QueryImpl(query._repo, query._path, newParams,
  13241. /*orderByCalled=*/ true);
  13242. }
  13243. }
  13244. /**
  13245. * Creates a new `QueryConstraint` that orders by priority.
  13246. *
  13247. * Applications need not use priority but can order collections by
  13248. * ordinary properties (see
  13249. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13250. * for alternatives to priority.
  13251. */
  13252. function orderByPriority() {
  13253. return new QueryOrderByPriorityConstraint();
  13254. }
  13255. class QueryOrderByValueConstraint extends QueryConstraint {
  13256. _apply(query) {
  13257. validateNoPreviousOrderByCall(query, 'orderByValue');
  13258. const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13259. validateQueryEndpoints(newParams);
  13260. return new QueryImpl(query._repo, query._path, newParams,
  13261. /*orderByCalled=*/ true);
  13262. }
  13263. }
  13264. /**
  13265. * Creates a new `QueryConstraint` that orders by value.
  13266. *
  13267. * If the children of a query are all scalar values (string, number, or
  13268. * boolean), you can order the results by their (ascending) values.
  13269. *
  13270. * You can read more about `orderByValue()` in
  13271. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13272. */
  13273. function orderByValue() {
  13274. return new QueryOrderByValueConstraint();
  13275. }
  13276. class QueryEqualToValueConstraint extends QueryConstraint {
  13277. constructor(_value, _key) {
  13278. super();
  13279. this._value = _value;
  13280. this._key = _key;
  13281. }
  13282. _apply(query) {
  13283. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13284. if (query._queryParams.hasStart()) {
  13285. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13286. 'equalTo).');
  13287. }
  13288. if (query._queryParams.hasEnd()) {
  13289. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13290. 'equalTo).');
  13291. }
  13292. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13293. }
  13294. }
  13295. /**
  13296. * Creates a `QueryConstraint` that includes children that match the specified
  13297. * value.
  13298. *
  13299. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13300. * allows you to choose arbitrary starting and ending points for your queries.
  13301. *
  13302. * The optional key argument can be used to further limit the range of the
  13303. * query. If it is specified, then children that have exactly the specified
  13304. * value must also have exactly the specified key as their key name. This can be
  13305. * used to filter result sets with many matches for the same value.
  13306. *
  13307. * You can read more about `equalTo()` in
  13308. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13309. *
  13310. * @param value - The value to match for. The argument type depends on which
  13311. * `orderBy*()` function was used in this query. Specify a value that matches
  13312. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13313. * value must be a string.
  13314. * @param key - The child key to start at, among the children with the
  13315. * previously specified priority. This argument is only allowed if ordering by
  13316. * child, value, or priority.
  13317. */
  13318. function equalTo(value, key) {
  13319. validateKey('equalTo', 'key', key, true);
  13320. return new QueryEqualToValueConstraint(value, key);
  13321. }
  13322. /**
  13323. * Creates a new immutable instance of `Query` that is extended to also include
  13324. * additional query constraints.
  13325. *
  13326. * @param query - The Query instance to use as a base for the new constraints.
  13327. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13328. * @throws if any of the provided query constraints cannot be combined with the
  13329. * existing or new constraints.
  13330. */
  13331. function query(query, ...queryConstraints) {
  13332. let queryImpl = getModularInstance(query);
  13333. for (const constraint of queryConstraints) {
  13334. queryImpl = constraint._apply(queryImpl);
  13335. }
  13336. return queryImpl;
  13337. }
  13338. /**
  13339. * Define reference constructor in various modules
  13340. *
  13341. * We are doing this here to avoid several circular
  13342. * dependency issues
  13343. */
  13344. syncPointSetReferenceConstructor(ReferenceImpl);
  13345. syncTreeSetReferenceConstructor(ReferenceImpl);
  13346. /**
  13347. * @license
  13348. * Copyright 2020 Google LLC
  13349. *
  13350. * Licensed under the Apache License, Version 2.0 (the "License");
  13351. * you may not use this file except in compliance with the License.
  13352. * You may obtain a copy of the License at
  13353. *
  13354. * http://www.apache.org/licenses/LICENSE-2.0
  13355. *
  13356. * Unless required by applicable law or agreed to in writing, software
  13357. * distributed under the License is distributed on an "AS IS" BASIS,
  13358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13359. * See the License for the specific language governing permissions and
  13360. * limitations under the License.
  13361. */
  13362. /**
  13363. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13364. * modifying this definition, consult the definition in:
  13365. *
  13366. * https://github.com/firebase/firebase-admin-node
  13367. *
  13368. * and make sure the two are consistent.
  13369. */
  13370. const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13371. /**
  13372. * Creates and caches `Repo` instances.
  13373. */
  13374. const repos = {};
  13375. /**
  13376. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13377. */
  13378. let useRestClient = false;
  13379. /**
  13380. * Update an existing `Repo` in place to point to a new host/port.
  13381. */
  13382. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13383. repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
  13384. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
  13385. if (tokenProvider) {
  13386. repo.authTokenProvider_ = tokenProvider;
  13387. }
  13388. }
  13389. /**
  13390. * This function should only ever be called to CREATE a new database instance.
  13391. * @internal
  13392. */
  13393. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13394. let dbUrl = url || app.options.databaseURL;
  13395. if (dbUrl === undefined) {
  13396. if (!app.options.projectId) {
  13397. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13398. ' a Project ID when calling firebase.initializeApp().');
  13399. }
  13400. log('Using default host for project ', app.options.projectId);
  13401. dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
  13402. }
  13403. let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13404. let repoInfo = parsedUrl.repoInfo;
  13405. let isEmulator;
  13406. let dbEmulatorHost = undefined;
  13407. if (typeof process !== 'undefined' && process.env) {
  13408. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13409. }
  13410. if (dbEmulatorHost) {
  13411. isEmulator = true;
  13412. dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
  13413. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13414. repoInfo = parsedUrl.repoInfo;
  13415. }
  13416. else {
  13417. isEmulator = !parsedUrl.repoInfo.secure;
  13418. }
  13419. const authTokenProvider = nodeAdmin && isEmulator
  13420. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13421. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13422. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13423. if (!pathIsEmpty(parsedUrl.path)) {
  13424. fatal('Database URL must point to the root of a Firebase Database ' +
  13425. '(not including a child path).');
  13426. }
  13427. const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13428. return new Database(repo, app);
  13429. }
  13430. /**
  13431. * Remove the repo and make sure it is disconnected.
  13432. *
  13433. */
  13434. function repoManagerDeleteRepo(repo, appName) {
  13435. const appRepos = repos[appName];
  13436. // This should never happen...
  13437. if (!appRepos || appRepos[repo.key] !== repo) {
  13438. fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
  13439. }
  13440. repoInterrupt(repo);
  13441. delete appRepos[repo.key];
  13442. }
  13443. /**
  13444. * Ensures a repo doesn't already exist and then creates one using the
  13445. * provided app.
  13446. *
  13447. * @param repoInfo - The metadata about the Repo
  13448. * @returns The Repo object for the specified server / repoName.
  13449. */
  13450. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13451. let appRepos = repos[app.name];
  13452. if (!appRepos) {
  13453. appRepos = {};
  13454. repos[app.name] = appRepos;
  13455. }
  13456. let repo = appRepos[repoInfo.toURLString()];
  13457. if (repo) {
  13458. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13459. }
  13460. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13461. appRepos[repoInfo.toURLString()] = repo;
  13462. return repo;
  13463. }
  13464. /**
  13465. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13466. */
  13467. function repoManagerForceRestClient(forceRestClient) {
  13468. useRestClient = forceRestClient;
  13469. }
  13470. /**
  13471. * Class representing a Firebase Realtime Database.
  13472. */
  13473. class Database {
  13474. /** @hideconstructor */
  13475. constructor(_repoInternal,
  13476. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13477. app) {
  13478. this._repoInternal = _repoInternal;
  13479. this.app = app;
  13480. /** Represents a `Database` instance. */
  13481. this['type'] = 'database';
  13482. /** Track if the instance has been used (root or repo accessed) */
  13483. this._instanceStarted = false;
  13484. }
  13485. get _repo() {
  13486. if (!this._instanceStarted) {
  13487. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13488. this._instanceStarted = true;
  13489. }
  13490. return this._repoInternal;
  13491. }
  13492. get _root() {
  13493. if (!this._rootInternal) {
  13494. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13495. }
  13496. return this._rootInternal;
  13497. }
  13498. _delete() {
  13499. if (this._rootInternal !== null) {
  13500. repoManagerDeleteRepo(this._repo, this.app.name);
  13501. this._repoInternal = null;
  13502. this._rootInternal = null;
  13503. }
  13504. return Promise.resolve();
  13505. }
  13506. _checkNotDeleted(apiName) {
  13507. if (this._rootInternal === null) {
  13508. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13509. }
  13510. }
  13511. }
  13512. function checkTransportInit() {
  13513. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13514. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13515. }
  13516. }
  13517. /**
  13518. * Force the use of websockets instead of longPolling.
  13519. */
  13520. function forceWebSockets() {
  13521. checkTransportInit();
  13522. BrowserPollConnection.forceDisallow();
  13523. }
  13524. /**
  13525. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  13526. */
  13527. function forceLongPolling() {
  13528. checkTransportInit();
  13529. WebSocketConnection.forceDisallow();
  13530. BrowserPollConnection.forceAllow();
  13531. }
  13532. /**
  13533. * Returns the instance of the Realtime Database SDK that is associated
  13534. * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with
  13535. * with default settings if no instance exists or if the existing instance uses
  13536. * a custom database URL.
  13537. *
  13538. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  13539. * Database instance is associated with.
  13540. * @param url - The URL of the Realtime Database instance to connect to. If not
  13541. * provided, the SDK connects to the default instance of the Firebase App.
  13542. * @returns The `Database` instance of the provided app.
  13543. */
  13544. function getDatabase(app = getApp(), url) {
  13545. const db = _getProvider(app, 'database').getImmediate({
  13546. identifier: url
  13547. });
  13548. if (!db._instanceStarted) {
  13549. const emulator = getDefaultEmulatorHostnameAndPort('database');
  13550. if (emulator) {
  13551. connectDatabaseEmulator(db, ...emulator);
  13552. }
  13553. }
  13554. return db;
  13555. }
  13556. /**
  13557. * Modify the provided instance to communicate with the Realtime Database
  13558. * emulator.
  13559. *
  13560. * <p>Note: This method must be called before performing any other operation.
  13561. *
  13562. * @param db - The instance to modify.
  13563. * @param host - The emulator host (ex: localhost)
  13564. * @param port - The emulator port (ex: 8080)
  13565. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  13566. */
  13567. function connectDatabaseEmulator(db, host, port, options = {}) {
  13568. db = getModularInstance(db);
  13569. db._checkNotDeleted('useEmulator');
  13570. if (db._instanceStarted) {
  13571. fatal('Cannot call useEmulator() after instance has already been initialized.');
  13572. }
  13573. const repo = db._repoInternal;
  13574. let tokenProvider = undefined;
  13575. if (repo.repoInfo_.nodeAdmin) {
  13576. if (options.mockUserToken) {
  13577. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  13578. }
  13579. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  13580. }
  13581. else if (options.mockUserToken) {
  13582. const token = typeof options.mockUserToken === 'string'
  13583. ? options.mockUserToken
  13584. : createMockUserToken(options.mockUserToken, db.app.options.projectId);
  13585. tokenProvider = new EmulatorTokenProvider(token);
  13586. }
  13587. // Modify the repo to apply emulator settings
  13588. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  13589. }
  13590. /**
  13591. * Disconnects from the server (all Database operations will be completed
  13592. * offline).
  13593. *
  13594. * The client automatically maintains a persistent connection to the Database
  13595. * server, which will remain active indefinitely and reconnect when
  13596. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  13597. * to control the client connection in cases where a persistent connection is
  13598. * undesirable.
  13599. *
  13600. * While offline, the client will no longer receive data updates from the
  13601. * Database. However, all Database operations performed locally will continue to
  13602. * immediately fire events, allowing your application to continue behaving
  13603. * normally. Additionally, each operation performed locally will automatically
  13604. * be queued and retried upon reconnection to the Database server.
  13605. *
  13606. * To reconnect to the Database and begin receiving remote events, see
  13607. * `goOnline()`.
  13608. *
  13609. * @param db - The instance to disconnect.
  13610. */
  13611. function goOffline(db) {
  13612. db = getModularInstance(db);
  13613. db._checkNotDeleted('goOffline');
  13614. repoInterrupt(db._repo);
  13615. }
  13616. /**
  13617. * Reconnects to the server and synchronizes the offline Database state
  13618. * with the server state.
  13619. *
  13620. * This method should be used after disabling the active connection with
  13621. * `goOffline()`. Once reconnected, the client will transmit the proper data
  13622. * and fire the appropriate events so that your client "catches up"
  13623. * automatically.
  13624. *
  13625. * @param db - The instance to reconnect.
  13626. */
  13627. function goOnline(db) {
  13628. db = getModularInstance(db);
  13629. db._checkNotDeleted('goOnline');
  13630. repoResume(db._repo);
  13631. }
  13632. function enableLogging(logger, persistent) {
  13633. enableLogging$1(logger, persistent);
  13634. }
  13635. /**
  13636. * @license
  13637. * Copyright 2021 Google LLC
  13638. *
  13639. * Licensed under the Apache License, Version 2.0 (the "License");
  13640. * you may not use this file except in compliance with the License.
  13641. * You may obtain a copy of the License at
  13642. *
  13643. * http://www.apache.org/licenses/LICENSE-2.0
  13644. *
  13645. * Unless required by applicable law or agreed to in writing, software
  13646. * distributed under the License is distributed on an "AS IS" BASIS,
  13647. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13648. * See the License for the specific language governing permissions and
  13649. * limitations under the License.
  13650. */
  13651. function registerDatabase(variant) {
  13652. setSDKVersion(SDK_VERSION$1);
  13653. _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {
  13654. const app = container.getProvider('app').getImmediate();
  13655. const authProvider = container.getProvider('auth-internal');
  13656. const appCheckProvider = container.getProvider('app-check-internal');
  13657. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  13658. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  13659. registerVersion(name, version, variant);
  13660. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  13661. registerVersion(name, version, 'esm2017');
  13662. }
  13663. /**
  13664. * @license
  13665. * Copyright 2020 Google LLC
  13666. *
  13667. * Licensed under the Apache License, Version 2.0 (the "License");
  13668. * you may not use this file except in compliance with the License.
  13669. * You may obtain a copy of the License at
  13670. *
  13671. * http://www.apache.org/licenses/LICENSE-2.0
  13672. *
  13673. * Unless required by applicable law or agreed to in writing, software
  13674. * distributed under the License is distributed on an "AS IS" BASIS,
  13675. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13676. * See the License for the specific language governing permissions and
  13677. * limitations under the License.
  13678. */
  13679. const SERVER_TIMESTAMP = {
  13680. '.sv': 'timestamp'
  13681. };
  13682. /**
  13683. * Returns a placeholder value for auto-populating the current timestamp (time
  13684. * since the Unix epoch, in milliseconds) as determined by the Firebase
  13685. * servers.
  13686. */
  13687. function serverTimestamp() {
  13688. return SERVER_TIMESTAMP;
  13689. }
  13690. /**
  13691. * Returns a placeholder value that can be used to atomically increment the
  13692. * current database value by the provided delta.
  13693. *
  13694. * @param delta - the amount to modify the current value atomically.
  13695. * @returns A placeholder value for modifying data atomically server-side.
  13696. */
  13697. function increment(delta) {
  13698. return {
  13699. '.sv': {
  13700. 'increment': delta
  13701. }
  13702. };
  13703. }
  13704. /**
  13705. * @license
  13706. * Copyright 2020 Google LLC
  13707. *
  13708. * Licensed under the Apache License, Version 2.0 (the "License");
  13709. * you may not use this file except in compliance with the License.
  13710. * You may obtain a copy of the License at
  13711. *
  13712. * http://www.apache.org/licenses/LICENSE-2.0
  13713. *
  13714. * Unless required by applicable law or agreed to in writing, software
  13715. * distributed under the License is distributed on an "AS IS" BASIS,
  13716. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13717. * See the License for the specific language governing permissions and
  13718. * limitations under the License.
  13719. */
  13720. /**
  13721. * A type for the resolve value of {@link runTransaction}.
  13722. */
  13723. class TransactionResult {
  13724. /** @hideconstructor */
  13725. constructor(
  13726. /** Whether the transaction was successfully committed. */
  13727. committed,
  13728. /** The resulting data snapshot. */
  13729. snapshot) {
  13730. this.committed = committed;
  13731. this.snapshot = snapshot;
  13732. }
  13733. /** Returns a JSON-serializable representation of this object. */
  13734. toJSON() {
  13735. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  13736. }
  13737. }
  13738. /**
  13739. * Atomically modifies the data at this location.
  13740. *
  13741. * Atomically modify the data at this location. Unlike a normal `set()`, which
  13742. * just overwrites the data regardless of its previous value, `runTransaction()` is
  13743. * used to modify the existing value to a new value, ensuring there are no
  13744. * conflicts with other clients writing to the same location at the same time.
  13745. *
  13746. * To accomplish this, you pass `runTransaction()` an update function which is
  13747. * used to transform the current value into a new value. If another client
  13748. * writes to the location before your new value is successfully written, your
  13749. * update function will be called again with the new current value, and the
  13750. * write will be retried. This will happen repeatedly until your write succeeds
  13751. * without conflict or you abort the transaction by not returning a value from
  13752. * your update function.
  13753. *
  13754. * Note: Modifying data with `set()` will cancel any pending transactions at
  13755. * that location, so extreme care should be taken if mixing `set()` and
  13756. * `runTransaction()` to update the same data.
  13757. *
  13758. * Note: When using transactions with Security and Firebase Rules in place, be
  13759. * aware that a client needs `.read` access in addition to `.write` access in
  13760. * order to perform a transaction. This is because the client-side nature of
  13761. * transactions requires the client to read the data in order to transactionally
  13762. * update it.
  13763. *
  13764. * @param ref - The location to atomically modify.
  13765. * @param transactionUpdate - A developer-supplied function which will be passed
  13766. * the current data stored at this location (as a JavaScript object). The
  13767. * function should return the new value it would like written (as a JavaScript
  13768. * object). If `undefined` is returned (i.e. you return with no arguments) the
  13769. * transaction will be aborted and the data at this location will not be
  13770. * modified.
  13771. * @param options - An options object to configure transactions.
  13772. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  13773. * callback to handle success and failure.
  13774. */
  13775. function runTransaction(ref,
  13776. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13777. transactionUpdate, options) {
  13778. var _a;
  13779. ref = getModularInstance(ref);
  13780. validateWritablePath('Reference.transaction', ref._path);
  13781. if (ref.key === '.length' || ref.key === '.keys') {
  13782. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  13783. }
  13784. const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  13785. const deferred = new Deferred();
  13786. const promiseComplete = (error, committed, node) => {
  13787. let dataSnapshot = null;
  13788. if (error) {
  13789. deferred.reject(error);
  13790. }
  13791. else {
  13792. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  13793. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  13794. }
  13795. };
  13796. // Add a watch to make sure we get server updates.
  13797. const unwatcher = onValue(ref, () => { });
  13798. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  13799. return deferred.promise;
  13800. }
  13801. /**
  13802. * @license
  13803. * Copyright 2017 Google LLC
  13804. *
  13805. * Licensed under the Apache License, Version 2.0 (the "License");
  13806. * you may not use this file except in compliance with the License.
  13807. * You may obtain a copy of the License at
  13808. *
  13809. * http://www.apache.org/licenses/LICENSE-2.0
  13810. *
  13811. * Unless required by applicable law or agreed to in writing, software
  13812. * distributed under the License is distributed on an "AS IS" BASIS,
  13813. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13814. * See the License for the specific language governing permissions and
  13815. * limitations under the License.
  13816. */
  13817. PersistentConnection;
  13818. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13819. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  13820. this.sendRequest('q', { p: pathString }, onComplete);
  13821. };
  13822. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  13823. PersistentConnection.prototype.echo = function (data, onEcho) {
  13824. this.sendRequest('echo', { d: data }, onEcho);
  13825. };
  13826. // RealTimeConnection properties that we use in tests.
  13827. Connection;
  13828. /**
  13829. * @internal
  13830. */
  13831. const hijackHash = function (newHash) {
  13832. const oldPut = PersistentConnection.prototype.put;
  13833. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  13834. if (hash !== undefined) {
  13835. hash = newHash();
  13836. }
  13837. oldPut.call(this, pathString, data, onComplete, hash);
  13838. };
  13839. return function () {
  13840. PersistentConnection.prototype.put = oldPut;
  13841. };
  13842. };
  13843. RepoInfo;
  13844. /**
  13845. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  13846. * @internal
  13847. */
  13848. const forceRestClient = function (forceRestClient) {
  13849. repoManagerForceRestClient(forceRestClient);
  13850. };
  13851. /**
  13852. * @license
  13853. * Copyright 2021 Google LLC
  13854. *
  13855. * Licensed under the Apache License, Version 2.0 (the "License");
  13856. * you may not use this file except in compliance with the License.
  13857. * You may obtain a copy of the License at
  13858. *
  13859. * http://www.apache.org/licenses/LICENSE-2.0
  13860. *
  13861. * Unless required by applicable law or agreed to in writing, software
  13862. * distributed under the License is distributed on an "AS IS" BASIS,
  13863. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13864. * See the License for the specific language governing permissions and
  13865. * limitations under the License.
  13866. */
  13867. setWebSocketImpl(Websocket.Client);
  13868. registerDatabase('node');
  13869. export { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };
  13870. //# sourceMappingURL=index.node.esm.js.map