1 | import { getApp, _getProvider, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';
|
2 | import { Component } from '@firebase/component';
|
3 | import { stringify, jsonEval, contains, assert, isNodeSdk, base64, stringToByteArray, Sha1, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, createMockUserToken } from '@firebase/util';
|
4 | import { Logger, LogLevel } from '@firebase/logger';
|
5 |
|
6 | const name = "@firebase/database";
|
7 | const version = "0.13.2";
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | let SDK_VERSION = '';
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | function setSDKVersion(version) {
|
32 | SDK_VERSION = version;
|
33 | }
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | class DOMStorageWrapper {
|
61 | |
62 |
|
63 |
|
64 | constructor(domStorage_) {
|
65 | this.domStorage_ = domStorage_;
|
66 |
|
67 | this.prefix_ = 'firebase:';
|
68 | }
|
69 | |
70 |
|
71 |
|
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 |
|
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 |
|
105 |
|
106 |
|
107 |
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 | class MemoryStorage {
|
125 | constructor() {
|
126 | this.cache_ = {};
|
127 | this.isInMemoryStorage = true;
|
128 | }
|
129 | set(key, value) {
|
130 | if (value == null) {
|
131 | delete this.cache_[key];
|
132 | }
|
133 | else {
|
134 | this.cache_[key] = value;
|
135 | }
|
136 | }
|
137 | get(key) {
|
138 | if (contains(this.cache_, key)) {
|
139 | return this.cache_[key];
|
140 | }
|
141 | return null;
|
142 | }
|
143 | remove(key) {
|
144 | delete this.cache_[key];
|
145 | }
|
146 | }
|
147 |
|
148 |
|
149 |
|
150 |
|
151 |
|
152 |
|
153 |
|
154 |
|
155 |
|
156 |
|
157 |
|
158 |
|
159 |
|
160 |
|
161 |
|
162 |
|
163 |
|
164 |
|
165 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 | const createStoragefor = function (domStorageName) {
|
174 | try {
|
175 |
|
176 |
|
177 | if (typeof window !== 'undefined' &&
|
178 | typeof window[domStorageName] !== 'undefined') {
|
179 |
|
180 | const domStorage = window[domStorageName];
|
181 | domStorage.setItem('firebase:sentinel', 'cache');
|
182 | domStorage.removeItem('firebase:sentinel');
|
183 | return new DOMStorageWrapper(domStorage);
|
184 | }
|
185 | }
|
186 | catch (e) { }
|
187 |
|
188 |
|
189 | return new MemoryStorage();
|
190 | };
|
191 |
|
192 | const PersistentStorage = createStoragefor('localStorage');
|
193 |
|
194 | const SessionStorage = createStoragefor('sessionStorage');
|
195 |
|
196 |
|
197 |
|
198 |
|
199 |
|
200 |
|
201 |
|
202 |
|
203 |
|
204 |
|
205 |
|
206 |
|
207 |
|
208 |
|
209 |
|
210 |
|
211 |
|
212 | const logClient = new Logger('@firebase/database');
|
213 |
|
214 |
|
215 |
|
216 | const LUIDGenerator = (function () {
|
217 | let id = 1;
|
218 | return function () {
|
219 | return id++;
|
220 | };
|
221 | })();
|
222 |
|
223 |
|
224 |
|
225 |
|
226 |
|
227 | const sha1 = function (str) {
|
228 | const utf8Bytes = stringToByteArray(str);
|
229 | const sha1 = new Sha1();
|
230 | sha1.update(utf8Bytes);
|
231 | const sha1Bytes = sha1.digest();
|
232 | return base64.encodeByteArray(sha1Bytes);
|
233 | };
|
234 | const buildLogMessage_ = function (...varArgs) {
|
235 | let message = '';
|
236 | for (let i = 0; i < varArgs.length; i++) {
|
237 | const arg = varArgs[i];
|
238 | if (Array.isArray(arg) ||
|
239 | (arg &&
|
240 | typeof arg === 'object' &&
|
241 |
|
242 | typeof arg.length === 'number')) {
|
243 | message += buildLogMessage_.apply(null, arg);
|
244 | }
|
245 | else if (typeof arg === 'object') {
|
246 | message += stringify(arg);
|
247 | }
|
248 | else {
|
249 | message += arg;
|
250 | }
|
251 | message += ' ';
|
252 | }
|
253 | return message;
|
254 | };
|
255 |
|
256 |
|
257 |
|
258 | let logger = null;
|
259 |
|
260 |
|
261 |
|
262 | let firstLog_ = true;
|
263 |
|
264 |
|
265 |
|
266 |
|
267 |
|
268 | const enableLogging$1 = function (logger_, persistent) {
|
269 | assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
|
270 | if (logger_ === true) {
|
271 | logClient.logLevel = LogLevel.VERBOSE;
|
272 | logger = logClient.log.bind(logClient);
|
273 | if (persistent) {
|
274 | SessionStorage.set('logging_enabled', true);
|
275 | }
|
276 | }
|
277 | else if (typeof logger_ === 'function') {
|
278 | logger = logger_;
|
279 | }
|
280 | else {
|
281 | logger = null;
|
282 | SessionStorage.remove('logging_enabled');
|
283 | }
|
284 | };
|
285 | const log = function (...varArgs) {
|
286 | if (firstLog_ === true) {
|
287 | firstLog_ = false;
|
288 | if (logger === null && SessionStorage.get('logging_enabled') === true) {
|
289 | enableLogging$1(true);
|
290 | }
|
291 | }
|
292 | if (logger) {
|
293 | const message = buildLogMessage_.apply(null, varArgs);
|
294 | logger(message);
|
295 | }
|
296 | };
|
297 | const logWrapper = function (prefix) {
|
298 | return function (...varArgs) {
|
299 | log(prefix, ...varArgs);
|
300 | };
|
301 | };
|
302 | const error = function (...varArgs) {
|
303 | const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);
|
304 | logClient.error(message);
|
305 | };
|
306 | const fatal = function (...varArgs) {
|
307 | const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
|
308 | logClient.error(message);
|
309 | throw new Error(message);
|
310 | };
|
311 | const warn = function (...varArgs) {
|
312 | const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);
|
313 | logClient.warn(message);
|
314 | };
|
315 |
|
316 |
|
317 |
|
318 |
|
319 | const warnIfPageIsSecure = function () {
|
320 |
|
321 | if (typeof window !== 'undefined' &&
|
322 | window.location &&
|
323 | window.location.protocol &&
|
324 | window.location.protocol.indexOf('https:') !== -1) {
|
325 | warn('Insecure Firebase access from a secure page. ' +
|
326 | 'Please use https in calls to new Firebase().');
|
327 | }
|
328 | };
|
329 |
|
330 |
|
331 |
|
332 | const isInvalidJSONNumber = function (data) {
|
333 | return (typeof data === 'number' &&
|
334 | (data !== data ||
|
335 | data === Number.POSITIVE_INFINITY ||
|
336 | data === Number.NEGATIVE_INFINITY));
|
337 | };
|
338 | const executeWhenDOMReady = function (fn) {
|
339 | if (isNodeSdk() || document.readyState === 'complete') {
|
340 | fn();
|
341 | }
|
342 | else {
|
343 |
|
344 |
|
345 | let called = false;
|
346 | const wrappedFn = function () {
|
347 | if (!document.body) {
|
348 | setTimeout(wrappedFn, Math.floor(10));
|
349 | return;
|
350 | }
|
351 | if (!called) {
|
352 | called = true;
|
353 | fn();
|
354 | }
|
355 | };
|
356 | if (document.addEventListener) {
|
357 | document.addEventListener('DOMContentLoaded', wrappedFn, false);
|
358 |
|
359 | window.addEventListener('load', wrappedFn, false);
|
360 |
|
361 | }
|
362 | else if (document.attachEvent) {
|
363 |
|
364 |
|
365 | document.attachEvent('onreadystatechange', () => {
|
366 | if (document.readyState === 'complete') {
|
367 | wrappedFn();
|
368 | }
|
369 | });
|
370 |
|
371 |
|
372 | window.attachEvent('onload', wrappedFn);
|
373 |
|
374 |
|
375 |
|
376 | }
|
377 | }
|
378 | };
|
379 |
|
380 |
|
381 |
|
382 | const MIN_NAME = '[MIN_NAME]';
|
383 |
|
384 |
|
385 |
|
386 | const MAX_NAME = '[MAX_NAME]';
|
387 |
|
388 |
|
389 |
|
390 | const nameCompare = function (a, b) {
|
391 | if (a === b) {
|
392 | return 0;
|
393 | }
|
394 | else if (a === MIN_NAME || b === MAX_NAME) {
|
395 | return -1;
|
396 | }
|
397 | else if (b === MIN_NAME || a === MAX_NAME) {
|
398 | return 1;
|
399 | }
|
400 | else {
|
401 | const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
|
402 | if (aAsInt !== null) {
|
403 | if (bAsInt !== null) {
|
404 | return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
|
405 | }
|
406 | else {
|
407 | return -1;
|
408 | }
|
409 | }
|
410 | else if (bAsInt !== null) {
|
411 | return 1;
|
412 | }
|
413 | else {
|
414 | return a < b ? -1 : 1;
|
415 | }
|
416 | }
|
417 | };
|
418 |
|
419 |
|
420 |
|
421 | const stringCompare = function (a, b) {
|
422 | if (a === b) {
|
423 | return 0;
|
424 | }
|
425 | else if (a < b) {
|
426 | return -1;
|
427 | }
|
428 | else {
|
429 | return 1;
|
430 | }
|
431 | };
|
432 | const requireKey = function (key, obj) {
|
433 | if (obj && key in obj) {
|
434 | return obj[key];
|
435 | }
|
436 | else {
|
437 | throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));
|
438 | }
|
439 | };
|
440 | const ObjectToUniqueKey = function (obj) {
|
441 | if (typeof obj !== 'object' || obj === null) {
|
442 | return stringify(obj);
|
443 | }
|
444 | const keys = [];
|
445 |
|
446 | for (const k in obj) {
|
447 | keys.push(k);
|
448 | }
|
449 |
|
450 | keys.sort();
|
451 | let key = '{';
|
452 | for (let i = 0; i < keys.length; i++) {
|
453 | if (i !== 0) {
|
454 | key += ',';
|
455 | }
|
456 | key += stringify(keys[i]);
|
457 | key += ':';
|
458 | key += ObjectToUniqueKey(obj[keys[i]]);
|
459 | }
|
460 | key += '}';
|
461 | return key;
|
462 | };
|
463 |
|
464 |
|
465 |
|
466 |
|
467 |
|
468 |
|
469 | const splitStringBySize = function (str, segsize) {
|
470 | const len = str.length;
|
471 | if (len <= segsize) {
|
472 | return [str];
|
473 | }
|
474 | const dataSegs = [];
|
475 | for (let c = 0; c < len; c += segsize) {
|
476 | if (c + segsize > len) {
|
477 | dataSegs.push(str.substring(c, len));
|
478 | }
|
479 | else {
|
480 | dataSegs.push(str.substring(c, c + segsize));
|
481 | }
|
482 | }
|
483 | return dataSegs;
|
484 | };
|
485 |
|
486 |
|
487 |
|
488 |
|
489 |
|
490 |
|
491 | function each(obj, fn) {
|
492 | for (const key in obj) {
|
493 | if (obj.hasOwnProperty(key)) {
|
494 | fn(key, obj[key]);
|
495 | }
|
496 | }
|
497 | }
|
498 |
|
499 |
|
500 |
|
501 |
|
502 |
|
503 |
|
504 |
|
505 | const doubleToIEEE754String = function (v) {
|
506 | assert(!isInvalidJSONNumber(v), 'Invalid JSON number');
|
507 | const ebits = 11, fbits = 52;
|
508 | const bias = (1 << (ebits - 1)) - 1;
|
509 | let s, e, f, ln, i;
|
510 |
|
511 |
|
512 | if (v === 0) {
|
513 | e = 0;
|
514 | f = 0;
|
515 | s = 1 / v === -Infinity ? 1 : 0;
|
516 | }
|
517 | else {
|
518 | s = v < 0;
|
519 | v = Math.abs(v);
|
520 | if (v >= Math.pow(2, 1 - bias)) {
|
521 |
|
522 | ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
|
523 | e = ln + bias;
|
524 | f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
|
525 | }
|
526 | else {
|
527 |
|
528 | e = 0;
|
529 | f = Math.round(v / Math.pow(2, 1 - bias - fbits));
|
530 | }
|
531 | }
|
532 |
|
533 | const bits = [];
|
534 | for (i = fbits; i; i -= 1) {
|
535 | bits.push(f % 2 ? 1 : 0);
|
536 | f = Math.floor(f / 2);
|
537 | }
|
538 | for (i = ebits; i; i -= 1) {
|
539 | bits.push(e % 2 ? 1 : 0);
|
540 | e = Math.floor(e / 2);
|
541 | }
|
542 | bits.push(s ? 1 : 0);
|
543 | bits.reverse();
|
544 | const str = bits.join('');
|
545 |
|
546 | let hexByteString = '';
|
547 | for (i = 0; i < 64; i += 8) {
|
548 | let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
|
549 | if (hexByte.length === 1) {
|
550 | hexByte = '0' + hexByte;
|
551 | }
|
552 | hexByteString = hexByteString + hexByte;
|
553 | }
|
554 | return hexByteString.toLowerCase();
|
555 | };
|
556 |
|
557 |
|
558 |
|
559 |
|
560 | const isChromeExtensionContentScript = function () {
|
561 | return !!(typeof window === 'object' &&
|
562 | window['chrome'] &&
|
563 | window['chrome']['extension'] &&
|
564 | !/^chrome/.test(window.location.href));
|
565 | };
|
566 |
|
567 |
|
568 |
|
569 | const isWindowsStoreApp = function () {
|
570 |
|
571 | return typeof Windows === 'object' && typeof Windows.UI === 'object';
|
572 | };
|
573 |
|
574 |
|
575 |
|
576 | function errorForServerCode(code, query) {
|
577 | let reason = 'Unknown Error';
|
578 | if (code === 'too_big') {
|
579 | reason =
|
580 | 'The data requested exceeds the maximum size ' +
|
581 | 'that can be accessed with a single request.';
|
582 | }
|
583 | else if (code === 'permission_denied') {
|
584 | reason = "Client doesn't have permission to access the desired data.";
|
585 | }
|
586 | else if (code === 'unavailable') {
|
587 | reason = 'The service is unavailable';
|
588 | }
|
589 | const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
|
590 |
|
591 | error.code = code.toUpperCase();
|
592 | return error;
|
593 | }
|
594 |
|
595 |
|
596 |
|
597 | const INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
|
598 |
|
599 |
|
600 |
|
601 | const INTEGER_32_MIN = -2147483648;
|
602 |
|
603 |
|
604 |
|
605 | const INTEGER_32_MAX = 2147483647;
|
606 |
|
607 |
|
608 |
|
609 | const tryParseInt = function (str) {
|
610 | if (INTEGER_REGEXP_.test(str)) {
|
611 | const intVal = Number(str);
|
612 | if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
|
613 | return intVal;
|
614 | }
|
615 | }
|
616 | return null;
|
617 | };
|
618 |
|
619 |
|
620 |
|
621 |
|
622 |
|
623 |
|
624 |
|
625 |
|
626 |
|
627 |
|
628 |
|
629 |
|
630 |
|
631 |
|
632 |
|
633 |
|
634 |
|
635 | const exceptionGuard = function (fn) {
|
636 | try {
|
637 | fn();
|
638 | }
|
639 | catch (e) {
|
640 |
|
641 | setTimeout(() => {
|
642 |
|
643 |
|
644 |
|
645 |
|
646 | const stack = e.stack || '';
|
647 | warn('Exception was thrown by user callback.', stack);
|
648 | throw e;
|
649 | }, Math.floor(0));
|
650 | }
|
651 | };
|
652 |
|
653 |
|
654 |
|
655 | const beingCrawled = function () {
|
656 | const userAgent = (typeof window === 'object' &&
|
657 | window['navigator'] &&
|
658 | window['navigator']['userAgent']) ||
|
659 | '';
|
660 |
|
661 |
|
662 |
|
663 |
|
664 | return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
|
665 | };
|
666 |
|
667 |
|
668 |
|
669 |
|
670 |
|
671 |
|
672 |
|
673 |
|
674 |
|
675 | const setTimeoutNonBlocking = function (fn, time) {
|
676 | const timeout = setTimeout(fn, time);
|
677 |
|
678 | if (typeof timeout === 'object' && timeout['unref']) {
|
679 |
|
680 | timeout['unref']();
|
681 | }
|
682 | return timeout;
|
683 | };
|
684 |
|
685 |
|
686 |
|
687 |
|
688 |
|
689 |
|
690 |
|
691 |
|
692 |
|
693 |
|
694 |
|
695 |
|
696 |
|
697 |
|
698 |
|
699 |
|
700 |
|
701 |
|
702 |
|
703 |
|
704 | class AppCheckTokenProvider {
|
705 | constructor(appName_, appCheckProvider) {
|
706 | this.appName_ = appName_;
|
707 | this.appCheckProvider = appCheckProvider;
|
708 | this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
|
709 | if (!this.appCheck) {
|
710 | appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));
|
711 | }
|
712 | }
|
713 | getToken(forceRefresh) {
|
714 | if (!this.appCheck) {
|
715 | return new Promise((resolve, reject) => {
|
716 |
|
717 |
|
718 |
|
719 |
|
720 | setTimeout(() => {
|
721 | if (this.appCheck) {
|
722 | this.getToken(forceRefresh).then(resolve, reject);
|
723 | }
|
724 | else {
|
725 | resolve(null);
|
726 | }
|
727 | }, 0);
|
728 | });
|
729 | }
|
730 | return this.appCheck.getToken(forceRefresh);
|
731 | }
|
732 | addTokenChangeListener(listener) {
|
733 | var _a;
|
734 | (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));
|
735 | }
|
736 | notifyForInvalidToken() {
|
737 | warn(`Provided AppCheck credentials for the app named "${this.appName_}" ` +
|
738 | 'are invalid. This usually indicates your app was not initialized correctly.');
|
739 | }
|
740 | }
|
741 |
|
742 |
|
743 |
|
744 |
|
745 |
|
746 |
|
747 |
|
748 |
|
749 |
|
750 |
|
751 |
|
752 |
|
753 |
|
754 |
|
755 |
|
756 |
|
757 |
|
758 |
|
759 |
|
760 |
|
761 | class FirebaseAuthTokenProvider {
|
762 | constructor(appName_, firebaseOptions_, authProvider_) {
|
763 | this.appName_ = appName_;
|
764 | this.firebaseOptions_ = firebaseOptions_;
|
765 | this.authProvider_ = authProvider_;
|
766 | this.auth_ = null;
|
767 | this.auth_ = authProvider_.getImmediate({ optional: true });
|
768 | if (!this.auth_) {
|
769 | authProvider_.onInit(auth => (this.auth_ = auth));
|
770 | }
|
771 | }
|
772 | getToken(forceRefresh) {
|
773 | if (!this.auth_) {
|
774 | return new Promise((resolve, reject) => {
|
775 |
|
776 |
|
777 |
|
778 |
|
779 | setTimeout(() => {
|
780 | if (this.auth_) {
|
781 | this.getToken(forceRefresh).then(resolve, reject);
|
782 | }
|
783 | else {
|
784 | resolve(null);
|
785 | }
|
786 | }, 0);
|
787 | });
|
788 | }
|
789 | return this.auth_.getToken(forceRefresh).catch(error => {
|
790 |
|
791 |
|
792 | if (error && error.code === 'auth/token-not-initialized') {
|
793 | log('Got auth/token-not-initialized error. Treating as null token.');
|
794 | return null;
|
795 | }
|
796 | else {
|
797 | return Promise.reject(error);
|
798 | }
|
799 | });
|
800 | }
|
801 | addTokenChangeListener(listener) {
|
802 |
|
803 |
|
804 | if (this.auth_) {
|
805 | this.auth_.addAuthTokenListener(listener);
|
806 | }
|
807 | else {
|
808 | this.authProvider_
|
809 | .get()
|
810 | .then(auth => auth.addAuthTokenListener(listener));
|
811 | }
|
812 | }
|
813 | removeTokenChangeListener(listener) {
|
814 | this.authProvider_
|
815 | .get()
|
816 | .then(auth => auth.removeAuthTokenListener(listener));
|
817 | }
|
818 | notifyForInvalidToken() {
|
819 | let errorMessage = 'Provided authentication credentials for the app named "' +
|
820 | this.appName_ +
|
821 | '" are invalid. This usually indicates your app was not ' +
|
822 | 'initialized correctly. ';
|
823 | if ('credential' in this.firebaseOptions_) {
|
824 | errorMessage +=
|
825 | 'Make sure the "credential" property provided to initializeApp() ' +
|
826 | 'is authorized to access the specified "databaseURL" and is from the correct ' +
|
827 | 'project.';
|
828 | }
|
829 | else if ('serviceAccount' in this.firebaseOptions_) {
|
830 | errorMessage +=
|
831 | 'Make sure the "serviceAccount" property provided to initializeApp() ' +
|
832 | 'is authorized to access the specified "databaseURL" and is from the correct ' +
|
833 | 'project.';
|
834 | }
|
835 | else {
|
836 | errorMessage +=
|
837 | 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
|
838 | 'initializeApp() match the values provided for your app at ' +
|
839 | 'https://console.firebase.google.com/.';
|
840 | }
|
841 | warn(errorMessage);
|
842 | }
|
843 | }
|
844 |
|
845 | class EmulatorTokenProvider {
|
846 | constructor(accessToken) {
|
847 | this.accessToken = accessToken;
|
848 | }
|
849 | getToken(forceRefresh) {
|
850 | return Promise.resolve({
|
851 | accessToken: this.accessToken
|
852 | });
|
853 | }
|
854 | addTokenChangeListener(listener) {
|
855 |
|
856 |
|
857 | listener(this.accessToken);
|
858 | }
|
859 | removeTokenChangeListener(listener) { }
|
860 | notifyForInvalidToken() { }
|
861 | }
|
862 |
|
863 | EmulatorTokenProvider.OWNER = 'owner';
|
864 |
|
865 |
|
866 |
|
867 |
|
868 |
|
869 |
|
870 |
|
871 |
|
872 |
|
873 |
|
874 |
|
875 |
|
876 |
|
877 |
|
878 |
|
879 |
|
880 |
|
881 | const PROTOCOL_VERSION = '5';
|
882 | const VERSION_PARAM = 'v';
|
883 | const TRANSPORT_SESSION_PARAM = 's';
|
884 | const REFERER_PARAM = 'r';
|
885 | const FORGE_REF = 'f';
|
886 |
|
887 |
|
888 | const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
|
889 | const LAST_SESSION_PARAM = 'ls';
|
890 | const APPLICATION_ID_PARAM = 'p';
|
891 | const APP_CHECK_TOKEN_PARAM = 'ac';
|
892 | const WEBSOCKET = 'websocket';
|
893 | const LONG_POLLING = 'long_polling';
|
894 |
|
895 |
|
896 |
|
897 |
|
898 |
|
899 |
|
900 |
|
901 |
|
902 |
|
903 |
|
904 |
|
905 |
|
906 |
|
907 |
|
908 |
|
909 |
|
910 |
|
911 |
|
912 |
|
913 |
|
914 | class RepoInfo {
|
915 | |
916 |
|
917 |
|
918 |
|
919 |
|
920 |
|
921 |
|
922 |
|
923 | constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false) {
|
924 | this.secure = secure;
|
925 | this.namespace = namespace;
|
926 | this.webSocketOnly = webSocketOnly;
|
927 | this.nodeAdmin = nodeAdmin;
|
928 | this.persistenceKey = persistenceKey;
|
929 | this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
|
930 | this._host = host.toLowerCase();
|
931 | this._domain = this._host.substr(this._host.indexOf('.') + 1);
|
932 | this.internalHost =
|
933 | PersistentStorage.get('host:' + host) || this._host;
|
934 | }
|
935 | isCacheableHost() {
|
936 | return this.internalHost.substr(0, 2) === 's-';
|
937 | }
|
938 | isCustomHost() {
|
939 | return (this._domain !== 'firebaseio.com' &&
|
940 | this._domain !== 'firebaseio-demo.com');
|
941 | }
|
942 | get host() {
|
943 | return this._host;
|
944 | }
|
945 | set host(newHost) {
|
946 | if (newHost !== this.internalHost) {
|
947 | this.internalHost = newHost;
|
948 | if (this.isCacheableHost()) {
|
949 | PersistentStorage.set('host:' + this._host, this.internalHost);
|
950 | }
|
951 | }
|
952 | }
|
953 | toString() {
|
954 | let str = this.toURLString();
|
955 | if (this.persistenceKey) {
|
956 | str += '<' + this.persistenceKey + '>';
|
957 | }
|
958 | return str;
|
959 | }
|
960 | toURLString() {
|
961 | const protocol = this.secure ? 'https://' : 'http://';
|
962 | const query = this.includeNamespaceInQueryParams
|
963 | ? `?ns=${this.namespace}`
|
964 | : '';
|
965 | return `${protocol}${this.host}/${query}`;
|
966 | }
|
967 | }
|
968 | function repoInfoNeedsQueryParam(repoInfo) {
|
969 | return (repoInfo.host !== repoInfo.internalHost ||
|
970 | repoInfo.isCustomHost() ||
|
971 | repoInfo.includeNamespaceInQueryParams);
|
972 | }
|
973 |
|
974 |
|
975 |
|
976 |
|
977 |
|
978 |
|
979 |
|
980 | function repoInfoConnectionURL(repoInfo, type, params) {
|
981 | assert(typeof type === 'string', 'typeof type must == string');
|
982 | assert(typeof params === 'object', 'typeof params must == object');
|
983 | let connURL;
|
984 | if (type === WEBSOCKET) {
|
985 | connURL =
|
986 | (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
|
987 | }
|
988 | else if (type === LONG_POLLING) {
|
989 | connURL =
|
990 | (repoInfo.secure ? 'https://' : 'http://') +
|
991 | repoInfo.internalHost +
|
992 | '/.lp?';
|
993 | }
|
994 | else {
|
995 | throw new Error('Unknown connection type: ' + type);
|
996 | }
|
997 | if (repoInfoNeedsQueryParam(repoInfo)) {
|
998 | params['ns'] = repoInfo.namespace;
|
999 | }
|
1000 | const pairs = [];
|
1001 | each(params, (key, value) => {
|
1002 | pairs.push(key + '=' + value);
|
1003 | });
|
1004 | return connURL + pairs.join('&');
|
1005 | }
|
1006 |
|
1007 |
|
1008 |
|
1009 |
|
1010 |
|
1011 |
|
1012 |
|
1013 |
|
1014 |
|
1015 |
|
1016 |
|
1017 |
|
1018 |
|
1019 |
|
1020 |
|
1021 |
|
1022 |
|
1023 |
|
1024 |
|
1025 |
|
1026 | class StatsCollection {
|
1027 | constructor() {
|
1028 | this.counters_ = {};
|
1029 | }
|
1030 | incrementCounter(name, amount = 1) {
|
1031 | if (!contains(this.counters_, name)) {
|
1032 | this.counters_[name] = 0;
|
1033 | }
|
1034 | this.counters_[name] += amount;
|
1035 | }
|
1036 | get() {
|
1037 | return deepCopy(this.counters_);
|
1038 | }
|
1039 | }
|
1040 |
|
1041 |
|
1042 |
|
1043 |
|
1044 |
|
1045 |
|
1046 |
|
1047 |
|
1048 |
|
1049 |
|
1050 |
|
1051 |
|
1052 |
|
1053 |
|
1054 |
|
1055 |
|
1056 |
|
1057 | const collections = {};
|
1058 | const reporters = {};
|
1059 | function statsManagerGetCollection(repoInfo) {
|
1060 | const hashString = repoInfo.toString();
|
1061 | if (!collections[hashString]) {
|
1062 | collections[hashString] = new StatsCollection();
|
1063 | }
|
1064 | return collections[hashString];
|
1065 | }
|
1066 | function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
|
1067 | const hashString = repoInfo.toString();
|
1068 | if (!reporters[hashString]) {
|
1069 | reporters[hashString] = creatorFunction();
|
1070 | }
|
1071 | return reporters[hashString];
|
1072 | }
|
1073 |
|
1074 |
|
1075 |
|
1076 |
|
1077 |
|
1078 |
|
1079 |
|
1080 |
|
1081 |
|
1082 |
|
1083 |
|
1084 |
|
1085 |
|
1086 |
|
1087 |
|
1088 |
|
1089 |
|
1090 |
|
1091 |
|
1092 |
|
1093 |
|
1094 | class PacketReceiver {
|
1095 | |
1096 |
|
1097 |
|
1098 | constructor(onMessage_) {
|
1099 | this.onMessage_ = onMessage_;
|
1100 | this.pendingResponses = [];
|
1101 | this.currentResponseNum = 0;
|
1102 | this.closeAfterResponse = -1;
|
1103 | this.onClose = null;
|
1104 | }
|
1105 | closeAfter(responseNum, callback) {
|
1106 | this.closeAfterResponse = responseNum;
|
1107 | this.onClose = callback;
|
1108 | if (this.closeAfterResponse < this.currentResponseNum) {
|
1109 | this.onClose();
|
1110 | this.onClose = null;
|
1111 | }
|
1112 | }
|
1113 | |
1114 |
|
1115 |
|
1116 |
|
1117 |
|
1118 | handleResponse(requestNum, data) {
|
1119 | this.pendingResponses[requestNum] = data;
|
1120 | while (this.pendingResponses[this.currentResponseNum]) {
|
1121 | const toProcess = this.pendingResponses[this.currentResponseNum];
|
1122 | delete this.pendingResponses[this.currentResponseNum];
|
1123 | for (let i = 0; i < toProcess.length; ++i) {
|
1124 | if (toProcess[i]) {
|
1125 | exceptionGuard(() => {
|
1126 | this.onMessage_(toProcess[i]);
|
1127 | });
|
1128 | }
|
1129 | }
|
1130 | if (this.currentResponseNum === this.closeAfterResponse) {
|
1131 | if (this.onClose) {
|
1132 | this.onClose();
|
1133 | this.onClose = null;
|
1134 | }
|
1135 | break;
|
1136 | }
|
1137 | this.currentResponseNum++;
|
1138 | }
|
1139 | }
|
1140 | }
|
1141 |
|
1142 |
|
1143 |
|
1144 |
|
1145 |
|
1146 |
|
1147 |
|
1148 |
|
1149 |
|
1150 |
|
1151 |
|
1152 |
|
1153 |
|
1154 |
|
1155 |
|
1156 |
|
1157 |
|
1158 |
|
1159 | const FIREBASE_LONGPOLL_START_PARAM = 'start';
|
1160 | const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
|
1161 | const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
|
1162 | const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
|
1163 | const FIREBASE_LONGPOLL_ID_PARAM = 'id';
|
1164 | const FIREBASE_LONGPOLL_PW_PARAM = 'pw';
|
1165 | const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
|
1166 | const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
|
1167 | const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
|
1168 | const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
|
1169 | const FIREBASE_LONGPOLL_DATA_PARAM = 'd';
|
1170 | const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
|
1171 |
|
1172 |
|
1173 |
|
1174 | const MAX_URL_DATA_SIZE = 1870;
|
1175 | const SEG_HEADER_SIZE = 30;
|
1176 | const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
|
1177 |
|
1178 |
|
1179 |
|
1180 |
|
1181 |
|
1182 | const KEEPALIVE_REQUEST_INTERVAL = 25000;
|
1183 |
|
1184 |
|
1185 |
|
1186 | const LP_CONNECT_TIMEOUT = 30000;
|
1187 |
|
1188 |
|
1189 |
|
1190 | class BrowserPollConnection {
|
1191 | |
1192 |
|
1193 |
|
1194 |
|
1195 |
|
1196 |
|
1197 |
|
1198 |
|
1199 |
|
1200 |
|
1201 |
|
1202 | constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
|
1203 | this.connId = connId;
|
1204 | this.repoInfo = repoInfo;
|
1205 | this.applicationId = applicationId;
|
1206 | this.appCheckToken = appCheckToken;
|
1207 | this.authToken = authToken;
|
1208 | this.transportSessionId = transportSessionId;
|
1209 | this.lastSessionId = lastSessionId;
|
1210 | this.bytesSent = 0;
|
1211 | this.bytesReceived = 0;
|
1212 | this.everConnected_ = false;
|
1213 | this.log_ = logWrapper(connId);
|
1214 | this.stats_ = statsManagerGetCollection(repoInfo);
|
1215 | this.urlFn = (params) => {
|
1216 |
|
1217 | if (this.appCheckToken) {
|
1218 | params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
|
1219 | }
|
1220 | return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
|
1221 | };
|
1222 | }
|
1223 | |
1224 |
|
1225 |
|
1226 |
|
1227 | open(onMessage, onDisconnect) {
|
1228 | this.curSegmentNum = 0;
|
1229 | this.onDisconnect_ = onDisconnect;
|
1230 | this.myPacketOrderer = new PacketReceiver(onMessage);
|
1231 | this.isClosed_ = false;
|
1232 | this.connectTimeoutTimer_ = setTimeout(() => {
|
1233 | this.log_('Timed out trying to connect.');
|
1234 |
|
1235 | this.onClosed_();
|
1236 | this.connectTimeoutTimer_ = null;
|
1237 |
|
1238 | }, Math.floor(LP_CONNECT_TIMEOUT));
|
1239 |
|
1240 | executeWhenDOMReady(() => {
|
1241 | if (this.isClosed_) {
|
1242 | return;
|
1243 | }
|
1244 |
|
1245 | this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
|
1246 | const [command, arg1, arg2, arg3, arg4] = args;
|
1247 | this.incrementIncomingBytes_(args);
|
1248 | if (!this.scriptTagHolder) {
|
1249 | return;
|
1250 | }
|
1251 | if (this.connectTimeoutTimer_) {
|
1252 | clearTimeout(this.connectTimeoutTimer_);
|
1253 | this.connectTimeoutTimer_ = null;
|
1254 | }
|
1255 | this.everConnected_ = true;
|
1256 | if (command === FIREBASE_LONGPOLL_START_PARAM) {
|
1257 | this.id = arg1;
|
1258 | this.password = arg2;
|
1259 | }
|
1260 | else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
|
1261 |
|
1262 | if (arg1) {
|
1263 |
|
1264 |
|
1265 | this.scriptTagHolder.sendNewPolls = false;
|
1266 |
|
1267 |
|
1268 | this.myPacketOrderer.closeAfter(arg1, () => {
|
1269 | this.onClosed_();
|
1270 | });
|
1271 | }
|
1272 | else {
|
1273 | this.onClosed_();
|
1274 | }
|
1275 | }
|
1276 | else {
|
1277 | throw new Error('Unrecognized command received: ' + command);
|
1278 | }
|
1279 | }, (...args) => {
|
1280 | const [pN, data] = args;
|
1281 | this.incrementIncomingBytes_(args);
|
1282 | this.myPacketOrderer.handleResponse(pN, data);
|
1283 | }, () => {
|
1284 | this.onClosed_();
|
1285 | }, this.urlFn);
|
1286 |
|
1287 |
|
1288 | const urlParams = {};
|
1289 | urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
|
1290 | urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
|
1291 | if (this.scriptTagHolder.uniqueCallbackIdentifier) {
|
1292 | urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
|
1293 | this.scriptTagHolder.uniqueCallbackIdentifier;
|
1294 | }
|
1295 | urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
|
1296 | if (this.transportSessionId) {
|
1297 | urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
|
1298 | }
|
1299 | if (this.lastSessionId) {
|
1300 | urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
|
1301 | }
|
1302 | if (this.applicationId) {
|
1303 | urlParams[APPLICATION_ID_PARAM] = this.applicationId;
|
1304 | }
|
1305 | if (this.appCheckToken) {
|
1306 | urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
|
1307 | }
|
1308 | if (typeof location !== 'undefined' &&
|
1309 | location.hostname &&
|
1310 | FORGE_DOMAIN_RE.test(location.hostname)) {
|
1311 | urlParams[REFERER_PARAM] = FORGE_REF;
|
1312 | }
|
1313 | const connectURL = this.urlFn(urlParams);
|
1314 | this.log_('Connecting via long-poll to ' + connectURL);
|
1315 | this.scriptTagHolder.addTag(connectURL, () => {
|
1316 |
|
1317 | });
|
1318 | });
|
1319 | }
|
1320 | |
1321 |
|
1322 |
|
1323 | start() {
|
1324 | this.scriptTagHolder.startLongPoll(this.id, this.password);
|
1325 | this.addDisconnectPingFrame(this.id, this.password);
|
1326 | }
|
1327 | |
1328 |
|
1329 |
|
1330 | static forceAllow() {
|
1331 | BrowserPollConnection.forceAllow_ = true;
|
1332 | }
|
1333 | |
1334 |
|
1335 |
|
1336 | static forceDisallow() {
|
1337 | BrowserPollConnection.forceDisallow_ = true;
|
1338 | }
|
1339 |
|
1340 | static isAvailable() {
|
1341 | if (isNodeSdk()) {
|
1342 | return false;
|
1343 | }
|
1344 | else if (BrowserPollConnection.forceAllow_) {
|
1345 | return true;
|
1346 | }
|
1347 | else {
|
1348 |
|
1349 |
|
1350 | return (!BrowserPollConnection.forceDisallow_ &&
|
1351 | typeof document !== 'undefined' &&
|
1352 | document.createElement != null &&
|
1353 | !isChromeExtensionContentScript() &&
|
1354 | !isWindowsStoreApp());
|
1355 | }
|
1356 | }
|
1357 | |
1358 |
|
1359 |
|
1360 | markConnectionHealthy() { }
|
1361 | |
1362 |
|
1363 |
|
1364 | shutdown_() {
|
1365 | this.isClosed_ = true;
|
1366 | if (this.scriptTagHolder) {
|
1367 | this.scriptTagHolder.close();
|
1368 | this.scriptTagHolder = null;
|
1369 | }
|
1370 |
|
1371 | if (this.myDisconnFrame) {
|
1372 | document.body.removeChild(this.myDisconnFrame);
|
1373 | this.myDisconnFrame = null;
|
1374 | }
|
1375 | if (this.connectTimeoutTimer_) {
|
1376 | clearTimeout(this.connectTimeoutTimer_);
|
1377 | this.connectTimeoutTimer_ = null;
|
1378 | }
|
1379 | }
|
1380 | |
1381 |
|
1382 |
|
1383 | onClosed_() {
|
1384 | if (!this.isClosed_) {
|
1385 | this.log_('Longpoll is closing itself');
|
1386 | this.shutdown_();
|
1387 | if (this.onDisconnect_) {
|
1388 | this.onDisconnect_(this.everConnected_);
|
1389 | this.onDisconnect_ = null;
|
1390 | }
|
1391 | }
|
1392 | }
|
1393 | |
1394 |
|
1395 |
|
1396 |
|
1397 | close() {
|
1398 | if (!this.isClosed_) {
|
1399 | this.log_('Longpoll is being closed.');
|
1400 | this.shutdown_();
|
1401 | }
|
1402 | }
|
1403 | |
1404 |
|
1405 |
|
1406 |
|
1407 |
|
1408 | send(data) {
|
1409 | const dataStr = stringify(data);
|
1410 | this.bytesSent += dataStr.length;
|
1411 | this.stats_.incrementCounter('bytes_sent', dataStr.length);
|
1412 |
|
1413 | const base64data = base64Encode(dataStr);
|
1414 |
|
1415 |
|
1416 | const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
|
1417 |
|
1418 |
|
1419 | for (let i = 0; i < dataSegs.length; i++) {
|
1420 | this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
|
1421 | this.curSegmentNum++;
|
1422 | }
|
1423 | }
|
1424 | |
1425 |
|
1426 |
|
1427 |
|
1428 |
|
1429 | addDisconnectPingFrame(id, pw) {
|
1430 | if (isNodeSdk()) {
|
1431 | return;
|
1432 | }
|
1433 | this.myDisconnFrame = document.createElement('iframe');
|
1434 | const urlParams = {};
|
1435 | urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
|
1436 | urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
|
1437 | urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
|
1438 | this.myDisconnFrame.src = this.urlFn(urlParams);
|
1439 | this.myDisconnFrame.style.display = 'none';
|
1440 | document.body.appendChild(this.myDisconnFrame);
|
1441 | }
|
1442 | |
1443 |
|
1444 |
|
1445 | incrementIncomingBytes_(args) {
|
1446 |
|
1447 | const bytesReceived = stringify(args).length;
|
1448 | this.bytesReceived += bytesReceived;
|
1449 | this.stats_.incrementCounter('bytes_received', bytesReceived);
|
1450 | }
|
1451 | }
|
1452 |
|
1453 |
|
1454 |
|
1455 | class FirebaseIFrameScriptHolder {
|
1456 | |
1457 |
|
1458 |
|
1459 |
|
1460 |
|
1461 |
|
1462 | constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
|
1463 | this.onDisconnect = onDisconnect;
|
1464 | this.urlFn = urlFn;
|
1465 |
|
1466 |
|
1467 | this.outstandingRequests = new Set();
|
1468 |
|
1469 | this.pendingSegs = [];
|
1470 |
|
1471 |
|
1472 |
|
1473 |
|
1474 |
|
1475 | this.currentSerial = Math.floor(Math.random() * 100000000);
|
1476 |
|
1477 |
|
1478 | this.sendNewPolls = true;
|
1479 | if (!isNodeSdk()) {
|
1480 |
|
1481 |
|
1482 |
|
1483 |
|
1484 | this.uniqueCallbackIdentifier = LUIDGenerator();
|
1485 | window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
|
1486 | window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
|
1487 | onMessageCB;
|
1488 |
|
1489 | this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
|
1490 |
|
1491 | let script = '';
|
1492 |
|
1493 |
|
1494 | if (this.myIFrame.src &&
|
1495 | this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
|
1496 | const currentDomain = document.domain;
|
1497 | script = '<script>document.domain="' + currentDomain + '";</script>';
|
1498 | }
|
1499 | const iframeContents = '<html><body>' + script + '</body></html>';
|
1500 | try {
|
1501 | this.myIFrame.doc.open();
|
1502 | this.myIFrame.doc.write(iframeContents);
|
1503 | this.myIFrame.doc.close();
|
1504 | }
|
1505 | catch (e) {
|
1506 | log('frame writing exception');
|
1507 | if (e.stack) {
|
1508 | log(e.stack);
|
1509 | }
|
1510 | log(e);
|
1511 | }
|
1512 | }
|
1513 | else {
|
1514 | this.commandCB = commandCB;
|
1515 | this.onMessageCB = onMessageCB;
|
1516 | }
|
1517 | }
|
1518 | |
1519 |
|
1520 |
|
1521 |
|
1522 | static createIFrame_() {
|
1523 | const iframe = document.createElement('iframe');
|
1524 | iframe.style.display = 'none';
|
1525 |
|
1526 | if (document.body) {
|
1527 | document.body.appendChild(iframe);
|
1528 | try {
|
1529 |
|
1530 |
|
1531 |
|
1532 | const a = iframe.contentWindow.document;
|
1533 | if (!a) {
|
1534 |
|
1535 | log('No IE domain setting required');
|
1536 | }
|
1537 | }
|
1538 | catch (e) {
|
1539 | const domain = document.domain;
|
1540 | iframe.src =
|
1541 | "javascript:void((function(){document.open();document.domain='" +
|
1542 | domain +
|
1543 | "';document.close();})())";
|
1544 | }
|
1545 | }
|
1546 | else {
|
1547 |
|
1548 |
|
1549 | throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
|
1550 | }
|
1551 |
|
1552 | if (iframe.contentDocument) {
|
1553 | iframe.doc = iframe.contentDocument;
|
1554 | }
|
1555 | else if (iframe.contentWindow) {
|
1556 | iframe.doc = iframe.contentWindow.document;
|
1557 |
|
1558 | }
|
1559 | else if (iframe.document) {
|
1560 |
|
1561 | iframe.doc = iframe.document;
|
1562 | }
|
1563 | return iframe;
|
1564 | }
|
1565 | |
1566 |
|
1567 |
|
1568 | close() {
|
1569 |
|
1570 | this.alive = false;
|
1571 | if (this.myIFrame) {
|
1572 |
|
1573 |
|
1574 |
|
1575 | this.myIFrame.doc.body.innerHTML = '';
|
1576 | setTimeout(() => {
|
1577 | if (this.myIFrame !== null) {
|
1578 | document.body.removeChild(this.myIFrame);
|
1579 | this.myIFrame = null;
|
1580 | }
|
1581 | }, Math.floor(0));
|
1582 | }
|
1583 |
|
1584 | const onDisconnect = this.onDisconnect;
|
1585 | if (onDisconnect) {
|
1586 | this.onDisconnect = null;
|
1587 | onDisconnect();
|
1588 | }
|
1589 | }
|
1590 | |
1591 |
|
1592 |
|
1593 |
|
1594 |
|
1595 | startLongPoll(id, pw) {
|
1596 | this.myID = id;
|
1597 | this.myPW = pw;
|
1598 | this.alive = true;
|
1599 |
|
1600 | while (this.newRequest_()) { }
|
1601 | }
|
1602 | |
1603 |
|
1604 |
|
1605 |
|
1606 |
|
1607 |
|
1608 |
|
1609 | newRequest_() {
|
1610 |
|
1611 |
|
1612 |
|
1613 | if (this.alive &&
|
1614 | this.sendNewPolls &&
|
1615 | this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
|
1616 |
|
1617 | this.currentSerial++;
|
1618 | const urlParams = {};
|
1619 | urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
|
1620 | urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
|
1621 | urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
|
1622 | let theURL = this.urlFn(urlParams);
|
1623 |
|
1624 | let curDataString = '';
|
1625 | let i = 0;
|
1626 | while (this.pendingSegs.length > 0) {
|
1627 |
|
1628 | const nextSeg = this.pendingSegs[0];
|
1629 | if (nextSeg.d.length +
|
1630 | SEG_HEADER_SIZE +
|
1631 | curDataString.length <=
|
1632 | MAX_URL_DATA_SIZE) {
|
1633 |
|
1634 | const theSeg = this.pendingSegs.shift();
|
1635 | curDataString =
|
1636 | curDataString +
|
1637 | '&' +
|
1638 | FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
|
1639 | i +
|
1640 | '=' +
|
1641 | theSeg.seg +
|
1642 | '&' +
|
1643 | FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
|
1644 | i +
|
1645 | '=' +
|
1646 | theSeg.ts +
|
1647 | '&' +
|
1648 | FIREBASE_LONGPOLL_DATA_PARAM +
|
1649 | i +
|
1650 | '=' +
|
1651 | theSeg.d;
|
1652 | i++;
|
1653 | }
|
1654 | else {
|
1655 | break;
|
1656 | }
|
1657 | }
|
1658 | theURL = theURL + curDataString;
|
1659 | this.addLongPollTag_(theURL, this.currentSerial);
|
1660 | return true;
|
1661 | }
|
1662 | else {
|
1663 | return false;
|
1664 | }
|
1665 | }
|
1666 | |
1667 |
|
1668 |
|
1669 |
|
1670 |
|
1671 |
|
1672 | enqueueSegment(segnum, totalsegs, data) {
|
1673 |
|
1674 | this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
|
1675 |
|
1676 |
|
1677 | if (this.alive) {
|
1678 | this.newRequest_();
|
1679 | }
|
1680 | }
|
1681 | |
1682 |
|
1683 |
|
1684 |
|
1685 |
|
1686 | addLongPollTag_(url, serial) {
|
1687 |
|
1688 | this.outstandingRequests.add(serial);
|
1689 | const doNewRequest = () => {
|
1690 | this.outstandingRequests.delete(serial);
|
1691 | this.newRequest_();
|
1692 | };
|
1693 |
|
1694 |
|
1695 | const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
|
1696 | const readyStateCB = () => {
|
1697 |
|
1698 | clearTimeout(keepaliveTimeout);
|
1699 |
|
1700 | doNewRequest();
|
1701 | };
|
1702 | this.addTag(url, readyStateCB);
|
1703 | }
|
1704 | |
1705 |
|
1706 |
|
1707 |
|
1708 |
|
1709 | addTag(url, loadCB) {
|
1710 | if (isNodeSdk()) {
|
1711 |
|
1712 | this.doNodeLongPoll(url, loadCB);
|
1713 | }
|
1714 | else {
|
1715 | setTimeout(() => {
|
1716 | try {
|
1717 |
|
1718 | if (!this.sendNewPolls) {
|
1719 | return;
|
1720 | }
|
1721 | const newScript = this.myIFrame.doc.createElement('script');
|
1722 | newScript.type = 'text/javascript';
|
1723 | newScript.async = true;
|
1724 | newScript.src = url;
|
1725 |
|
1726 | newScript.onload = newScript.onreadystatechange =
|
1727 | function () {
|
1728 |
|
1729 | const rstate = newScript.readyState;
|
1730 | if (!rstate || rstate === 'loaded' || rstate === 'complete') {
|
1731 |
|
1732 | newScript.onload = newScript.onreadystatechange = null;
|
1733 | if (newScript.parentNode) {
|
1734 | newScript.parentNode.removeChild(newScript);
|
1735 | }
|
1736 | loadCB();
|
1737 | }
|
1738 | };
|
1739 | newScript.onerror = () => {
|
1740 | log('Long-poll script failed to load: ' + url);
|
1741 | this.sendNewPolls = false;
|
1742 | this.close();
|
1743 | };
|
1744 | this.myIFrame.doc.body.appendChild(newScript);
|
1745 | }
|
1746 | catch (e) {
|
1747 |
|
1748 | }
|
1749 | }, Math.floor(1));
|
1750 | }
|
1751 | }
|
1752 | }
|
1753 |
|
1754 |
|
1755 |
|
1756 |
|
1757 |
|
1758 |
|
1759 |
|
1760 |
|
1761 |
|
1762 |
|
1763 |
|
1764 |
|
1765 |
|
1766 |
|
1767 |
|
1768 |
|
1769 |
|
1770 | const WEBSOCKET_MAX_FRAME_SIZE = 16384;
|
1771 | const WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
|
1772 | let WebSocketImpl = null;
|
1773 | if (typeof MozWebSocket !== 'undefined') {
|
1774 | WebSocketImpl = MozWebSocket;
|
1775 | }
|
1776 | else if (typeof WebSocket !== 'undefined') {
|
1777 | WebSocketImpl = WebSocket;
|
1778 | }
|
1779 |
|
1780 |
|
1781 |
|
1782 | class WebSocketConnection {
|
1783 | |
1784 |
|
1785 |
|
1786 |
|
1787 |
|
1788 |
|
1789 |
|
1790 |
|
1791 |
|
1792 |
|
1793 |
|
1794 | constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
|
1795 | this.connId = connId;
|
1796 | this.applicationId = applicationId;
|
1797 | this.appCheckToken = appCheckToken;
|
1798 | this.authToken = authToken;
|
1799 | this.keepaliveTimer = null;
|
1800 | this.frames = null;
|
1801 | this.totalFrames = 0;
|
1802 | this.bytesSent = 0;
|
1803 | this.bytesReceived = 0;
|
1804 | this.log_ = logWrapper(this.connId);
|
1805 | this.stats_ = statsManagerGetCollection(repoInfo);
|
1806 | this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
|
1807 | this.nodeAdmin = repoInfo.nodeAdmin;
|
1808 | }
|
1809 | |
1810 |
|
1811 |
|
1812 |
|
1813 |
|
1814 |
|
1815 |
|
1816 | static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
|
1817 | const urlParams = {};
|
1818 | urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
|
1819 | if (!isNodeSdk() &&
|
1820 | typeof location !== 'undefined' &&
|
1821 | location.hostname &&
|
1822 | FORGE_DOMAIN_RE.test(location.hostname)) {
|
1823 | urlParams[REFERER_PARAM] = FORGE_REF;
|
1824 | }
|
1825 | if (transportSessionId) {
|
1826 | urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
|
1827 | }
|
1828 | if (lastSessionId) {
|
1829 | urlParams[LAST_SESSION_PARAM] = lastSessionId;
|
1830 | }
|
1831 | if (appCheckToken) {
|
1832 | urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
|
1833 | }
|
1834 | if (applicationId) {
|
1835 | urlParams[APPLICATION_ID_PARAM] = applicationId;
|
1836 | }
|
1837 | return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
|
1838 | }
|
1839 | |
1840 |
|
1841 |
|
1842 |
|
1843 | open(onMessage, onDisconnect) {
|
1844 | this.onDisconnect = onDisconnect;
|
1845 | this.onMessage = onMessage;
|
1846 | this.log_('Websocket connecting to ' + this.connURL);
|
1847 | this.everConnected_ = false;
|
1848 |
|
1849 | PersistentStorage.set('previous_websocket_failure', true);
|
1850 | try {
|
1851 | let options;
|
1852 | if (isNodeSdk()) {
|
1853 | const device = this.nodeAdmin ? 'AdminNode' : 'Node';
|
1854 |
|
1855 | const options = {
|
1856 | headers: {
|
1857 | 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,
|
1858 | 'X-Firebase-GMPID': this.applicationId || ''
|
1859 | }
|
1860 | };
|
1861 |
|
1862 |
|
1863 |
|
1864 |
|
1865 |
|
1866 | if (this.authToken) {
|
1867 | options.headers['Authorization'] = `Bearer ${this.authToken}`;
|
1868 | }
|
1869 | if (this.appCheckToken) {
|
1870 | options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
|
1871 | }
|
1872 |
|
1873 | const env = process['env'];
|
1874 | const proxy = this.connURL.indexOf('wss://') === 0
|
1875 | ? env['HTTPS_PROXY'] || env['https_proxy']
|
1876 | : env['HTTP_PROXY'] || env['http_proxy'];
|
1877 | if (proxy) {
|
1878 | options['proxy'] = { origin: proxy };
|
1879 | }
|
1880 | }
|
1881 | this.mySock = new WebSocketImpl(this.connURL, [], options);
|
1882 | }
|
1883 | catch (e) {
|
1884 | this.log_('Error instantiating WebSocket.');
|
1885 | const error = e.message || e.data;
|
1886 | if (error) {
|
1887 | this.log_(error);
|
1888 | }
|
1889 | this.onClosed_();
|
1890 | return;
|
1891 | }
|
1892 | this.mySock.onopen = () => {
|
1893 | this.log_('Websocket connected.');
|
1894 | this.everConnected_ = true;
|
1895 | };
|
1896 | this.mySock.onclose = () => {
|
1897 | this.log_('Websocket connection was disconnected.');
|
1898 | this.mySock = null;
|
1899 | this.onClosed_();
|
1900 | };
|
1901 | this.mySock.onmessage = m => {
|
1902 | this.handleIncomingFrame(m);
|
1903 | };
|
1904 | this.mySock.onerror = e => {
|
1905 | this.log_('WebSocket error. Closing connection.');
|
1906 |
|
1907 | const error = e.message || e.data;
|
1908 | if (error) {
|
1909 | this.log_(error);
|
1910 | }
|
1911 | this.onClosed_();
|
1912 | };
|
1913 | }
|
1914 | |
1915 |
|
1916 |
|
1917 | start() { }
|
1918 | static forceDisallow() {
|
1919 | WebSocketConnection.forceDisallow_ = true;
|
1920 | }
|
1921 | static isAvailable() {
|
1922 | let isOldAndroid = false;
|
1923 | if (typeof navigator !== 'undefined' && navigator.userAgent) {
|
1924 | const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
|
1925 | const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
|
1926 | if (oldAndroidMatch && oldAndroidMatch.length > 1) {
|
1927 | if (parseFloat(oldAndroidMatch[1]) < 4.4) {
|
1928 | isOldAndroid = true;
|
1929 | }
|
1930 | }
|
1931 | }
|
1932 | return (!isOldAndroid &&
|
1933 | WebSocketImpl !== null &&
|
1934 | !WebSocketConnection.forceDisallow_);
|
1935 | }
|
1936 | |
1937 |
|
1938 |
|
1939 | static previouslyFailed() {
|
1940 |
|
1941 |
|
1942 | return (PersistentStorage.isInMemoryStorage ||
|
1943 | PersistentStorage.get('previous_websocket_failure') === true);
|
1944 | }
|
1945 | markConnectionHealthy() {
|
1946 | PersistentStorage.remove('previous_websocket_failure');
|
1947 | }
|
1948 | appendFrame_(data) {
|
1949 | this.frames.push(data);
|
1950 | if (this.frames.length === this.totalFrames) {
|
1951 | const fullMess = this.frames.join('');
|
1952 | this.frames = null;
|
1953 | const jsonMess = jsonEval(fullMess);
|
1954 |
|
1955 | this.onMessage(jsonMess);
|
1956 | }
|
1957 | }
|
1958 | |
1959 |
|
1960 |
|
1961 | handleNewFrameCount_(frameCount) {
|
1962 | this.totalFrames = frameCount;
|
1963 | this.frames = [];
|
1964 | }
|
1965 | |
1966 |
|
1967 |
|
1968 |
|
1969 | extractFrameCount_(data) {
|
1970 | assert(this.frames === null, 'We already have a frame buffer');
|
1971 |
|
1972 |
|
1973 | if (data.length <= 6) {
|
1974 | const frameCount = Number(data);
|
1975 | if (!isNaN(frameCount)) {
|
1976 | this.handleNewFrameCount_(frameCount);
|
1977 | return null;
|
1978 | }
|
1979 | }
|
1980 | this.handleNewFrameCount_(1);
|
1981 | return data;
|
1982 | }
|
1983 | |
1984 |
|
1985 |
|
1986 |
|
1987 | handleIncomingFrame(mess) {
|
1988 | if (this.mySock === null) {
|
1989 | return;
|
1990 | }
|
1991 | const data = mess['data'];
|
1992 | this.bytesReceived += data.length;
|
1993 | this.stats_.incrementCounter('bytes_received', data.length);
|
1994 | this.resetKeepAlive();
|
1995 | if (this.frames !== null) {
|
1996 |
|
1997 | this.appendFrame_(data);
|
1998 | }
|
1999 | else {
|
2000 |
|
2001 | const remainingData = this.extractFrameCount_(data);
|
2002 | if (remainingData !== null) {
|
2003 | this.appendFrame_(remainingData);
|
2004 | }
|
2005 | }
|
2006 | }
|
2007 | |
2008 |
|
2009 |
|
2010 |
|
2011 | send(data) {
|
2012 | this.resetKeepAlive();
|
2013 | const dataStr = stringify(data);
|
2014 | this.bytesSent += dataStr.length;
|
2015 | this.stats_.incrementCounter('bytes_sent', dataStr.length);
|
2016 |
|
2017 |
|
2018 | const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
|
2019 |
|
2020 | if (dataSegs.length > 1) {
|
2021 | this.sendString_(String(dataSegs.length));
|
2022 | }
|
2023 |
|
2024 | for (let i = 0; i < dataSegs.length; i++) {
|
2025 | this.sendString_(dataSegs[i]);
|
2026 | }
|
2027 | }
|
2028 | shutdown_() {
|
2029 | this.isClosed_ = true;
|
2030 | if (this.keepaliveTimer) {
|
2031 | clearInterval(this.keepaliveTimer);
|
2032 | this.keepaliveTimer = null;
|
2033 | }
|
2034 | if (this.mySock) {
|
2035 | this.mySock.close();
|
2036 | this.mySock = null;
|
2037 | }
|
2038 | }
|
2039 | onClosed_() {
|
2040 | if (!this.isClosed_) {
|
2041 | this.log_('WebSocket is closing itself');
|
2042 | this.shutdown_();
|
2043 |
|
2044 | if (this.onDisconnect) {
|
2045 | this.onDisconnect(this.everConnected_);
|
2046 | this.onDisconnect = null;
|
2047 | }
|
2048 | }
|
2049 | }
|
2050 | |
2051 |
|
2052 |
|
2053 |
|
2054 | close() {
|
2055 | if (!this.isClosed_) {
|
2056 | this.log_('WebSocket is being closed');
|
2057 | this.shutdown_();
|
2058 | }
|
2059 | }
|
2060 | |
2061 |
|
2062 |
|
2063 |
|
2064 | resetKeepAlive() {
|
2065 | clearInterval(this.keepaliveTimer);
|
2066 | this.keepaliveTimer = setInterval(() => {
|
2067 |
|
2068 | if (this.mySock) {
|
2069 | this.sendString_('0');
|
2070 | }
|
2071 | this.resetKeepAlive();
|
2072 |
|
2073 | }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
|
2074 | }
|
2075 | |
2076 |
|
2077 |
|
2078 |
|
2079 |
|
2080 | sendString_(str) {
|
2081 |
|
2082 |
|
2083 |
|
2084 | try {
|
2085 | this.mySock.send(str);
|
2086 | }
|
2087 | catch (e) {
|
2088 | this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
|
2089 | setTimeout(this.onClosed_.bind(this), 0);
|
2090 | }
|
2091 | }
|
2092 | }
|
2093 |
|
2094 |
|
2095 |
|
2096 | WebSocketConnection.responsesRequiredToBeHealthy = 2;
|
2097 |
|
2098 |
|
2099 |
|
2100 | WebSocketConnection.healthyTimeout = 30000;
|
2101 |
|
2102 |
|
2103 |
|
2104 |
|
2105 |
|
2106 |
|
2107 |
|
2108 |
|
2109 |
|
2110 |
|
2111 |
|
2112 |
|
2113 |
|
2114 |
|
2115 |
|
2116 |
|
2117 |
|
2118 |
|
2119 |
|
2120 |
|
2121 |
|
2122 |
|
2123 |
|
2124 |
|
2125 | class TransportManager {
|
2126 | |
2127 |
|
2128 |
|
2129 | constructor(repoInfo) {
|
2130 | this.initTransports_(repoInfo);
|
2131 | }
|
2132 | static get ALL_TRANSPORTS() {
|
2133 | return [BrowserPollConnection, WebSocketConnection];
|
2134 | }
|
2135 | |
2136 |
|
2137 |
|
2138 |
|
2139 | static get IS_TRANSPORT_INITIALIZED() {
|
2140 | return this.globalTransportInitialized_;
|
2141 | }
|
2142 | initTransports_(repoInfo) {
|
2143 | const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
|
2144 | let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
|
2145 | if (repoInfo.webSocketOnly) {
|
2146 | if (!isWebSocketsAvailable) {
|
2147 | warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
|
2148 | }
|
2149 | isSkipPollConnection = true;
|
2150 | }
|
2151 | if (isSkipPollConnection) {
|
2152 | this.transports_ = [WebSocketConnection];
|
2153 | }
|
2154 | else {
|
2155 | const transports = (this.transports_ = []);
|
2156 | for (const transport of TransportManager.ALL_TRANSPORTS) {
|
2157 | if (transport && transport['isAvailable']()) {
|
2158 | transports.push(transport);
|
2159 | }
|
2160 | }
|
2161 | TransportManager.globalTransportInitialized_ = true;
|
2162 | }
|
2163 | }
|
2164 | |
2165 |
|
2166 |
|
2167 | initialTransport() {
|
2168 | if (this.transports_.length > 0) {
|
2169 | return this.transports_[0];
|
2170 | }
|
2171 | else {
|
2172 | throw new Error('No transports available');
|
2173 | }
|
2174 | }
|
2175 | |
2176 |
|
2177 |
|
2178 | upgradeTransport() {
|
2179 | if (this.transports_.length > 1) {
|
2180 | return this.transports_[1];
|
2181 | }
|
2182 | else {
|
2183 | return null;
|
2184 | }
|
2185 | }
|
2186 | }
|
2187 |
|
2188 | TransportManager.globalTransportInitialized_ = false;
|
2189 |
|
2190 |
|
2191 |
|
2192 |
|
2193 |
|
2194 |
|
2195 |
|
2196 |
|
2197 |
|
2198 |
|
2199 |
|
2200 |
|
2201 |
|
2202 |
|
2203 |
|
2204 |
|
2205 |
|
2206 |
|
2207 | const UPGRADE_TIMEOUT = 60000;
|
2208 |
|
2209 |
|
2210 | const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
|
2211 |
|
2212 |
|
2213 |
|
2214 | const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
|
2215 | const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
|
2216 | const MESSAGE_TYPE = 't';
|
2217 | const MESSAGE_DATA = 'd';
|
2218 | const CONTROL_SHUTDOWN = 's';
|
2219 | const CONTROL_RESET = 'r';
|
2220 | const CONTROL_ERROR = 'e';
|
2221 | const CONTROL_PONG = 'o';
|
2222 | const SWITCH_ACK = 'a';
|
2223 | const END_TRANSMISSION = 'n';
|
2224 | const PING = 'p';
|
2225 | const SERVER_HELLO = 'h';
|
2226 |
|
2227 |
|
2228 |
|
2229 |
|
2230 | class Connection {
|
2231 | |
2232 |
|
2233 |
|
2234 |
|
2235 |
|
2236 |
|
2237 |
|
2238 |
|
2239 |
|
2240 |
|
2241 |
|
2242 |
|
2243 | constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
|
2244 | this.id = id;
|
2245 | this.repoInfo_ = repoInfo_;
|
2246 | this.applicationId_ = applicationId_;
|
2247 | this.appCheckToken_ = appCheckToken_;
|
2248 | this.authToken_ = authToken_;
|
2249 | this.onMessage_ = onMessage_;
|
2250 | this.onReady_ = onReady_;
|
2251 | this.onDisconnect_ = onDisconnect_;
|
2252 | this.onKill_ = onKill_;
|
2253 | this.lastSessionId = lastSessionId;
|
2254 | this.connectionCount = 0;
|
2255 | this.pendingDataMessages = [];
|
2256 | this.state_ = 0 ;
|
2257 | this.log_ = logWrapper('c:' + this.id + ':');
|
2258 | this.transportManager_ = new TransportManager(repoInfo_);
|
2259 | this.log_('Connection created');
|
2260 | this.start_();
|
2261 | }
|
2262 | |
2263 |
|
2264 |
|
2265 | start_() {
|
2266 | const conn = this.transportManager_.initialTransport();
|
2267 | this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
|
2268 |
|
2269 |
|
2270 | this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
|
2271 | const onMessageReceived = this.connReceiver_(this.conn_);
|
2272 | const onConnectionLost = this.disconnReceiver_(this.conn_);
|
2273 | this.tx_ = this.conn_;
|
2274 | this.rx_ = this.conn_;
|
2275 | this.secondaryConn_ = null;
|
2276 | this.isHealthy_ = false;
|
2277 | |
2278 |
|
2279 |
|
2280 |
|
2281 |
|
2282 |
|
2283 | setTimeout(() => {
|
2284 |
|
2285 | this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
|
2286 | }, Math.floor(0));
|
2287 | const healthyTimeoutMS = conn['healthyTimeout'] || 0;
|
2288 | if (healthyTimeoutMS > 0) {
|
2289 | this.healthyTimeout_ = setTimeoutNonBlocking(() => {
|
2290 | this.healthyTimeout_ = null;
|
2291 | if (!this.isHealthy_) {
|
2292 | if (this.conn_ &&
|
2293 | this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
|
2294 | this.log_('Connection exceeded healthy timeout but has received ' +
|
2295 | this.conn_.bytesReceived +
|
2296 | ' bytes. Marking connection healthy.');
|
2297 | this.isHealthy_ = true;
|
2298 | this.conn_.markConnectionHealthy();
|
2299 | }
|
2300 | else if (this.conn_ &&
|
2301 | this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
|
2302 | this.log_('Connection exceeded healthy timeout but has sent ' +
|
2303 | this.conn_.bytesSent +
|
2304 | ' bytes. Leaving connection alive.');
|
2305 |
|
2306 |
|
2307 | }
|
2308 | else {
|
2309 | this.log_('Closing unhealthy connection after timeout.');
|
2310 | this.close();
|
2311 | }
|
2312 | }
|
2313 |
|
2314 | }, Math.floor(healthyTimeoutMS));
|
2315 | }
|
2316 | }
|
2317 | nextTransportId_() {
|
2318 | return 'c:' + this.id + ':' + this.connectionCount++;
|
2319 | }
|
2320 | disconnReceiver_(conn) {
|
2321 | return everConnected => {
|
2322 | if (conn === this.conn_) {
|
2323 | this.onConnectionLost_(everConnected);
|
2324 | }
|
2325 | else if (conn === this.secondaryConn_) {
|
2326 | this.log_('Secondary connection lost.');
|
2327 | this.onSecondaryConnectionLost_();
|
2328 | }
|
2329 | else {
|
2330 | this.log_('closing an old connection');
|
2331 | }
|
2332 | };
|
2333 | }
|
2334 | connReceiver_(conn) {
|
2335 | return (message) => {
|
2336 | if (this.state_ !== 2 ) {
|
2337 | if (conn === this.rx_) {
|
2338 | this.onPrimaryMessageReceived_(message);
|
2339 | }
|
2340 | else if (conn === this.secondaryConn_) {
|
2341 | this.onSecondaryMessageReceived_(message);
|
2342 | }
|
2343 | else {
|
2344 | this.log_('message on old connection');
|
2345 | }
|
2346 | }
|
2347 | };
|
2348 | }
|
2349 | |
2350 |
|
2351 |
|
2352 | sendRequest(dataMsg) {
|
2353 |
|
2354 | const msg = { t: 'd', d: dataMsg };
|
2355 | this.sendData_(msg);
|
2356 | }
|
2357 | tryCleanupConnection() {
|
2358 | if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
|
2359 | this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
|
2360 | this.conn_ = this.secondaryConn_;
|
2361 | this.secondaryConn_ = null;
|
2362 |
|
2363 | }
|
2364 | }
|
2365 | onSecondaryControl_(controlData) {
|
2366 | if (MESSAGE_TYPE in controlData) {
|
2367 | const cmd = controlData[MESSAGE_TYPE];
|
2368 | if (cmd === SWITCH_ACK) {
|
2369 | this.upgradeIfSecondaryHealthy_();
|
2370 | }
|
2371 | else if (cmd === CONTROL_RESET) {
|
2372 |
|
2373 | this.log_('Got a reset on secondary, closing it');
|
2374 | this.secondaryConn_.close();
|
2375 |
|
2376 | if (this.tx_ === this.secondaryConn_ ||
|
2377 | this.rx_ === this.secondaryConn_) {
|
2378 | this.close();
|
2379 | }
|
2380 | }
|
2381 | else if (cmd === CONTROL_PONG) {
|
2382 | this.log_('got pong on secondary.');
|
2383 | this.secondaryResponsesRequired_--;
|
2384 | this.upgradeIfSecondaryHealthy_();
|
2385 | }
|
2386 | }
|
2387 | }
|
2388 | onSecondaryMessageReceived_(parsedData) {
|
2389 | const layer = requireKey('t', parsedData);
|
2390 | const data = requireKey('d', parsedData);
|
2391 | if (layer === 'c') {
|
2392 | this.onSecondaryControl_(data);
|
2393 | }
|
2394 | else if (layer === 'd') {
|
2395 |
|
2396 | this.pendingDataMessages.push(data);
|
2397 | }
|
2398 | else {
|
2399 | throw new Error('Unknown protocol layer: ' + layer);
|
2400 | }
|
2401 | }
|
2402 | upgradeIfSecondaryHealthy_() {
|
2403 | if (this.secondaryResponsesRequired_ <= 0) {
|
2404 | this.log_('Secondary connection is healthy.');
|
2405 | this.isHealthy_ = true;
|
2406 | this.secondaryConn_.markConnectionHealthy();
|
2407 | this.proceedWithUpgrade_();
|
2408 | }
|
2409 | else {
|
2410 |
|
2411 | this.log_('sending ping on secondary.');
|
2412 | this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
|
2413 | }
|
2414 | }
|
2415 | proceedWithUpgrade_() {
|
2416 |
|
2417 | this.secondaryConn_.start();
|
2418 |
|
2419 | this.log_('sending client ack on secondary');
|
2420 | this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
|
2421 |
|
2422 |
|
2423 | this.log_('Ending transmission on primary');
|
2424 | this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
|
2425 | this.tx_ = this.secondaryConn_;
|
2426 | this.tryCleanupConnection();
|
2427 | }
|
2428 | onPrimaryMessageReceived_(parsedData) {
|
2429 |
|
2430 | const layer = requireKey('t', parsedData);
|
2431 | const data = requireKey('d', parsedData);
|
2432 | if (layer === 'c') {
|
2433 | this.onControl_(data);
|
2434 | }
|
2435 | else if (layer === 'd') {
|
2436 | this.onDataMessage_(data);
|
2437 | }
|
2438 | }
|
2439 | onDataMessage_(message) {
|
2440 | this.onPrimaryResponse_();
|
2441 |
|
2442 | this.onMessage_(message);
|
2443 | }
|
2444 | onPrimaryResponse_() {
|
2445 | if (!this.isHealthy_) {
|
2446 | this.primaryResponsesRequired_--;
|
2447 | if (this.primaryResponsesRequired_ <= 0) {
|
2448 | this.log_('Primary connection is healthy.');
|
2449 | this.isHealthy_ = true;
|
2450 | this.conn_.markConnectionHealthy();
|
2451 | }
|
2452 | }
|
2453 | }
|
2454 | onControl_(controlData) {
|
2455 | const cmd = requireKey(MESSAGE_TYPE, controlData);
|
2456 | if (MESSAGE_DATA in controlData) {
|
2457 | const payload = controlData[MESSAGE_DATA];
|
2458 | if (cmd === SERVER_HELLO) {
|
2459 | this.onHandshake_(payload);
|
2460 | }
|
2461 | else if (cmd === END_TRANSMISSION) {
|
2462 | this.log_('recvd end transmission on primary');
|
2463 | this.rx_ = this.secondaryConn_;
|
2464 | for (let i = 0; i < this.pendingDataMessages.length; ++i) {
|
2465 | this.onDataMessage_(this.pendingDataMessages[i]);
|
2466 | }
|
2467 | this.pendingDataMessages = [];
|
2468 | this.tryCleanupConnection();
|
2469 | }
|
2470 | else if (cmd === CONTROL_SHUTDOWN) {
|
2471 |
|
2472 |
|
2473 | this.onConnectionShutdown_(payload);
|
2474 | }
|
2475 | else if (cmd === CONTROL_RESET) {
|
2476 |
|
2477 | this.onReset_(payload);
|
2478 | }
|
2479 | else if (cmd === CONTROL_ERROR) {
|
2480 | error('Server Error: ' + payload);
|
2481 | }
|
2482 | else if (cmd === CONTROL_PONG) {
|
2483 | this.log_('got pong on primary.');
|
2484 | this.onPrimaryResponse_();
|
2485 | this.sendPingOnPrimaryIfNecessary_();
|
2486 | }
|
2487 | else {
|
2488 | error('Unknown control packet command: ' + cmd);
|
2489 | }
|
2490 | }
|
2491 | }
|
2492 | |
2493 |
|
2494 |
|
2495 | onHandshake_(handshake) {
|
2496 | const timestamp = handshake.ts;
|
2497 | const version = handshake.v;
|
2498 | const host = handshake.h;
|
2499 | this.sessionId = handshake.s;
|
2500 | this.repoInfo_.host = host;
|
2501 |
|
2502 | if (this.state_ === 0 ) {
|
2503 | this.conn_.start();
|
2504 | this.onConnectionEstablished_(this.conn_, timestamp);
|
2505 | if (PROTOCOL_VERSION !== version) {
|
2506 | warn('Protocol version mismatch detected');
|
2507 | }
|
2508 |
|
2509 | this.tryStartUpgrade_();
|
2510 | }
|
2511 | }
|
2512 | tryStartUpgrade_() {
|
2513 | const conn = this.transportManager_.upgradeTransport();
|
2514 | if (conn) {
|
2515 | this.startUpgrade_(conn);
|
2516 | }
|
2517 | }
|
2518 | startUpgrade_(conn) {
|
2519 | this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
|
2520 |
|
2521 |
|
2522 | this.secondaryResponsesRequired_ =
|
2523 | conn['responsesRequiredToBeHealthy'] || 0;
|
2524 | const onMessage = this.connReceiver_(this.secondaryConn_);
|
2525 | const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
|
2526 | this.secondaryConn_.open(onMessage, onDisconnect);
|
2527 |
|
2528 | setTimeoutNonBlocking(() => {
|
2529 | if (this.secondaryConn_) {
|
2530 | this.log_('Timed out trying to upgrade.');
|
2531 | this.secondaryConn_.close();
|
2532 | }
|
2533 | }, Math.floor(UPGRADE_TIMEOUT));
|
2534 | }
|
2535 | onReset_(host) {
|
2536 | this.log_('Reset packet received. New host: ' + host);
|
2537 | this.repoInfo_.host = host;
|
2538 |
|
2539 |
|
2540 | if (this.state_ === 1 ) {
|
2541 | this.close();
|
2542 | }
|
2543 | else {
|
2544 |
|
2545 | this.closeConnections_();
|
2546 | this.start_();
|
2547 | }
|
2548 | }
|
2549 | onConnectionEstablished_(conn, timestamp) {
|
2550 | this.log_('Realtime connection established.');
|
2551 | this.conn_ = conn;
|
2552 | this.state_ = 1 ;
|
2553 | if (this.onReady_) {
|
2554 | this.onReady_(timestamp, this.sessionId);
|
2555 | this.onReady_ = null;
|
2556 | }
|
2557 |
|
2558 |
|
2559 | if (this.primaryResponsesRequired_ === 0) {
|
2560 | this.log_('Primary connection is healthy.');
|
2561 | this.isHealthy_ = true;
|
2562 | }
|
2563 | else {
|
2564 | setTimeoutNonBlocking(() => {
|
2565 | this.sendPingOnPrimaryIfNecessary_();
|
2566 | }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
|
2567 | }
|
2568 | }
|
2569 | sendPingOnPrimaryIfNecessary_() {
|
2570 |
|
2571 | if (!this.isHealthy_ && this.state_ === 1 ) {
|
2572 | this.log_('sending ping on primary.');
|
2573 | this.sendData_({ t: 'c', d: { t: PING, d: {} } });
|
2574 | }
|
2575 | }
|
2576 | onSecondaryConnectionLost_() {
|
2577 | const conn = this.secondaryConn_;
|
2578 | this.secondaryConn_ = null;
|
2579 | if (this.tx_ === conn || this.rx_ === conn) {
|
2580 |
|
2581 | this.close();
|
2582 | }
|
2583 | }
|
2584 | |
2585 |
|
2586 |
|
2587 |
|
2588 | onConnectionLost_(everConnected) {
|
2589 | this.conn_ = null;
|
2590 |
|
2591 |
|
2592 | if (!everConnected && this.state_ === 0 ) {
|
2593 | this.log_('Realtime connection failed.');
|
2594 |
|
2595 | if (this.repoInfo_.isCacheableHost()) {
|
2596 | PersistentStorage.remove('host:' + this.repoInfo_.host);
|
2597 |
|
2598 | this.repoInfo_.internalHost = this.repoInfo_.host;
|
2599 | }
|
2600 | }
|
2601 | else if (this.state_ === 1 ) {
|
2602 | this.log_('Realtime connection lost.');
|
2603 | }
|
2604 | this.close();
|
2605 | }
|
2606 | onConnectionShutdown_(reason) {
|
2607 | this.log_('Connection shutdown command received. Shutting down...');
|
2608 | if (this.onKill_) {
|
2609 | this.onKill_(reason);
|
2610 | this.onKill_ = null;
|
2611 | }
|
2612 |
|
2613 |
|
2614 | this.onDisconnect_ = null;
|
2615 | this.close();
|
2616 | }
|
2617 | sendData_(data) {
|
2618 | if (this.state_ !== 1 ) {
|
2619 | throw 'Connection is not connected';
|
2620 | }
|
2621 | else {
|
2622 | this.tx_.send(data);
|
2623 | }
|
2624 | }
|
2625 | |
2626 |
|
2627 |
|
2628 | close() {
|
2629 | if (this.state_ !== 2 ) {
|
2630 | this.log_('Closing realtime connection.');
|
2631 | this.state_ = 2 ;
|
2632 | this.closeConnections_();
|
2633 | if (this.onDisconnect_) {
|
2634 | this.onDisconnect_();
|
2635 | this.onDisconnect_ = null;
|
2636 | }
|
2637 | }
|
2638 | }
|
2639 | closeConnections_() {
|
2640 | this.log_('Shutting down all connections');
|
2641 | if (this.conn_) {
|
2642 | this.conn_.close();
|
2643 | this.conn_ = null;
|
2644 | }
|
2645 | if (this.secondaryConn_) {
|
2646 | this.secondaryConn_.close();
|
2647 | this.secondaryConn_ = null;
|
2648 | }
|
2649 | if (this.healthyTimeout_) {
|
2650 | clearTimeout(this.healthyTimeout_);
|
2651 | this.healthyTimeout_ = null;
|
2652 | }
|
2653 | }
|
2654 | }
|
2655 |
|
2656 |
|
2657 |
|
2658 |
|
2659 |
|
2660 |
|
2661 |
|
2662 |
|
2663 |
|
2664 |
|
2665 |
|
2666 |
|
2667 |
|
2668 |
|
2669 |
|
2670 |
|
2671 |
|
2672 |
|
2673 |
|
2674 |
|
2675 |
|
2676 |
|
2677 |
|
2678 | class ServerActions {
|
2679 | put(pathString, data, onComplete, hash) { }
|
2680 | merge(pathString, data, onComplete, hash) { }
|
2681 | |
2682 |
|
2683 |
|
2684 |
|
2685 | refreshAuthToken(token) { }
|
2686 | |
2687 |
|
2688 |
|
2689 |
|
2690 | refreshAppCheckToken(token) { }
|
2691 | onDisconnectPut(pathString, data, onComplete) { }
|
2692 | onDisconnectMerge(pathString, data, onComplete) { }
|
2693 | onDisconnectCancel(pathString, onComplete) { }
|
2694 | reportStats(stats) { }
|
2695 | }
|
2696 |
|
2697 |
|
2698 |
|
2699 |
|
2700 |
|
2701 |
|
2702 |
|
2703 |
|
2704 |
|
2705 |
|
2706 |
|
2707 |
|
2708 |
|
2709 |
|
2710 |
|
2711 |
|
2712 |
|
2713 |
|
2714 |
|
2715 |
|
2716 |
|
2717 | class EventEmitter {
|
2718 | constructor(allowedEvents_) {
|
2719 | this.allowedEvents_ = allowedEvents_;
|
2720 | this.listeners_ = {};
|
2721 | assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
|
2722 | }
|
2723 | |
2724 |
|
2725 |
|
2726 | trigger(eventType, ...varArgs) {
|
2727 | if (Array.isArray(this.listeners_[eventType])) {
|
2728 |
|
2729 | const listeners = [...this.listeners_[eventType]];
|
2730 | for (let i = 0; i < listeners.length; i++) {
|
2731 | listeners[i].callback.apply(listeners[i].context, varArgs);
|
2732 | }
|
2733 | }
|
2734 | }
|
2735 | on(eventType, callback, context) {
|
2736 | this.validateEventType_(eventType);
|
2737 | this.listeners_[eventType] = this.listeners_[eventType] || [];
|
2738 | this.listeners_[eventType].push({ callback, context });
|
2739 | const eventData = this.getInitialEvent(eventType);
|
2740 | if (eventData) {
|
2741 | callback.apply(context, eventData);
|
2742 | }
|
2743 | }
|
2744 | off(eventType, callback, context) {
|
2745 | this.validateEventType_(eventType);
|
2746 | const listeners = this.listeners_[eventType] || [];
|
2747 | for (let i = 0; i < listeners.length; i++) {
|
2748 | if (listeners[i].callback === callback &&
|
2749 | (!context || context === listeners[i].context)) {
|
2750 | listeners.splice(i, 1);
|
2751 | return;
|
2752 | }
|
2753 | }
|
2754 | }
|
2755 | validateEventType_(eventType) {
|
2756 | assert(this.allowedEvents_.find(et => {
|
2757 | return et === eventType;
|
2758 | }), 'Unknown event: ' + eventType);
|
2759 | }
|
2760 | }
|
2761 |
|
2762 |
|
2763 |
|
2764 |
|
2765 |
|
2766 |
|
2767 |
|
2768 |
|
2769 |
|
2770 |
|
2771 |
|
2772 |
|
2773 |
|
2774 |
|
2775 |
|
2776 |
|
2777 |
|
2778 |
|
2779 |
|
2780 |
|
2781 |
|
2782 |
|
2783 |
|
2784 |
|
2785 | class OnlineMonitor extends EventEmitter {
|
2786 | constructor() {
|
2787 | super(['online']);
|
2788 | this.online_ = true;
|
2789 |
|
2790 |
|
2791 |
|
2792 |
|
2793 | if (typeof window !== 'undefined' &&
|
2794 | typeof window.addEventListener !== 'undefined' &&
|
2795 | !isMobileCordova()) {
|
2796 | window.addEventListener('online', () => {
|
2797 | if (!this.online_) {
|
2798 | this.online_ = true;
|
2799 | this.trigger('online', true);
|
2800 | }
|
2801 | }, false);
|
2802 | window.addEventListener('offline', () => {
|
2803 | if (this.online_) {
|
2804 | this.online_ = false;
|
2805 | this.trigger('online', false);
|
2806 | }
|
2807 | }, false);
|
2808 | }
|
2809 | }
|
2810 | static getInstance() {
|
2811 | return new OnlineMonitor();
|
2812 | }
|
2813 | getInitialEvent(eventType) {
|
2814 | assert(eventType === 'online', 'Unknown event type: ' + eventType);
|
2815 | return [this.online_];
|
2816 | }
|
2817 | currentlyOnline() {
|
2818 | return this.online_;
|
2819 | }
|
2820 | }
|
2821 |
|
2822 |
|
2823 |
|
2824 |
|
2825 |
|
2826 |
|
2827 |
|
2828 |
|
2829 |
|
2830 |
|
2831 |
|
2832 |
|
2833 |
|
2834 |
|
2835 |
|
2836 |
|
2837 |
|
2838 |
|
2839 | const MAX_PATH_DEPTH = 32;
|
2840 |
|
2841 | const MAX_PATH_LENGTH_BYTES = 768;
|
2842 |
|
2843 |
|
2844 |
|
2845 |
|
2846 |
|
2847 | class Path {
|
2848 | |
2849 |
|
2850 |
|
2851 |
|
2852 | constructor(pathOrString, pieceNum) {
|
2853 | if (pieceNum === void 0) {
|
2854 | this.pieces_ = pathOrString.split('/');
|
2855 |
|
2856 | let copyTo = 0;
|
2857 | for (let i = 0; i < this.pieces_.length; i++) {
|
2858 | if (this.pieces_[i].length > 0) {
|
2859 | this.pieces_[copyTo] = this.pieces_[i];
|
2860 | copyTo++;
|
2861 | }
|
2862 | }
|
2863 | this.pieces_.length = copyTo;
|
2864 | this.pieceNum_ = 0;
|
2865 | }
|
2866 | else {
|
2867 | this.pieces_ = pathOrString;
|
2868 | this.pieceNum_ = pieceNum;
|
2869 | }
|
2870 | }
|
2871 | toString() {
|
2872 | let pathString = '';
|
2873 | for (let i = this.pieceNum_; i < this.pieces_.length; i++) {
|
2874 | if (this.pieces_[i] !== '') {
|
2875 | pathString += '/' + this.pieces_[i];
|
2876 | }
|
2877 | }
|
2878 | return pathString || '/';
|
2879 | }
|
2880 | }
|
2881 | function newEmptyPath() {
|
2882 | return new Path('');
|
2883 | }
|
2884 | function pathGetFront(path) {
|
2885 | if (path.pieceNum_ >= path.pieces_.length) {
|
2886 | return null;
|
2887 | }
|
2888 | return path.pieces_[path.pieceNum_];
|
2889 | }
|
2890 |
|
2891 |
|
2892 |
|
2893 | function pathGetLength(path) {
|
2894 | return path.pieces_.length - path.pieceNum_;
|
2895 | }
|
2896 | function pathPopFront(path) {
|
2897 | let pieceNum = path.pieceNum_;
|
2898 | if (pieceNum < path.pieces_.length) {
|
2899 | pieceNum++;
|
2900 | }
|
2901 | return new Path(path.pieces_, pieceNum);
|
2902 | }
|
2903 | function pathGetBack(path) {
|
2904 | if (path.pieceNum_ < path.pieces_.length) {
|
2905 | return path.pieces_[path.pieces_.length - 1];
|
2906 | }
|
2907 | return null;
|
2908 | }
|
2909 | function pathToUrlEncodedString(path) {
|
2910 | let pathString = '';
|
2911 | for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
|
2912 | if (path.pieces_[i] !== '') {
|
2913 | pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
|
2914 | }
|
2915 | }
|
2916 | return pathString || '/';
|
2917 | }
|
2918 |
|
2919 |
|
2920 |
|
2921 |
|
2922 | function pathSlice(path, begin = 0) {
|
2923 | return path.pieces_.slice(path.pieceNum_ + begin);
|
2924 | }
|
2925 | function pathParent(path) {
|
2926 | if (path.pieceNum_ >= path.pieces_.length) {
|
2927 | return null;
|
2928 | }
|
2929 | const pieces = [];
|
2930 | for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
|
2931 | pieces.push(path.pieces_[i]);
|
2932 | }
|
2933 | return new Path(pieces, 0);
|
2934 | }
|
2935 | function pathChild(path, childPathObj) {
|
2936 | const pieces = [];
|
2937 | for (let i = path.pieceNum_; i < path.pieces_.length; i++) {
|
2938 | pieces.push(path.pieces_[i]);
|
2939 | }
|
2940 | if (childPathObj instanceof Path) {
|
2941 | for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
|
2942 | pieces.push(childPathObj.pieces_[i]);
|
2943 | }
|
2944 | }
|
2945 | else {
|
2946 | const childPieces = childPathObj.split('/');
|
2947 | for (let i = 0; i < childPieces.length; i++) {
|
2948 | if (childPieces[i].length > 0) {
|
2949 | pieces.push(childPieces[i]);
|
2950 | }
|
2951 | }
|
2952 | }
|
2953 | return new Path(pieces, 0);
|
2954 | }
|
2955 |
|
2956 |
|
2957 |
|
2958 | function pathIsEmpty(path) {
|
2959 | return path.pieceNum_ >= path.pieces_.length;
|
2960 | }
|
2961 |
|
2962 |
|
2963 |
|
2964 | function newRelativePath(outerPath, innerPath) {
|
2965 | const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
|
2966 | if (outer === null) {
|
2967 | return innerPath;
|
2968 | }
|
2969 | else if (outer === inner) {
|
2970 | return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
|
2971 | }
|
2972 | else {
|
2973 | throw new Error('INTERNAL ERROR: innerPath (' +
|
2974 | innerPath +
|
2975 | ') is not within ' +
|
2976 | 'outerPath (' +
|
2977 | outerPath +
|
2978 | ')');
|
2979 | }
|
2980 | }
|
2981 |
|
2982 |
|
2983 |
|
2984 | function pathCompare(left, right) {
|
2985 | const leftKeys = pathSlice(left, 0);
|
2986 | const rightKeys = pathSlice(right, 0);
|
2987 | for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
|
2988 | const cmp = nameCompare(leftKeys[i], rightKeys[i]);
|
2989 | if (cmp !== 0) {
|
2990 | return cmp;
|
2991 | }
|
2992 | }
|
2993 | if (leftKeys.length === rightKeys.length) {
|
2994 | return 0;
|
2995 | }
|
2996 | return leftKeys.length < rightKeys.length ? -1 : 1;
|
2997 | }
|
2998 |
|
2999 |
|
3000 |
|
3001 | function pathEquals(path, other) {
|
3002 | if (pathGetLength(path) !== pathGetLength(other)) {
|
3003 | return false;
|
3004 | }
|
3005 | for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
|
3006 | if (path.pieces_[i] !== other.pieces_[j]) {
|
3007 | return false;
|
3008 | }
|
3009 | }
|
3010 | return true;
|
3011 | }
|
3012 |
|
3013 |
|
3014 |
|
3015 | function pathContains(path, other) {
|
3016 | let i = path.pieceNum_;
|
3017 | let j = other.pieceNum_;
|
3018 | if (pathGetLength(path) > pathGetLength(other)) {
|
3019 | return false;
|
3020 | }
|
3021 | while (i < path.pieces_.length) {
|
3022 | if (path.pieces_[i] !== other.pieces_[j]) {
|
3023 | return false;
|
3024 | }
|
3025 | ++i;
|
3026 | ++j;
|
3027 | }
|
3028 | return true;
|
3029 | }
|
3030 |
|
3031 |
|
3032 |
|
3033 |
|
3034 |
|
3035 |
|
3036 |
|
3037 |
|
3038 |
|
3039 |
|
3040 | class ValidationPath {
|
3041 | |
3042 |
|
3043 |
|
3044 |
|
3045 | constructor(path, errorPrefix_) {
|
3046 | this.errorPrefix_ = errorPrefix_;
|
3047 | this.parts_ = pathSlice(path, 0);
|
3048 |
|
3049 | this.byteLength_ = Math.max(1, this.parts_.length);
|
3050 | for (let i = 0; i < this.parts_.length; i++) {
|
3051 | this.byteLength_ += stringLength(this.parts_[i]);
|
3052 | }
|
3053 | validationPathCheckValid(this);
|
3054 | }
|
3055 | }
|
3056 | function validationPathPush(validationPath, child) {
|
3057 |
|
3058 | if (validationPath.parts_.length > 0) {
|
3059 | validationPath.byteLength_ += 1;
|
3060 | }
|
3061 | validationPath.parts_.push(child);
|
3062 | validationPath.byteLength_ += stringLength(child);
|
3063 | validationPathCheckValid(validationPath);
|
3064 | }
|
3065 | function validationPathPop(validationPath) {
|
3066 | const last = validationPath.parts_.pop();
|
3067 | validationPath.byteLength_ -= stringLength(last);
|
3068 |
|
3069 | if (validationPath.parts_.length > 0) {
|
3070 | validationPath.byteLength_ -= 1;
|
3071 | }
|
3072 | }
|
3073 | function validationPathCheckValid(validationPath) {
|
3074 | if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
|
3075 | throw new Error(validationPath.errorPrefix_ +
|
3076 | 'has a key path longer than ' +
|
3077 | MAX_PATH_LENGTH_BYTES +
|
3078 | ' bytes (' +
|
3079 | validationPath.byteLength_ +
|
3080 | ').');
|
3081 | }
|
3082 | if (validationPath.parts_.length > MAX_PATH_DEPTH) {
|
3083 | throw new Error(validationPath.errorPrefix_ +
|
3084 | 'path specified exceeds the maximum depth that can be written (' +
|
3085 | MAX_PATH_DEPTH +
|
3086 | ') or object contains a cycle ' +
|
3087 | validationPathToErrorString(validationPath));
|
3088 | }
|
3089 | }
|
3090 |
|
3091 |
|
3092 |
|
3093 | function validationPathToErrorString(validationPath) {
|
3094 | if (validationPath.parts_.length === 0) {
|
3095 | return '';
|
3096 | }
|
3097 | return "in property '" + validationPath.parts_.join('.') + "'";
|
3098 | }
|
3099 |
|
3100 |
|
3101 |
|
3102 |
|
3103 |
|
3104 |
|
3105 |
|
3106 |
|
3107 |
|
3108 |
|
3109 |
|
3110 |
|
3111 |
|
3112 |
|
3113 |
|
3114 |
|
3115 |
|
3116 | class VisibilityMonitor extends EventEmitter {
|
3117 | constructor() {
|
3118 | super(['visible']);
|
3119 | let hidden;
|
3120 | let visibilityChange;
|
3121 | if (typeof document !== 'undefined' &&
|
3122 | typeof document.addEventListener !== 'undefined') {
|
3123 | if (typeof document['hidden'] !== 'undefined') {
|
3124 |
|
3125 | visibilityChange = 'visibilitychange';
|
3126 | hidden = 'hidden';
|
3127 | }
|
3128 | else if (typeof document['mozHidden'] !== 'undefined') {
|
3129 | visibilityChange = 'mozvisibilitychange';
|
3130 | hidden = 'mozHidden';
|
3131 | }
|
3132 | else if (typeof document['msHidden'] !== 'undefined') {
|
3133 | visibilityChange = 'msvisibilitychange';
|
3134 | hidden = 'msHidden';
|
3135 | }
|
3136 | else if (typeof document['webkitHidden'] !== 'undefined') {
|
3137 | visibilityChange = 'webkitvisibilitychange';
|
3138 | hidden = 'webkitHidden';
|
3139 | }
|
3140 | }
|
3141 |
|
3142 |
|
3143 |
|
3144 |
|
3145 | this.visible_ = true;
|
3146 | if (visibilityChange) {
|
3147 | document.addEventListener(visibilityChange, () => {
|
3148 | const visible = !document[hidden];
|
3149 | if (visible !== this.visible_) {
|
3150 | this.visible_ = visible;
|
3151 | this.trigger('visible', visible);
|
3152 | }
|
3153 | }, false);
|
3154 | }
|
3155 | }
|
3156 | static getInstance() {
|
3157 | return new VisibilityMonitor();
|
3158 | }
|
3159 | getInitialEvent(eventType) {
|
3160 | assert(eventType === 'visible', 'Unknown event type: ' + eventType);
|
3161 | return [this.visible_];
|
3162 | }
|
3163 | }
|
3164 |
|
3165 |
|
3166 |
|
3167 |
|
3168 |
|
3169 |
|
3170 |
|
3171 |
|
3172 |
|
3173 |
|
3174 |
|
3175 |
|
3176 |
|
3177 |
|
3178 |
|
3179 |
|
3180 |
|
3181 | const RECONNECT_MIN_DELAY = 1000;
|
3182 | const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000;
|
3183 | const GET_CONNECT_TIMEOUT = 3 * 1000;
|
3184 | const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000;
|
3185 | const RECONNECT_DELAY_MULTIPLIER = 1.3;
|
3186 | const RECONNECT_DELAY_RESET_TIMEOUT = 30000;
|
3187 | const SERVER_KILL_INTERRUPT_REASON = 'server_kill';
|
3188 |
|
3189 | const INVALID_TOKEN_THRESHOLD = 3;
|
3190 |
|
3191 |
|
3192 |
|
3193 |
|
3194 |
|
3195 |
|
3196 | class PersistentConnection extends ServerActions {
|
3197 | |
3198 |
|
3199 |
|
3200 |
|
3201 |
|
3202 | constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
|
3203 | super();
|
3204 | this.repoInfo_ = repoInfo_;
|
3205 | this.applicationId_ = applicationId_;
|
3206 | this.onDataUpdate_ = onDataUpdate_;
|
3207 | this.onConnectStatus_ = onConnectStatus_;
|
3208 | this.onServerInfoUpdate_ = onServerInfoUpdate_;
|
3209 | this.authTokenProvider_ = authTokenProvider_;
|
3210 | this.appCheckTokenProvider_ = appCheckTokenProvider_;
|
3211 | this.authOverride_ = authOverride_;
|
3212 |
|
3213 | this.id = PersistentConnection.nextPersistentConnectionId_++;
|
3214 | this.log_ = logWrapper('p:' + this.id + ':');
|
3215 | this.interruptReasons_ = {};
|
3216 | this.listens = new Map();
|
3217 | this.outstandingPuts_ = [];
|
3218 | this.outstandingGets_ = [];
|
3219 | this.outstandingPutCount_ = 0;
|
3220 | this.outstandingGetCount_ = 0;
|
3221 | this.onDisconnectRequestQueue_ = [];
|
3222 | this.connected_ = false;
|
3223 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3224 | this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
|
3225 | this.securityDebugCallback_ = null;
|
3226 | this.lastSessionId = null;
|
3227 | this.establishConnectionTimer_ = null;
|
3228 | this.visible_ = false;
|
3229 |
|
3230 | this.requestCBHash_ = {};
|
3231 | this.requestNumber_ = 0;
|
3232 | this.realtime_ = null;
|
3233 | this.authToken_ = null;
|
3234 | this.appCheckToken_ = null;
|
3235 | this.forceTokenRefresh_ = false;
|
3236 | this.invalidAuthTokenCount_ = 0;
|
3237 | this.invalidAppCheckTokenCount_ = 0;
|
3238 | this.firstConnection_ = true;
|
3239 | this.lastConnectionAttemptTime_ = null;
|
3240 | this.lastConnectionEstablishedTime_ = null;
|
3241 | if (authOverride_ && !isNodeSdk()) {
|
3242 | throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
|
3243 | }
|
3244 | VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);
|
3245 | if (repoInfo_.host.indexOf('fblocal') === -1) {
|
3246 | OnlineMonitor.getInstance().on('online', this.onOnline_, this);
|
3247 | }
|
3248 | }
|
3249 | sendRequest(action, body, onResponse) {
|
3250 | const curReqNum = ++this.requestNumber_;
|
3251 | const msg = { r: curReqNum, a: action, b: body };
|
3252 | this.log_(stringify(msg));
|
3253 | assert(this.connected_, "sendRequest call when we're not connected not allowed.");
|
3254 | this.realtime_.sendRequest(msg);
|
3255 | if (onResponse) {
|
3256 | this.requestCBHash_[curReqNum] = onResponse;
|
3257 | }
|
3258 | }
|
3259 | get(query) {
|
3260 | this.initConnection_();
|
3261 | const deferred = new Deferred();
|
3262 | const request = {
|
3263 | p: query._path.toString(),
|
3264 | q: query._queryObject
|
3265 | };
|
3266 | const outstandingGet = {
|
3267 | action: 'g',
|
3268 | request,
|
3269 | onComplete: (message) => {
|
3270 | const payload = message['d'];
|
3271 | if (message['s'] === 'ok') {
|
3272 | deferred.resolve(payload);
|
3273 | }
|
3274 | else {
|
3275 | deferred.reject(payload);
|
3276 | }
|
3277 | }
|
3278 | };
|
3279 | this.outstandingGets_.push(outstandingGet);
|
3280 | this.outstandingGetCount_++;
|
3281 | const index = this.outstandingGets_.length - 1;
|
3282 | if (!this.connected_) {
|
3283 | setTimeout(() => {
|
3284 | const get = this.outstandingGets_[index];
|
3285 | if (get === undefined || outstandingGet !== get) {
|
3286 | return;
|
3287 | }
|
3288 | delete this.outstandingGets_[index];
|
3289 | this.outstandingGetCount_--;
|
3290 | if (this.outstandingGetCount_ === 0) {
|
3291 | this.outstandingGets_ = [];
|
3292 | }
|
3293 | this.log_('get ' + index + ' timed out on connection');
|
3294 | deferred.reject(new Error('Client is offline.'));
|
3295 | }, GET_CONNECT_TIMEOUT);
|
3296 | }
|
3297 | if (this.connected_) {
|
3298 | this.sendGet_(index);
|
3299 | }
|
3300 | return deferred.promise;
|
3301 | }
|
3302 | listen(query, currentHashFn, tag, onComplete) {
|
3303 | this.initConnection_();
|
3304 | const queryId = query._queryIdentifier;
|
3305 | const pathString = query._path.toString();
|
3306 | this.log_('Listen called for ' + pathString + ' ' + queryId);
|
3307 | if (!this.listens.has(pathString)) {
|
3308 | this.listens.set(pathString, new Map());
|
3309 | }
|
3310 | assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
|
3311 | assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
|
3312 | const listenSpec = {
|
3313 | onComplete,
|
3314 | hashFn: currentHashFn,
|
3315 | query,
|
3316 | tag
|
3317 | };
|
3318 | this.listens.get(pathString).set(queryId, listenSpec);
|
3319 | if (this.connected_) {
|
3320 | this.sendListen_(listenSpec);
|
3321 | }
|
3322 | }
|
3323 | sendGet_(index) {
|
3324 | const get = this.outstandingGets_[index];
|
3325 | this.sendRequest('g', get.request, (message) => {
|
3326 | delete this.outstandingGets_[index];
|
3327 | this.outstandingGetCount_--;
|
3328 | if (this.outstandingGetCount_ === 0) {
|
3329 | this.outstandingGets_ = [];
|
3330 | }
|
3331 | if (get.onComplete) {
|
3332 | get.onComplete(message);
|
3333 | }
|
3334 | });
|
3335 | }
|
3336 | sendListen_(listenSpec) {
|
3337 | const query = listenSpec.query;
|
3338 | const pathString = query._path.toString();
|
3339 | const queryId = query._queryIdentifier;
|
3340 | this.log_('Listen on ' + pathString + ' for ' + queryId);
|
3341 | const req = { p: pathString };
|
3342 | const action = 'q';
|
3343 |
|
3344 | if (listenSpec.tag) {
|
3345 | req['q'] = query._queryObject;
|
3346 | req['t'] = listenSpec.tag;
|
3347 | }
|
3348 | req[ 'h'] = listenSpec.hashFn();
|
3349 | this.sendRequest(action, req, (message) => {
|
3350 | const payload = message[ 'd'];
|
3351 | const status = message[ 's'];
|
3352 |
|
3353 | PersistentConnection.warnOnListenWarnings_(payload, query);
|
3354 | const currentListenSpec = this.listens.get(pathString) &&
|
3355 | this.listens.get(pathString).get(queryId);
|
3356 |
|
3357 | if (currentListenSpec === listenSpec) {
|
3358 | this.log_('listen response', message);
|
3359 | if (status !== 'ok') {
|
3360 | this.removeListen_(pathString, queryId);
|
3361 | }
|
3362 | if (listenSpec.onComplete) {
|
3363 | listenSpec.onComplete(status, payload);
|
3364 | }
|
3365 | }
|
3366 | });
|
3367 | }
|
3368 | static warnOnListenWarnings_(payload, query) {
|
3369 | if (payload && typeof payload === 'object' && contains(payload, 'w')) {
|
3370 |
|
3371 | const warnings = safeGet(payload, 'w');
|
3372 | if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
|
3373 | const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
|
3374 | const indexPath = query._path.toString();
|
3375 | warn(`Using an unspecified index. Your data will be downloaded and ` +
|
3376 | `filtered on the client. Consider adding ${indexSpec} at ` +
|
3377 | `${indexPath} to your security rules for better performance.`);
|
3378 | }
|
3379 | }
|
3380 | }
|
3381 | refreshAuthToken(token) {
|
3382 | this.authToken_ = token;
|
3383 | this.log_('Auth token refreshed');
|
3384 | if (this.authToken_) {
|
3385 | this.tryAuth();
|
3386 | }
|
3387 | else {
|
3388 |
|
3389 |
|
3390 | if (this.connected_) {
|
3391 | this.sendRequest('unauth', {}, () => { });
|
3392 | }
|
3393 | }
|
3394 | this.reduceReconnectDelayIfAdminCredential_(token);
|
3395 | }
|
3396 | reduceReconnectDelayIfAdminCredential_(credential) {
|
3397 |
|
3398 |
|
3399 | const isFirebaseSecret = credential && credential.length === 40;
|
3400 | if (isFirebaseSecret || isAdmin(credential)) {
|
3401 | this.log_('Admin auth credential detected. Reducing max reconnect time.');
|
3402 | this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
|
3403 | }
|
3404 | }
|
3405 | refreshAppCheckToken(token) {
|
3406 | this.appCheckToken_ = token;
|
3407 | this.log_('App check token refreshed');
|
3408 | if (this.appCheckToken_) {
|
3409 | this.tryAppCheck();
|
3410 | }
|
3411 | else {
|
3412 |
|
3413 |
|
3414 |
|
3415 | if (this.connected_) {
|
3416 | this.sendRequest('unappeck', {}, () => { });
|
3417 | }
|
3418 | }
|
3419 | }
|
3420 | |
3421 |
|
3422 |
|
3423 |
|
3424 | tryAuth() {
|
3425 | if (this.connected_ && this.authToken_) {
|
3426 | const token = this.authToken_;
|
3427 | const authMethod = isValidFormat(token) ? 'auth' : 'gauth';
|
3428 | const requestData = { cred: token };
|
3429 | if (this.authOverride_ === null) {
|
3430 | requestData['noauth'] = true;
|
3431 | }
|
3432 | else if (typeof this.authOverride_ === 'object') {
|
3433 | requestData['authvar'] = this.authOverride_;
|
3434 | }
|
3435 | this.sendRequest(authMethod, requestData, (res) => {
|
3436 | const status = res[ 's'];
|
3437 | const data = res[ 'd'] || 'error';
|
3438 | if (this.authToken_ === token) {
|
3439 | if (status === 'ok') {
|
3440 | this.invalidAuthTokenCount_ = 0;
|
3441 | }
|
3442 | else {
|
3443 |
|
3444 | this.onAuthRevoked_(status, data);
|
3445 | }
|
3446 | }
|
3447 | });
|
3448 | }
|
3449 | }
|
3450 | |
3451 |
|
3452 |
|
3453 |
|
3454 |
|
3455 | tryAppCheck() {
|
3456 | if (this.connected_ && this.appCheckToken_) {
|
3457 | this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {
|
3458 | const status = res[ 's'];
|
3459 | const data = res[ 'd'] || 'error';
|
3460 | if (status === 'ok') {
|
3461 | this.invalidAppCheckTokenCount_ = 0;
|
3462 | }
|
3463 | else {
|
3464 | this.onAppCheckRevoked_(status, data);
|
3465 | }
|
3466 | });
|
3467 | }
|
3468 | }
|
3469 | |
3470 |
|
3471 |
|
3472 | unlisten(query, tag) {
|
3473 | const pathString = query._path.toString();
|
3474 | const queryId = query._queryIdentifier;
|
3475 | this.log_('Unlisten called for ' + pathString + ' ' + queryId);
|
3476 | assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
|
3477 | const listen = this.removeListen_(pathString, queryId);
|
3478 | if (listen && this.connected_) {
|
3479 | this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
|
3480 | }
|
3481 | }
|
3482 | sendUnlisten_(pathString, queryId, queryObj, tag) {
|
3483 | this.log_('Unlisten on ' + pathString + ' for ' + queryId);
|
3484 | const req = { p: pathString };
|
3485 | const action = 'n';
|
3486 |
|
3487 | if (tag) {
|
3488 | req['q'] = queryObj;
|
3489 | req['t'] = tag;
|
3490 | }
|
3491 | this.sendRequest(action, req);
|
3492 | }
|
3493 | onDisconnectPut(pathString, data, onComplete) {
|
3494 | this.initConnection_();
|
3495 | if (this.connected_) {
|
3496 | this.sendOnDisconnect_('o', pathString, data, onComplete);
|
3497 | }
|
3498 | else {
|
3499 | this.onDisconnectRequestQueue_.push({
|
3500 | pathString,
|
3501 | action: 'o',
|
3502 | data,
|
3503 | onComplete
|
3504 | });
|
3505 | }
|
3506 | }
|
3507 | onDisconnectMerge(pathString, data, onComplete) {
|
3508 | this.initConnection_();
|
3509 | if (this.connected_) {
|
3510 | this.sendOnDisconnect_('om', pathString, data, onComplete);
|
3511 | }
|
3512 | else {
|
3513 | this.onDisconnectRequestQueue_.push({
|
3514 | pathString,
|
3515 | action: 'om',
|
3516 | data,
|
3517 | onComplete
|
3518 | });
|
3519 | }
|
3520 | }
|
3521 | onDisconnectCancel(pathString, onComplete) {
|
3522 | this.initConnection_();
|
3523 | if (this.connected_) {
|
3524 | this.sendOnDisconnect_('oc', pathString, null, onComplete);
|
3525 | }
|
3526 | else {
|
3527 | this.onDisconnectRequestQueue_.push({
|
3528 | pathString,
|
3529 | action: 'oc',
|
3530 | data: null,
|
3531 | onComplete
|
3532 | });
|
3533 | }
|
3534 | }
|
3535 | sendOnDisconnect_(action, pathString, data, onComplete) {
|
3536 | const request = { p: pathString, d: data };
|
3537 | this.log_('onDisconnect ' + action, request);
|
3538 | this.sendRequest(action, request, (response) => {
|
3539 | if (onComplete) {
|
3540 | setTimeout(() => {
|
3541 | onComplete(response[ 's'], response[ 'd']);
|
3542 | }, Math.floor(0));
|
3543 | }
|
3544 | });
|
3545 | }
|
3546 | put(pathString, data, onComplete, hash) {
|
3547 | this.putInternal('p', pathString, data, onComplete, hash);
|
3548 | }
|
3549 | merge(pathString, data, onComplete, hash) {
|
3550 | this.putInternal('m', pathString, data, onComplete, hash);
|
3551 | }
|
3552 | putInternal(action, pathString, data, onComplete, hash) {
|
3553 | this.initConnection_();
|
3554 | const request = {
|
3555 | p: pathString,
|
3556 | d: data
|
3557 | };
|
3558 | if (hash !== undefined) {
|
3559 | request[ 'h'] = hash;
|
3560 | }
|
3561 |
|
3562 | this.outstandingPuts_.push({
|
3563 | action,
|
3564 | request,
|
3565 | onComplete
|
3566 | });
|
3567 | this.outstandingPutCount_++;
|
3568 | const index = this.outstandingPuts_.length - 1;
|
3569 | if (this.connected_) {
|
3570 | this.sendPut_(index);
|
3571 | }
|
3572 | else {
|
3573 | this.log_('Buffering put: ' + pathString);
|
3574 | }
|
3575 | }
|
3576 | sendPut_(index) {
|
3577 | const action = this.outstandingPuts_[index].action;
|
3578 | const request = this.outstandingPuts_[index].request;
|
3579 | const onComplete = this.outstandingPuts_[index].onComplete;
|
3580 | this.outstandingPuts_[index].queued = this.connected_;
|
3581 | this.sendRequest(action, request, (message) => {
|
3582 | this.log_(action + ' response', message);
|
3583 | delete this.outstandingPuts_[index];
|
3584 | this.outstandingPutCount_--;
|
3585 |
|
3586 | if (this.outstandingPutCount_ === 0) {
|
3587 | this.outstandingPuts_ = [];
|
3588 | }
|
3589 | if (onComplete) {
|
3590 | onComplete(message[ 's'], message[ 'd']);
|
3591 | }
|
3592 | });
|
3593 | }
|
3594 | reportStats(stats) {
|
3595 |
|
3596 | if (this.connected_) {
|
3597 | const request = { c: stats };
|
3598 | this.log_('reportStats', request);
|
3599 | this.sendRequest( 's', request, result => {
|
3600 | const status = result[ 's'];
|
3601 | if (status !== 'ok') {
|
3602 | const errorReason = result[ 'd'];
|
3603 | this.log_('reportStats', 'Error sending stats: ' + errorReason);
|
3604 | }
|
3605 | });
|
3606 | }
|
3607 | }
|
3608 | onDataMessage_(message) {
|
3609 | if ('r' in message) {
|
3610 |
|
3611 | this.log_('from server: ' + stringify(message));
|
3612 | const reqNum = message['r'];
|
3613 | const onResponse = this.requestCBHash_[reqNum];
|
3614 | if (onResponse) {
|
3615 | delete this.requestCBHash_[reqNum];
|
3616 | onResponse(message[ 'b']);
|
3617 | }
|
3618 | }
|
3619 | else if ('error' in message) {
|
3620 | throw 'A server-side error has occurred: ' + message['error'];
|
3621 | }
|
3622 | else if ('a' in message) {
|
3623 |
|
3624 | this.onDataPush_(message['a'], message['b']);
|
3625 | }
|
3626 | }
|
3627 | onDataPush_(action, body) {
|
3628 | this.log_('handleServerMessage', action, body);
|
3629 | if (action === 'd') {
|
3630 | this.onDataUpdate_(body[ 'p'], body[ 'd'],
|
3631 | false, body['t']);
|
3632 | }
|
3633 | else if (action === 'm') {
|
3634 | this.onDataUpdate_(body[ 'p'], body[ 'd'],
|
3635 | true, body['t']);
|
3636 | }
|
3637 | else if (action === 'c') {
|
3638 | this.onListenRevoked_(body[ 'p'], body[ 'q']);
|
3639 | }
|
3640 | else if (action === 'ac') {
|
3641 | this.onAuthRevoked_(body[ 's'], body[ 'd']);
|
3642 | }
|
3643 | else if (action === 'apc') {
|
3644 | this.onAppCheckRevoked_(body[ 's'], body[ 'd']);
|
3645 | }
|
3646 | else if (action === 'sd') {
|
3647 | this.onSecurityDebugPacket_(body);
|
3648 | }
|
3649 | else {
|
3650 | error('Unrecognized action received from server: ' +
|
3651 | stringify(action) +
|
3652 | '\nAre you using the latest client?');
|
3653 | }
|
3654 | }
|
3655 | onReady_(timestamp, sessionId) {
|
3656 | this.log_('connection ready');
|
3657 | this.connected_ = true;
|
3658 | this.lastConnectionEstablishedTime_ = new Date().getTime();
|
3659 | this.handleTimestamp_(timestamp);
|
3660 | this.lastSessionId = sessionId;
|
3661 | if (this.firstConnection_) {
|
3662 | this.sendConnectStats_();
|
3663 | }
|
3664 | this.restoreState_();
|
3665 | this.firstConnection_ = false;
|
3666 | this.onConnectStatus_(true);
|
3667 | }
|
3668 | scheduleConnect_(timeout) {
|
3669 | assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
|
3670 | if (this.establishConnectionTimer_) {
|
3671 | clearTimeout(this.establishConnectionTimer_);
|
3672 | }
|
3673 |
|
3674 |
|
3675 | this.establishConnectionTimer_ = setTimeout(() => {
|
3676 | this.establishConnectionTimer_ = null;
|
3677 | this.establishConnection_();
|
3678 |
|
3679 | }, Math.floor(timeout));
|
3680 | }
|
3681 | initConnection_() {
|
3682 | if (!this.realtime_ && this.firstConnection_) {
|
3683 | this.scheduleConnect_(0);
|
3684 | }
|
3685 | }
|
3686 | onVisible_(visible) {
|
3687 |
|
3688 | if (visible &&
|
3689 | !this.visible_ &&
|
3690 | this.reconnectDelay_ === this.maxReconnectDelay_) {
|
3691 | this.log_('Window became visible. Reducing delay.');
|
3692 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3693 | if (!this.realtime_) {
|
3694 | this.scheduleConnect_(0);
|
3695 | }
|
3696 | }
|
3697 | this.visible_ = visible;
|
3698 | }
|
3699 | onOnline_(online) {
|
3700 | if (online) {
|
3701 | this.log_('Browser went online.');
|
3702 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3703 | if (!this.realtime_) {
|
3704 | this.scheduleConnect_(0);
|
3705 | }
|
3706 | }
|
3707 | else {
|
3708 | this.log_('Browser went offline. Killing connection.');
|
3709 | if (this.realtime_) {
|
3710 | this.realtime_.close();
|
3711 | }
|
3712 | }
|
3713 | }
|
3714 | onRealtimeDisconnect_() {
|
3715 | this.log_('data client disconnected');
|
3716 | this.connected_ = false;
|
3717 | this.realtime_ = null;
|
3718 |
|
3719 | this.cancelSentTransactions_();
|
3720 |
|
3721 | this.requestCBHash_ = {};
|
3722 | if (this.shouldReconnect_()) {
|
3723 | if (!this.visible_) {
|
3724 | this.log_("Window isn't visible. Delaying reconnect.");
|
3725 | this.reconnectDelay_ = this.maxReconnectDelay_;
|
3726 | this.lastConnectionAttemptTime_ = new Date().getTime();
|
3727 | }
|
3728 | else if (this.lastConnectionEstablishedTime_) {
|
3729 |
|
3730 | const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
|
3731 | if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
|
3732 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3733 | }
|
3734 | this.lastConnectionEstablishedTime_ = null;
|
3735 | }
|
3736 | const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
|
3737 | let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
|
3738 | reconnectDelay = Math.random() * reconnectDelay;
|
3739 | this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
|
3740 | this.scheduleConnect_(reconnectDelay);
|
3741 |
|
3742 | this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
|
3743 | }
|
3744 | this.onConnectStatus_(false);
|
3745 | }
|
3746 | async establishConnection_() {
|
3747 | if (this.shouldReconnect_()) {
|
3748 | this.log_('Making a connection attempt');
|
3749 | this.lastConnectionAttemptTime_ = new Date().getTime();
|
3750 | this.lastConnectionEstablishedTime_ = null;
|
3751 | const onDataMessage = this.onDataMessage_.bind(this);
|
3752 | const onReady = this.onReady_.bind(this);
|
3753 | const onDisconnect = this.onRealtimeDisconnect_.bind(this);
|
3754 | const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
|
3755 | const lastSessionId = this.lastSessionId;
|
3756 | let canceled = false;
|
3757 | let connection = null;
|
3758 | const closeFn = function () {
|
3759 | if (connection) {
|
3760 | connection.close();
|
3761 | }
|
3762 | else {
|
3763 | canceled = true;
|
3764 | onDisconnect();
|
3765 | }
|
3766 | };
|
3767 | const sendRequestFn = function (msg) {
|
3768 | assert(connection, "sendRequest call when we're not connected not allowed.");
|
3769 | connection.sendRequest(msg);
|
3770 | };
|
3771 | this.realtime_ = {
|
3772 | close: closeFn,
|
3773 | sendRequest: sendRequestFn
|
3774 | };
|
3775 | const forceRefresh = this.forceTokenRefresh_;
|
3776 | this.forceTokenRefresh_ = false;
|
3777 | try {
|
3778 |
|
3779 |
|
3780 | const [authToken, appCheckToken] = await Promise.all([
|
3781 | this.authTokenProvider_.getToken(forceRefresh),
|
3782 | this.appCheckTokenProvider_.getToken(forceRefresh)
|
3783 | ]);
|
3784 | if (!canceled) {
|
3785 | log('getToken() completed. Creating connection.');
|
3786 | this.authToken_ = authToken && authToken.accessToken;
|
3787 | this.appCheckToken_ = appCheckToken && appCheckToken.token;
|
3788 | connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect,
|
3789 | reason => {
|
3790 | warn(reason + ' (' + this.repoInfo_.toString() + ')');
|
3791 | this.interrupt(SERVER_KILL_INTERRUPT_REASON);
|
3792 | }, lastSessionId);
|
3793 | }
|
3794 | else {
|
3795 | log('getToken() completed but was canceled');
|
3796 | }
|
3797 | }
|
3798 | catch (error) {
|
3799 | this.log_('Failed to get token: ' + error);
|
3800 | if (!canceled) {
|
3801 | if (this.repoInfo_.nodeAdmin) {
|
3802 |
|
3803 |
|
3804 |
|
3805 | warn(error);
|
3806 | }
|
3807 | closeFn();
|
3808 | }
|
3809 | }
|
3810 | }
|
3811 | }
|
3812 | interrupt(reason) {
|
3813 | log('Interrupting connection for reason: ' + reason);
|
3814 | this.interruptReasons_[reason] = true;
|
3815 | if (this.realtime_) {
|
3816 | this.realtime_.close();
|
3817 | }
|
3818 | else {
|
3819 | if (this.establishConnectionTimer_) {
|
3820 | clearTimeout(this.establishConnectionTimer_);
|
3821 | this.establishConnectionTimer_ = null;
|
3822 | }
|
3823 | if (this.connected_) {
|
3824 | this.onRealtimeDisconnect_();
|
3825 | }
|
3826 | }
|
3827 | }
|
3828 | resume(reason) {
|
3829 | log('Resuming connection for reason: ' + reason);
|
3830 | delete this.interruptReasons_[reason];
|
3831 | if (isEmpty(this.interruptReasons_)) {
|
3832 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3833 | if (!this.realtime_) {
|
3834 | this.scheduleConnect_(0);
|
3835 | }
|
3836 | }
|
3837 | }
|
3838 | handleTimestamp_(timestamp) {
|
3839 | const delta = timestamp - new Date().getTime();
|
3840 | this.onServerInfoUpdate_({ serverTimeOffset: delta });
|
3841 | }
|
3842 | cancelSentTransactions_() {
|
3843 | for (let i = 0; i < this.outstandingPuts_.length; i++) {
|
3844 | const put = this.outstandingPuts_[i];
|
3845 | if (put && 'h' in put.request && put.queued) {
|
3846 | if (put.onComplete) {
|
3847 | put.onComplete('disconnect');
|
3848 | }
|
3849 | delete this.outstandingPuts_[i];
|
3850 | this.outstandingPutCount_--;
|
3851 | }
|
3852 | }
|
3853 |
|
3854 | if (this.outstandingPutCount_ === 0) {
|
3855 | this.outstandingPuts_ = [];
|
3856 | }
|
3857 | }
|
3858 | onListenRevoked_(pathString, query) {
|
3859 |
|
3860 | let queryId;
|
3861 | if (!query) {
|
3862 | queryId = 'default';
|
3863 | }
|
3864 | else {
|
3865 | queryId = query.map(q => ObjectToUniqueKey(q)).join('$');
|
3866 | }
|
3867 | const listen = this.removeListen_(pathString, queryId);
|
3868 | if (listen && listen.onComplete) {
|
3869 | listen.onComplete('permission_denied');
|
3870 | }
|
3871 | }
|
3872 | removeListen_(pathString, queryId) {
|
3873 | const normalizedPathString = new Path(pathString).toString();
|
3874 | let listen;
|
3875 | if (this.listens.has(normalizedPathString)) {
|
3876 | const map = this.listens.get(normalizedPathString);
|
3877 | listen = map.get(queryId);
|
3878 | map.delete(queryId);
|
3879 | if (map.size === 0) {
|
3880 | this.listens.delete(normalizedPathString);
|
3881 | }
|
3882 | }
|
3883 | else {
|
3884 |
|
3885 | listen = undefined;
|
3886 | }
|
3887 | return listen;
|
3888 | }
|
3889 | onAuthRevoked_(statusCode, explanation) {
|
3890 | log('Auth token revoked: ' + statusCode + '/' + explanation);
|
3891 | this.authToken_ = null;
|
3892 | this.forceTokenRefresh_ = true;
|
3893 | this.realtime_.close();
|
3894 | if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
|
3895 |
|
3896 |
|
3897 |
|
3898 | this.invalidAuthTokenCount_++;
|
3899 | if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
|
3900 |
|
3901 | this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
|
3902 |
|
3903 |
|
3904 | this.authTokenProvider_.notifyForInvalidToken();
|
3905 | }
|
3906 | }
|
3907 | }
|
3908 | onAppCheckRevoked_(statusCode, explanation) {
|
3909 | log('App check token revoked: ' + statusCode + '/' + explanation);
|
3910 | this.appCheckToken_ = null;
|
3911 | this.forceTokenRefresh_ = true;
|
3912 |
|
3913 |
|
3914 | if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
|
3915 |
|
3916 |
|
3917 |
|
3918 | this.invalidAppCheckTokenCount_++;
|
3919 | if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
|
3920 | this.appCheckTokenProvider_.notifyForInvalidToken();
|
3921 | }
|
3922 | }
|
3923 | }
|
3924 | onSecurityDebugPacket_(body) {
|
3925 | if (this.securityDebugCallback_) {
|
3926 | this.securityDebugCallback_(body);
|
3927 | }
|
3928 | else {
|
3929 | if ('msg' in body) {
|
3930 | console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
|
3931 | }
|
3932 | }
|
3933 | }
|
3934 | restoreState_() {
|
3935 |
|
3936 | this.tryAuth();
|
3937 | this.tryAppCheck();
|
3938 |
|
3939 |
|
3940 | for (const queries of this.listens.values()) {
|
3941 | for (const listenSpec of queries.values()) {
|
3942 | this.sendListen_(listenSpec);
|
3943 | }
|
3944 | }
|
3945 | for (let i = 0; i < this.outstandingPuts_.length; i++) {
|
3946 | if (this.outstandingPuts_[i]) {
|
3947 | this.sendPut_(i);
|
3948 | }
|
3949 | }
|
3950 | while (this.onDisconnectRequestQueue_.length) {
|
3951 | const request = this.onDisconnectRequestQueue_.shift();
|
3952 | this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
|
3953 | }
|
3954 | for (let i = 0; i < this.outstandingGets_.length; i++) {
|
3955 | if (this.outstandingGets_[i]) {
|
3956 | this.sendGet_(i);
|
3957 | }
|
3958 | }
|
3959 | }
|
3960 | |
3961 |
|
3962 |
|
3963 | sendConnectStats_() {
|
3964 | const stats = {};
|
3965 | let clientName = 'js';
|
3966 | if (isNodeSdk()) {
|
3967 | if (this.repoInfo_.nodeAdmin) {
|
3968 | clientName = 'admin_node';
|
3969 | }
|
3970 | else {
|
3971 | clientName = 'node';
|
3972 | }
|
3973 | }
|
3974 | stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
|
3975 | if (isMobileCordova()) {
|
3976 | stats['framework.cordova'] = 1;
|
3977 | }
|
3978 | else if (isReactNative()) {
|
3979 | stats['framework.reactnative'] = 1;
|
3980 | }
|
3981 | this.reportStats(stats);
|
3982 | }
|
3983 | shouldReconnect_() {
|
3984 | const online = OnlineMonitor.getInstance().currentlyOnline();
|
3985 | return isEmpty(this.interruptReasons_) && online;
|
3986 | }
|
3987 | }
|
3988 | PersistentConnection.nextPersistentConnectionId_ = 0;
|
3989 |
|
3990 |
|
3991 |
|
3992 | PersistentConnection.nextConnectionId_ = 0;
|
3993 |
|
3994 |
|
3995 |
|
3996 |
|
3997 |
|
3998 |
|
3999 |
|
4000 |
|
4001 |
|
4002 |
|
4003 |
|
4004 |
|
4005 |
|
4006 |
|
4007 |
|
4008 |
|
4009 |
|
4010 | class NamedNode {
|
4011 | constructor(name, node) {
|
4012 | this.name = name;
|
4013 | this.node = node;
|
4014 | }
|
4015 | static Wrap(name, node) {
|
4016 | return new NamedNode(name, node);
|
4017 | }
|
4018 | }
|
4019 |
|
4020 |
|
4021 |
|
4022 |
|
4023 |
|
4024 |
|
4025 |
|
4026 |
|
4027 |
|
4028 |
|
4029 |
|
4030 |
|
4031 |
|
4032 |
|
4033 |
|
4034 |
|
4035 |
|
4036 | class Index {
|
4037 | |
4038 |
|
4039 |
|
4040 |
|
4041 | getCompare() {
|
4042 | return this.compare.bind(this);
|
4043 | }
|
4044 | |
4045 |
|
4046 |
|
4047 |
|
4048 |
|
4049 |
|
4050 |
|
4051 | indexedValueChanged(oldNode, newNode) {
|
4052 | const oldWrapped = new NamedNode(MIN_NAME, oldNode);
|
4053 | const newWrapped = new NamedNode(MIN_NAME, newNode);
|
4054 | return this.compare(oldWrapped, newWrapped) !== 0;
|
4055 | }
|
4056 | |
4057 |
|
4058 |
|
4059 |
|
4060 | minPost() {
|
4061 |
|
4062 | return NamedNode.MIN;
|
4063 | }
|
4064 | }
|
4065 |
|
4066 |
|
4067 |
|
4068 |
|
4069 |
|
4070 |
|
4071 |
|
4072 |
|
4073 |
|
4074 |
|
4075 |
|
4076 |
|
4077 |
|
4078 |
|
4079 |
|
4080 |
|
4081 |
|
4082 | let __EMPTY_NODE;
|
4083 | class KeyIndex extends Index {
|
4084 | static get __EMPTY_NODE() {
|
4085 | return __EMPTY_NODE;
|
4086 | }
|
4087 | static set __EMPTY_NODE(val) {
|
4088 | __EMPTY_NODE = val;
|
4089 | }
|
4090 | compare(a, b) {
|
4091 | return nameCompare(a.name, b.name);
|
4092 | }
|
4093 | isDefinedOn(node) {
|
4094 |
|
4095 |
|
4096 | throw assertionError('KeyIndex.isDefinedOn not expected to be called.');
|
4097 | }
|
4098 | indexedValueChanged(oldNode, newNode) {
|
4099 | return false;
|
4100 | }
|
4101 | minPost() {
|
4102 |
|
4103 | return NamedNode.MIN;
|
4104 | }
|
4105 | maxPost() {
|
4106 |
|
4107 |
|
4108 | return new NamedNode(MAX_NAME, __EMPTY_NODE);
|
4109 | }
|
4110 | makePost(indexValue, name) {
|
4111 | assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
|
4112 |
|
4113 | return new NamedNode(indexValue, __EMPTY_NODE);
|
4114 | }
|
4115 | |
4116 |
|
4117 |
|
4118 | toString() {
|
4119 | return '.key';
|
4120 | }
|
4121 | }
|
4122 | const KEY_INDEX = new KeyIndex();
|
4123 |
|
4124 |
|
4125 |
|
4126 |
|
4127 |
|
4128 |
|
4129 |
|
4130 |
|
4131 |
|
4132 |
|
4133 |
|
4134 |
|
4135 |
|
4136 |
|
4137 |
|
4138 |
|
4139 |
|
4140 |
|
4141 |
|
4142 |
|
4143 | class SortedMapIterator {
|
4144 | |
4145 |
|
4146 |
|
4147 |
|
4148 | constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
|
4149 | this.isReverse_ = isReverse_;
|
4150 | this.resultGenerator_ = resultGenerator_;
|
4151 | this.nodeStack_ = [];
|
4152 | let cmp = 1;
|
4153 | while (!node.isEmpty()) {
|
4154 | node = node;
|
4155 | cmp = startKey ? comparator(node.key, startKey) : 1;
|
4156 |
|
4157 | if (isReverse_) {
|
4158 | cmp *= -1;
|
4159 | }
|
4160 | if (cmp < 0) {
|
4161 |
|
4162 | if (this.isReverse_) {
|
4163 | node = node.left;
|
4164 | }
|
4165 | else {
|
4166 | node = node.right;
|
4167 | }
|
4168 | }
|
4169 | else if (cmp === 0) {
|
4170 |
|
4171 | this.nodeStack_.push(node);
|
4172 | break;
|
4173 | }
|
4174 | else {
|
4175 |
|
4176 | this.nodeStack_.push(node);
|
4177 | if (this.isReverse_) {
|
4178 | node = node.right;
|
4179 | }
|
4180 | else {
|
4181 | node = node.left;
|
4182 | }
|
4183 | }
|
4184 | }
|
4185 | }
|
4186 | getNext() {
|
4187 | if (this.nodeStack_.length === 0) {
|
4188 | return null;
|
4189 | }
|
4190 | let node = this.nodeStack_.pop();
|
4191 | let result;
|
4192 | if (this.resultGenerator_) {
|
4193 | result = this.resultGenerator_(node.key, node.value);
|
4194 | }
|
4195 | else {
|
4196 | result = { key: node.key, value: node.value };
|
4197 | }
|
4198 | if (this.isReverse_) {
|
4199 | node = node.left;
|
4200 | while (!node.isEmpty()) {
|
4201 | this.nodeStack_.push(node);
|
4202 | node = node.right;
|
4203 | }
|
4204 | }
|
4205 | else {
|
4206 | node = node.right;
|
4207 | while (!node.isEmpty()) {
|
4208 | this.nodeStack_.push(node);
|
4209 | node = node.left;
|
4210 | }
|
4211 | }
|
4212 | return result;
|
4213 | }
|
4214 | hasNext() {
|
4215 | return this.nodeStack_.length > 0;
|
4216 | }
|
4217 | peek() {
|
4218 | if (this.nodeStack_.length === 0) {
|
4219 | return null;
|
4220 | }
|
4221 | const node = this.nodeStack_[this.nodeStack_.length - 1];
|
4222 | if (this.resultGenerator_) {
|
4223 | return this.resultGenerator_(node.key, node.value);
|
4224 | }
|
4225 | else {
|
4226 | return { key: node.key, value: node.value };
|
4227 | }
|
4228 | }
|
4229 | }
|
4230 |
|
4231 |
|
4232 |
|
4233 | class LLRBNode {
|
4234 | |
4235 |
|
4236 |
|
4237 |
|
4238 |
|
4239 |
|
4240 |
|
4241 | constructor(key, value, color, left, right) {
|
4242 | this.key = key;
|
4243 | this.value = value;
|
4244 | this.color = color != null ? color : LLRBNode.RED;
|
4245 | this.left =
|
4246 | left != null ? left : SortedMap.EMPTY_NODE;
|
4247 | this.right =
|
4248 | right != null ? right : SortedMap.EMPTY_NODE;
|
4249 | }
|
4250 | |
4251 |
|
4252 |
|
4253 |
|
4254 |
|
4255 |
|
4256 |
|
4257 |
|
4258 |
|
4259 |
|
4260 | copy(key, value, color, left, right) {
|
4261 | 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);
|
4262 | }
|
4263 | |
4264 |
|
4265 |
|
4266 | count() {
|
4267 | return this.left.count() + 1 + this.right.count();
|
4268 | }
|
4269 | |
4270 |
|
4271 |
|
4272 | isEmpty() {
|
4273 | return false;
|
4274 | }
|
4275 | |
4276 |
|
4277 |
|
4278 |
|
4279 |
|
4280 |
|
4281 |
|
4282 |
|
4283 |
|
4284 | inorderTraversal(action) {
|
4285 | return (this.left.inorderTraversal(action) ||
|
4286 | !!action(this.key, this.value) ||
|
4287 | this.right.inorderTraversal(action));
|
4288 | }
|
4289 | |
4290 |
|
4291 |
|
4292 |
|
4293 |
|
4294 |
|
4295 |
|
4296 |
|
4297 | reverseTraversal(action) {
|
4298 | return (this.right.reverseTraversal(action) ||
|
4299 | action(this.key, this.value) ||
|
4300 | this.left.reverseTraversal(action));
|
4301 | }
|
4302 | |
4303 |
|
4304 |
|
4305 | min_() {
|
4306 | if (this.left.isEmpty()) {
|
4307 | return this;
|
4308 | }
|
4309 | else {
|
4310 | return this.left.min_();
|
4311 | }
|
4312 | }
|
4313 | |
4314 |
|
4315 |
|
4316 | minKey() {
|
4317 | return this.min_().key;
|
4318 | }
|
4319 | |
4320 |
|
4321 |
|
4322 | maxKey() {
|
4323 | if (this.right.isEmpty()) {
|
4324 | return this.key;
|
4325 | }
|
4326 | else {
|
4327 | return this.right.maxKey();
|
4328 | }
|
4329 | }
|
4330 | |
4331 |
|
4332 |
|
4333 |
|
4334 |
|
4335 |
|
4336 | insert(key, value, comparator) {
|
4337 | let n = this;
|
4338 | const cmp = comparator(key, n.key);
|
4339 | if (cmp < 0) {
|
4340 | n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
|
4341 | }
|
4342 | else if (cmp === 0) {
|
4343 | n = n.copy(null, value, null, null, null);
|
4344 | }
|
4345 | else {
|
4346 | n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
|
4347 | }
|
4348 | return n.fixUp_();
|
4349 | }
|
4350 | |
4351 |
|
4352 |
|
4353 | removeMin_() {
|
4354 | if (this.left.isEmpty()) {
|
4355 | return SortedMap.EMPTY_NODE;
|
4356 | }
|
4357 | let n = this;
|
4358 | if (!n.left.isRed_() && !n.left.left.isRed_()) {
|
4359 | n = n.moveRedLeft_();
|
4360 | }
|
4361 | n = n.copy(null, null, null, n.left.removeMin_(), null);
|
4362 | return n.fixUp_();
|
4363 | }
|
4364 | |
4365 |
|
4366 |
|
4367 |
|
4368 |
|
4369 | remove(key, comparator) {
|
4370 | let n, smallest;
|
4371 | n = this;
|
4372 | if (comparator(key, n.key) < 0) {
|
4373 | if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
|
4374 | n = n.moveRedLeft_();
|
4375 | }
|
4376 | n = n.copy(null, null, null, n.left.remove(key, comparator), null);
|
4377 | }
|
4378 | else {
|
4379 | if (n.left.isRed_()) {
|
4380 | n = n.rotateRight_();
|
4381 | }
|
4382 | if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
|
4383 | n = n.moveRedRight_();
|
4384 | }
|
4385 | if (comparator(key, n.key) === 0) {
|
4386 | if (n.right.isEmpty()) {
|
4387 | return SortedMap.EMPTY_NODE;
|
4388 | }
|
4389 | else {
|
4390 | smallest = n.right.min_();
|
4391 | n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
|
4392 | }
|
4393 | }
|
4394 | n = n.copy(null, null, null, null, n.right.remove(key, comparator));
|
4395 | }
|
4396 | return n.fixUp_();
|
4397 | }
|
4398 | |
4399 |
|
4400 |
|
4401 | isRed_() {
|
4402 | return this.color;
|
4403 | }
|
4404 | |
4405 |
|
4406 |
|
4407 | fixUp_() {
|
4408 | let n = this;
|
4409 | if (n.right.isRed_() && !n.left.isRed_()) {
|
4410 | n = n.rotateLeft_();
|
4411 | }
|
4412 | if (n.left.isRed_() && n.left.left.isRed_()) {
|
4413 | n = n.rotateRight_();
|
4414 | }
|
4415 | if (n.left.isRed_() && n.right.isRed_()) {
|
4416 | n = n.colorFlip_();
|
4417 | }
|
4418 | return n;
|
4419 | }
|
4420 | |
4421 |
|
4422 |
|
4423 | moveRedLeft_() {
|
4424 | let n = this.colorFlip_();
|
4425 | if (n.right.left.isRed_()) {
|
4426 | n = n.copy(null, null, null, null, n.right.rotateRight_());
|
4427 | n = n.rotateLeft_();
|
4428 | n = n.colorFlip_();
|
4429 | }
|
4430 | return n;
|
4431 | }
|
4432 | |
4433 |
|
4434 |
|
4435 | moveRedRight_() {
|
4436 | let n = this.colorFlip_();
|
4437 | if (n.left.left.isRed_()) {
|
4438 | n = n.rotateRight_();
|
4439 | n = n.colorFlip_();
|
4440 | }
|
4441 | return n;
|
4442 | }
|
4443 | |
4444 |
|
4445 |
|
4446 | rotateLeft_() {
|
4447 | const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
|
4448 | return this.right.copy(null, null, this.color, nl, null);
|
4449 | }
|
4450 | |
4451 |
|
4452 |
|
4453 | rotateRight_() {
|
4454 | const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
|
4455 | return this.left.copy(null, null, this.color, null, nr);
|
4456 | }
|
4457 | |
4458 |
|
4459 |
|
4460 | colorFlip_() {
|
4461 | const left = this.left.copy(null, null, !this.left.color, null, null);
|
4462 | const right = this.right.copy(null, null, !this.right.color, null, null);
|
4463 | return this.copy(null, null, !this.color, left, right);
|
4464 | }
|
4465 | |
4466 |
|
4467 |
|
4468 |
|
4469 |
|
4470 | checkMaxDepth_() {
|
4471 | const blackDepth = this.check_();
|
4472 | return Math.pow(2.0, blackDepth) <= this.count() + 1;
|
4473 | }
|
4474 | check_() {
|
4475 | if (this.isRed_() && this.left.isRed_()) {
|
4476 | throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
|
4477 | }
|
4478 | if (this.right.isRed_()) {
|
4479 | throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
|
4480 | }
|
4481 | const blackDepth = this.left.check_();
|
4482 | if (blackDepth !== this.right.check_()) {
|
4483 | throw new Error('Black depths differ');
|
4484 | }
|
4485 | else {
|
4486 | return blackDepth + (this.isRed_() ? 0 : 1);
|
4487 | }
|
4488 | }
|
4489 | }
|
4490 | LLRBNode.RED = true;
|
4491 | LLRBNode.BLACK = false;
|
4492 |
|
4493 |
|
4494 |
|
4495 | class LLRBEmptyNode {
|
4496 | |
4497 |
|
4498 |
|
4499 |
|
4500 |
|
4501 | copy(key, value, color, left, right) {
|
4502 | return this;
|
4503 | }
|
4504 | |
4505 |
|
4506 |
|
4507 |
|
4508 |
|
4509 |
|
4510 |
|
4511 |
|
4512 | insert(key, value, comparator) {
|
4513 | return new LLRBNode(key, value, null);
|
4514 | }
|
4515 | |
4516 |
|
4517 |
|
4518 |
|
4519 |
|
4520 |
|
4521 |
|
4522 | remove(key, comparator) {
|
4523 | return this;
|
4524 | }
|
4525 | |
4526 |
|
4527 |
|
4528 | count() {
|
4529 | return 0;
|
4530 | }
|
4531 | |
4532 |
|
4533 |
|
4534 | isEmpty() {
|
4535 | return true;
|
4536 | }
|
4537 | |
4538 |
|
4539 |
|
4540 |
|
4541 |
|
4542 |
|
4543 |
|
4544 |
|
4545 | inorderTraversal(action) {
|
4546 | return false;
|
4547 | }
|
4548 | |
4549 |
|
4550 |
|
4551 |
|
4552 |
|
4553 |
|
4554 |
|
4555 |
|
4556 | reverseTraversal(action) {
|
4557 | return false;
|
4558 | }
|
4559 | minKey() {
|
4560 | return null;
|
4561 | }
|
4562 | maxKey() {
|
4563 | return null;
|
4564 | }
|
4565 | check_() {
|
4566 | return 0;
|
4567 | }
|
4568 | |
4569 |
|
4570 |
|
4571 | isRed_() {
|
4572 | return false;
|
4573 | }
|
4574 | }
|
4575 |
|
4576 |
|
4577 |
|
4578 |
|
4579 | class SortedMap {
|
4580 | |
4581 |
|
4582 |
|
4583 |
|
4584 | constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
|
4585 | this.comparator_ = comparator_;
|
4586 | this.root_ = root_;
|
4587 | }
|
4588 | |
4589 |
|
4590 |
|
4591 |
|
4592 |
|
4593 |
|
4594 |
|
4595 |
|
4596 | insert(key, value) {
|
4597 | return new SortedMap(this.comparator_, this.root_
|
4598 | .insert(key, value, this.comparator_)
|
4599 | .copy(null, null, LLRBNode.BLACK, null, null));
|
4600 | }
|
4601 | |
4602 |
|
4603 |
|
4604 |
|
4605 |
|
4606 |
|
4607 | remove(key) {
|
4608 | return new SortedMap(this.comparator_, this.root_
|
4609 | .remove(key, this.comparator_)
|
4610 | .copy(null, null, LLRBNode.BLACK, null, null));
|
4611 | }
|
4612 | |
4613 |
|
4614 |
|
4615 |
|
4616 |
|
4617 |
|
4618 |
|
4619 | get(key) {
|
4620 | let cmp;
|
4621 | let node = this.root_;
|
4622 | while (!node.isEmpty()) {
|
4623 | cmp = this.comparator_(key, node.key);
|
4624 | if (cmp === 0) {
|
4625 | return node.value;
|
4626 | }
|
4627 | else if (cmp < 0) {
|
4628 | node = node.left;
|
4629 | }
|
4630 | else if (cmp > 0) {
|
4631 | node = node.right;
|
4632 | }
|
4633 | }
|
4634 | return null;
|
4635 | }
|
4636 | |
4637 |
|
4638 |
|
4639 |
|
4640 |
|
4641 | getPredecessorKey(key) {
|
4642 | let cmp, node = this.root_, rightParent = null;
|
4643 | while (!node.isEmpty()) {
|
4644 | cmp = this.comparator_(key, node.key);
|
4645 | if (cmp === 0) {
|
4646 | if (!node.left.isEmpty()) {
|
4647 | node = node.left;
|
4648 | while (!node.right.isEmpty()) {
|
4649 | node = node.right;
|
4650 | }
|
4651 | return node.key;
|
4652 | }
|
4653 | else if (rightParent) {
|
4654 | return rightParent.key;
|
4655 | }
|
4656 | else {
|
4657 | return null;
|
4658 | }
|
4659 | }
|
4660 | else if (cmp < 0) {
|
4661 | node = node.left;
|
4662 | }
|
4663 | else if (cmp > 0) {
|
4664 | rightParent = node;
|
4665 | node = node.right;
|
4666 | }
|
4667 | }
|
4668 | throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
|
4669 | }
|
4670 | |
4671 |
|
4672 |
|
4673 | isEmpty() {
|
4674 | return this.root_.isEmpty();
|
4675 | }
|
4676 | |
4677 |
|
4678 |
|
4679 | count() {
|
4680 | return this.root_.count();
|
4681 | }
|
4682 | |
4683 |
|
4684 |
|
4685 | minKey() {
|
4686 | return this.root_.minKey();
|
4687 | }
|
4688 | |
4689 |
|
4690 |
|
4691 | maxKey() {
|
4692 | return this.root_.maxKey();
|
4693 | }
|
4694 | |
4695 |
|
4696 |
|
4697 |
|
4698 |
|
4699 |
|
4700 |
|
4701 |
|
4702 |
|
4703 | inorderTraversal(action) {
|
4704 | return this.root_.inorderTraversal(action);
|
4705 | }
|
4706 | |
4707 |
|
4708 |
|
4709 |
|
4710 |
|
4711 |
|
4712 |
|
4713 |
|
4714 | reverseTraversal(action) {
|
4715 | return this.root_.reverseTraversal(action);
|
4716 | }
|
4717 | |
4718 |
|
4719 |
|
4720 |
|
4721 | getIterator(resultGenerator) {
|
4722 | return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
|
4723 | }
|
4724 | getIteratorFrom(key, resultGenerator) {
|
4725 | return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
|
4726 | }
|
4727 | getReverseIteratorFrom(key, resultGenerator) {
|
4728 | return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
|
4729 | }
|
4730 | getReverseIterator(resultGenerator) {
|
4731 | return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
|
4732 | }
|
4733 | }
|
4734 |
|
4735 |
|
4736 |
|
4737 | SortedMap.EMPTY_NODE = new LLRBEmptyNode();
|
4738 |
|
4739 |
|
4740 |
|
4741 |
|
4742 |
|
4743 |
|
4744 |
|
4745 |
|
4746 |
|
4747 |
|
4748 |
|
4749 |
|
4750 |
|
4751 |
|
4752 |
|
4753 |
|
4754 |
|
4755 | function NAME_ONLY_COMPARATOR(left, right) {
|
4756 | return nameCompare(left.name, right.name);
|
4757 | }
|
4758 | function NAME_COMPARATOR(left, right) {
|
4759 | return nameCompare(left, right);
|
4760 | }
|
4761 |
|
4762 |
|
4763 |
|
4764 |
|
4765 |
|
4766 |
|
4767 |
|
4768 |
|
4769 |
|
4770 |
|
4771 |
|
4772 |
|
4773 |
|
4774 |
|
4775 |
|
4776 |
|
4777 |
|
4778 | let MAX_NODE$2;
|
4779 | function setMaxNode$1(val) {
|
4780 | MAX_NODE$2 = val;
|
4781 | }
|
4782 | const priorityHashText = function (priority) {
|
4783 | if (typeof priority === 'number') {
|
4784 | return 'number:' + doubleToIEEE754String(priority);
|
4785 | }
|
4786 | else {
|
4787 | return 'string:' + priority;
|
4788 | }
|
4789 | };
|
4790 |
|
4791 |
|
4792 |
|
4793 | const validatePriorityNode = function (priorityNode) {
|
4794 | if (priorityNode.isLeafNode()) {
|
4795 | const val = priorityNode.val();
|
4796 | assert(typeof val === 'string' ||
|
4797 | typeof val === 'number' ||
|
4798 | (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');
|
4799 | }
|
4800 | else {
|
4801 | assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
|
4802 | }
|
4803 |
|
4804 | assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
|
4805 | };
|
4806 |
|
4807 |
|
4808 |
|
4809 |
|
4810 |
|
4811 |
|
4812 |
|
4813 |
|
4814 |
|
4815 |
|
4816 |
|
4817 |
|
4818 |
|
4819 |
|
4820 |
|
4821 |
|
4822 |
|
4823 | let __childrenNodeConstructor;
|
4824 |
|
4825 |
|
4826 |
|
4827 |
|
4828 |
|
4829 | class LeafNode {
|
4830 | |
4831 |
|
4832 |
|
4833 |
|
4834 |
|
4835 | constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
|
4836 | this.value_ = value_;
|
4837 | this.priorityNode_ = priorityNode_;
|
4838 | this.lazyHash_ = null;
|
4839 | assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
|
4840 | validatePriorityNode(this.priorityNode_);
|
4841 | }
|
4842 | static set __childrenNodeConstructor(val) {
|
4843 | __childrenNodeConstructor = val;
|
4844 | }
|
4845 | static get __childrenNodeConstructor() {
|
4846 | return __childrenNodeConstructor;
|
4847 | }
|
4848 |
|
4849 | isLeafNode() {
|
4850 | return true;
|
4851 | }
|
4852 |
|
4853 | getPriority() {
|
4854 | return this.priorityNode_;
|
4855 | }
|
4856 |
|
4857 | updatePriority(newPriorityNode) {
|
4858 | return new LeafNode(this.value_, newPriorityNode);
|
4859 | }
|
4860 |
|
4861 | getImmediateChild(childName) {
|
4862 |
|
4863 | if (childName === '.priority') {
|
4864 | return this.priorityNode_;
|
4865 | }
|
4866 | else {
|
4867 | return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
|
4868 | }
|
4869 | }
|
4870 |
|
4871 | getChild(path) {
|
4872 | if (pathIsEmpty(path)) {
|
4873 | return this;
|
4874 | }
|
4875 | else if (pathGetFront(path) === '.priority') {
|
4876 | return this.priorityNode_;
|
4877 | }
|
4878 | else {
|
4879 | return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
|
4880 | }
|
4881 | }
|
4882 | hasChild() {
|
4883 | return false;
|
4884 | }
|
4885 |
|
4886 | getPredecessorChildName(childName, childNode) {
|
4887 | return null;
|
4888 | }
|
4889 |
|
4890 | updateImmediateChild(childName, newChildNode) {
|
4891 | if (childName === '.priority') {
|
4892 | return this.updatePriority(newChildNode);
|
4893 | }
|
4894 | else if (newChildNode.isEmpty() && childName !== '.priority') {
|
4895 | return this;
|
4896 | }
|
4897 | else {
|
4898 | return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
|
4899 | }
|
4900 | }
|
4901 |
|
4902 | updateChild(path, newChildNode) {
|
4903 | const front = pathGetFront(path);
|
4904 | if (front === null) {
|
4905 | return newChildNode;
|
4906 | }
|
4907 | else if (newChildNode.isEmpty() && front !== '.priority') {
|
4908 | return this;
|
4909 | }
|
4910 | else {
|
4911 | assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
|
4912 | return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
|
4913 | }
|
4914 | }
|
4915 |
|
4916 | isEmpty() {
|
4917 | return false;
|
4918 | }
|
4919 |
|
4920 | numChildren() {
|
4921 | return 0;
|
4922 | }
|
4923 |
|
4924 | forEachChild(index, action) {
|
4925 | return false;
|
4926 | }
|
4927 | val(exportFormat) {
|
4928 | if (exportFormat && !this.getPriority().isEmpty()) {
|
4929 | return {
|
4930 | '.value': this.getValue(),
|
4931 | '.priority': this.getPriority().val()
|
4932 | };
|
4933 | }
|
4934 | else {
|
4935 | return this.getValue();
|
4936 | }
|
4937 | }
|
4938 |
|
4939 | hash() {
|
4940 | if (this.lazyHash_ === null) {
|
4941 | let toHash = '';
|
4942 | if (!this.priorityNode_.isEmpty()) {
|
4943 | toHash +=
|
4944 | 'priority:' +
|
4945 | priorityHashText(this.priorityNode_.val()) +
|
4946 | ':';
|
4947 | }
|
4948 | const type = typeof this.value_;
|
4949 | toHash += type + ':';
|
4950 | if (type === 'number') {
|
4951 | toHash += doubleToIEEE754String(this.value_);
|
4952 | }
|
4953 | else {
|
4954 | toHash += this.value_;
|
4955 | }
|
4956 | this.lazyHash_ = sha1(toHash);
|
4957 | }
|
4958 | return this.lazyHash_;
|
4959 | }
|
4960 | |
4961 |
|
4962 |
|
4963 |
|
4964 | getValue() {
|
4965 | return this.value_;
|
4966 | }
|
4967 | compareTo(other) {
|
4968 | if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
|
4969 | return 1;
|
4970 | }
|
4971 | else if (other instanceof LeafNode.__childrenNodeConstructor) {
|
4972 | return -1;
|
4973 | }
|
4974 | else {
|
4975 | assert(other.isLeafNode(), 'Unknown node type');
|
4976 | return this.compareToLeafNode_(other);
|
4977 | }
|
4978 | }
|
4979 | |
4980 |
|
4981 |
|
4982 | compareToLeafNode_(otherLeaf) {
|
4983 | const otherLeafType = typeof otherLeaf.value_;
|
4984 | const thisLeafType = typeof this.value_;
|
4985 | const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
|
4986 | const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
|
4987 | assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
|
4988 | assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
|
4989 | if (otherIndex === thisIndex) {
|
4990 |
|
4991 | if (thisLeafType === 'object') {
|
4992 |
|
4993 | return 0;
|
4994 | }
|
4995 | else {
|
4996 |
|
4997 | if (this.value_ < otherLeaf.value_) {
|
4998 | return -1;
|
4999 | }
|
5000 | else if (this.value_ === otherLeaf.value_) {
|
5001 | return 0;
|
5002 | }
|
5003 | else {
|
5004 | return 1;
|
5005 | }
|
5006 | }
|
5007 | }
|
5008 | else {
|
5009 | return thisIndex - otherIndex;
|
5010 | }
|
5011 | }
|
5012 | withIndex() {
|
5013 | return this;
|
5014 | }
|
5015 | isIndexed() {
|
5016 | return true;
|
5017 | }
|
5018 | equals(other) {
|
5019 | if (other === this) {
|
5020 | return true;
|
5021 | }
|
5022 | else if (other.isLeafNode()) {
|
5023 | const otherLeaf = other;
|
5024 | return (this.value_ === otherLeaf.value_ &&
|
5025 | this.priorityNode_.equals(otherLeaf.priorityNode_));
|
5026 | }
|
5027 | else {
|
5028 | return false;
|
5029 | }
|
5030 | }
|
5031 | }
|
5032 |
|
5033 |
|
5034 |
|
5035 |
|
5036 | LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
|
5037 |
|
5038 |
|
5039 |
|
5040 |
|
5041 |
|
5042 |
|
5043 |
|
5044 |
|
5045 |
|
5046 |
|
5047 |
|
5048 |
|
5049 |
|
5050 |
|
5051 |
|
5052 |
|
5053 |
|
5054 | let nodeFromJSON$1;
|
5055 | let MAX_NODE$1;
|
5056 | function setNodeFromJSON(val) {
|
5057 | nodeFromJSON$1 = val;
|
5058 | }
|
5059 | function setMaxNode(val) {
|
5060 | MAX_NODE$1 = val;
|
5061 | }
|
5062 | class PriorityIndex extends Index {
|
5063 | compare(a, b) {
|
5064 | const aPriority = a.node.getPriority();
|
5065 | const bPriority = b.node.getPriority();
|
5066 | const indexCmp = aPriority.compareTo(bPriority);
|
5067 | if (indexCmp === 0) {
|
5068 | return nameCompare(a.name, b.name);
|
5069 | }
|
5070 | else {
|
5071 | return indexCmp;
|
5072 | }
|
5073 | }
|
5074 | isDefinedOn(node) {
|
5075 | return !node.getPriority().isEmpty();
|
5076 | }
|
5077 | indexedValueChanged(oldNode, newNode) {
|
5078 | return !oldNode.getPriority().equals(newNode.getPriority());
|
5079 | }
|
5080 | minPost() {
|
5081 |
|
5082 | return NamedNode.MIN;
|
5083 | }
|
5084 | maxPost() {
|
5085 | return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
|
5086 | }
|
5087 | makePost(indexValue, name) {
|
5088 | const priorityNode = nodeFromJSON$1(indexValue);
|
5089 | return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
|
5090 | }
|
5091 | |
5092 |
|
5093 |
|
5094 | toString() {
|
5095 | return '.priority';
|
5096 | }
|
5097 | }
|
5098 | const PRIORITY_INDEX = new PriorityIndex();
|
5099 |
|
5100 |
|
5101 |
|
5102 |
|
5103 |
|
5104 |
|
5105 |
|
5106 |
|
5107 |
|
5108 |
|
5109 |
|
5110 |
|
5111 |
|
5112 |
|
5113 |
|
5114 |
|
5115 |
|
5116 | const LOG_2 = Math.log(2);
|
5117 | class Base12Num {
|
5118 | constructor(length) {
|
5119 | const logBase2 = (num) =>
|
5120 |
|
5121 | parseInt((Math.log(num) / LOG_2), 10);
|
5122 | const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);
|
5123 | this.count = logBase2(length + 1);
|
5124 | this.current_ = this.count - 1;
|
5125 | const mask = bitMask(this.count);
|
5126 | this.bits_ = (length + 1) & mask;
|
5127 | }
|
5128 | nextBitIsOne() {
|
5129 |
|
5130 | const result = !(this.bits_ & (0x1 << this.current_));
|
5131 | this.current_--;
|
5132 | return result;
|
5133 | }
|
5134 | }
|
5135 |
|
5136 |
|
5137 |
|
5138 |
|
5139 |
|
5140 |
|
5141 |
|
5142 |
|
5143 |
|
5144 |
|
5145 |
|
5146 |
|
5147 |
|
5148 | const buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
|
5149 | childList.sort(cmp);
|
5150 | const buildBalancedTree = function (low, high) {
|
5151 | const length = high - low;
|
5152 | let namedNode;
|
5153 | let key;
|
5154 | if (length === 0) {
|
5155 | return null;
|
5156 | }
|
5157 | else if (length === 1) {
|
5158 | namedNode = childList[low];
|
5159 | key = keyFn ? keyFn(namedNode) : namedNode;
|
5160 | return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
|
5161 | }
|
5162 | else {
|
5163 |
|
5164 | const middle = parseInt((length / 2), 10) + low;
|
5165 | const left = buildBalancedTree(low, middle);
|
5166 | const right = buildBalancedTree(middle + 1, high);
|
5167 | namedNode = childList[middle];
|
5168 | key = keyFn ? keyFn(namedNode) : namedNode;
|
5169 | return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
|
5170 | }
|
5171 | };
|
5172 | const buildFrom12Array = function (base12) {
|
5173 | let node = null;
|
5174 | let root = null;
|
5175 | let index = childList.length;
|
5176 | const buildPennant = function (chunkSize, color) {
|
5177 | const low = index - chunkSize;
|
5178 | const high = index;
|
5179 | index -= chunkSize;
|
5180 | const childTree = buildBalancedTree(low + 1, high);
|
5181 | const namedNode = childList[low];
|
5182 | const key = keyFn ? keyFn(namedNode) : namedNode;
|
5183 | attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
|
5184 | };
|
5185 | const attachPennant = function (pennant) {
|
5186 | if (node) {
|
5187 | node.left = pennant;
|
5188 | node = pennant;
|
5189 | }
|
5190 | else {
|
5191 | root = pennant;
|
5192 | node = pennant;
|
5193 | }
|
5194 | };
|
5195 | for (let i = 0; i < base12.count; ++i) {
|
5196 | const isOne = base12.nextBitIsOne();
|
5197 |
|
5198 | const chunkSize = Math.pow(2, base12.count - (i + 1));
|
5199 | if (isOne) {
|
5200 | buildPennant(chunkSize, LLRBNode.BLACK);
|
5201 | }
|
5202 | else {
|
5203 |
|
5204 | buildPennant(chunkSize, LLRBNode.BLACK);
|
5205 | buildPennant(chunkSize, LLRBNode.RED);
|
5206 | }
|
5207 | }
|
5208 | return root;
|
5209 | };
|
5210 | const base12 = new Base12Num(childList.length);
|
5211 | const root = buildFrom12Array(base12);
|
5212 |
|
5213 | return new SortedMap(mapSortFn || cmp, root);
|
5214 | };
|
5215 |
|
5216 |
|
5217 |
|
5218 |
|
5219 |
|
5220 |
|
5221 |
|
5222 |
|
5223 |
|
5224 |
|
5225 |
|
5226 |
|
5227 |
|
5228 |
|
5229 |
|
5230 |
|
5231 |
|
5232 | let _defaultIndexMap;
|
5233 | const fallbackObject = {};
|
5234 | class IndexMap {
|
5235 | constructor(indexes_, indexSet_) {
|
5236 | this.indexes_ = indexes_;
|
5237 | this.indexSet_ = indexSet_;
|
5238 | }
|
5239 | |
5240 |
|
5241 |
|
5242 | static get Default() {
|
5243 | assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
|
5244 | _defaultIndexMap =
|
5245 | _defaultIndexMap ||
|
5246 | new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
|
5247 | return _defaultIndexMap;
|
5248 | }
|
5249 | get(indexKey) {
|
5250 | const sortedMap = safeGet(this.indexes_, indexKey);
|
5251 | if (!sortedMap) {
|
5252 | throw new Error('No index defined for ' + indexKey);
|
5253 | }
|
5254 | if (sortedMap instanceof SortedMap) {
|
5255 | return sortedMap;
|
5256 | }
|
5257 | else {
|
5258 |
|
5259 |
|
5260 | return null;
|
5261 | }
|
5262 | }
|
5263 | hasIndex(indexDefinition) {
|
5264 | return contains(this.indexSet_, indexDefinition.toString());
|
5265 | }
|
5266 | addIndex(indexDefinition, existingChildren) {
|
5267 | assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
|
5268 | const childList = [];
|
5269 | let sawIndexedValue = false;
|
5270 | const iter = existingChildren.getIterator(NamedNode.Wrap);
|
5271 | let next = iter.getNext();
|
5272 | while (next) {
|
5273 | sawIndexedValue =
|
5274 | sawIndexedValue || indexDefinition.isDefinedOn(next.node);
|
5275 | childList.push(next);
|
5276 | next = iter.getNext();
|
5277 | }
|
5278 | let newIndex;
|
5279 | if (sawIndexedValue) {
|
5280 | newIndex = buildChildSet(childList, indexDefinition.getCompare());
|
5281 | }
|
5282 | else {
|
5283 | newIndex = fallbackObject;
|
5284 | }
|
5285 | const indexName = indexDefinition.toString();
|
5286 | const newIndexSet = Object.assign({}, this.indexSet_);
|
5287 | newIndexSet[indexName] = indexDefinition;
|
5288 | const newIndexes = Object.assign({}, this.indexes_);
|
5289 | newIndexes[indexName] = newIndex;
|
5290 | return new IndexMap(newIndexes, newIndexSet);
|
5291 | }
|
5292 | |
5293 |
|
5294 |
|
5295 | addToIndexes(namedNode, existingChildren) {
|
5296 | const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {
|
5297 | const index = safeGet(this.indexSet_, indexName);
|
5298 | assert(index, 'Missing index implementation for ' + indexName);
|
5299 | if (indexedChildren === fallbackObject) {
|
5300 |
|
5301 | if (index.isDefinedOn(namedNode.node)) {
|
5302 |
|
5303 | const childList = [];
|
5304 | const iter = existingChildren.getIterator(NamedNode.Wrap);
|
5305 | let next = iter.getNext();
|
5306 | while (next) {
|
5307 | if (next.name !== namedNode.name) {
|
5308 | childList.push(next);
|
5309 | }
|
5310 | next = iter.getNext();
|
5311 | }
|
5312 | childList.push(namedNode);
|
5313 | return buildChildSet(childList, index.getCompare());
|
5314 | }
|
5315 | else {
|
5316 |
|
5317 | return fallbackObject;
|
5318 | }
|
5319 | }
|
5320 | else {
|
5321 | const existingSnap = existingChildren.get(namedNode.name);
|
5322 | let newChildren = indexedChildren;
|
5323 | if (existingSnap) {
|
5324 | newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
|
5325 | }
|
5326 | return newChildren.insert(namedNode, namedNode.node);
|
5327 | }
|
5328 | });
|
5329 | return new IndexMap(newIndexes, this.indexSet_);
|
5330 | }
|
5331 | |
5332 |
|
5333 |
|
5334 | removeFromIndexes(namedNode, existingChildren) {
|
5335 | const newIndexes = map(this.indexes_, (indexedChildren) => {
|
5336 | if (indexedChildren === fallbackObject) {
|
5337 |
|
5338 | return indexedChildren;
|
5339 | }
|
5340 | else {
|
5341 | const existingSnap = existingChildren.get(namedNode.name);
|
5342 | if (existingSnap) {
|
5343 | return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
|
5344 | }
|
5345 | else {
|
5346 |
|
5347 | return indexedChildren;
|
5348 | }
|
5349 | }
|
5350 | });
|
5351 | return new IndexMap(newIndexes, this.indexSet_);
|
5352 | }
|
5353 | }
|
5354 |
|
5355 |
|
5356 |
|
5357 |
|
5358 |
|
5359 |
|
5360 |
|
5361 |
|
5362 |
|
5363 |
|
5364 |
|
5365 |
|
5366 |
|
5367 |
|
5368 |
|
5369 |
|
5370 |
|
5371 |
|
5372 | let EMPTY_NODE;
|
5373 |
|
5374 |
|
5375 |
|
5376 |
|
5377 |
|
5378 | class ChildrenNode {
|
5379 | |
5380 |
|
5381 |
|
5382 |
|
5383 | constructor(children_, priorityNode_, indexMap_) {
|
5384 | this.children_ = children_;
|
5385 | this.priorityNode_ = priorityNode_;
|
5386 | this.indexMap_ = indexMap_;
|
5387 | this.lazyHash_ = null;
|
5388 | |
5389 |
|
5390 |
|
5391 |
|
5392 |
|
5393 | if (this.priorityNode_) {
|
5394 | validatePriorityNode(this.priorityNode_);
|
5395 | }
|
5396 | if (this.children_.isEmpty()) {
|
5397 | assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
|
5398 | }
|
5399 | }
|
5400 | static get EMPTY_NODE() {
|
5401 | return (EMPTY_NODE ||
|
5402 | (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
|
5403 | }
|
5404 |
|
5405 | isLeafNode() {
|
5406 | return false;
|
5407 | }
|
5408 |
|
5409 | getPriority() {
|
5410 | return this.priorityNode_ || EMPTY_NODE;
|
5411 | }
|
5412 |
|
5413 | updatePriority(newPriorityNode) {
|
5414 | if (this.children_.isEmpty()) {
|
5415 |
|
5416 | return this;
|
5417 | }
|
5418 | else {
|
5419 | return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
|
5420 | }
|
5421 | }
|
5422 |
|
5423 | getImmediateChild(childName) {
|
5424 |
|
5425 | if (childName === '.priority') {
|
5426 | return this.getPriority();
|
5427 | }
|
5428 | else {
|
5429 | const child = this.children_.get(childName);
|
5430 | return child === null ? EMPTY_NODE : child;
|
5431 | }
|
5432 | }
|
5433 |
|
5434 | getChild(path) {
|
5435 | const front = pathGetFront(path);
|
5436 | if (front === null) {
|
5437 | return this;
|
5438 | }
|
5439 | return this.getImmediateChild(front).getChild(pathPopFront(path));
|
5440 | }
|
5441 |
|
5442 | hasChild(childName) {
|
5443 | return this.children_.get(childName) !== null;
|
5444 | }
|
5445 |
|
5446 | updateImmediateChild(childName, newChildNode) {
|
5447 | assert(newChildNode, 'We should always be passing snapshot nodes');
|
5448 | if (childName === '.priority') {
|
5449 | return this.updatePriority(newChildNode);
|
5450 | }
|
5451 | else {
|
5452 | const namedNode = new NamedNode(childName, newChildNode);
|
5453 | let newChildren, newIndexMap;
|
5454 | if (newChildNode.isEmpty()) {
|
5455 | newChildren = this.children_.remove(childName);
|
5456 | newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
|
5457 | }
|
5458 | else {
|
5459 | newChildren = this.children_.insert(childName, newChildNode);
|
5460 | newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
|
5461 | }
|
5462 | const newPriority = newChildren.isEmpty()
|
5463 | ? EMPTY_NODE
|
5464 | : this.priorityNode_;
|
5465 | return new ChildrenNode(newChildren, newPriority, newIndexMap);
|
5466 | }
|
5467 | }
|
5468 |
|
5469 | updateChild(path, newChildNode) {
|
5470 | const front = pathGetFront(path);
|
5471 | if (front === null) {
|
5472 | return newChildNode;
|
5473 | }
|
5474 | else {
|
5475 | assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
|
5476 | const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
|
5477 | return this.updateImmediateChild(front, newImmediateChild);
|
5478 | }
|
5479 | }
|
5480 |
|
5481 | isEmpty() {
|
5482 | return this.children_.isEmpty();
|
5483 | }
|
5484 |
|
5485 | numChildren() {
|
5486 | return this.children_.count();
|
5487 | }
|
5488 |
|
5489 | val(exportFormat) {
|
5490 | if (this.isEmpty()) {
|
5491 | return null;
|
5492 | }
|
5493 | const obj = {};
|
5494 | let numKeys = 0, maxKey = 0, allIntegerKeys = true;
|
5495 | this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
|
5496 | obj[key] = childNode.val(exportFormat);
|
5497 | numKeys++;
|
5498 | if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
|
5499 | maxKey = Math.max(maxKey, Number(key));
|
5500 | }
|
5501 | else {
|
5502 | allIntegerKeys = false;
|
5503 | }
|
5504 | });
|
5505 | if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
|
5506 |
|
5507 | const array = [];
|
5508 |
|
5509 | for (const key in obj) {
|
5510 | array[key] = obj[key];
|
5511 | }
|
5512 | return array;
|
5513 | }
|
5514 | else {
|
5515 | if (exportFormat && !this.getPriority().isEmpty()) {
|
5516 | obj['.priority'] = this.getPriority().val();
|
5517 | }
|
5518 | return obj;
|
5519 | }
|
5520 | }
|
5521 |
|
5522 | hash() {
|
5523 | if (this.lazyHash_ === null) {
|
5524 | let toHash = '';
|
5525 | if (!this.getPriority().isEmpty()) {
|
5526 | toHash +=
|
5527 | 'priority:' +
|
5528 | priorityHashText(this.getPriority().val()) +
|
5529 | ':';
|
5530 | }
|
5531 | this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
|
5532 | const childHash = childNode.hash();
|
5533 | if (childHash !== '') {
|
5534 | toHash += ':' + key + ':' + childHash;
|
5535 | }
|
5536 | });
|
5537 | this.lazyHash_ = toHash === '' ? '' : sha1(toHash);
|
5538 | }
|
5539 | return this.lazyHash_;
|
5540 | }
|
5541 |
|
5542 | getPredecessorChildName(childName, childNode, index) {
|
5543 | const idx = this.resolveIndex_(index);
|
5544 | if (idx) {
|
5545 | const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
|
5546 | return predecessor ? predecessor.name : null;
|
5547 | }
|
5548 | else {
|
5549 | return this.children_.getPredecessorKey(childName);
|
5550 | }
|
5551 | }
|
5552 | getFirstChildName(indexDefinition) {
|
5553 | const idx = this.resolveIndex_(indexDefinition);
|
5554 | if (idx) {
|
5555 | const minKey = idx.minKey();
|
5556 | return minKey && minKey.name;
|
5557 | }
|
5558 | else {
|
5559 | return this.children_.minKey();
|
5560 | }
|
5561 | }
|
5562 | getFirstChild(indexDefinition) {
|
5563 | const minKey = this.getFirstChildName(indexDefinition);
|
5564 | if (minKey) {
|
5565 | return new NamedNode(minKey, this.children_.get(minKey));
|
5566 | }
|
5567 | else {
|
5568 | return null;
|
5569 | }
|
5570 | }
|
5571 | |
5572 |
|
5573 |
|
5574 | getLastChildName(indexDefinition) {
|
5575 | const idx = this.resolveIndex_(indexDefinition);
|
5576 | if (idx) {
|
5577 | const maxKey = idx.maxKey();
|
5578 | return maxKey && maxKey.name;
|
5579 | }
|
5580 | else {
|
5581 | return this.children_.maxKey();
|
5582 | }
|
5583 | }
|
5584 | getLastChild(indexDefinition) {
|
5585 | const maxKey = this.getLastChildName(indexDefinition);
|
5586 | if (maxKey) {
|
5587 | return new NamedNode(maxKey, this.children_.get(maxKey));
|
5588 | }
|
5589 | else {
|
5590 | return null;
|
5591 | }
|
5592 | }
|
5593 | forEachChild(index, action) {
|
5594 | const idx = this.resolveIndex_(index);
|
5595 | if (idx) {
|
5596 | return idx.inorderTraversal(wrappedNode => {
|
5597 | return action(wrappedNode.name, wrappedNode.node);
|
5598 | });
|
5599 | }
|
5600 | else {
|
5601 | return this.children_.inorderTraversal(action);
|
5602 | }
|
5603 | }
|
5604 | getIterator(indexDefinition) {
|
5605 | return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
|
5606 | }
|
5607 | getIteratorFrom(startPost, indexDefinition) {
|
5608 | const idx = this.resolveIndex_(indexDefinition);
|
5609 | if (idx) {
|
5610 | return idx.getIteratorFrom(startPost, key => key);
|
5611 | }
|
5612 | else {
|
5613 | const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
|
5614 | let next = iterator.peek();
|
5615 | while (next != null && indexDefinition.compare(next, startPost) < 0) {
|
5616 | iterator.getNext();
|
5617 | next = iterator.peek();
|
5618 | }
|
5619 | return iterator;
|
5620 | }
|
5621 | }
|
5622 | getReverseIterator(indexDefinition) {
|
5623 | return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
|
5624 | }
|
5625 | getReverseIteratorFrom(endPost, indexDefinition) {
|
5626 | const idx = this.resolveIndex_(indexDefinition);
|
5627 | if (idx) {
|
5628 | return idx.getReverseIteratorFrom(endPost, key => {
|
5629 | return key;
|
5630 | });
|
5631 | }
|
5632 | else {
|
5633 | const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
|
5634 | let next = iterator.peek();
|
5635 | while (next != null && indexDefinition.compare(next, endPost) > 0) {
|
5636 | iterator.getNext();
|
5637 | next = iterator.peek();
|
5638 | }
|
5639 | return iterator;
|
5640 | }
|
5641 | }
|
5642 | compareTo(other) {
|
5643 | if (this.isEmpty()) {
|
5644 | if (other.isEmpty()) {
|
5645 | return 0;
|
5646 | }
|
5647 | else {
|
5648 | return -1;
|
5649 | }
|
5650 | }
|
5651 | else if (other.isLeafNode() || other.isEmpty()) {
|
5652 | return 1;
|
5653 | }
|
5654 | else if (other === MAX_NODE) {
|
5655 | return -1;
|
5656 | }
|
5657 | else {
|
5658 |
|
5659 | return 0;
|
5660 | }
|
5661 | }
|
5662 | withIndex(indexDefinition) {
|
5663 | if (indexDefinition === KEY_INDEX ||
|
5664 | this.indexMap_.hasIndex(indexDefinition)) {
|
5665 | return this;
|
5666 | }
|
5667 | else {
|
5668 | const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
|
5669 | return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
|
5670 | }
|
5671 | }
|
5672 | isIndexed(index) {
|
5673 | return index === KEY_INDEX || this.indexMap_.hasIndex(index);
|
5674 | }
|
5675 | equals(other) {
|
5676 | if (other === this) {
|
5677 | return true;
|
5678 | }
|
5679 | else if (other.isLeafNode()) {
|
5680 | return false;
|
5681 | }
|
5682 | else {
|
5683 | const otherChildrenNode = other;
|
5684 | if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
|
5685 | return false;
|
5686 | }
|
5687 | else if (this.children_.count() === otherChildrenNode.children_.count()) {
|
5688 | const thisIter = this.getIterator(PRIORITY_INDEX);
|
5689 | const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
|
5690 | let thisCurrent = thisIter.getNext();
|
5691 | let otherCurrent = otherIter.getNext();
|
5692 | while (thisCurrent && otherCurrent) {
|
5693 | if (thisCurrent.name !== otherCurrent.name ||
|
5694 | !thisCurrent.node.equals(otherCurrent.node)) {
|
5695 | return false;
|
5696 | }
|
5697 | thisCurrent = thisIter.getNext();
|
5698 | otherCurrent = otherIter.getNext();
|
5699 | }
|
5700 | return thisCurrent === null && otherCurrent === null;
|
5701 | }
|
5702 | else {
|
5703 | return false;
|
5704 | }
|
5705 | }
|
5706 | }
|
5707 | |
5708 |
|
5709 |
|
5710 |
|
5711 |
|
5712 | resolveIndex_(indexDefinition) {
|
5713 | if (indexDefinition === KEY_INDEX) {
|
5714 | return null;
|
5715 | }
|
5716 | else {
|
5717 | return this.indexMap_.get(indexDefinition.toString());
|
5718 | }
|
5719 | }
|
5720 | }
|
5721 | ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
|
5722 | class MaxNode extends ChildrenNode {
|
5723 | constructor() {
|
5724 | super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
|
5725 | }
|
5726 | compareTo(other) {
|
5727 | if (other === this) {
|
5728 | return 0;
|
5729 | }
|
5730 | else {
|
5731 | return 1;
|
5732 | }
|
5733 | }
|
5734 | equals(other) {
|
5735 |
|
5736 | return other === this;
|
5737 | }
|
5738 | getPriority() {
|
5739 | return this;
|
5740 | }
|
5741 | getImmediateChild(childName) {
|
5742 | return ChildrenNode.EMPTY_NODE;
|
5743 | }
|
5744 | isEmpty() {
|
5745 | return false;
|
5746 | }
|
5747 | }
|
5748 |
|
5749 |
|
5750 |
|
5751 | const MAX_NODE = new MaxNode();
|
5752 | Object.defineProperties(NamedNode, {
|
5753 | MIN: {
|
5754 | value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
|
5755 | },
|
5756 | MAX: {
|
5757 | value: new NamedNode(MAX_NAME, MAX_NODE)
|
5758 | }
|
5759 | });
|
5760 |
|
5761 |
|
5762 |
|
5763 | KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
|
5764 | LeafNode.__childrenNodeConstructor = ChildrenNode;
|
5765 | setMaxNode$1(MAX_NODE);
|
5766 | setMaxNode(MAX_NODE);
|
5767 |
|
5768 |
|
5769 |
|
5770 |
|
5771 |
|
5772 |
|
5773 |
|
5774 |
|
5775 |
|
5776 |
|
5777 |
|
5778 |
|
5779 |
|
5780 |
|
5781 |
|
5782 |
|
5783 |
|
5784 | const USE_HINZE = true;
|
5785 |
|
5786 |
|
5787 |
|
5788 |
|
5789 |
|
5790 |
|
5791 | function nodeFromJSON(json, priority = null) {
|
5792 | if (json === null) {
|
5793 | return ChildrenNode.EMPTY_NODE;
|
5794 | }
|
5795 | if (typeof json === 'object' && '.priority' in json) {
|
5796 | priority = json['.priority'];
|
5797 | }
|
5798 | assert(priority === null ||
|
5799 | typeof priority === 'string' ||
|
5800 | typeof priority === 'number' ||
|
5801 | (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
|
5802 | if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
|
5803 | json = json['.value'];
|
5804 | }
|
5805 |
|
5806 | if (typeof json !== 'object' || '.sv' in json) {
|
5807 | const jsonLeaf = json;
|
5808 | return new LeafNode(jsonLeaf, nodeFromJSON(priority));
|
5809 | }
|
5810 | if (!(json instanceof Array) && USE_HINZE) {
|
5811 | const children = [];
|
5812 | let childrenHavePriority = false;
|
5813 | const hinzeJsonObj = json;
|
5814 | each(hinzeJsonObj, (key, child) => {
|
5815 | if (key.substring(0, 1) !== '.') {
|
5816 |
|
5817 | const childNode = nodeFromJSON(child);
|
5818 | if (!childNode.isEmpty()) {
|
5819 | childrenHavePriority =
|
5820 | childrenHavePriority || !childNode.getPriority().isEmpty();
|
5821 | children.push(new NamedNode(key, childNode));
|
5822 | }
|
5823 | }
|
5824 | });
|
5825 | if (children.length === 0) {
|
5826 | return ChildrenNode.EMPTY_NODE;
|
5827 | }
|
5828 | const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);
|
5829 | if (childrenHavePriority) {
|
5830 | const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
|
5831 | return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
|
5832 | }
|
5833 | else {
|
5834 | return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
|
5835 | }
|
5836 | }
|
5837 | else {
|
5838 | let node = ChildrenNode.EMPTY_NODE;
|
5839 | each(json, (key, childData) => {
|
5840 | if (contains(json, key)) {
|
5841 | if (key.substring(0, 1) !== '.') {
|
5842 |
|
5843 | const childNode = nodeFromJSON(childData);
|
5844 | if (childNode.isLeafNode() || !childNode.isEmpty()) {
|
5845 | node = node.updateImmediateChild(key, childNode);
|
5846 | }
|
5847 | }
|
5848 | }
|
5849 | });
|
5850 | return node.updatePriority(nodeFromJSON(priority));
|
5851 | }
|
5852 | }
|
5853 | setNodeFromJSON(nodeFromJSON);
|
5854 |
|
5855 |
|
5856 |
|
5857 |
|
5858 |
|
5859 |
|
5860 |
|
5861 |
|
5862 |
|
5863 |
|
5864 |
|
5865 |
|
5866 |
|
5867 |
|
5868 |
|
5869 |
|
5870 |
|
5871 | class PathIndex extends Index {
|
5872 | constructor(indexPath_) {
|
5873 | super();
|
5874 | this.indexPath_ = indexPath_;
|
5875 | assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
|
5876 | }
|
5877 | extractChild(snap) {
|
5878 | return snap.getChild(this.indexPath_);
|
5879 | }
|
5880 | isDefinedOn(node) {
|
5881 | return !node.getChild(this.indexPath_).isEmpty();
|
5882 | }
|
5883 | compare(a, b) {
|
5884 | const aChild = this.extractChild(a.node);
|
5885 | const bChild = this.extractChild(b.node);
|
5886 | const indexCmp = aChild.compareTo(bChild);
|
5887 | if (indexCmp === 0) {
|
5888 | return nameCompare(a.name, b.name);
|
5889 | }
|
5890 | else {
|
5891 | return indexCmp;
|
5892 | }
|
5893 | }
|
5894 | makePost(indexValue, name) {
|
5895 | const valueNode = nodeFromJSON(indexValue);
|
5896 | const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
|
5897 | return new NamedNode(name, node);
|
5898 | }
|
5899 | maxPost() {
|
5900 | const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
|
5901 | return new NamedNode(MAX_NAME, node);
|
5902 | }
|
5903 | toString() {
|
5904 | return pathSlice(this.indexPath_, 0).join('/');
|
5905 | }
|
5906 | }
|
5907 |
|
5908 |
|
5909 |
|
5910 |
|
5911 |
|
5912 |
|
5913 |
|
5914 |
|
5915 |
|
5916 |
|
5917 |
|
5918 |
|
5919 |
|
5920 |
|
5921 |
|
5922 |
|
5923 |
|
5924 | class ValueIndex extends Index {
|
5925 | compare(a, b) {
|
5926 | const indexCmp = a.node.compareTo(b.node);
|
5927 | if (indexCmp === 0) {
|
5928 | return nameCompare(a.name, b.name);
|
5929 | }
|
5930 | else {
|
5931 | return indexCmp;
|
5932 | }
|
5933 | }
|
5934 | isDefinedOn(node) {
|
5935 | return true;
|
5936 | }
|
5937 | indexedValueChanged(oldNode, newNode) {
|
5938 | return !oldNode.equals(newNode);
|
5939 | }
|
5940 | minPost() {
|
5941 |
|
5942 | return NamedNode.MIN;
|
5943 | }
|
5944 | maxPost() {
|
5945 |
|
5946 | return NamedNode.MAX;
|
5947 | }
|
5948 | makePost(indexValue, name) {
|
5949 | const valueNode = nodeFromJSON(indexValue);
|
5950 | return new NamedNode(name, valueNode);
|
5951 | }
|
5952 | |
5953 |
|
5954 |
|
5955 | toString() {
|
5956 | return '.value';
|
5957 | }
|
5958 | }
|
5959 | const VALUE_INDEX = new ValueIndex();
|
5960 |
|
5961 |
|
5962 |
|
5963 |
|
5964 |
|
5965 |
|
5966 |
|
5967 |
|
5968 |
|
5969 |
|
5970 |
|
5971 |
|
5972 |
|
5973 |
|
5974 |
|
5975 |
|
5976 |
|
5977 |
|
5978 | const PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
|
5979 | const MIN_PUSH_CHAR = '-';
|
5980 | const MAX_PUSH_CHAR = 'z';
|
5981 | const MAX_KEY_LEN = 786;
|
5982 |
|
5983 |
|
5984 |
|
5985 |
|
5986 |
|
5987 |
|
5988 |
|
5989 |
|
5990 |
|
5991 |
|
5992 |
|
5993 |
|
5994 |
|
5995 |
|
5996 | const nextPushId = (function () {
|
5997 |
|
5998 |
|
5999 | let lastPushTime = 0;
|
6000 |
|
6001 |
|
6002 |
|
6003 |
|
6004 | const lastRandChars = [];
|
6005 | return function (now) {
|
6006 | const duplicateTime = now === lastPushTime;
|
6007 | lastPushTime = now;
|
6008 | let i;
|
6009 | const timeStampChars = new Array(8);
|
6010 | for (i = 7; i >= 0; i--) {
|
6011 | timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
|
6012 |
|
6013 |
|
6014 | now = Math.floor(now / 64);
|
6015 | }
|
6016 | assert(now === 0, 'Cannot push at time == 0');
|
6017 | let id = timeStampChars.join('');
|
6018 | if (!duplicateTime) {
|
6019 | for (i = 0; i < 12; i++) {
|
6020 | lastRandChars[i] = Math.floor(Math.random() * 64);
|
6021 | }
|
6022 | }
|
6023 | else {
|
6024 |
|
6025 |
|
6026 | for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
|
6027 | lastRandChars[i] = 0;
|
6028 | }
|
6029 | lastRandChars[i]++;
|
6030 | }
|
6031 | for (i = 0; i < 12; i++) {
|
6032 | id += PUSH_CHARS.charAt(lastRandChars[i]);
|
6033 | }
|
6034 | assert(id.length === 20, 'nextPushId: Length should be 20.');
|
6035 | return id;
|
6036 | };
|
6037 | })();
|
6038 | const successor = function (key) {
|
6039 | if (key === '' + INTEGER_32_MAX) {
|
6040 |
|
6041 | return MIN_PUSH_CHAR;
|
6042 | }
|
6043 | const keyAsInt = tryParseInt(key);
|
6044 | if (keyAsInt != null) {
|
6045 | return '' + (keyAsInt + 1);
|
6046 | }
|
6047 | const next = new Array(key.length);
|
6048 | for (let i = 0; i < next.length; i++) {
|
6049 | next[i] = key.charAt(i);
|
6050 | }
|
6051 | if (next.length < MAX_KEY_LEN) {
|
6052 | next.push(MIN_PUSH_CHAR);
|
6053 | return next.join('');
|
6054 | }
|
6055 | let i = next.length - 1;
|
6056 | while (i >= 0 && next[i] === MAX_PUSH_CHAR) {
|
6057 | i--;
|
6058 | }
|
6059 |
|
6060 |
|
6061 | if (i === -1) {
|
6062 | return MAX_NAME;
|
6063 | }
|
6064 | const source = next[i];
|
6065 | const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);
|
6066 | next[i] = sourcePlusOne;
|
6067 | return next.slice(0, i + 1).join('');
|
6068 | };
|
6069 |
|
6070 | const predecessor = function (key) {
|
6071 | if (key === '' + INTEGER_32_MIN) {
|
6072 | return MIN_NAME;
|
6073 | }
|
6074 | const keyAsInt = tryParseInt(key);
|
6075 | if (keyAsInt != null) {
|
6076 | return '' + (keyAsInt - 1);
|
6077 | }
|
6078 | const next = new Array(key.length);
|
6079 | for (let i = 0; i < next.length; i++) {
|
6080 | next[i] = key.charAt(i);
|
6081 | }
|
6082 |
|
6083 |
|
6084 |
|
6085 |
|
6086 |
|
6087 |
|
6088 |
|
6089 |
|
6090 |
|
6091 |
|
6092 |
|
6093 | if (next[next.length - 1] === MIN_PUSH_CHAR) {
|
6094 | if (next.length === 1) {
|
6095 |
|
6096 | return '' + INTEGER_32_MAX;
|
6097 | }
|
6098 | delete next[next.length - 1];
|
6099 | return next.join('');
|
6100 | }
|
6101 |
|
6102 |
|
6103 |
|
6104 | next[next.length - 1] = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(next[next.length - 1]) - 1);
|
6105 | return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);
|
6106 | };
|
6107 |
|
6108 |
|
6109 |
|
6110 |
|
6111 |
|
6112 |
|
6113 |
|
6114 |
|
6115 |
|
6116 |
|
6117 |
|
6118 |
|
6119 |
|
6120 |
|
6121 |
|
6122 |
|
6123 |
|
6124 | function changeValue(snapshotNode) {
|
6125 | return { type: "value" , snapshotNode };
|
6126 | }
|
6127 | function changeChildAdded(childName, snapshotNode) {
|
6128 | return { type: "child_added" , snapshotNode, childName };
|
6129 | }
|
6130 | function changeChildRemoved(childName, snapshotNode) {
|
6131 | return { type: "child_removed" , snapshotNode, childName };
|
6132 | }
|
6133 | function changeChildChanged(childName, snapshotNode, oldSnap) {
|
6134 | return {
|
6135 | type: "child_changed" ,
|
6136 | snapshotNode,
|
6137 | childName,
|
6138 | oldSnap
|
6139 | };
|
6140 | }
|
6141 | function changeChildMoved(childName, snapshotNode) {
|
6142 | return { type: "child_moved" , snapshotNode, childName };
|
6143 | }
|
6144 |
|
6145 |
|
6146 |
|
6147 |
|
6148 |
|
6149 |
|
6150 |
|
6151 |
|
6152 |
|
6153 |
|
6154 |
|
6155 |
|
6156 |
|
6157 |
|
6158 |
|
6159 |
|
6160 |
|
6161 |
|
6162 |
|
6163 |
|
6164 | class IndexedFilter {
|
6165 | constructor(index_) {
|
6166 | this.index_ = index_;
|
6167 | }
|
6168 | updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
|
6169 | assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
|
6170 | const oldChild = snap.getImmediateChild(key);
|
6171 |
|
6172 | if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
|
6173 |
|
6174 |
|
6175 |
|
6176 | if (oldChild.isEmpty() === newChild.isEmpty()) {
|
6177 |
|
6178 |
|
6179 |
|
6180 | return snap;
|
6181 | }
|
6182 | }
|
6183 | if (optChangeAccumulator != null) {
|
6184 | if (newChild.isEmpty()) {
|
6185 | if (snap.hasChild(key)) {
|
6186 | optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
|
6187 | }
|
6188 | else {
|
6189 | assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
|
6190 | }
|
6191 | }
|
6192 | else if (oldChild.isEmpty()) {
|
6193 | optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
|
6194 | }
|
6195 | else {
|
6196 | optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
|
6197 | }
|
6198 | }
|
6199 | if (snap.isLeafNode() && newChild.isEmpty()) {
|
6200 | return snap;
|
6201 | }
|
6202 | else {
|
6203 |
|
6204 | return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
|
6205 | }
|
6206 | }
|
6207 | updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
|
6208 | if (optChangeAccumulator != null) {
|
6209 | if (!oldSnap.isLeafNode()) {
|
6210 | oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
|
6211 | if (!newSnap.hasChild(key)) {
|
6212 | optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
|
6213 | }
|
6214 | });
|
6215 | }
|
6216 | if (!newSnap.isLeafNode()) {
|
6217 | newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
|
6218 | if (oldSnap.hasChild(key)) {
|
6219 | const oldChild = oldSnap.getImmediateChild(key);
|
6220 | if (!oldChild.equals(childNode)) {
|
6221 | optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
|
6222 | }
|
6223 | }
|
6224 | else {
|
6225 | optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
|
6226 | }
|
6227 | });
|
6228 | }
|
6229 | }
|
6230 | return newSnap.withIndex(this.index_);
|
6231 | }
|
6232 | updatePriority(oldSnap, newPriority) {
|
6233 | if (oldSnap.isEmpty()) {
|
6234 | return ChildrenNode.EMPTY_NODE;
|
6235 | }
|
6236 | else {
|
6237 | return oldSnap.updatePriority(newPriority);
|
6238 | }
|
6239 | }
|
6240 | filtersNodes() {
|
6241 | return false;
|
6242 | }
|
6243 | getIndexedFilter() {
|
6244 | return this;
|
6245 | }
|
6246 | getIndex() {
|
6247 | return this.index_;
|
6248 | }
|
6249 | }
|
6250 |
|
6251 |
|
6252 |
|
6253 |
|
6254 |
|
6255 |
|
6256 |
|
6257 |
|
6258 |
|
6259 |
|
6260 |
|
6261 |
|
6262 |
|
6263 |
|
6264 |
|
6265 |
|
6266 |
|
6267 |
|
6268 |
|
6269 |
|
6270 | class RangedFilter {
|
6271 | constructor(params) {
|
6272 | this.indexedFilter_ = new IndexedFilter(params.getIndex());
|
6273 | this.index_ = params.getIndex();
|
6274 | this.startPost_ = RangedFilter.getStartPost_(params);
|
6275 | this.endPost_ = RangedFilter.getEndPost_(params);
|
6276 | }
|
6277 | getStartPost() {
|
6278 | return this.startPost_;
|
6279 | }
|
6280 | getEndPost() {
|
6281 | return this.endPost_;
|
6282 | }
|
6283 | matches(node) {
|
6284 | return (this.index_.compare(this.getStartPost(), node) <= 0 &&
|
6285 | this.index_.compare(node, this.getEndPost()) <= 0);
|
6286 | }
|
6287 | updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
|
6288 | if (!this.matches(new NamedNode(key, newChild))) {
|
6289 | newChild = ChildrenNode.EMPTY_NODE;
|
6290 | }
|
6291 | return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
|
6292 | }
|
6293 | updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
|
6294 | if (newSnap.isLeafNode()) {
|
6295 |
|
6296 | newSnap = ChildrenNode.EMPTY_NODE;
|
6297 | }
|
6298 | let filtered = newSnap.withIndex(this.index_);
|
6299 |
|
6300 | filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
|
6301 | const self = this;
|
6302 | newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
|
6303 | if (!self.matches(new NamedNode(key, childNode))) {
|
6304 | filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
|
6305 | }
|
6306 | });
|
6307 | return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
|
6308 | }
|
6309 | updatePriority(oldSnap, newPriority) {
|
6310 |
|
6311 | return oldSnap;
|
6312 | }
|
6313 | filtersNodes() {
|
6314 | return true;
|
6315 | }
|
6316 | getIndexedFilter() {
|
6317 | return this.indexedFilter_;
|
6318 | }
|
6319 | getIndex() {
|
6320 | return this.index_;
|
6321 | }
|
6322 | static getStartPost_(params) {
|
6323 | if (params.hasStart()) {
|
6324 | const startName = params.getIndexStartName();
|
6325 | return params.getIndex().makePost(params.getIndexStartValue(), startName);
|
6326 | }
|
6327 | else {
|
6328 | return params.getIndex().minPost();
|
6329 | }
|
6330 | }
|
6331 | static getEndPost_(params) {
|
6332 | if (params.hasEnd()) {
|
6333 | const endName = params.getIndexEndName();
|
6334 | return params.getIndex().makePost(params.getIndexEndValue(), endName);
|
6335 | }
|
6336 | else {
|
6337 | return params.getIndex().maxPost();
|
6338 | }
|
6339 | }
|
6340 | }
|
6341 |
|
6342 |
|
6343 |
|
6344 |
|
6345 |
|
6346 |
|
6347 |
|
6348 |
|
6349 |
|
6350 |
|
6351 |
|
6352 |
|
6353 |
|
6354 |
|
6355 |
|
6356 |
|
6357 |
|
6358 |
|
6359 |
|
6360 |
|
6361 | class LimitedFilter {
|
6362 | constructor(params) {
|
6363 | this.rangedFilter_ = new RangedFilter(params);
|
6364 | this.index_ = params.getIndex();
|
6365 | this.limit_ = params.getLimit();
|
6366 | this.reverse_ = !params.isViewFromLeft();
|
6367 | }
|
6368 | updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
|
6369 | if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
|
6370 | newChild = ChildrenNode.EMPTY_NODE;
|
6371 | }
|
6372 | if (snap.getImmediateChild(key).equals(newChild)) {
|
6373 |
|
6374 | return snap;
|
6375 | }
|
6376 | else if (snap.numChildren() < this.limit_) {
|
6377 | return this.rangedFilter_
|
6378 | .getIndexedFilter()
|
6379 | .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
|
6380 | }
|
6381 | else {
|
6382 | return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
|
6383 | }
|
6384 | }
|
6385 | updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
|
6386 | let filtered;
|
6387 | if (newSnap.isLeafNode() || newSnap.isEmpty()) {
|
6388 |
|
6389 | filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
|
6390 | }
|
6391 | else {
|
6392 | if (this.limit_ * 2 < newSnap.numChildren() &&
|
6393 | newSnap.isIndexed(this.index_)) {
|
6394 |
|
6395 | filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
|
6396 |
|
6397 | let iterator;
|
6398 | if (this.reverse_) {
|
6399 | iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
|
6400 | }
|
6401 | else {
|
6402 | iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
|
6403 | }
|
6404 | let count = 0;
|
6405 | while (iterator.hasNext() && count < this.limit_) {
|
6406 | const next = iterator.getNext();
|
6407 | let inRange;
|
6408 | if (this.reverse_) {
|
6409 | inRange =
|
6410 | this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;
|
6411 | }
|
6412 | else {
|
6413 | inRange =
|
6414 | this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;
|
6415 | }
|
6416 | if (inRange) {
|
6417 | filtered = filtered.updateImmediateChild(next.name, next.node);
|
6418 | count++;
|
6419 | }
|
6420 | else {
|
6421 |
|
6422 | break;
|
6423 | }
|
6424 | }
|
6425 | }
|
6426 | else {
|
6427 |
|
6428 | filtered = newSnap.withIndex(this.index_);
|
6429 |
|
6430 | filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
|
6431 | let startPost;
|
6432 | let endPost;
|
6433 | let cmp;
|
6434 | let iterator;
|
6435 | if (this.reverse_) {
|
6436 | iterator = filtered.getReverseIterator(this.index_);
|
6437 | startPost = this.rangedFilter_.getEndPost();
|
6438 | endPost = this.rangedFilter_.getStartPost();
|
6439 | const indexCompare = this.index_.getCompare();
|
6440 | cmp = (a, b) => indexCompare(b, a);
|
6441 | }
|
6442 | else {
|
6443 | iterator = filtered.getIterator(this.index_);
|
6444 | startPost = this.rangedFilter_.getStartPost();
|
6445 | endPost = this.rangedFilter_.getEndPost();
|
6446 | cmp = this.index_.getCompare();
|
6447 | }
|
6448 | let count = 0;
|
6449 | let foundStartPost = false;
|
6450 | while (iterator.hasNext()) {
|
6451 | const next = iterator.getNext();
|
6452 | if (!foundStartPost && cmp(startPost, next) <= 0) {
|
6453 |
|
6454 | foundStartPost = true;
|
6455 | }
|
6456 | const inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;
|
6457 | if (inRange) {
|
6458 | count++;
|
6459 | }
|
6460 | else {
|
6461 | filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
|
6462 | }
|
6463 | }
|
6464 | }
|
6465 | }
|
6466 | return this.rangedFilter_
|
6467 | .getIndexedFilter()
|
6468 | .updateFullNode(oldSnap, filtered, optChangeAccumulator);
|
6469 | }
|
6470 | updatePriority(oldSnap, newPriority) {
|
6471 |
|
6472 | return oldSnap;
|
6473 | }
|
6474 | filtersNodes() {
|
6475 | return true;
|
6476 | }
|
6477 | getIndexedFilter() {
|
6478 | return this.rangedFilter_.getIndexedFilter();
|
6479 | }
|
6480 | getIndex() {
|
6481 | return this.index_;
|
6482 | }
|
6483 | fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
|
6484 |
|
6485 | let cmp;
|
6486 | if (this.reverse_) {
|
6487 | const indexCmp = this.index_.getCompare();
|
6488 | cmp = (a, b) => indexCmp(b, a);
|
6489 | }
|
6490 | else {
|
6491 | cmp = this.index_.getCompare();
|
6492 | }
|
6493 | const oldEventCache = snap;
|
6494 | assert(oldEventCache.numChildren() === this.limit_, '');
|
6495 | const newChildNamedNode = new NamedNode(childKey, childSnap);
|
6496 | const windowBoundary = this.reverse_
|
6497 | ? oldEventCache.getFirstChild(this.index_)
|
6498 | : oldEventCache.getLastChild(this.index_);
|
6499 | const inRange = this.rangedFilter_.matches(newChildNamedNode);
|
6500 | if (oldEventCache.hasChild(childKey)) {
|
6501 | const oldChildSnap = oldEventCache.getImmediateChild(childKey);
|
6502 | let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
|
6503 | while (nextChild != null &&
|
6504 | (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
|
6505 |
|
6506 |
|
6507 |
|
6508 | nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
|
6509 | }
|
6510 | const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
|
6511 | const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
|
6512 | if (remainsInWindow) {
|
6513 | if (changeAccumulator != null) {
|
6514 | changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
|
6515 | }
|
6516 | return oldEventCache.updateImmediateChild(childKey, childSnap);
|
6517 | }
|
6518 | else {
|
6519 | if (changeAccumulator != null) {
|
6520 | changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
|
6521 | }
|
6522 | const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
|
6523 | const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
|
6524 | if (nextChildInRange) {
|
6525 | if (changeAccumulator != null) {
|
6526 | changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
|
6527 | }
|
6528 | return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
|
6529 | }
|
6530 | else {
|
6531 | return newEventCache;
|
6532 | }
|
6533 | }
|
6534 | }
|
6535 | else if (childSnap.isEmpty()) {
|
6536 |
|
6537 | return snap;
|
6538 | }
|
6539 | else if (inRange) {
|
6540 | if (cmp(windowBoundary, newChildNamedNode) >= 0) {
|
6541 | if (changeAccumulator != null) {
|
6542 | changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
|
6543 | changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
|
6544 | }
|
6545 | return oldEventCache
|
6546 | .updateImmediateChild(childKey, childSnap)
|
6547 | .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
|
6548 | }
|
6549 | else {
|
6550 | return snap;
|
6551 | }
|
6552 | }
|
6553 | else {
|
6554 | return snap;
|
6555 | }
|
6556 | }
|
6557 | }
|
6558 |
|
6559 |
|
6560 |
|
6561 |
|
6562 |
|
6563 |
|
6564 |
|
6565 |
|
6566 |
|
6567 |
|
6568 |
|
6569 |
|
6570 |
|
6571 |
|
6572 |
|
6573 |
|
6574 |
|
6575 |
|
6576 |
|
6577 |
|
6578 |
|
6579 |
|
6580 |
|
6581 |
|
6582 | class QueryParams {
|
6583 | constructor() {
|
6584 | this.limitSet_ = false;
|
6585 | this.startSet_ = false;
|
6586 | this.startNameSet_ = false;
|
6587 | this.startAfterSet_ = false;
|
6588 | this.endSet_ = false;
|
6589 | this.endNameSet_ = false;
|
6590 | this.endBeforeSet_ = false;
|
6591 | this.limit_ = 0;
|
6592 | this.viewFrom_ = '';
|
6593 | this.indexStartValue_ = null;
|
6594 | this.indexStartName_ = '';
|
6595 | this.indexEndValue_ = null;
|
6596 | this.indexEndName_ = '';
|
6597 | this.index_ = PRIORITY_INDEX;
|
6598 | }
|
6599 | hasStart() {
|
6600 | return this.startSet_;
|
6601 | }
|
6602 | hasStartAfter() {
|
6603 | return this.startAfterSet_;
|
6604 | }
|
6605 | hasEndBefore() {
|
6606 | return this.endBeforeSet_;
|
6607 | }
|
6608 | |
6609 |
|
6610 |
|
6611 | isViewFromLeft() {
|
6612 | if (this.viewFrom_ === '') {
|
6613 |
|
6614 |
|
6615 |
|
6616 |
|
6617 | return this.startSet_;
|
6618 | }
|
6619 | else {
|
6620 | return this.viewFrom_ === "l" ;
|
6621 | }
|
6622 | }
|
6623 | |
6624 |
|
6625 |
|
6626 | getIndexStartValue() {
|
6627 | assert(this.startSet_, 'Only valid if start has been set');
|
6628 | return this.indexStartValue_;
|
6629 | }
|
6630 | |
6631 |
|
6632 |
|
6633 |
|
6634 | getIndexStartName() {
|
6635 | assert(this.startSet_, 'Only valid if start has been set');
|
6636 | if (this.startNameSet_) {
|
6637 | return this.indexStartName_;
|
6638 | }
|
6639 | else {
|
6640 | return MIN_NAME;
|
6641 | }
|
6642 | }
|
6643 | hasEnd() {
|
6644 | return this.endSet_;
|
6645 | }
|
6646 | |
6647 |
|
6648 |
|
6649 | getIndexEndValue() {
|
6650 | assert(this.endSet_, 'Only valid if end has been set');
|
6651 | return this.indexEndValue_;
|
6652 | }
|
6653 | |
6654 |
|
6655 |
|
6656 |
|
6657 | getIndexEndName() {
|
6658 | assert(this.endSet_, 'Only valid if end has been set');
|
6659 | if (this.endNameSet_) {
|
6660 | return this.indexEndName_;
|
6661 | }
|
6662 | else {
|
6663 | return MAX_NAME;
|
6664 | }
|
6665 | }
|
6666 | hasLimit() {
|
6667 | return this.limitSet_;
|
6668 | }
|
6669 | |
6670 |
|
6671 |
|
6672 | hasAnchoredLimit() {
|
6673 | return this.limitSet_ && this.viewFrom_ !== '';
|
6674 | }
|
6675 | |
6676 |
|
6677 |
|
6678 | getLimit() {
|
6679 | assert(this.limitSet_, 'Only valid if limit has been set');
|
6680 | return this.limit_;
|
6681 | }
|
6682 | getIndex() {
|
6683 | return this.index_;
|
6684 | }
|
6685 | loadsAllData() {
|
6686 | return !(this.startSet_ || this.endSet_ || this.limitSet_);
|
6687 | }
|
6688 | isDefault() {
|
6689 | return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
|
6690 | }
|
6691 | copy() {
|
6692 | const copy = new QueryParams();
|
6693 | copy.limitSet_ = this.limitSet_;
|
6694 | copy.limit_ = this.limit_;
|
6695 | copy.startSet_ = this.startSet_;
|
6696 | copy.indexStartValue_ = this.indexStartValue_;
|
6697 | copy.startNameSet_ = this.startNameSet_;
|
6698 | copy.indexStartName_ = this.indexStartName_;
|
6699 | copy.endSet_ = this.endSet_;
|
6700 | copy.indexEndValue_ = this.indexEndValue_;
|
6701 | copy.endNameSet_ = this.endNameSet_;
|
6702 | copy.indexEndName_ = this.indexEndName_;
|
6703 | copy.index_ = this.index_;
|
6704 | copy.viewFrom_ = this.viewFrom_;
|
6705 | return copy;
|
6706 | }
|
6707 | }
|
6708 | function queryParamsGetNodeFilter(queryParams) {
|
6709 | if (queryParams.loadsAllData()) {
|
6710 | return new IndexedFilter(queryParams.getIndex());
|
6711 | }
|
6712 | else if (queryParams.hasLimit()) {
|
6713 | return new LimitedFilter(queryParams);
|
6714 | }
|
6715 | else {
|
6716 | return new RangedFilter(queryParams);
|
6717 | }
|
6718 | }
|
6719 | function queryParamsLimitToFirst(queryParams, newLimit) {
|
6720 | const newParams = queryParams.copy();
|
6721 | newParams.limitSet_ = true;
|
6722 | newParams.limit_ = newLimit;
|
6723 | newParams.viewFrom_ = "l" ;
|
6724 | return newParams;
|
6725 | }
|
6726 | function queryParamsLimitToLast(queryParams, newLimit) {
|
6727 | const newParams = queryParams.copy();
|
6728 | newParams.limitSet_ = true;
|
6729 | newParams.limit_ = newLimit;
|
6730 | newParams.viewFrom_ = "r" ;
|
6731 | return newParams;
|
6732 | }
|
6733 | function queryParamsStartAt(queryParams, indexValue, key) {
|
6734 | const newParams = queryParams.copy();
|
6735 | newParams.startSet_ = true;
|
6736 | if (indexValue === undefined) {
|
6737 | indexValue = null;
|
6738 | }
|
6739 | newParams.indexStartValue_ = indexValue;
|
6740 | if (key != null) {
|
6741 | newParams.startNameSet_ = true;
|
6742 | newParams.indexStartName_ = key;
|
6743 | }
|
6744 | else {
|
6745 | newParams.startNameSet_ = false;
|
6746 | newParams.indexStartName_ = '';
|
6747 | }
|
6748 | return newParams;
|
6749 | }
|
6750 | function queryParamsStartAfter(queryParams, indexValue, key) {
|
6751 | let params;
|
6752 | if (queryParams.index_ === KEY_INDEX) {
|
6753 | if (typeof indexValue === 'string') {
|
6754 | indexValue = successor(indexValue);
|
6755 | }
|
6756 | params = queryParamsStartAt(queryParams, indexValue, key);
|
6757 | }
|
6758 | else {
|
6759 | let childKey;
|
6760 | if (key == null) {
|
6761 | childKey = MAX_NAME;
|
6762 | }
|
6763 | else {
|
6764 | childKey = successor(key);
|
6765 | }
|
6766 | params = queryParamsStartAt(queryParams, indexValue, childKey);
|
6767 | }
|
6768 | params.startAfterSet_ = true;
|
6769 | return params;
|
6770 | }
|
6771 | function queryParamsEndAt(queryParams, indexValue, key) {
|
6772 | const newParams = queryParams.copy();
|
6773 | newParams.endSet_ = true;
|
6774 | if (indexValue === undefined) {
|
6775 | indexValue = null;
|
6776 | }
|
6777 | newParams.indexEndValue_ = indexValue;
|
6778 | if (key !== undefined) {
|
6779 | newParams.endNameSet_ = true;
|
6780 | newParams.indexEndName_ = key;
|
6781 | }
|
6782 | else {
|
6783 | newParams.endNameSet_ = false;
|
6784 | newParams.indexEndName_ = '';
|
6785 | }
|
6786 | return newParams;
|
6787 | }
|
6788 | function queryParamsEndBefore(queryParams, indexValue, key) {
|
6789 | let childKey;
|
6790 | let params;
|
6791 | if (queryParams.index_ === KEY_INDEX) {
|
6792 | if (typeof indexValue === 'string') {
|
6793 | indexValue = predecessor(indexValue);
|
6794 | }
|
6795 | params = queryParamsEndAt(queryParams, indexValue, key);
|
6796 | }
|
6797 | else {
|
6798 | if (key == null) {
|
6799 | childKey = MIN_NAME;
|
6800 | }
|
6801 | else {
|
6802 | childKey = predecessor(key);
|
6803 | }
|
6804 | params = queryParamsEndAt(queryParams, indexValue, childKey);
|
6805 | }
|
6806 | params.endBeforeSet_ = true;
|
6807 | return params;
|
6808 | }
|
6809 | function queryParamsOrderBy(queryParams, index) {
|
6810 | const newParams = queryParams.copy();
|
6811 | newParams.index_ = index;
|
6812 | return newParams;
|
6813 | }
|
6814 |
|
6815 |
|
6816 |
|
6817 |
|
6818 |
|
6819 | function queryParamsToRestQueryStringParameters(queryParams) {
|
6820 | const qs = {};
|
6821 | if (queryParams.isDefault()) {
|
6822 | return qs;
|
6823 | }
|
6824 | let orderBy;
|
6825 | if (queryParams.index_ === PRIORITY_INDEX) {
|
6826 | orderBy = "$priority" ;
|
6827 | }
|
6828 | else if (queryParams.index_ === VALUE_INDEX) {
|
6829 | orderBy = "$value" ;
|
6830 | }
|
6831 | else if (queryParams.index_ === KEY_INDEX) {
|
6832 | orderBy = "$key" ;
|
6833 | }
|
6834 | else {
|
6835 | assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
|
6836 | orderBy = queryParams.index_.toString();
|
6837 | }
|
6838 | qs["orderBy" ] = stringify(orderBy);
|
6839 | if (queryParams.startSet_) {
|
6840 | qs["startAt" ] = stringify(queryParams.indexStartValue_);
|
6841 | if (queryParams.startNameSet_) {
|
6842 | qs["startAt" ] +=
|
6843 | ',' + stringify(queryParams.indexStartName_);
|
6844 | }
|
6845 | }
|
6846 | if (queryParams.endSet_) {
|
6847 | qs["endAt" ] = stringify(queryParams.indexEndValue_);
|
6848 | if (queryParams.endNameSet_) {
|
6849 | qs["endAt" ] +=
|
6850 | ',' + stringify(queryParams.indexEndName_);
|
6851 | }
|
6852 | }
|
6853 | if (queryParams.limitSet_) {
|
6854 | if (queryParams.isViewFromLeft()) {
|
6855 | qs["limitToFirst" ] = queryParams.limit_;
|
6856 | }
|
6857 | else {
|
6858 | qs["limitToLast" ] = queryParams.limit_;
|
6859 | }
|
6860 | }
|
6861 | return qs;
|
6862 | }
|
6863 | function queryParamsGetQueryObject(queryParams) {
|
6864 | const obj = {};
|
6865 | if (queryParams.startSet_) {
|
6866 | obj["sp" ] =
|
6867 | queryParams.indexStartValue_;
|
6868 | if (queryParams.startNameSet_) {
|
6869 | obj["sn" ] =
|
6870 | queryParams.indexStartName_;
|
6871 | }
|
6872 | }
|
6873 | if (queryParams.endSet_) {
|
6874 | obj["ep" ] = queryParams.indexEndValue_;
|
6875 | if (queryParams.endNameSet_) {
|
6876 | obj["en" ] = queryParams.indexEndName_;
|
6877 | }
|
6878 | }
|
6879 | if (queryParams.limitSet_) {
|
6880 | obj["l" ] = queryParams.limit_;
|
6881 | let viewFrom = queryParams.viewFrom_;
|
6882 | if (viewFrom === '') {
|
6883 | if (queryParams.isViewFromLeft()) {
|
6884 | viewFrom = "l" ;
|
6885 | }
|
6886 | else {
|
6887 | viewFrom = "r" ;
|
6888 | }
|
6889 | }
|
6890 | obj["vf" ] = viewFrom;
|
6891 | }
|
6892 |
|
6893 | if (queryParams.index_ !== PRIORITY_INDEX) {
|
6894 | obj["i" ] = queryParams.index_.toString();
|
6895 | }
|
6896 | return obj;
|
6897 | }
|
6898 |
|
6899 |
|
6900 |
|
6901 |
|
6902 |
|
6903 |
|
6904 |
|
6905 |
|
6906 |
|
6907 |
|
6908 |
|
6909 |
|
6910 |
|
6911 |
|
6912 |
|
6913 |
|
6914 |
|
6915 |
|
6916 |
|
6917 |
|
6918 |
|
6919 |
|
6920 | class ReadonlyRestClient extends ServerActions {
|
6921 | |
6922 |
|
6923 |
|
6924 |
|
6925 | constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
|
6926 | super();
|
6927 | this.repoInfo_ = repoInfo_;
|
6928 | this.onDataUpdate_ = onDataUpdate_;
|
6929 | this.authTokenProvider_ = authTokenProvider_;
|
6930 | this.appCheckTokenProvider_ = appCheckTokenProvider_;
|
6931 |
|
6932 | this.log_ = logWrapper('p:rest:');
|
6933 | |
6934 |
|
6935 |
|
6936 |
|
6937 | this.listens_ = {};
|
6938 | }
|
6939 | reportStats(stats) {
|
6940 | throw new Error('Method not implemented.');
|
6941 | }
|
6942 | static getListenId_(query, tag) {
|
6943 | if (tag !== undefined) {
|
6944 | return 'tag$' + tag;
|
6945 | }
|
6946 | else {
|
6947 | assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
|
6948 | return query._path.toString();
|
6949 | }
|
6950 | }
|
6951 |
|
6952 | listen(query, currentHashFn, tag, onComplete) {
|
6953 | const pathString = query._path.toString();
|
6954 | this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
|
6955 |
|
6956 | const listenId = ReadonlyRestClient.getListenId_(query, tag);
|
6957 | const thisListen = {};
|
6958 | this.listens_[listenId] = thisListen;
|
6959 | const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
|
6960 | this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
|
6961 | let data = result;
|
6962 | if (error === 404) {
|
6963 | data = null;
|
6964 | error = null;
|
6965 | }
|
6966 | if (error === null) {
|
6967 | this.onDataUpdate_(pathString, data, false, tag);
|
6968 | }
|
6969 | if (safeGet(this.listens_, listenId) === thisListen) {
|
6970 | let status;
|
6971 | if (!error) {
|
6972 | status = 'ok';
|
6973 | }
|
6974 | else if (error === 401) {
|
6975 | status = 'permission_denied';
|
6976 | }
|
6977 | else {
|
6978 | status = 'rest_error:' + error;
|
6979 | }
|
6980 | onComplete(status, null);
|
6981 | }
|
6982 | });
|
6983 | }
|
6984 |
|
6985 | unlisten(query, tag) {
|
6986 | const listenId = ReadonlyRestClient.getListenId_(query, tag);
|
6987 | delete this.listens_[listenId];
|
6988 | }
|
6989 | get(query) {
|
6990 | const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
|
6991 | const pathString = query._path.toString();
|
6992 | const deferred = new Deferred();
|
6993 | this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {
|
6994 | let data = result;
|
6995 | if (error === 404) {
|
6996 | data = null;
|
6997 | error = null;
|
6998 | }
|
6999 | if (error === null) {
|
7000 | this.onDataUpdate_(pathString, data,
|
7001 | false,
|
7002 | null);
|
7003 | deferred.resolve(data);
|
7004 | }
|
7005 | else {
|
7006 | deferred.reject(new Error(data));
|
7007 | }
|
7008 | });
|
7009 | return deferred.promise;
|
7010 | }
|
7011 |
|
7012 | refreshAuthToken(token) {
|
7013 |
|
7014 | }
|
7015 | |
7016 |
|
7017 |
|
7018 |
|
7019 | restRequest_(pathString, queryStringParameters = {}, callback) {
|
7020 | queryStringParameters['format'] = 'export';
|
7021 | return Promise.all([
|
7022 | this.authTokenProvider_.getToken( false),
|
7023 | this.appCheckTokenProvider_.getToken( false)
|
7024 | ]).then(([authToken, appCheckToken]) => {
|
7025 | if (authToken && authToken.accessToken) {
|
7026 | queryStringParameters['auth'] = authToken.accessToken;
|
7027 | }
|
7028 | if (appCheckToken && appCheckToken.token) {
|
7029 | queryStringParameters['ac'] = appCheckToken.token;
|
7030 | }
|
7031 | const url = (this.repoInfo_.secure ? 'https://' : 'http://') +
|
7032 | this.repoInfo_.host +
|
7033 | pathString +
|
7034 | '?' +
|
7035 | 'ns=' +
|
7036 | this.repoInfo_.namespace +
|
7037 | querystring(queryStringParameters);
|
7038 | this.log_('Sending REST request for ' + url);
|
7039 | const xhr = new XMLHttpRequest();
|
7040 | xhr.onreadystatechange = () => {
|
7041 | if (callback && xhr.readyState === 4) {
|
7042 | this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
|
7043 | let res = null;
|
7044 | if (xhr.status >= 200 && xhr.status < 300) {
|
7045 | try {
|
7046 | res = jsonEval(xhr.responseText);
|
7047 | }
|
7048 | catch (e) {
|
7049 | warn('Failed to parse JSON response for ' +
|
7050 | url +
|
7051 | ': ' +
|
7052 | xhr.responseText);
|
7053 | }
|
7054 | callback(null, res);
|
7055 | }
|
7056 | else {
|
7057 |
|
7058 | if (xhr.status !== 401 && xhr.status !== 404) {
|
7059 | warn('Got unsuccessful REST response for ' +
|
7060 | url +
|
7061 | ' Status: ' +
|
7062 | xhr.status);
|
7063 | }
|
7064 | callback(xhr.status);
|
7065 | }
|
7066 | callback = null;
|
7067 | }
|
7068 | };
|
7069 | xhr.open('GET', url, true);
|
7070 | xhr.send();
|
7071 | });
|
7072 | }
|
7073 | }
|
7074 |
|
7075 |
|
7076 |
|
7077 |
|
7078 |
|
7079 |
|
7080 |
|
7081 |
|
7082 |
|
7083 |
|
7084 |
|
7085 |
|
7086 |
|
7087 |
|
7088 |
|
7089 |
|
7090 |
|
7091 |
|
7092 |
|
7093 |
|
7094 | class SnapshotHolder {
|
7095 | constructor() {
|
7096 | this.rootNode_ = ChildrenNode.EMPTY_NODE;
|
7097 | }
|
7098 | getNode(path) {
|
7099 | return this.rootNode_.getChild(path);
|
7100 | }
|
7101 | updateSnapshot(path, newSnapshotNode) {
|
7102 | this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
|
7103 | }
|
7104 | }
|
7105 |
|
7106 |
|
7107 |
|
7108 |
|
7109 |
|
7110 |
|
7111 |
|
7112 |
|
7113 |
|
7114 |
|
7115 |
|
7116 |
|
7117 |
|
7118 |
|
7119 |
|
7120 |
|
7121 |
|
7122 | function newSparseSnapshotTree() {
|
7123 | return {
|
7124 | value: null,
|
7125 | children: new Map()
|
7126 | };
|
7127 | }
|
7128 |
|
7129 |
|
7130 |
|
7131 |
|
7132 |
|
7133 |
|
7134 |
|
7135 | function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
|
7136 | if (pathIsEmpty(path)) {
|
7137 | sparseSnapshotTree.value = data;
|
7138 | sparseSnapshotTree.children.clear();
|
7139 | }
|
7140 | else if (sparseSnapshotTree.value !== null) {
|
7141 | sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
|
7142 | }
|
7143 | else {
|
7144 | const childKey = pathGetFront(path);
|
7145 | if (!sparseSnapshotTree.children.has(childKey)) {
|
7146 | sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
|
7147 | }
|
7148 | const child = sparseSnapshotTree.children.get(childKey);
|
7149 | path = pathPopFront(path);
|
7150 | sparseSnapshotTreeRemember(child, path, data);
|
7151 | }
|
7152 | }
|
7153 |
|
7154 |
|
7155 |
|
7156 |
|
7157 |
|
7158 |
|
7159 | function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
|
7160 | if (pathIsEmpty(path)) {
|
7161 | sparseSnapshotTree.value = null;
|
7162 | sparseSnapshotTree.children.clear();
|
7163 | return true;
|
7164 | }
|
7165 | else {
|
7166 | if (sparseSnapshotTree.value !== null) {
|
7167 | if (sparseSnapshotTree.value.isLeafNode()) {
|
7168 |
|
7169 | return false;
|
7170 | }
|
7171 | else {
|
7172 | const value = sparseSnapshotTree.value;
|
7173 | sparseSnapshotTree.value = null;
|
7174 | value.forEachChild(PRIORITY_INDEX, (key, tree) => {
|
7175 | sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
|
7176 | });
|
7177 | return sparseSnapshotTreeForget(sparseSnapshotTree, path);
|
7178 | }
|
7179 | }
|
7180 | else if (sparseSnapshotTree.children.size > 0) {
|
7181 | const childKey = pathGetFront(path);
|
7182 | path = pathPopFront(path);
|
7183 | if (sparseSnapshotTree.children.has(childKey)) {
|
7184 | const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
|
7185 | if (safeToRemove) {
|
7186 | sparseSnapshotTree.children.delete(childKey);
|
7187 | }
|
7188 | }
|
7189 | return sparseSnapshotTree.children.size === 0;
|
7190 | }
|
7191 | else {
|
7192 | return true;
|
7193 | }
|
7194 | }
|
7195 | }
|
7196 |
|
7197 |
|
7198 |
|
7199 |
|
7200 |
|
7201 |
|
7202 |
|
7203 | function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
|
7204 | if (sparseSnapshotTree.value !== null) {
|
7205 | func(prefixPath, sparseSnapshotTree.value);
|
7206 | }
|
7207 | else {
|
7208 | sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
|
7209 | const path = new Path(prefixPath.toString() + '/' + key);
|
7210 | sparseSnapshotTreeForEachTree(tree, path, func);
|
7211 | });
|
7212 | }
|
7213 | }
|
7214 |
|
7215 |
|
7216 |
|
7217 |
|
7218 |
|
7219 |
|
7220 | function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
|
7221 | sparseSnapshotTree.children.forEach((tree, key) => {
|
7222 | func(key, tree);
|
7223 | });
|
7224 | }
|
7225 |
|
7226 |
|
7227 |
|
7228 |
|
7229 |
|
7230 |
|
7231 |
|
7232 |
|
7233 |
|
7234 |
|
7235 |
|
7236 |
|
7237 |
|
7238 |
|
7239 |
|
7240 |
|
7241 |
|
7242 |
|
7243 |
|
7244 |
|
7245 |
|
7246 |
|
7247 | class StatsListener {
|
7248 | constructor(collection_) {
|
7249 | this.collection_ = collection_;
|
7250 | this.last_ = null;
|
7251 | }
|
7252 | get() {
|
7253 | const newStats = this.collection_.get();
|
7254 | const delta = Object.assign({}, newStats);
|
7255 | if (this.last_) {
|
7256 | each(this.last_, (stat, value) => {
|
7257 | delta[stat] = delta[stat] - value;
|
7258 | });
|
7259 | }
|
7260 | this.last_ = newStats;
|
7261 | return delta;
|
7262 | }
|
7263 | }
|
7264 |
|
7265 |
|
7266 |
|
7267 |
|
7268 |
|
7269 |
|
7270 |
|
7271 |
|
7272 |
|
7273 |
|
7274 |
|
7275 |
|
7276 |
|
7277 |
|
7278 |
|
7279 |
|
7280 |
|
7281 |
|
7282 |
|
7283 |
|
7284 | const FIRST_STATS_MIN_TIME = 10 * 1000;
|
7285 | const FIRST_STATS_MAX_TIME = 30 * 1000;
|
7286 |
|
7287 | const REPORT_STATS_INTERVAL = 5 * 60 * 1000;
|
7288 | class StatsReporter {
|
7289 | constructor(collection, server_) {
|
7290 | this.server_ = server_;
|
7291 | this.statsToReport_ = {};
|
7292 | this.statsListener_ = new StatsListener(collection);
|
7293 | const timeout = FIRST_STATS_MIN_TIME +
|
7294 | (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
|
7295 | setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
|
7296 | }
|
7297 | reportStats_() {
|
7298 | const stats = this.statsListener_.get();
|
7299 | const reportedStats = {};
|
7300 | let haveStatsToReport = false;
|
7301 | each(stats, (stat, value) => {
|
7302 | if (value > 0 && contains(this.statsToReport_, stat)) {
|
7303 | reportedStats[stat] = value;
|
7304 | haveStatsToReport = true;
|
7305 | }
|
7306 | });
|
7307 | if (haveStatsToReport) {
|
7308 | this.server_.reportStats(reportedStats);
|
7309 | }
|
7310 |
|
7311 | setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
|
7312 | }
|
7313 | }
|
7314 |
|
7315 |
|
7316 |
|
7317 |
|
7318 |
|
7319 |
|
7320 |
|
7321 |
|
7322 |
|
7323 |
|
7324 |
|
7325 |
|
7326 |
|
7327 |
|
7328 |
|
7329 |
|
7330 |
|
7331 |
|
7332 |
|
7333 |
|
7334 |
|
7335 | var OperationType;
|
7336 | (function (OperationType) {
|
7337 | OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
|
7338 | OperationType[OperationType["MERGE"] = 1] = "MERGE";
|
7339 | OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
|
7340 | OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
|
7341 | })(OperationType || (OperationType = {}));
|
7342 | function newOperationSourceUser() {
|
7343 | return {
|
7344 | fromUser: true,
|
7345 | fromServer: false,
|
7346 | queryId: null,
|
7347 | tagged: false
|
7348 | };
|
7349 | }
|
7350 | function newOperationSourceServer() {
|
7351 | return {
|
7352 | fromUser: false,
|
7353 | fromServer: true,
|
7354 | queryId: null,
|
7355 | tagged: false
|
7356 | };
|
7357 | }
|
7358 | function newOperationSourceServerTaggedQuery(queryId) {
|
7359 | return {
|
7360 | fromUser: false,
|
7361 | fromServer: true,
|
7362 | queryId,
|
7363 | tagged: true
|
7364 | };
|
7365 | }
|
7366 |
|
7367 |
|
7368 |
|
7369 |
|
7370 |
|
7371 |
|
7372 |
|
7373 |
|
7374 |
|
7375 |
|
7376 |
|
7377 |
|
7378 |
|
7379 |
|
7380 |
|
7381 |
|
7382 |
|
7383 | class AckUserWrite {
|
7384 | |
7385 |
|
7386 |
|
7387 | constructor(
|
7388 | /** @inheritDoc */ path,
|
7389 | /** @inheritDoc */ affectedTree,
|
7390 | /** @inheritDoc */ revert) {
|
7391 | this.path = path;
|
7392 | this.affectedTree = affectedTree;
|
7393 | this.revert = revert;
|
7394 |
|
7395 | this.type = OperationType.ACK_USER_WRITE;
|
7396 |
|
7397 | this.source = newOperationSourceUser();
|
7398 | }
|
7399 | operationForChild(childName) {
|
7400 | if (!pathIsEmpty(this.path)) {
|
7401 | assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
|
7402 | return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
|
7403 | }
|
7404 | else if (this.affectedTree.value != null) {
|
7405 | assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
|
7406 |
|
7407 | return this;
|
7408 | }
|
7409 | else {
|
7410 | const childTree = this.affectedTree.subtree(new Path(childName));
|
7411 | return new AckUserWrite(newEmptyPath(), childTree, this.revert);
|
7412 | }
|
7413 | }
|
7414 | }
|
7415 |
|
7416 |
|
7417 |
|
7418 |
|
7419 |
|
7420 |
|
7421 |
|
7422 |
|
7423 |
|
7424 |
|
7425 |
|
7426 |
|
7427 |
|
7428 |
|
7429 |
|
7430 |
|
7431 |
|
7432 | class ListenComplete {
|
7433 | constructor(source, path) {
|
7434 | this.source = source;
|
7435 | this.path = path;
|
7436 |
|
7437 | this.type = OperationType.LISTEN_COMPLETE;
|
7438 | }
|
7439 | operationForChild(childName) {
|
7440 | if (pathIsEmpty(this.path)) {
|
7441 | return new ListenComplete(this.source, newEmptyPath());
|
7442 | }
|
7443 | else {
|
7444 | return new ListenComplete(this.source, pathPopFront(this.path));
|
7445 | }
|
7446 | }
|
7447 | }
|
7448 |
|
7449 |
|
7450 |
|
7451 |
|
7452 |
|
7453 |
|
7454 |
|
7455 |
|
7456 |
|
7457 |
|
7458 |
|
7459 |
|
7460 |
|
7461 |
|
7462 |
|
7463 |
|
7464 |
|
7465 | class Overwrite {
|
7466 | constructor(source, path, snap) {
|
7467 | this.source = source;
|
7468 | this.path = path;
|
7469 | this.snap = snap;
|
7470 |
|
7471 | this.type = OperationType.OVERWRITE;
|
7472 | }
|
7473 | operationForChild(childName) {
|
7474 | if (pathIsEmpty(this.path)) {
|
7475 | return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
|
7476 | }
|
7477 | else {
|
7478 | return new Overwrite(this.source, pathPopFront(this.path), this.snap);
|
7479 | }
|
7480 | }
|
7481 | }
|
7482 |
|
7483 |
|
7484 |
|
7485 |
|
7486 |
|
7487 |
|
7488 |
|
7489 |
|
7490 |
|
7491 |
|
7492 |
|
7493 |
|
7494 |
|
7495 |
|
7496 |
|
7497 |
|
7498 |
|
7499 | class Merge {
|
7500 | constructor(
|
7501 | /** @inheritDoc */ source,
|
7502 | /** @inheritDoc */ path,
|
7503 | /** @inheritDoc */ children) {
|
7504 | this.source = source;
|
7505 | this.path = path;
|
7506 | this.children = children;
|
7507 |
|
7508 | this.type = OperationType.MERGE;
|
7509 | }
|
7510 | operationForChild(childName) {
|
7511 | if (pathIsEmpty(this.path)) {
|
7512 | const childTree = this.children.subtree(new Path(childName));
|
7513 | if (childTree.isEmpty()) {
|
7514 |
|
7515 | return null;
|
7516 | }
|
7517 | else if (childTree.value) {
|
7518 |
|
7519 | return new Overwrite(this.source, newEmptyPath(), childTree.value);
|
7520 | }
|
7521 | else {
|
7522 |
|
7523 | return new Merge(this.source, newEmptyPath(), childTree);
|
7524 | }
|
7525 | }
|
7526 | else {
|
7527 | assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
|
7528 | return new Merge(this.source, pathPopFront(this.path), this.children);
|
7529 | }
|
7530 | }
|
7531 | toString() {
|
7532 | return ('Operation(' +
|
7533 | this.path +
|
7534 | ': ' +
|
7535 | this.source.toString() +
|
7536 | ' merge: ' +
|
7537 | this.children.toString() +
|
7538 | ')');
|
7539 | }
|
7540 | }
|
7541 |
|
7542 |
|
7543 |
|
7544 |
|
7545 |
|
7546 |
|
7547 |
|
7548 |
|
7549 |
|
7550 |
|
7551 |
|
7552 |
|
7553 |
|
7554 |
|
7555 |
|
7556 |
|
7557 |
|
7558 |
|
7559 |
|
7560 |
|
7561 |
|
7562 |
|
7563 |
|
7564 | class CacheNode {
|
7565 | constructor(node_, fullyInitialized_, filtered_) {
|
7566 | this.node_ = node_;
|
7567 | this.fullyInitialized_ = fullyInitialized_;
|
7568 | this.filtered_ = filtered_;
|
7569 | }
|
7570 | |
7571 |
|
7572 |
|
7573 | isFullyInitialized() {
|
7574 | return this.fullyInitialized_;
|
7575 | }
|
7576 | |
7577 |
|
7578 |
|
7579 | isFiltered() {
|
7580 | return this.filtered_;
|
7581 | }
|
7582 | isCompleteForPath(path) {
|
7583 | if (pathIsEmpty(path)) {
|
7584 | return this.isFullyInitialized() && !this.filtered_;
|
7585 | }
|
7586 | const childKey = pathGetFront(path);
|
7587 | return this.isCompleteForChild(childKey);
|
7588 | }
|
7589 | isCompleteForChild(key) {
|
7590 | return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
|
7591 | }
|
7592 | getNode() {
|
7593 | return this.node_;
|
7594 | }
|
7595 | }
|
7596 |
|
7597 |
|
7598 |
|
7599 |
|
7600 |
|
7601 |
|
7602 |
|
7603 |
|
7604 |
|
7605 |
|
7606 |
|
7607 |
|
7608 |
|
7609 |
|
7610 |
|
7611 |
|
7612 |
|
7613 |
|
7614 |
|
7615 |
|
7616 |
|
7617 |
|
7618 |
|
7619 | class EventGenerator {
|
7620 | constructor(query_) {
|
7621 | this.query_ = query_;
|
7622 | this.index_ = this.query_._queryParams.getIndex();
|
7623 | }
|
7624 | }
|
7625 |
|
7626 |
|
7627 |
|
7628 |
|
7629 |
|
7630 |
|
7631 |
|
7632 |
|
7633 |
|
7634 | function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
|
7635 | const events = [];
|
7636 | const moves = [];
|
7637 | changes.forEach(change => {
|
7638 | if (change.type === "child_changed" &&
|
7639 | eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
|
7640 | moves.push(changeChildMoved(change.childName, change.snapshotNode));
|
7641 | }
|
7642 | });
|
7643 | eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" , changes, eventRegistrations, eventCache);
|
7644 | eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" , changes, eventRegistrations, eventCache);
|
7645 | eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" , moves, eventRegistrations, eventCache);
|
7646 | eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" , changes, eventRegistrations, eventCache);
|
7647 | eventGeneratorGenerateEventsForType(eventGenerator, events, "value" , changes, eventRegistrations, eventCache);
|
7648 | return events;
|
7649 | }
|
7650 |
|
7651 |
|
7652 |
|
7653 | function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
|
7654 | const filteredChanges = changes.filter(change => change.type === eventType);
|
7655 | filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));
|
7656 | filteredChanges.forEach(change => {
|
7657 | const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
|
7658 | registrations.forEach(registration => {
|
7659 | if (registration.respondsTo(change.type)) {
|
7660 | events.push(registration.createEvent(materializedChange, eventGenerator.query_));
|
7661 | }
|
7662 | });
|
7663 | });
|
7664 | }
|
7665 | function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
|
7666 | if (change.type === 'value' || change.type === 'child_removed') {
|
7667 | return change;
|
7668 | }
|
7669 | else {
|
7670 | change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
|
7671 | return change;
|
7672 | }
|
7673 | }
|
7674 | function eventGeneratorCompareChanges(eventGenerator, a, b) {
|
7675 | if (a.childName == null || b.childName == null) {
|
7676 | throw assertionError('Should only compare child_ events.');
|
7677 | }
|
7678 | const aWrapped = new NamedNode(a.childName, a.snapshotNode);
|
7679 | const bWrapped = new NamedNode(b.childName, b.snapshotNode);
|
7680 | return eventGenerator.index_.compare(aWrapped, bWrapped);
|
7681 | }
|
7682 |
|
7683 |
|
7684 |
|
7685 |
|
7686 |
|
7687 |
|
7688 |
|
7689 |
|
7690 |
|
7691 |
|
7692 |
|
7693 |
|
7694 |
|
7695 |
|
7696 |
|
7697 |
|
7698 |
|
7699 | function newViewCache(eventCache, serverCache) {
|
7700 | return { eventCache, serverCache };
|
7701 | }
|
7702 | function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
|
7703 | return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
|
7704 | }
|
7705 | function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
|
7706 | return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
|
7707 | }
|
7708 | function viewCacheGetCompleteEventSnap(viewCache) {
|
7709 | return viewCache.eventCache.isFullyInitialized()
|
7710 | ? viewCache.eventCache.getNode()
|
7711 | : null;
|
7712 | }
|
7713 | function viewCacheGetCompleteServerSnap(viewCache) {
|
7714 | return viewCache.serverCache.isFullyInitialized()
|
7715 | ? viewCache.serverCache.getNode()
|
7716 | : null;
|
7717 | }
|
7718 |
|
7719 |
|
7720 |
|
7721 |
|
7722 |
|
7723 |
|
7724 |
|
7725 |
|
7726 |
|
7727 |
|
7728 |
|
7729 |
|
7730 |
|
7731 |
|
7732 |
|
7733 |
|
7734 |
|
7735 | let emptyChildrenSingleton;
|
7736 |
|
7737 |
|
7738 |
|
7739 |
|
7740 | const EmptyChildren = () => {
|
7741 | if (!emptyChildrenSingleton) {
|
7742 | emptyChildrenSingleton = new SortedMap(stringCompare);
|
7743 | }
|
7744 | return emptyChildrenSingleton;
|
7745 | };
|
7746 |
|
7747 |
|
7748 |
|
7749 | class ImmutableTree {
|
7750 | constructor(value, children = EmptyChildren()) {
|
7751 | this.value = value;
|
7752 | this.children = children;
|
7753 | }
|
7754 | static fromObject(obj) {
|
7755 | let tree = new ImmutableTree(null);
|
7756 | each(obj, (childPath, childSnap) => {
|
7757 | tree = tree.set(new Path(childPath), childSnap);
|
7758 | });
|
7759 | return tree;
|
7760 | }
|
7761 | |
7762 |
|
7763 |
|
7764 | isEmpty() {
|
7765 | return this.value === null && this.children.isEmpty();
|
7766 | }
|
7767 | |
7768 |
|
7769 |
|
7770 |
|
7771 |
|
7772 |
|
7773 |
|
7774 |
|
7775 |
|
7776 |
|
7777 | findRootMostMatchingPathAndValue(relativePath, predicate) {
|
7778 | if (this.value != null && predicate(this.value)) {
|
7779 | return { path: newEmptyPath(), value: this.value };
|
7780 | }
|
7781 | else {
|
7782 | if (pathIsEmpty(relativePath)) {
|
7783 | return null;
|
7784 | }
|
7785 | else {
|
7786 | const front = pathGetFront(relativePath);
|
7787 | const child = this.children.get(front);
|
7788 | if (child !== null) {
|
7789 | const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
|
7790 | if (childExistingPathAndValue != null) {
|
7791 | const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
|
7792 | return { path: fullPath, value: childExistingPathAndValue.value };
|
7793 | }
|
7794 | else {
|
7795 | return null;
|
7796 | }
|
7797 | }
|
7798 | else {
|
7799 | return null;
|
7800 | }
|
7801 | }
|
7802 | }
|
7803 | }
|
7804 | |
7805 |
|
7806 |
|
7807 |
|
7808 | findRootMostValueAndPath(relativePath) {
|
7809 | return this.findRootMostMatchingPathAndValue(relativePath, () => true);
|
7810 | }
|
7811 | |
7812 |
|
7813 |
|
7814 | subtree(relativePath) {
|
7815 | if (pathIsEmpty(relativePath)) {
|
7816 | return this;
|
7817 | }
|
7818 | else {
|
7819 | const front = pathGetFront(relativePath);
|
7820 | const childTree = this.children.get(front);
|
7821 | if (childTree !== null) {
|
7822 | return childTree.subtree(pathPopFront(relativePath));
|
7823 | }
|
7824 | else {
|
7825 | return new ImmutableTree(null);
|
7826 | }
|
7827 | }
|
7828 | }
|
7829 | |
7830 |
|
7831 |
|
7832 |
|
7833 |
|
7834 |
|
7835 |
|
7836 | set(relativePath, toSet) {
|
7837 | if (pathIsEmpty(relativePath)) {
|
7838 | return new ImmutableTree(toSet, this.children);
|
7839 | }
|
7840 | else {
|
7841 | const front = pathGetFront(relativePath);
|
7842 | const child = this.children.get(front) || new ImmutableTree(null);
|
7843 | const newChild = child.set(pathPopFront(relativePath), toSet);
|
7844 | const newChildren = this.children.insert(front, newChild);
|
7845 | return new ImmutableTree(this.value, newChildren);
|
7846 | }
|
7847 | }
|
7848 | |
7849 |
|
7850 |
|
7851 |
|
7852 |
|
7853 |
|
7854 | remove(relativePath) {
|
7855 | if (pathIsEmpty(relativePath)) {
|
7856 | if (this.children.isEmpty()) {
|
7857 | return new ImmutableTree(null);
|
7858 | }
|
7859 | else {
|
7860 | return new ImmutableTree(null, this.children);
|
7861 | }
|
7862 | }
|
7863 | else {
|
7864 | const front = pathGetFront(relativePath);
|
7865 | const child = this.children.get(front);
|
7866 | if (child) {
|
7867 | const newChild = child.remove(pathPopFront(relativePath));
|
7868 | let newChildren;
|
7869 | if (newChild.isEmpty()) {
|
7870 | newChildren = this.children.remove(front);
|
7871 | }
|
7872 | else {
|
7873 | newChildren = this.children.insert(front, newChild);
|
7874 | }
|
7875 | if (this.value === null && newChildren.isEmpty()) {
|
7876 | return new ImmutableTree(null);
|
7877 | }
|
7878 | else {
|
7879 | return new ImmutableTree(this.value, newChildren);
|
7880 | }
|
7881 | }
|
7882 | else {
|
7883 | return this;
|
7884 | }
|
7885 | }
|
7886 | }
|
7887 | |
7888 |
|
7889 |
|
7890 |
|
7891 |
|
7892 |
|
7893 | get(relativePath) {
|
7894 | if (pathIsEmpty(relativePath)) {
|
7895 | return this.value;
|
7896 | }
|
7897 | else {
|
7898 | const front = pathGetFront(relativePath);
|
7899 | const child = this.children.get(front);
|
7900 | if (child) {
|
7901 | return child.get(pathPopFront(relativePath));
|
7902 | }
|
7903 | else {
|
7904 | return null;
|
7905 | }
|
7906 | }
|
7907 | }
|
7908 | |
7909 |
|
7910 |
|
7911 |
|
7912 |
|
7913 |
|
7914 |
|
7915 | setTree(relativePath, newTree) {
|
7916 | if (pathIsEmpty(relativePath)) {
|
7917 | return newTree;
|
7918 | }
|
7919 | else {
|
7920 | const front = pathGetFront(relativePath);
|
7921 | const child = this.children.get(front) || new ImmutableTree(null);
|
7922 | const newChild = child.setTree(pathPopFront(relativePath), newTree);
|
7923 | let newChildren;
|
7924 | if (newChild.isEmpty()) {
|
7925 | newChildren = this.children.remove(front);
|
7926 | }
|
7927 | else {
|
7928 | newChildren = this.children.insert(front, newChild);
|
7929 | }
|
7930 | return new ImmutableTree(this.value, newChildren);
|
7931 | }
|
7932 | }
|
7933 | |
7934 |
|
7935 |
|
7936 |
|
7937 |
|
7938 | fold(fn) {
|
7939 | return this.fold_(newEmptyPath(), fn);
|
7940 | }
|
7941 | |
7942 |
|
7943 |
|
7944 | fold_(pathSoFar, fn) {
|
7945 | const accum = {};
|
7946 | this.children.inorderTraversal((childKey, childTree) => {
|
7947 | accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
|
7948 | });
|
7949 | return fn(pathSoFar, this.value, accum);
|
7950 | }
|
7951 | |
7952 |
|
7953 |
|
7954 | findOnPath(path, f) {
|
7955 | return this.findOnPath_(path, newEmptyPath(), f);
|
7956 | }
|
7957 | findOnPath_(pathToFollow, pathSoFar, f) {
|
7958 | const result = this.value ? f(pathSoFar, this.value) : false;
|
7959 | if (result) {
|
7960 | return result;
|
7961 | }
|
7962 | else {
|
7963 | if (pathIsEmpty(pathToFollow)) {
|
7964 | return null;
|
7965 | }
|
7966 | else {
|
7967 | const front = pathGetFront(pathToFollow);
|
7968 | const nextChild = this.children.get(front);
|
7969 | if (nextChild) {
|
7970 | return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
|
7971 | }
|
7972 | else {
|
7973 | return null;
|
7974 | }
|
7975 | }
|
7976 | }
|
7977 | }
|
7978 | foreachOnPath(path, f) {
|
7979 | return this.foreachOnPath_(path, newEmptyPath(), f);
|
7980 | }
|
7981 | foreachOnPath_(pathToFollow, currentRelativePath, f) {
|
7982 | if (pathIsEmpty(pathToFollow)) {
|
7983 | return this;
|
7984 | }
|
7985 | else {
|
7986 | if (this.value) {
|
7987 | f(currentRelativePath, this.value);
|
7988 | }
|
7989 | const front = pathGetFront(pathToFollow);
|
7990 | const nextChild = this.children.get(front);
|
7991 | if (nextChild) {
|
7992 | return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
|
7993 | }
|
7994 | else {
|
7995 | return new ImmutableTree(null);
|
7996 | }
|
7997 | }
|
7998 | }
|
7999 | |
8000 |
|
8001 |
|
8002 |
|
8003 |
|
8004 |
|
8005 | foreach(f) {
|
8006 | this.foreach_(newEmptyPath(), f);
|
8007 | }
|
8008 | foreach_(currentRelativePath, f) {
|
8009 | this.children.inorderTraversal((childName, childTree) => {
|
8010 | childTree.foreach_(pathChild(currentRelativePath, childName), f);
|
8011 | });
|
8012 | if (this.value) {
|
8013 | f(currentRelativePath, this.value);
|
8014 | }
|
8015 | }
|
8016 | foreachChild(f) {
|
8017 | this.children.inorderTraversal((childName, childTree) => {
|
8018 | if (childTree.value) {
|
8019 | f(childName, childTree.value);
|
8020 | }
|
8021 | });
|
8022 | }
|
8023 | }
|
8024 |
|
8025 |
|
8026 |
|
8027 |
|
8028 |
|
8029 |
|
8030 |
|
8031 |
|
8032 |
|
8033 |
|
8034 |
|
8035 |
|
8036 |
|
8037 |
|
8038 |
|
8039 |
|
8040 |
|
8041 |
|
8042 |
|
8043 |
|
8044 |
|
8045 |
|
8046 |
|
8047 | class CompoundWrite {
|
8048 | constructor(writeTree_) {
|
8049 | this.writeTree_ = writeTree_;
|
8050 | }
|
8051 | static empty() {
|
8052 | return new CompoundWrite(new ImmutableTree(null));
|
8053 | }
|
8054 | }
|
8055 | function compoundWriteAddWrite(compoundWrite, path, node) {
|
8056 | if (pathIsEmpty(path)) {
|
8057 | return new CompoundWrite(new ImmutableTree(node));
|
8058 | }
|
8059 | else {
|
8060 | const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
|
8061 | if (rootmost != null) {
|
8062 | const rootMostPath = rootmost.path;
|
8063 | let value = rootmost.value;
|
8064 | const relativePath = newRelativePath(rootMostPath, path);
|
8065 | value = value.updateChild(relativePath, node);
|
8066 | return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
|
8067 | }
|
8068 | else {
|
8069 | const subtree = new ImmutableTree(node);
|
8070 | const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
|
8071 | return new CompoundWrite(newWriteTree);
|
8072 | }
|
8073 | }
|
8074 | }
|
8075 | function compoundWriteAddWrites(compoundWrite, path, updates) {
|
8076 | let newWrite = compoundWrite;
|
8077 | each(updates, (childKey, node) => {
|
8078 | newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
|
8079 | });
|
8080 | return newWrite;
|
8081 | }
|
8082 |
|
8083 |
|
8084 |
|
8085 |
|
8086 |
|
8087 |
|
8088 |
|
8089 |
|
8090 | function compoundWriteRemoveWrite(compoundWrite, path) {
|
8091 | if (pathIsEmpty(path)) {
|
8092 | return CompoundWrite.empty();
|
8093 | }
|
8094 | else {
|
8095 | const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
|
8096 | return new CompoundWrite(newWriteTree);
|
8097 | }
|
8098 | }
|
8099 |
|
8100 |
|
8101 |
|
8102 |
|
8103 |
|
8104 |
|
8105 |
|
8106 |
|
8107 | function compoundWriteHasCompleteWrite(compoundWrite, path) {
|
8108 | return compoundWriteGetCompleteNode(compoundWrite, path) != null;
|
8109 | }
|
8110 |
|
8111 |
|
8112 |
|
8113 |
|
8114 |
|
8115 |
|
8116 |
|
8117 |
|
8118 | function compoundWriteGetCompleteNode(compoundWrite, path) {
|
8119 | const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
|
8120 | if (rootmost != null) {
|
8121 | return compoundWrite.writeTree_
|
8122 | .get(rootmost.path)
|
8123 | .getChild(newRelativePath(rootmost.path, path));
|
8124 | }
|
8125 | else {
|
8126 | return null;
|
8127 | }
|
8128 | }
|
8129 |
|
8130 |
|
8131 |
|
8132 |
|
8133 |
|
8134 |
|
8135 | function compoundWriteGetCompleteChildren(compoundWrite) {
|
8136 | const children = [];
|
8137 | const node = compoundWrite.writeTree_.value;
|
8138 | if (node != null) {
|
8139 |
|
8140 | if (!node.isLeafNode()) {
|
8141 | node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
|
8142 | children.push(new NamedNode(childName, childNode));
|
8143 | });
|
8144 | }
|
8145 | }
|
8146 | else {
|
8147 | compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
|
8148 | if (childTree.value != null) {
|
8149 | children.push(new NamedNode(childName, childTree.value));
|
8150 | }
|
8151 | });
|
8152 | }
|
8153 | return children;
|
8154 | }
|
8155 | function compoundWriteChildCompoundWrite(compoundWrite, path) {
|
8156 | if (pathIsEmpty(path)) {
|
8157 | return compoundWrite;
|
8158 | }
|
8159 | else {
|
8160 | const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
|
8161 | if (shadowingNode != null) {
|
8162 | return new CompoundWrite(new ImmutableTree(shadowingNode));
|
8163 | }
|
8164 | else {
|
8165 | return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
|
8166 | }
|
8167 | }
|
8168 | }
|
8169 |
|
8170 |
|
8171 |
|
8172 |
|
8173 | function compoundWriteIsEmpty(compoundWrite) {
|
8174 | return compoundWrite.writeTree_.isEmpty();
|
8175 | }
|
8176 |
|
8177 |
|
8178 |
|
8179 |
|
8180 |
|
8181 |
|
8182 | function compoundWriteApply(compoundWrite, node) {
|
8183 | return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
|
8184 | }
|
8185 | function applySubtreeWrite(relativePath, writeTree, node) {
|
8186 | if (writeTree.value != null) {
|
8187 |
|
8188 | return node.updateChild(relativePath, writeTree.value);
|
8189 | }
|
8190 | else {
|
8191 | let priorityWrite = null;
|
8192 | writeTree.children.inorderTraversal((childKey, childTree) => {
|
8193 | if (childKey === '.priority') {
|
8194 |
|
8195 |
|
8196 | assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
|
8197 | priorityWrite = childTree.value;
|
8198 | }
|
8199 | else {
|
8200 | node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
|
8201 | }
|
8202 | });
|
8203 |
|
8204 | if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
|
8205 | node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);
|
8206 | }
|
8207 | return node;
|
8208 | }
|
8209 | }
|
8210 |
|
8211 |
|
8212 |
|
8213 |
|
8214 |
|
8215 |
|
8216 |
|
8217 |
|
8218 |
|
8219 |
|
8220 |
|
8221 |
|
8222 |
|
8223 |
|
8224 |
|
8225 |
|
8226 |
|
8227 |
|
8228 |
|
8229 |
|
8230 |
|
8231 | function writeTreeChildWrites(writeTree, path) {
|
8232 | return newWriteTreeRef(path, writeTree);
|
8233 | }
|
8234 |
|
8235 |
|
8236 |
|
8237 |
|
8238 |
|
8239 | function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
|
8240 | assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
|
8241 | if (visible === undefined) {
|
8242 | visible = true;
|
8243 | }
|
8244 | writeTree.allWrites.push({
|
8245 | path,
|
8246 | snap,
|
8247 | writeId,
|
8248 | visible
|
8249 | });
|
8250 | if (visible) {
|
8251 | writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
|
8252 | }
|
8253 | writeTree.lastWriteId = writeId;
|
8254 | }
|
8255 |
|
8256 |
|
8257 |
|
8258 | function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
|
8259 | assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
|
8260 | writeTree.allWrites.push({
|
8261 | path,
|
8262 | children: changedChildren,
|
8263 | writeId,
|
8264 | visible: true
|
8265 | });
|
8266 | writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
|
8267 | writeTree.lastWriteId = writeId;
|
8268 | }
|
8269 | function writeTreeGetWrite(writeTree, writeId) {
|
8270 | for (let i = 0; i < writeTree.allWrites.length; i++) {
|
8271 | const record = writeTree.allWrites[i];
|
8272 | if (record.writeId === writeId) {
|
8273 | return record;
|
8274 | }
|
8275 | }
|
8276 | return null;
|
8277 | }
|
8278 |
|
8279 |
|
8280 |
|
8281 |
|
8282 |
|
8283 |
|
8284 |
|
8285 | function writeTreeRemoveWrite(writeTree, writeId) {
|
8286 |
|
8287 |
|
8288 |
|
8289 |
|
8290 | const idx = writeTree.allWrites.findIndex(s => {
|
8291 | return s.writeId === writeId;
|
8292 | });
|
8293 | assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
|
8294 | const writeToRemove = writeTree.allWrites[idx];
|
8295 | writeTree.allWrites.splice(idx, 1);
|
8296 | let removedWriteWasVisible = writeToRemove.visible;
|
8297 | let removedWriteOverlapsWithOtherWrites = false;
|
8298 | let i = writeTree.allWrites.length - 1;
|
8299 | while (removedWriteWasVisible && i >= 0) {
|
8300 | const currentWrite = writeTree.allWrites[i];
|
8301 | if (currentWrite.visible) {
|
8302 | if (i >= idx &&
|
8303 | writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
|
8304 |
|
8305 | removedWriteWasVisible = false;
|
8306 | }
|
8307 | else if (pathContains(writeToRemove.path, currentWrite.path)) {
|
8308 |
|
8309 | removedWriteOverlapsWithOtherWrites = true;
|
8310 | }
|
8311 | }
|
8312 | i--;
|
8313 | }
|
8314 | if (!removedWriteWasVisible) {
|
8315 | return false;
|
8316 | }
|
8317 | else if (removedWriteOverlapsWithOtherWrites) {
|
8318 |
|
8319 | writeTreeResetTree_(writeTree);
|
8320 | return true;
|
8321 | }
|
8322 | else {
|
8323 |
|
8324 | if (writeToRemove.snap) {
|
8325 | writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
|
8326 | }
|
8327 | else {
|
8328 | const children = writeToRemove.children;
|
8329 | each(children, (childName) => {
|
8330 | writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
|
8331 | });
|
8332 | }
|
8333 | return true;
|
8334 | }
|
8335 | }
|
8336 | function writeTreeRecordContainsPath_(writeRecord, path) {
|
8337 | if (writeRecord.snap) {
|
8338 | return pathContains(writeRecord.path, path);
|
8339 | }
|
8340 | else {
|
8341 | for (const childName in writeRecord.children) {
|
8342 | if (writeRecord.children.hasOwnProperty(childName) &&
|
8343 | pathContains(pathChild(writeRecord.path, childName), path)) {
|
8344 | return true;
|
8345 | }
|
8346 | }
|
8347 | return false;
|
8348 | }
|
8349 | }
|
8350 |
|
8351 |
|
8352 |
|
8353 | function writeTreeResetTree_(writeTree) {
|
8354 | writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
|
8355 | if (writeTree.allWrites.length > 0) {
|
8356 | writeTree.lastWriteId =
|
8357 | writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
|
8358 | }
|
8359 | else {
|
8360 | writeTree.lastWriteId = -1;
|
8361 | }
|
8362 | }
|
8363 |
|
8364 |
|
8365 |
|
8366 | function writeTreeDefaultFilter_(write) {
|
8367 | return write.visible;
|
8368 | }
|
8369 |
|
8370 |
|
8371 |
|
8372 |
|
8373 | function writeTreeLayerTree_(writes, filter, treeRoot) {
|
8374 | let compoundWrite = CompoundWrite.empty();
|
8375 | for (let i = 0; i < writes.length; ++i) {
|
8376 | const write = writes[i];
|
8377 |
|
8378 |
|
8379 |
|
8380 | if (filter(write)) {
|
8381 | const writePath = write.path;
|
8382 | let relativePath;
|
8383 | if (write.snap) {
|
8384 | if (pathContains(treeRoot, writePath)) {
|
8385 | relativePath = newRelativePath(treeRoot, writePath);
|
8386 | compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
|
8387 | }
|
8388 | else if (pathContains(writePath, treeRoot)) {
|
8389 | relativePath = newRelativePath(writePath, treeRoot);
|
8390 | compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
|
8391 | }
|
8392 | else ;
|
8393 | }
|
8394 | else if (write.children) {
|
8395 | if (pathContains(treeRoot, writePath)) {
|
8396 | relativePath = newRelativePath(treeRoot, writePath);
|
8397 | compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
|
8398 | }
|
8399 | else if (pathContains(writePath, treeRoot)) {
|
8400 | relativePath = newRelativePath(writePath, treeRoot);
|
8401 | if (pathIsEmpty(relativePath)) {
|
8402 | compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
|
8403 | }
|
8404 | else {
|
8405 | const child = safeGet(write.children, pathGetFront(relativePath));
|
8406 | if (child) {
|
8407 |
|
8408 | const deepNode = child.getChild(pathPopFront(relativePath));
|
8409 | compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
|
8410 | }
|
8411 | }
|
8412 | }
|
8413 | else ;
|
8414 | }
|
8415 | else {
|
8416 | throw assertionError('WriteRecord should have .snap or .children');
|
8417 | }
|
8418 | }
|
8419 | }
|
8420 | return compoundWrite;
|
8421 | }
|
8422 |
|
8423 |
|
8424 |
|
8425 |
|
8426 |
|
8427 |
|
8428 |
|
8429 | function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
|
8430 | if (!writeIdsToExclude && !includeHiddenWrites) {
|
8431 | const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
|
8432 | if (shadowingNode != null) {
|
8433 | return shadowingNode;
|
8434 | }
|
8435 | else {
|
8436 | const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8437 | if (compoundWriteIsEmpty(subMerge)) {
|
8438 | return completeServerCache;
|
8439 | }
|
8440 | else if (completeServerCache == null &&
|
8441 | !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
|
8442 |
|
8443 | return null;
|
8444 | }
|
8445 | else {
|
8446 | const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
|
8447 | return compoundWriteApply(subMerge, layeredCache);
|
8448 | }
|
8449 | }
|
8450 | }
|
8451 | else {
|
8452 | const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8453 | if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
|
8454 | return completeServerCache;
|
8455 | }
|
8456 | else {
|
8457 |
|
8458 | if (!includeHiddenWrites &&
|
8459 | completeServerCache == null &&
|
8460 | !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
|
8461 | return null;
|
8462 | }
|
8463 | else {
|
8464 | const filter = function (write) {
|
8465 | return ((write.visible || includeHiddenWrites) &&
|
8466 | (!writeIdsToExclude ||
|
8467 | !~writeIdsToExclude.indexOf(write.writeId)) &&
|
8468 | (pathContains(write.path, treePath) ||
|
8469 | pathContains(treePath, write.path)));
|
8470 | };
|
8471 | const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
|
8472 | const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
|
8473 | return compoundWriteApply(mergeAtPath, layeredCache);
|
8474 | }
|
8475 | }
|
8476 | }
|
8477 | }
|
8478 |
|
8479 |
|
8480 |
|
8481 |
|
8482 | function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
|
8483 | let completeChildren = ChildrenNode.EMPTY_NODE;
|
8484 | const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
|
8485 | if (topLevelSet) {
|
8486 | if (!topLevelSet.isLeafNode()) {
|
8487 |
|
8488 | topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
|
8489 | completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
|
8490 | });
|
8491 | }
|
8492 | return completeChildren;
|
8493 | }
|
8494 | else if (completeServerChildren) {
|
8495 |
|
8496 |
|
8497 | const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8498 | completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
|
8499 | const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
|
8500 | completeChildren = completeChildren.updateImmediateChild(childName, node);
|
8501 | });
|
8502 |
|
8503 | compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
|
8504 | completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
|
8505 | });
|
8506 | return completeChildren;
|
8507 | }
|
8508 | else {
|
8509 |
|
8510 |
|
8511 | const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8512 | compoundWriteGetCompleteChildren(merge).forEach(namedNode => {
|
8513 | completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
|
8514 | });
|
8515 | return completeChildren;
|
8516 | }
|
8517 | }
|
8518 |
|
8519 |
|
8520 |
|
8521 |
|
8522 |
|
8523 |
|
8524 |
|
8525 |
|
8526 |
|
8527 |
|
8528 |
|
8529 |
|
8530 |
|
8531 |
|
8532 | function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
|
8533 | assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
|
8534 | const path = pathChild(treePath, childPath);
|
8535 | if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
|
8536 |
|
8537 |
|
8538 | return null;
|
8539 | }
|
8540 | else {
|
8541 |
|
8542 | const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
|
8543 | if (compoundWriteIsEmpty(childMerge)) {
|
8544 |
|
8545 | return existingServerSnap.getChild(childPath);
|
8546 | }
|
8547 | else {
|
8548 |
|
8549 |
|
8550 |
|
8551 |
|
8552 |
|
8553 |
|
8554 | return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
|
8555 | }
|
8556 | }
|
8557 | }
|
8558 |
|
8559 |
|
8560 |
|
8561 |
|
8562 | function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
|
8563 | const path = pathChild(treePath, childKey);
|
8564 | const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
|
8565 | if (shadowingNode != null) {
|
8566 | return shadowingNode;
|
8567 | }
|
8568 | else {
|
8569 | if (existingServerSnap.isCompleteForChild(childKey)) {
|
8570 | const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
|
8571 | return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
|
8572 | }
|
8573 | else {
|
8574 | return null;
|
8575 | }
|
8576 | }
|
8577 | }
|
8578 |
|
8579 |
|
8580 |
|
8581 |
|
8582 |
|
8583 | function writeTreeShadowingWrite(writeTree, path) {
|
8584 | return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
|
8585 | }
|
8586 |
|
8587 |
|
8588 |
|
8589 |
|
8590 | function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
|
8591 | let toIterate;
|
8592 | const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8593 | const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
|
8594 | if (shadowingNode != null) {
|
8595 | toIterate = shadowingNode;
|
8596 | }
|
8597 | else if (completeServerData != null) {
|
8598 | toIterate = compoundWriteApply(merge, completeServerData);
|
8599 | }
|
8600 | else {
|
8601 |
|
8602 | return [];
|
8603 | }
|
8604 | toIterate = toIterate.withIndex(index);
|
8605 | if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
|
8606 | const nodes = [];
|
8607 | const cmp = index.getCompare();
|
8608 | const iter = reverse
|
8609 | ? toIterate.getReverseIteratorFrom(startPost, index)
|
8610 | : toIterate.getIteratorFrom(startPost, index);
|
8611 | let next = iter.getNext();
|
8612 | while (next && nodes.length < count) {
|
8613 | if (cmp(next, startPost) !== 0) {
|
8614 | nodes.push(next);
|
8615 | }
|
8616 | next = iter.getNext();
|
8617 | }
|
8618 | return nodes;
|
8619 | }
|
8620 | else {
|
8621 | return [];
|
8622 | }
|
8623 | }
|
8624 | function newWriteTree() {
|
8625 | return {
|
8626 | visibleWrites: CompoundWrite.empty(),
|
8627 | allWrites: [],
|
8628 | lastWriteId: -1
|
8629 | };
|
8630 | }
|
8631 |
|
8632 |
|
8633 |
|
8634 |
|
8635 |
|
8636 |
|
8637 |
|
8638 |
|
8639 | function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
|
8640 | return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
|
8641 | }
|
8642 |
|
8643 |
|
8644 |
|
8645 |
|
8646 |
|
8647 | function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
|
8648 | return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
|
8649 | }
|
8650 |
|
8651 |
|
8652 |
|
8653 |
|
8654 |
|
8655 |
|
8656 |
|
8657 |
|
8658 |
|
8659 |
|
8660 |
|
8661 |
|
8662 |
|
8663 |
|
8664 |
|
8665 |
|
8666 | function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
|
8667 | return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
|
8668 | }
|
8669 |
|
8670 |
|
8671 |
|
8672 |
|
8673 |
|
8674 |
|
8675 | function writeTreeRefShadowingWrite(writeTreeRef, path) {
|
8676 | return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
|
8677 | }
|
8678 |
|
8679 |
|
8680 |
|
8681 |
|
8682 | function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
|
8683 | return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
|
8684 | }
|
8685 |
|
8686 |
|
8687 |
|
8688 |
|
8689 | function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
|
8690 | return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
|
8691 | }
|
8692 |
|
8693 |
|
8694 |
|
8695 | function writeTreeRefChild(writeTreeRef, childName) {
|
8696 | return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
|
8697 | }
|
8698 | function newWriteTreeRef(path, writeTree) {
|
8699 | return {
|
8700 | treePath: path,
|
8701 | writeTree
|
8702 | };
|
8703 | }
|
8704 |
|
8705 |
|
8706 |
|
8707 |
|
8708 |
|
8709 |
|
8710 |
|
8711 |
|
8712 |
|
8713 |
|
8714 |
|
8715 |
|
8716 |
|
8717 |
|
8718 |
|
8719 |
|
8720 |
|
8721 | class ChildChangeAccumulator {
|
8722 | constructor() {
|
8723 | this.changeMap = new Map();
|
8724 | }
|
8725 | trackChildChange(change) {
|
8726 | const type = change.type;
|
8727 | const childKey = change.childName;
|
8728 | assert(type === "child_added" ||
|
8729 | type === "child_changed" ||
|
8730 | type === "child_removed" , 'Only child changes supported for tracking');
|
8731 | assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
|
8732 | const oldChange = this.changeMap.get(childKey);
|
8733 | if (oldChange) {
|
8734 | const oldType = oldChange.type;
|
8735 | if (type === "child_added" &&
|
8736 | oldType === "child_removed" ) {
|
8737 | this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
|
8738 | }
|
8739 | else if (type === "child_removed" &&
|
8740 | oldType === "child_added" ) {
|
8741 | this.changeMap.delete(childKey);
|
8742 | }
|
8743 | else if (type === "child_removed" &&
|
8744 | oldType === "child_changed" ) {
|
8745 | this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
|
8746 | }
|
8747 | else if (type === "child_changed" &&
|
8748 | oldType === "child_added" ) {
|
8749 | this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
|
8750 | }
|
8751 | else if (type === "child_changed" &&
|
8752 | oldType === "child_changed" ) {
|
8753 | this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
|
8754 | }
|
8755 | else {
|
8756 | throw assertionError('Illegal combination of changes: ' +
|
8757 | change +
|
8758 | ' occurred after ' +
|
8759 | oldChange);
|
8760 | }
|
8761 | }
|
8762 | else {
|
8763 | this.changeMap.set(childKey, change);
|
8764 | }
|
8765 | }
|
8766 | getChanges() {
|
8767 | return Array.from(this.changeMap.values());
|
8768 | }
|
8769 | }
|
8770 |
|
8771 |
|
8772 |
|
8773 |
|
8774 |
|
8775 |
|
8776 |
|
8777 |
|
8778 |
|
8779 |
|
8780 |
|
8781 |
|
8782 |
|
8783 |
|
8784 |
|
8785 |
|
8786 |
|
8787 |
|
8788 |
|
8789 |
|
8790 |
|
8791 | class NoCompleteChildSource_ {
|
8792 | getCompleteChild(childKey) {
|
8793 | return null;
|
8794 | }
|
8795 | getChildAfterChild(index, child, reverse) {
|
8796 | return null;
|
8797 | }
|
8798 | }
|
8799 |
|
8800 |
|
8801 |
|
8802 | const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
|
8803 |
|
8804 |
|
8805 |
|
8806 |
|
8807 | class WriteTreeCompleteChildSource {
|
8808 | constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
|
8809 | this.writes_ = writes_;
|
8810 | this.viewCache_ = viewCache_;
|
8811 | this.optCompleteServerCache_ = optCompleteServerCache_;
|
8812 | }
|
8813 | getCompleteChild(childKey) {
|
8814 | const node = this.viewCache_.eventCache;
|
8815 | if (node.isCompleteForChild(childKey)) {
|
8816 | return node.getNode().getImmediateChild(childKey);
|
8817 | }
|
8818 | else {
|
8819 | const serverNode = this.optCompleteServerCache_ != null
|
8820 | ? new CacheNode(this.optCompleteServerCache_, true, false)
|
8821 | : this.viewCache_.serverCache;
|
8822 | return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
|
8823 | }
|
8824 | }
|
8825 | getChildAfterChild(index, child, reverse) {
|
8826 | const completeServerData = this.optCompleteServerCache_ != null
|
8827 | ? this.optCompleteServerCache_
|
8828 | : viewCacheGetCompleteServerSnap(this.viewCache_);
|
8829 | const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
|
8830 | if (nodes.length === 0) {
|
8831 | return null;
|
8832 | }
|
8833 | else {
|
8834 | return nodes[0];
|
8835 | }
|
8836 | }
|
8837 | }
|
8838 |
|
8839 |
|
8840 |
|
8841 |
|
8842 |
|
8843 |
|
8844 |
|
8845 |
|
8846 |
|
8847 |
|
8848 |
|
8849 |
|
8850 |
|
8851 |
|
8852 |
|
8853 |
|
8854 |
|
8855 | function newViewProcessor(filter) {
|
8856 | return { filter };
|
8857 | }
|
8858 | function viewProcessorAssertIndexed(viewProcessor, viewCache) {
|
8859 | assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
|
8860 | assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
|
8861 | }
|
8862 | function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
|
8863 | const accumulator = new ChildChangeAccumulator();
|
8864 | let newViewCache, filterServerNode;
|
8865 | if (operation.type === OperationType.OVERWRITE) {
|
8866 | const overwrite = operation;
|
8867 | if (overwrite.source.fromUser) {
|
8868 | newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
|
8869 | }
|
8870 | else {
|
8871 | assert(overwrite.source.fromServer, 'Unknown source.');
|
8872 |
|
8873 |
|
8874 |
|
8875 | filterServerNode =
|
8876 | overwrite.source.tagged ||
|
8877 | (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
|
8878 | newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
|
8879 | }
|
8880 | }
|
8881 | else if (operation.type === OperationType.MERGE) {
|
8882 | const merge = operation;
|
8883 | if (merge.source.fromUser) {
|
8884 | newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
|
8885 | }
|
8886 | else {
|
8887 | assert(merge.source.fromServer, 'Unknown source.');
|
8888 |
|
8889 | filterServerNode =
|
8890 | merge.source.tagged || oldViewCache.serverCache.isFiltered();
|
8891 | newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
|
8892 | }
|
8893 | }
|
8894 | else if (operation.type === OperationType.ACK_USER_WRITE) {
|
8895 | const ackUserWrite = operation;
|
8896 | if (!ackUserWrite.revert) {
|
8897 | newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
|
8898 | }
|
8899 | else {
|
8900 | newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
|
8901 | }
|
8902 | }
|
8903 | else if (operation.type === OperationType.LISTEN_COMPLETE) {
|
8904 | newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
|
8905 | }
|
8906 | else {
|
8907 | throw assertionError('Unknown operation type: ' + operation.type);
|
8908 | }
|
8909 | const changes = accumulator.getChanges();
|
8910 | viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
|
8911 | return { viewCache: newViewCache, changes };
|
8912 | }
|
8913 | function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
|
8914 | const eventSnap = newViewCache.eventCache;
|
8915 | if (eventSnap.isFullyInitialized()) {
|
8916 | const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
|
8917 | const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
|
8918 | if (accumulator.length > 0 ||
|
8919 | !oldViewCache.eventCache.isFullyInitialized() ||
|
8920 | (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
|
8921 | !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
|
8922 | accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
|
8923 | }
|
8924 | }
|
8925 | }
|
8926 | function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
|
8927 | const oldEventSnap = viewCache.eventCache;
|
8928 | if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
|
8929 |
|
8930 | return viewCache;
|
8931 | }
|
8932 | else {
|
8933 | let newEventCache, serverNode;
|
8934 | if (pathIsEmpty(changePath)) {
|
8935 |
|
8936 | assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
|
8937 | if (viewCache.serverCache.isFiltered()) {
|
8938 |
|
8939 |
|
8940 |
|
8941 | const serverCache = viewCacheGetCompleteServerSnap(viewCache);
|
8942 | const completeChildren = serverCache instanceof ChildrenNode
|
8943 | ? serverCache
|
8944 | : ChildrenNode.EMPTY_NODE;
|
8945 | const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
|
8946 | newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
|
8947 | }
|
8948 | else {
|
8949 | const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
|
8950 | newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
|
8951 | }
|
8952 | }
|
8953 | else {
|
8954 | const childKey = pathGetFront(changePath);
|
8955 | if (childKey === '.priority') {
|
8956 | assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
|
8957 | const oldEventNode = oldEventSnap.getNode();
|
8958 | serverNode = viewCache.serverCache.getNode();
|
8959 |
|
8960 | const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
|
8961 | if (updatedPriority != null) {
|
8962 | newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
|
8963 | }
|
8964 | else {
|
8965 |
|
8966 | newEventCache = oldEventSnap.getNode();
|
8967 | }
|
8968 | }
|
8969 | else {
|
8970 | const childChangePath = pathPopFront(changePath);
|
8971 |
|
8972 | let newEventChild;
|
8973 | if (oldEventSnap.isCompleteForChild(childKey)) {
|
8974 | serverNode = viewCache.serverCache.getNode();
|
8975 | const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
|
8976 | if (eventChildUpdate != null) {
|
8977 | newEventChild = oldEventSnap
|
8978 | .getNode()
|
8979 | .getImmediateChild(childKey)
|
8980 | .updateChild(childChangePath, eventChildUpdate);
|
8981 | }
|
8982 | else {
|
8983 |
|
8984 | newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
|
8985 | }
|
8986 | }
|
8987 | else {
|
8988 | newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
|
8989 | }
|
8990 | if (newEventChild != null) {
|
8991 | newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
|
8992 | }
|
8993 | else {
|
8994 |
|
8995 | newEventCache = oldEventSnap.getNode();
|
8996 | }
|
8997 | }
|
8998 | }
|
8999 | return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
|
9000 | }
|
9001 | }
|
9002 | function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
|
9003 | const oldServerSnap = oldViewCache.serverCache;
|
9004 | let newServerCache;
|
9005 | const serverFilter = filterServerNode
|
9006 | ? viewProcessor.filter
|
9007 | : viewProcessor.filter.getIndexedFilter();
|
9008 | if (pathIsEmpty(changePath)) {
|
9009 | newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
|
9010 | }
|
9011 | else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
|
9012 |
|
9013 | const newServerNode = oldServerSnap
|
9014 | .getNode()
|
9015 | .updateChild(changePath, changedSnap);
|
9016 | newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
|
9017 | }
|
9018 | else {
|
9019 | const childKey = pathGetFront(changePath);
|
9020 | if (!oldServerSnap.isCompleteForPath(changePath) &&
|
9021 | pathGetLength(changePath) > 1) {
|
9022 |
|
9023 | return oldViewCache;
|
9024 | }
|
9025 | const childChangePath = pathPopFront(changePath);
|
9026 | const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
|
9027 | const newChildNode = childNode.updateChild(childChangePath, changedSnap);
|
9028 | if (childKey === '.priority') {
|
9029 | newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
|
9030 | }
|
9031 | else {
|
9032 | newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
|
9033 | }
|
9034 | }
|
9035 | const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
|
9036 | const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
|
9037 | return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
|
9038 | }
|
9039 | function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
|
9040 | const oldEventSnap = oldViewCache.eventCache;
|
9041 | let newViewCache, newEventCache;
|
9042 | const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
|
9043 | if (pathIsEmpty(changePath)) {
|
9044 | newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
|
9045 | newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
|
9046 | }
|
9047 | else {
|
9048 | const childKey = pathGetFront(changePath);
|
9049 | if (childKey === '.priority') {
|
9050 | newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
|
9051 | newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
|
9052 | }
|
9053 | else {
|
9054 | const childChangePath = pathPopFront(changePath);
|
9055 | const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
|
9056 | let newChild;
|
9057 | if (pathIsEmpty(childChangePath)) {
|
9058 |
|
9059 | newChild = changedSnap;
|
9060 | }
|
9061 | else {
|
9062 | const childNode = source.getCompleteChild(childKey);
|
9063 | if (childNode != null) {
|
9064 | if (pathGetBack(childChangePath) === '.priority' &&
|
9065 | childNode.getChild(pathParent(childChangePath)).isEmpty()) {
|
9066 |
|
9067 |
|
9068 | newChild = childNode;
|
9069 | }
|
9070 | else {
|
9071 | newChild = childNode.updateChild(childChangePath, changedSnap);
|
9072 | }
|
9073 | }
|
9074 | else {
|
9075 |
|
9076 | newChild = ChildrenNode.EMPTY_NODE;
|
9077 | }
|
9078 | }
|
9079 | if (!oldChild.equals(newChild)) {
|
9080 | const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
|
9081 | newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
|
9082 | }
|
9083 | else {
|
9084 | newViewCache = oldViewCache;
|
9085 | }
|
9086 | }
|
9087 | }
|
9088 | return newViewCache;
|
9089 | }
|
9090 | function viewProcessorCacheHasChild(viewCache, childKey) {
|
9091 | return viewCache.eventCache.isCompleteForChild(childKey);
|
9092 | }
|
9093 | function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
|
9094 |
|
9095 |
|
9096 |
|
9097 |
|
9098 |
|
9099 |
|
9100 | let curViewCache = viewCache;
|
9101 | changedChildren.foreach((relativePath, childNode) => {
|
9102 | const writePath = pathChild(path, relativePath);
|
9103 | if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
|
9104 | curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
|
9105 | }
|
9106 | });
|
9107 | changedChildren.foreach((relativePath, childNode) => {
|
9108 | const writePath = pathChild(path, relativePath);
|
9109 | if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
|
9110 | curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
|
9111 | }
|
9112 | });
|
9113 | return curViewCache;
|
9114 | }
|
9115 | function viewProcessorApplyMerge(viewProcessor, node, merge) {
|
9116 | merge.foreach((relativePath, childNode) => {
|
9117 | node = node.updateChild(relativePath, childNode);
|
9118 | });
|
9119 | return node;
|
9120 | }
|
9121 | function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
|
9122 |
|
9123 |
|
9124 | if (viewCache.serverCache.getNode().isEmpty() &&
|
9125 | !viewCache.serverCache.isFullyInitialized()) {
|
9126 | return viewCache;
|
9127 | }
|
9128 |
|
9129 |
|
9130 |
|
9131 |
|
9132 |
|
9133 |
|
9134 | let curViewCache = viewCache;
|
9135 | let viewMergeTree;
|
9136 | if (pathIsEmpty(path)) {
|
9137 | viewMergeTree = changedChildren;
|
9138 | }
|
9139 | else {
|
9140 | viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
|
9141 | }
|
9142 | const serverNode = viewCache.serverCache.getNode();
|
9143 | viewMergeTree.children.inorderTraversal((childKey, childTree) => {
|
9144 | if (serverNode.hasChild(childKey)) {
|
9145 | const serverChild = viewCache.serverCache
|
9146 | .getNode()
|
9147 | .getImmediateChild(childKey);
|
9148 | const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
|
9149 | curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
|
9150 | }
|
9151 | });
|
9152 | viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
|
9153 | const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
|
9154 | childMergeTree.value === undefined;
|
9155 | if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
|
9156 | const serverChild = viewCache.serverCache
|
9157 | .getNode()
|
9158 | .getImmediateChild(childKey);
|
9159 | const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
|
9160 | curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
|
9161 | }
|
9162 | });
|
9163 | return curViewCache;
|
9164 | }
|
9165 | function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
|
9166 | if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
|
9167 | return viewCache;
|
9168 | }
|
9169 |
|
9170 | const filterServerNode = viewCache.serverCache.isFiltered();
|
9171 |
|
9172 |
|
9173 | const serverCache = viewCache.serverCache;
|
9174 | if (affectedTree.value != null) {
|
9175 |
|
9176 | if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
|
9177 | serverCache.isCompleteForPath(ackPath)) {
|
9178 | return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
|
9179 | }
|
9180 | else if (pathIsEmpty(ackPath)) {
|
9181 |
|
9182 |
|
9183 | let changedChildren = new ImmutableTree(null);
|
9184 | serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {
|
9185 | changedChildren = changedChildren.set(new Path(name), node);
|
9186 | });
|
9187 | return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
|
9188 | }
|
9189 | else {
|
9190 | return viewCache;
|
9191 | }
|
9192 | }
|
9193 | else {
|
9194 |
|
9195 | let changedChildren = new ImmutableTree(null);
|
9196 | affectedTree.foreach((mergePath, value) => {
|
9197 | const serverCachePath = pathChild(ackPath, mergePath);
|
9198 | if (serverCache.isCompleteForPath(serverCachePath)) {
|
9199 | changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
|
9200 | }
|
9201 | });
|
9202 | return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
|
9203 | }
|
9204 | }
|
9205 | function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
|
9206 | const oldServerNode = viewCache.serverCache;
|
9207 | const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
|
9208 | return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
|
9209 | }
|
9210 | function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
|
9211 | let complete;
|
9212 | if (writeTreeRefShadowingWrite(writesCache, path) != null) {
|
9213 | return viewCache;
|
9214 | }
|
9215 | else {
|
9216 | const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
|
9217 | const oldEventCache = viewCache.eventCache.getNode();
|
9218 | let newEventCache;
|
9219 | if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
|
9220 | let newNode;
|
9221 | if (viewCache.serverCache.isFullyInitialized()) {
|
9222 | newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
|
9223 | }
|
9224 | else {
|
9225 | const serverChildren = viewCache.serverCache.getNode();
|
9226 | assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
|
9227 | newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
|
9228 | }
|
9229 | newNode = newNode;
|
9230 | newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
|
9231 | }
|
9232 | else {
|
9233 | const childKey = pathGetFront(path);
|
9234 | let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
|
9235 | if (newChild == null &&
|
9236 | viewCache.serverCache.isCompleteForChild(childKey)) {
|
9237 | newChild = oldEventCache.getImmediateChild(childKey);
|
9238 | }
|
9239 | if (newChild != null) {
|
9240 | newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
|
9241 | }
|
9242 | else if (viewCache.eventCache.getNode().hasChild(childKey)) {
|
9243 |
|
9244 | newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
|
9245 | }
|
9246 | else {
|
9247 | newEventCache = oldEventCache;
|
9248 | }
|
9249 | if (newEventCache.isEmpty() &&
|
9250 | viewCache.serverCache.isFullyInitialized()) {
|
9251 |
|
9252 | complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
|
9253 | if (complete.isLeafNode()) {
|
9254 | newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
|
9255 | }
|
9256 | }
|
9257 | }
|
9258 | complete =
|
9259 | viewCache.serverCache.isFullyInitialized() ||
|
9260 | writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
|
9261 | return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
|
9262 | }
|
9263 | }
|
9264 |
|
9265 |
|
9266 |
|
9267 |
|
9268 |
|
9269 |
|
9270 |
|
9271 |
|
9272 |
|
9273 |
|
9274 |
|
9275 |
|
9276 |
|
9277 |
|
9278 |
|
9279 |
|
9280 |
|
9281 |
|
9282 |
|
9283 |
|
9284 |
|
9285 |
|
9286 |
|
9287 |
|
9288 |
|
9289 |
|
9290 | class View {
|
9291 | constructor(query_, initialViewCache) {
|
9292 | this.query_ = query_;
|
9293 | this.eventRegistrations_ = [];
|
9294 | const params = this.query_._queryParams;
|
9295 | const indexFilter = new IndexedFilter(params.getIndex());
|
9296 | const filter = queryParamsGetNodeFilter(params);
|
9297 | this.processor_ = newViewProcessor(filter);
|
9298 | const initialServerCache = initialViewCache.serverCache;
|
9299 | const initialEventCache = initialViewCache.eventCache;
|
9300 |
|
9301 | const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
|
9302 | const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
|
9303 | const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
|
9304 | const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
|
9305 | this.viewCache_ = newViewCache(newEventCache, newServerCache);
|
9306 | this.eventGenerator_ = new EventGenerator(this.query_);
|
9307 | }
|
9308 | get query() {
|
9309 | return this.query_;
|
9310 | }
|
9311 | }
|
9312 | function viewGetServerCache(view) {
|
9313 | return view.viewCache_.serverCache.getNode();
|
9314 | }
|
9315 | function viewGetCompleteNode(view) {
|
9316 | return viewCacheGetCompleteEventSnap(view.viewCache_);
|
9317 | }
|
9318 | function viewGetCompleteServerCache(view, path) {
|
9319 | const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
|
9320 | if (cache) {
|
9321 |
|
9322 |
|
9323 | if (view.query._queryParams.loadsAllData() ||
|
9324 | (!pathIsEmpty(path) &&
|
9325 | !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
|
9326 | return cache.getChild(path);
|
9327 | }
|
9328 | }
|
9329 | return null;
|
9330 | }
|
9331 | function viewIsEmpty(view) {
|
9332 | return view.eventRegistrations_.length === 0;
|
9333 | }
|
9334 | function viewAddEventRegistration(view, eventRegistration) {
|
9335 | view.eventRegistrations_.push(eventRegistration);
|
9336 | }
|
9337 |
|
9338 |
|
9339 |
|
9340 |
|
9341 |
|
9342 | function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
|
9343 | const cancelEvents = [];
|
9344 | if (cancelError) {
|
9345 | assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
|
9346 | const path = view.query._path;
|
9347 | view.eventRegistrations_.forEach(registration => {
|
9348 | const maybeEvent = registration.createCancelEvent(cancelError, path);
|
9349 | if (maybeEvent) {
|
9350 | cancelEvents.push(maybeEvent);
|
9351 | }
|
9352 | });
|
9353 | }
|
9354 | if (eventRegistration) {
|
9355 | let remaining = [];
|
9356 | for (let i = 0; i < view.eventRegistrations_.length; ++i) {
|
9357 | const existing = view.eventRegistrations_[i];
|
9358 | if (!existing.matches(eventRegistration)) {
|
9359 | remaining.push(existing);
|
9360 | }
|
9361 | else if (eventRegistration.hasAnyCallback()) {
|
9362 |
|
9363 | remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
|
9364 | break;
|
9365 | }
|
9366 | }
|
9367 | view.eventRegistrations_ = remaining;
|
9368 | }
|
9369 | else {
|
9370 | view.eventRegistrations_ = [];
|
9371 | }
|
9372 | return cancelEvents;
|
9373 | }
|
9374 |
|
9375 |
|
9376 |
|
9377 | function viewApplyOperation(view, operation, writesCache, completeServerCache) {
|
9378 | if (operation.type === OperationType.MERGE &&
|
9379 | operation.source.queryId !== null) {
|
9380 | assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
|
9381 | assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
|
9382 | }
|
9383 | const oldViewCache = view.viewCache_;
|
9384 | const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
|
9385 | viewProcessorAssertIndexed(view.processor_, result.viewCache);
|
9386 | assert(result.viewCache.serverCache.isFullyInitialized() ||
|
9387 | !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
|
9388 | view.viewCache_ = result.viewCache;
|
9389 | return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
|
9390 | }
|
9391 | function viewGetInitialEvents(view, registration) {
|
9392 | const eventSnap = view.viewCache_.eventCache;
|
9393 | const initialChanges = [];
|
9394 | if (!eventSnap.getNode().isLeafNode()) {
|
9395 | const eventNode = eventSnap.getNode();
|
9396 | eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
|
9397 | initialChanges.push(changeChildAdded(key, childNode));
|
9398 | });
|
9399 | }
|
9400 | if (eventSnap.isFullyInitialized()) {
|
9401 | initialChanges.push(changeValue(eventSnap.getNode()));
|
9402 | }
|
9403 | return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
|
9404 | }
|
9405 | function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
|
9406 | const registrations = eventRegistration
|
9407 | ? [eventRegistration]
|
9408 | : view.eventRegistrations_;
|
9409 | return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
|
9410 | }
|
9411 |
|
9412 |
|
9413 |
|
9414 |
|
9415 |
|
9416 |
|
9417 |
|
9418 |
|
9419 |
|
9420 |
|
9421 |
|
9422 |
|
9423 |
|
9424 |
|
9425 |
|
9426 |
|
9427 |
|
9428 | let referenceConstructor$1;
|
9429 |
|
9430 |
|
9431 |
|
9432 |
|
9433 |
|
9434 |
|
9435 |
|
9436 |
|
9437 |
|
9438 |
|
9439 | class SyncPoint {
|
9440 | constructor() {
|
9441 | |
9442 |
|
9443 |
|
9444 |
|
9445 |
|
9446 |
|
9447 | this.views = new Map();
|
9448 | }
|
9449 | }
|
9450 | function syncPointSetReferenceConstructor(val) {
|
9451 | assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
|
9452 | referenceConstructor$1 = val;
|
9453 | }
|
9454 | function syncPointGetReferenceConstructor() {
|
9455 | assert(referenceConstructor$1, 'Reference.ts has not been loaded');
|
9456 | return referenceConstructor$1;
|
9457 | }
|
9458 | function syncPointIsEmpty(syncPoint) {
|
9459 | return syncPoint.views.size === 0;
|
9460 | }
|
9461 | function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
|
9462 | const queryId = operation.source.queryId;
|
9463 | if (queryId !== null) {
|
9464 | const view = syncPoint.views.get(queryId);
|
9465 | assert(view != null, 'SyncTree gave us an op for an invalid query.');
|
9466 | return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
|
9467 | }
|
9468 | else {
|
9469 | let events = [];
|
9470 | for (const view of syncPoint.views.values()) {
|
9471 | events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
|
9472 | }
|
9473 | return events;
|
9474 | }
|
9475 | }
|
9476 |
|
9477 |
|
9478 |
|
9479 |
|
9480 |
|
9481 |
|
9482 |
|
9483 |
|
9484 |
|
9485 | function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
|
9486 | const queryId = query._queryIdentifier;
|
9487 | const view = syncPoint.views.get(queryId);
|
9488 | if (!view) {
|
9489 |
|
9490 | let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
|
9491 | let eventCacheComplete = false;
|
9492 | if (eventCache) {
|
9493 | eventCacheComplete = true;
|
9494 | }
|
9495 | else if (serverCache instanceof ChildrenNode) {
|
9496 | eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
|
9497 | eventCacheComplete = false;
|
9498 | }
|
9499 | else {
|
9500 | eventCache = ChildrenNode.EMPTY_NODE;
|
9501 | eventCacheComplete = false;
|
9502 | }
|
9503 | const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
|
9504 | return new View(query, viewCache);
|
9505 | }
|
9506 | return view;
|
9507 | }
|
9508 |
|
9509 |
|
9510 |
|
9511 |
|
9512 |
|
9513 |
|
9514 |
|
9515 |
|
9516 |
|
9517 |
|
9518 | function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
|
9519 | const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
|
9520 | if (!syncPoint.views.has(query._queryIdentifier)) {
|
9521 | syncPoint.views.set(query._queryIdentifier, view);
|
9522 | }
|
9523 |
|
9524 | viewAddEventRegistration(view, eventRegistration);
|
9525 | return viewGetInitialEvents(view, eventRegistration);
|
9526 | }
|
9527 |
|
9528 |
|
9529 |
|
9530 |
|
9531 |
|
9532 |
|
9533 |
|
9534 |
|
9535 |
|
9536 |
|
9537 | function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
|
9538 | const queryId = query._queryIdentifier;
|
9539 | const removed = [];
|
9540 | let cancelEvents = [];
|
9541 | const hadCompleteView = syncPointHasCompleteView(syncPoint);
|
9542 | if (queryId === 'default') {
|
9543 |
|
9544 | for (const [viewQueryId, view] of syncPoint.views.entries()) {
|
9545 | cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
|
9546 | if (viewIsEmpty(view)) {
|
9547 | syncPoint.views.delete(viewQueryId);
|
9548 |
|
9549 | if (!view.query._queryParams.loadsAllData()) {
|
9550 | removed.push(view.query);
|
9551 | }
|
9552 | }
|
9553 | }
|
9554 | }
|
9555 | else {
|
9556 |
|
9557 | const view = syncPoint.views.get(queryId);
|
9558 | if (view) {
|
9559 | cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
|
9560 | if (viewIsEmpty(view)) {
|
9561 | syncPoint.views.delete(queryId);
|
9562 |
|
9563 | if (!view.query._queryParams.loadsAllData()) {
|
9564 | removed.push(view.query);
|
9565 | }
|
9566 | }
|
9567 | }
|
9568 | }
|
9569 | if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
|
9570 |
|
9571 | removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
|
9572 | }
|
9573 | return { removed, events: cancelEvents };
|
9574 | }
|
9575 | function syncPointGetQueryViews(syncPoint) {
|
9576 | const result = [];
|
9577 | for (const view of syncPoint.views.values()) {
|
9578 | if (!view.query._queryParams.loadsAllData()) {
|
9579 | result.push(view);
|
9580 | }
|
9581 | }
|
9582 | return result;
|
9583 | }
|
9584 |
|
9585 |
|
9586 |
|
9587 |
|
9588 | function syncPointGetCompleteServerCache(syncPoint, path) {
|
9589 | let serverCache = null;
|
9590 | for (const view of syncPoint.views.values()) {
|
9591 | serverCache = serverCache || viewGetCompleteServerCache(view, path);
|
9592 | }
|
9593 | return serverCache;
|
9594 | }
|
9595 | function syncPointViewForQuery(syncPoint, query) {
|
9596 | const params = query._queryParams;
|
9597 | if (params.loadsAllData()) {
|
9598 | return syncPointGetCompleteView(syncPoint);
|
9599 | }
|
9600 | else {
|
9601 | const queryId = query._queryIdentifier;
|
9602 | return syncPoint.views.get(queryId);
|
9603 | }
|
9604 | }
|
9605 | function syncPointViewExistsForQuery(syncPoint, query) {
|
9606 | return syncPointViewForQuery(syncPoint, query) != null;
|
9607 | }
|
9608 | function syncPointHasCompleteView(syncPoint) {
|
9609 | return syncPointGetCompleteView(syncPoint) != null;
|
9610 | }
|
9611 | function syncPointGetCompleteView(syncPoint) {
|
9612 | for (const view of syncPoint.views.values()) {
|
9613 | if (view.query._queryParams.loadsAllData()) {
|
9614 | return view;
|
9615 | }
|
9616 | }
|
9617 | return null;
|
9618 | }
|
9619 |
|
9620 |
|
9621 |
|
9622 |
|
9623 |
|
9624 |
|
9625 |
|
9626 |
|
9627 |
|
9628 |
|
9629 |
|
9630 |
|
9631 |
|
9632 |
|
9633 |
|
9634 |
|
9635 |
|
9636 | let referenceConstructor;
|
9637 | function syncTreeSetReferenceConstructor(val) {
|
9638 | assert(!referenceConstructor, '__referenceConstructor has already been defined');
|
9639 | referenceConstructor = val;
|
9640 | }
|
9641 | function syncTreeGetReferenceConstructor() {
|
9642 | assert(referenceConstructor, 'Reference.ts has not been loaded');
|
9643 | return referenceConstructor;
|
9644 | }
|
9645 |
|
9646 |
|
9647 |
|
9648 | let syncTreeNextQueryTag_ = 1;
|
9649 |
|
9650 |
|
9651 |
|
9652 |
|
9653 |
|
9654 |
|
9655 |
|
9656 |
|
9657 |
|
9658 |
|
9659 |
|
9660 |
|
9661 |
|
9662 |
|
9663 |
|
9664 |
|
9665 |
|
9666 |
|
9667 |
|
9668 |
|
9669 |
|
9670 | class SyncTree {
|
9671 | |
9672 |
|
9673 |
|
9674 |
|
9675 | constructor(listenProvider_) {
|
9676 | this.listenProvider_ = listenProvider_;
|
9677 | |
9678 |
|
9679 |
|
9680 | this.syncPointTree_ = new ImmutableTree(null);
|
9681 | |
9682 |
|
9683 |
|
9684 | this.pendingWriteTree_ = newWriteTree();
|
9685 | this.tagToQueryMap = new Map();
|
9686 | this.queryToTagMap = new Map();
|
9687 | }
|
9688 | }
|
9689 |
|
9690 |
|
9691 |
|
9692 |
|
9693 |
|
9694 | function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
|
9695 |
|
9696 | writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
|
9697 | if (!visible) {
|
9698 | return [];
|
9699 | }
|
9700 | else {
|
9701 | return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
|
9702 | }
|
9703 | }
|
9704 |
|
9705 |
|
9706 |
|
9707 |
|
9708 |
|
9709 | function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
|
9710 |
|
9711 | writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
|
9712 | const changeTree = ImmutableTree.fromObject(changedChildren);
|
9713 | return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
|
9714 | }
|
9715 |
|
9716 |
|
9717 |
|
9718 |
|
9719 |
|
9720 |
|
9721 | function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
|
9722 | const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
|
9723 | const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
|
9724 | if (!needToReevaluate) {
|
9725 | return [];
|
9726 | }
|
9727 | else {
|
9728 | let affectedTree = new ImmutableTree(null);
|
9729 | if (write.snap != null) {
|
9730 |
|
9731 | affectedTree = affectedTree.set(newEmptyPath(), true);
|
9732 | }
|
9733 | else {
|
9734 | each(write.children, (pathString) => {
|
9735 | affectedTree = affectedTree.set(new Path(pathString), true);
|
9736 | });
|
9737 | }
|
9738 | return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
|
9739 | }
|
9740 | }
|
9741 |
|
9742 |
|
9743 |
|
9744 |
|
9745 |
|
9746 | function syncTreeApplyServerOverwrite(syncTree, path, newData) {
|
9747 | return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
|
9748 | }
|
9749 |
|
9750 |
|
9751 |
|
9752 |
|
9753 |
|
9754 | function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
|
9755 | const changeTree = ImmutableTree.fromObject(changedChildren);
|
9756 | return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
|
9757 | }
|
9758 |
|
9759 |
|
9760 |
|
9761 |
|
9762 |
|
9763 | function syncTreeApplyListenComplete(syncTree, path) {
|
9764 | return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
|
9765 | }
|
9766 |
|
9767 |
|
9768 |
|
9769 |
|
9770 |
|
9771 | function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
|
9772 | const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
|
9773 | if (queryKey) {
|
9774 | const r = syncTreeParseQueryKey_(queryKey);
|
9775 | const queryPath = r.path, queryId = r.queryId;
|
9776 | const relativePath = newRelativePath(queryPath, path);
|
9777 | const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
|
9778 | return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
|
9779 | }
|
9780 | else {
|
9781 |
|
9782 | return [];
|
9783 | }
|
9784 | }
|
9785 |
|
9786 |
|
9787 |
|
9788 |
|
9789 |
|
9790 |
|
9791 |
|
9792 |
|
9793 |
|
9794 |
|
9795 | function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError) {
|
9796 |
|
9797 | const path = query._path;
|
9798 | const maybeSyncPoint = syncTree.syncPointTree_.get(path);
|
9799 | let cancelEvents = [];
|
9800 |
|
9801 |
|
9802 |
|
9803 | if (maybeSyncPoint &&
|
9804 | (query._queryIdentifier === 'default' ||
|
9805 | syncPointViewExistsForQuery(maybeSyncPoint, query))) {
|
9806 | const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
|
9807 | if (syncPointIsEmpty(maybeSyncPoint)) {
|
9808 | syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
|
9809 | }
|
9810 | const removed = removedAndEvents.removed;
|
9811 | cancelEvents = removedAndEvents.events;
|
9812 |
|
9813 |
|
9814 |
|
9815 |
|
9816 |
|
9817 |
|
9818 | const removingDefault = -1 !==
|
9819 | removed.findIndex(query => {
|
9820 | return query._queryParams.loadsAllData();
|
9821 | });
|
9822 | const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
|
9823 | if (removingDefault && !covered) {
|
9824 | const subtree = syncTree.syncPointTree_.subtree(path);
|
9825 |
|
9826 |
|
9827 | if (!subtree.isEmpty()) {
|
9828 |
|
9829 | const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
|
9830 |
|
9831 | for (let i = 0; i < newViews.length; ++i) {
|
9832 | const view = newViews[i], newQuery = view.query;
|
9833 | const listener = syncTreeCreateListenerForView_(syncTree, view);
|
9834 | syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery_(syncTree, newQuery), listener.hashFn, listener.onComplete);
|
9835 | }
|
9836 | }
|
9837 | }
|
9838 |
|
9839 |
|
9840 |
|
9841 | if (!covered && removed.length > 0 && !cancelError) {
|
9842 |
|
9843 |
|
9844 | if (removingDefault) {
|
9845 |
|
9846 | const defaultTag = null;
|
9847 | syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
|
9848 | }
|
9849 | else {
|
9850 | removed.forEach((queryToRemove) => {
|
9851 | const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
|
9852 | syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
|
9853 | });
|
9854 | }
|
9855 | }
|
9856 |
|
9857 | syncTreeRemoveTags_(syncTree, removed);
|
9858 | }
|
9859 | return cancelEvents;
|
9860 | }
|
9861 |
|
9862 |
|
9863 |
|
9864 |
|
9865 |
|
9866 |
|
9867 |
|
9868 |
|
9869 |
|
9870 |
|
9871 |
|
9872 |
|
9873 |
|
9874 | function syncTreeRegisterQuery(syncTree, query) {
|
9875 | const { syncPoint, serverCache, writesCache, serverCacheComplete } = syncTreeRegisterSyncPoint(query, syncTree);
|
9876 | const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
|
9877 | if (!syncPoint.views.has(query._queryIdentifier)) {
|
9878 | syncPoint.views.set(query._queryIdentifier, view);
|
9879 | }
|
9880 | if (!query._queryParams.loadsAllData()) {
|
9881 | return syncTreeTagForQuery_(syncTree, query);
|
9882 | }
|
9883 | return null;
|
9884 | }
|
9885 |
|
9886 |
|
9887 |
|
9888 |
|
9889 |
|
9890 | function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
|
9891 | const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
|
9892 | if (queryKey != null) {
|
9893 | const r = syncTreeParseQueryKey_(queryKey);
|
9894 | const queryPath = r.path, queryId = r.queryId;
|
9895 | const relativePath = newRelativePath(queryPath, path);
|
9896 | const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
|
9897 | return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
|
9898 | }
|
9899 | else {
|
9900 |
|
9901 | return [];
|
9902 | }
|
9903 | }
|
9904 |
|
9905 |
|
9906 |
|
9907 |
|
9908 |
|
9909 | function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
|
9910 | const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
|
9911 | if (queryKey) {
|
9912 | const r = syncTreeParseQueryKey_(queryKey);
|
9913 | const queryPath = r.path, queryId = r.queryId;
|
9914 | const relativePath = newRelativePath(queryPath, path);
|
9915 | const changeTree = ImmutableTree.fromObject(changedChildren);
|
9916 | const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
|
9917 | return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
|
9918 | }
|
9919 | else {
|
9920 |
|
9921 | return [];
|
9922 | }
|
9923 | }
|
9924 |
|
9925 |
|
9926 |
|
9927 |
|
9928 |
|
9929 | function syncTreeRegisterSyncPoint(query, syncTree) {
|
9930 | const path = query._path;
|
9931 | let serverCache = null;
|
9932 | let foundAncestorDefaultView = false;
|
9933 |
|
9934 |
|
9935 | syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
|
9936 | const relativePath = newRelativePath(pathToSyncPoint, path);
|
9937 | serverCache =
|
9938 | serverCache || syncPointGetCompleteServerCache(sp, relativePath);
|
9939 | foundAncestorDefaultView =
|
9940 | foundAncestorDefaultView || syncPointHasCompleteView(sp);
|
9941 | });
|
9942 | let syncPoint = syncTree.syncPointTree_.get(path);
|
9943 | if (!syncPoint) {
|
9944 | syncPoint = new SyncPoint();
|
9945 | syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
|
9946 | }
|
9947 | else {
|
9948 | foundAncestorDefaultView =
|
9949 | foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
|
9950 | serverCache =
|
9951 | serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
|
9952 | }
|
9953 | let serverCacheComplete;
|
9954 | if (serverCache != null) {
|
9955 | serverCacheComplete = true;
|
9956 | }
|
9957 | else {
|
9958 | serverCacheComplete = false;
|
9959 | serverCache = ChildrenNode.EMPTY_NODE;
|
9960 | const subtree = syncTree.syncPointTree_.subtree(path);
|
9961 | subtree.foreachChild((childName, childSyncPoint) => {
|
9962 | const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
|
9963 | if (completeCache) {
|
9964 | serverCache = serverCache.updateImmediateChild(childName, completeCache);
|
9965 | }
|
9966 | });
|
9967 | }
|
9968 | const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
|
9969 | if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
|
9970 |
|
9971 | const queryKey = syncTreeMakeQueryKey_(query);
|
9972 | assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
|
9973 | const tag = syncTreeGetNextQueryTag_();
|
9974 | syncTree.queryToTagMap.set(queryKey, tag);
|
9975 | syncTree.tagToQueryMap.set(tag, queryKey);
|
9976 | }
|
9977 | const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
|
9978 | return {
|
9979 | syncPoint,
|
9980 | writesCache,
|
9981 | serverCache,
|
9982 | serverCacheComplete,
|
9983 | foundAncestorDefaultView,
|
9984 | viewAlreadyExists
|
9985 | };
|
9986 | }
|
9987 |
|
9988 |
|
9989 |
|
9990 |
|
9991 |
|
9992 | function syncTreeAddEventRegistration(syncTree, query, eventRegistration) {
|
9993 | const { syncPoint, serverCache, writesCache, serverCacheComplete, viewAlreadyExists, foundAncestorDefaultView } = syncTreeRegisterSyncPoint(query, syncTree);
|
9994 | let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
|
9995 | if (!viewAlreadyExists && !foundAncestorDefaultView) {
|
9996 | const view = syncPointViewForQuery(syncPoint, query);
|
9997 | events = events.concat(syncTreeSetupListener_(syncTree, query, view));
|
9998 | }
|
9999 | return events;
|
10000 | }
|
10001 |
|
10002 |
|
10003 |
|
10004 |
|
10005 |
|
10006 |
|
10007 |
|
10008 |
|
10009 |
|
10010 |
|
10011 |
|
10012 | function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
|
10013 | const includeHiddenSets = true;
|
10014 | const writeTree = syncTree.pendingWriteTree_;
|
10015 | const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
|
10016 | const relativePath = newRelativePath(pathSoFar, path);
|
10017 | const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
|
10018 | if (serverCache) {
|
10019 | return serverCache;
|
10020 | }
|
10021 | });
|
10022 | return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
|
10023 | }
|
10024 | function syncTreeGetServerValue(syncTree, query) {
|
10025 | const path = query._path;
|
10026 | let serverCache = null;
|
10027 |
|
10028 |
|
10029 | syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
|
10030 | const relativePath = newRelativePath(pathToSyncPoint, path);
|
10031 | serverCache =
|
10032 | serverCache || syncPointGetCompleteServerCache(sp, relativePath);
|
10033 | });
|
10034 | let syncPoint = syncTree.syncPointTree_.get(path);
|
10035 | if (!syncPoint) {
|
10036 | syncPoint = new SyncPoint();
|
10037 | syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
|
10038 | }
|
10039 | else {
|
10040 | serverCache =
|
10041 | serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
|
10042 | }
|
10043 | const serverCacheComplete = serverCache != null;
|
10044 | const serverCacheNode = serverCacheComplete
|
10045 | ? new CacheNode(serverCache, true, false)
|
10046 | : null;
|
10047 | const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
|
10048 | const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
|
10049 | return viewGetCompleteNode(view);
|
10050 | }
|
10051 |
|
10052 |
|
10053 |
|
10054 |
|
10055 |
|
10056 |
|
10057 |
|
10058 |
|
10059 |
|
10060 |
|
10061 |
|
10062 |
|
10063 |
|
10064 | function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
|
10065 | return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
|
10066 | null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
|
10067 | }
|
10068 |
|
10069 |
|
10070 |
|
10071 | function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
|
10072 | if (pathIsEmpty(operation.path)) {
|
10073 | return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
|
10074 | }
|
10075 | else {
|
10076 | const syncPoint = syncPointTree.get(newEmptyPath());
|
10077 |
|
10078 | if (serverCache == null && syncPoint != null) {
|
10079 | serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
|
10080 | }
|
10081 | let events = [];
|
10082 | const childName = pathGetFront(operation.path);
|
10083 | const childOperation = operation.operationForChild(childName);
|
10084 | const childTree = syncPointTree.children.get(childName);
|
10085 | if (childTree && childOperation) {
|
10086 | const childServerCache = serverCache
|
10087 | ? serverCache.getImmediateChild(childName)
|
10088 | : null;
|
10089 | const childWritesCache = writeTreeRefChild(writesCache, childName);
|
10090 | events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
|
10091 | }
|
10092 | if (syncPoint) {
|
10093 | events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
|
10094 | }
|
10095 | return events;
|
10096 | }
|
10097 | }
|
10098 |
|
10099 |
|
10100 |
|
10101 | function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
|
10102 | const syncPoint = syncPointTree.get(newEmptyPath());
|
10103 |
|
10104 | if (serverCache == null && syncPoint != null) {
|
10105 | serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
|
10106 | }
|
10107 | let events = [];
|
10108 | syncPointTree.children.inorderTraversal((childName, childTree) => {
|
10109 | const childServerCache = serverCache
|
10110 | ? serverCache.getImmediateChild(childName)
|
10111 | : null;
|
10112 | const childWritesCache = writeTreeRefChild(writesCache, childName);
|
10113 | const childOperation = operation.operationForChild(childName);
|
10114 | if (childOperation) {
|
10115 | events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
|
10116 | }
|
10117 | });
|
10118 | if (syncPoint) {
|
10119 | events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
|
10120 | }
|
10121 | return events;
|
10122 | }
|
10123 | function syncTreeCreateListenerForView_(syncTree, view) {
|
10124 | const query = view.query;
|
10125 | const tag = syncTreeTagForQuery_(syncTree, query);
|
10126 | return {
|
10127 | hashFn: () => {
|
10128 | const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
|
10129 | return cache.hash();
|
10130 | },
|
10131 | onComplete: (status) => {
|
10132 | if (status === 'ok') {
|
10133 | if (tag) {
|
10134 | return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
|
10135 | }
|
10136 | else {
|
10137 | return syncTreeApplyListenComplete(syncTree, query._path);
|
10138 | }
|
10139 | }
|
10140 | else {
|
10141 |
|
10142 |
|
10143 | const error = errorForServerCode(status, query);
|
10144 | return syncTreeRemoveEventRegistration(syncTree, query,
|
10145 | null, error);
|
10146 | }
|
10147 | }
|
10148 | };
|
10149 | }
|
10150 |
|
10151 |
|
10152 |
|
10153 | function syncTreeTagForQuery_(syncTree, query) {
|
10154 | const queryKey = syncTreeMakeQueryKey_(query);
|
10155 | return syncTree.queryToTagMap.get(queryKey);
|
10156 | }
|
10157 |
|
10158 |
|
10159 |
|
10160 | function syncTreeMakeQueryKey_(query) {
|
10161 | return query._path.toString() + '$' + query._queryIdentifier;
|
10162 | }
|
10163 |
|
10164 |
|
10165 |
|
10166 | function syncTreeQueryKeyForTag_(syncTree, tag) {
|
10167 | return syncTree.tagToQueryMap.get(tag);
|
10168 | }
|
10169 |
|
10170 |
|
10171 |
|
10172 | function syncTreeParseQueryKey_(queryKey) {
|
10173 | const splitIndex = queryKey.indexOf('$');
|
10174 | assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
|
10175 | return {
|
10176 | queryId: queryKey.substr(splitIndex + 1),
|
10177 | path: new Path(queryKey.substr(0, splitIndex))
|
10178 | };
|
10179 | }
|
10180 |
|
10181 |
|
10182 |
|
10183 | function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
|
10184 | const syncPoint = syncTree.syncPointTree_.get(queryPath);
|
10185 | assert(syncPoint, "Missing sync point for query tag that we're tracking");
|
10186 | const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
|
10187 | return syncPointApplyOperation(syncPoint, operation, writesCache, null);
|
10188 | }
|
10189 |
|
10190 |
|
10191 |
|
10192 |
|
10193 | function syncTreeCollectDistinctViewsForSubTree_(subtree) {
|
10194 | return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
|
10195 | if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
|
10196 | const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
|
10197 | return [completeView];
|
10198 | }
|
10199 | else {
|
10200 |
|
10201 | let views = [];
|
10202 | if (maybeChildSyncPoint) {
|
10203 | views = syncPointGetQueryViews(maybeChildSyncPoint);
|
10204 | }
|
10205 | each(childMap, (_key, childViews) => {
|
10206 | views = views.concat(childViews);
|
10207 | });
|
10208 | return views;
|
10209 | }
|
10210 | });
|
10211 | }
|
10212 |
|
10213 |
|
10214 |
|
10215 |
|
10216 |
|
10217 | function syncTreeQueryForListening_(query) {
|
10218 | if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
|
10219 |
|
10220 |
|
10221 |
|
10222 | return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
|
10223 | }
|
10224 | else {
|
10225 | return query;
|
10226 | }
|
10227 | }
|
10228 | function syncTreeRemoveTags_(syncTree, queries) {
|
10229 | for (let j = 0; j < queries.length; ++j) {
|
10230 | const removedQuery = queries[j];
|
10231 | if (!removedQuery._queryParams.loadsAllData()) {
|
10232 |
|
10233 | const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
|
10234 | const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
|
10235 | syncTree.queryToTagMap.delete(removedQueryKey);
|
10236 | syncTree.tagToQueryMap.delete(removedQueryTag);
|
10237 | }
|
10238 | }
|
10239 | }
|
10240 |
|
10241 |
|
10242 |
|
10243 | function syncTreeGetNextQueryTag_() {
|
10244 | return syncTreeNextQueryTag_++;
|
10245 | }
|
10246 |
|
10247 |
|
10248 |
|
10249 |
|
10250 |
|
10251 | function syncTreeSetupListener_(syncTree, query, view) {
|
10252 | const path = query._path;
|
10253 | const tag = syncTreeTagForQuery_(syncTree, query);
|
10254 | const listener = syncTreeCreateListenerForView_(syncTree, view);
|
10255 | const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
|
10256 | const subtree = syncTree.syncPointTree_.subtree(path);
|
10257 |
|
10258 |
|
10259 | if (tag) {
|
10260 | assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
|
10261 | }
|
10262 | else {
|
10263 |
|
10264 | const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
|
10265 | if (!pathIsEmpty(relativePath) &&
|
10266 | maybeChildSyncPoint &&
|
10267 | syncPointHasCompleteView(maybeChildSyncPoint)) {
|
10268 | return [syncPointGetCompleteView(maybeChildSyncPoint).query];
|
10269 | }
|
10270 | else {
|
10271 |
|
10272 | let queries = [];
|
10273 | if (maybeChildSyncPoint) {
|
10274 | queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));
|
10275 | }
|
10276 | each(childMap, (_key, childQueries) => {
|
10277 | queries = queries.concat(childQueries);
|
10278 | });
|
10279 | return queries;
|
10280 | }
|
10281 | });
|
10282 | for (let i = 0; i < queriesToStop.length; ++i) {
|
10283 | const queryToStop = queriesToStop[i];
|
10284 | syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery_(syncTree, queryToStop));
|
10285 | }
|
10286 | }
|
10287 | return events;
|
10288 | }
|
10289 |
|
10290 |
|
10291 |
|
10292 |
|
10293 |
|
10294 |
|
10295 |
|
10296 |
|
10297 |
|
10298 |
|
10299 |
|
10300 |
|
10301 |
|
10302 |
|
10303 |
|
10304 |
|
10305 |
|
10306 | class ExistingValueProvider {
|
10307 | constructor(node_) {
|
10308 | this.node_ = node_;
|
10309 | }
|
10310 | getImmediateChild(childName) {
|
10311 | const child = this.node_.getImmediateChild(childName);
|
10312 | return new ExistingValueProvider(child);
|
10313 | }
|
10314 | node() {
|
10315 | return this.node_;
|
10316 | }
|
10317 | }
|
10318 | class DeferredValueProvider {
|
10319 | constructor(syncTree, path) {
|
10320 | this.syncTree_ = syncTree;
|
10321 | this.path_ = path;
|
10322 | }
|
10323 | getImmediateChild(childName) {
|
10324 | const childPath = pathChild(this.path_, childName);
|
10325 | return new DeferredValueProvider(this.syncTree_, childPath);
|
10326 | }
|
10327 | node() {
|
10328 | return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
|
10329 | }
|
10330 | }
|
10331 |
|
10332 |
|
10333 |
|
10334 | const generateWithValues = function (values) {
|
10335 | values = values || {};
|
10336 | values['timestamp'] = values['timestamp'] || new Date().getTime();
|
10337 | return values;
|
10338 | };
|
10339 |
|
10340 |
|
10341 |
|
10342 |
|
10343 | const resolveDeferredLeafValue = function (value, existingVal, serverValues) {
|
10344 | if (!value || typeof value !== 'object') {
|
10345 | return value;
|
10346 | }
|
10347 | assert('.sv' in value, 'Unexpected leaf node or priority contents');
|
10348 | if (typeof value['.sv'] === 'string') {
|
10349 | return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
|
10350 | }
|
10351 | else if (typeof value['.sv'] === 'object') {
|
10352 | return resolveComplexDeferredValue(value['.sv'], existingVal);
|
10353 | }
|
10354 | else {
|
10355 | assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
|
10356 | }
|
10357 | };
|
10358 | const resolveScalarDeferredValue = function (op, existing, serverValues) {
|
10359 | switch (op) {
|
10360 | case 'timestamp':
|
10361 | return serverValues['timestamp'];
|
10362 | default:
|
10363 | assert(false, 'Unexpected server value: ' + op);
|
10364 | }
|
10365 | };
|
10366 | const resolveComplexDeferredValue = function (op, existing, unused) {
|
10367 | if (!op.hasOwnProperty('increment')) {
|
10368 | assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
|
10369 | }
|
10370 | const delta = op['increment'];
|
10371 | if (typeof delta !== 'number') {
|
10372 | assert(false, 'Unexpected increment value: ' + delta);
|
10373 | }
|
10374 | const existingNode = existing.node();
|
10375 | assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
|
10376 |
|
10377 | if (!existingNode.isLeafNode()) {
|
10378 | return delta;
|
10379 | }
|
10380 | const leaf = existingNode;
|
10381 | const existingVal = leaf.getValue();
|
10382 | if (typeof existingVal !== 'number') {
|
10383 | return delta;
|
10384 | }
|
10385 |
|
10386 | return existingVal + delta;
|
10387 | };
|
10388 |
|
10389 |
|
10390 |
|
10391 |
|
10392 |
|
10393 |
|
10394 |
|
10395 | const resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
|
10396 | return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
|
10397 | };
|
10398 |
|
10399 |
|
10400 |
|
10401 |
|
10402 |
|
10403 | const resolveDeferredValueSnapshot = function (node, existing, serverValues) {
|
10404 | return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
|
10405 | };
|
10406 | function resolveDeferredValue(node, existingVal, serverValues) {
|
10407 | const rawPri = node.getPriority().val();
|
10408 | const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
|
10409 | let newNode;
|
10410 | if (node.isLeafNode()) {
|
10411 | const leafNode = node;
|
10412 | const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
|
10413 | if (value !== leafNode.getValue() ||
|
10414 | priority !== leafNode.getPriority().val()) {
|
10415 | return new LeafNode(value, nodeFromJSON(priority));
|
10416 | }
|
10417 | else {
|
10418 | return node;
|
10419 | }
|
10420 | }
|
10421 | else {
|
10422 | const childrenNode = node;
|
10423 | newNode = childrenNode;
|
10424 | if (priority !== childrenNode.getPriority().val()) {
|
10425 | newNode = newNode.updatePriority(new LeafNode(priority));
|
10426 | }
|
10427 | childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
|
10428 | const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
|
10429 | if (newChildNode !== childNode) {
|
10430 | newNode = newNode.updateImmediateChild(childName, newChildNode);
|
10431 | }
|
10432 | });
|
10433 | return newNode;
|
10434 | }
|
10435 | }
|
10436 |
|
10437 |
|
10438 |
|
10439 |
|
10440 |
|
10441 |
|
10442 |
|
10443 |
|
10444 |
|
10445 |
|
10446 |
|
10447 |
|
10448 |
|
10449 |
|
10450 |
|
10451 |
|
10452 |
|
10453 |
|
10454 |
|
10455 |
|
10456 |
|
10457 |
|
10458 | class Tree {
|
10459 | |
10460 |
|
10461 |
|
10462 |
|
10463 |
|
10464 | constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {
|
10465 | this.name = name;
|
10466 | this.parent = parent;
|
10467 | this.node = node;
|
10468 | }
|
10469 | }
|
10470 |
|
10471 |
|
10472 |
|
10473 |
|
10474 |
|
10475 |
|
10476 | function treeSubTree(tree, pathObj) {
|
10477 |
|
10478 | let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
|
10479 | let child = tree, next = pathGetFront(path);
|
10480 | while (next !== null) {
|
10481 | const childNode = safeGet(child.node.children, next) || {
|
10482 | children: {},
|
10483 | childCount: 0
|
10484 | };
|
10485 | child = new Tree(next, child, childNode);
|
10486 | path = pathPopFront(path);
|
10487 | next = pathGetFront(path);
|
10488 | }
|
10489 | return child;
|
10490 | }
|
10491 |
|
10492 |
|
10493 |
|
10494 |
|
10495 |
|
10496 | function treeGetValue(tree) {
|
10497 | return tree.node.value;
|
10498 | }
|
10499 |
|
10500 |
|
10501 |
|
10502 |
|
10503 |
|
10504 | function treeSetValue(tree, value) {
|
10505 | tree.node.value = value;
|
10506 | treeUpdateParents(tree);
|
10507 | }
|
10508 |
|
10509 |
|
10510 |
|
10511 | function treeHasChildren(tree) {
|
10512 | return tree.node.childCount > 0;
|
10513 | }
|
10514 |
|
10515 |
|
10516 |
|
10517 | function treeIsEmpty(tree) {
|
10518 | return treeGetValue(tree) === undefined && !treeHasChildren(tree);
|
10519 | }
|
10520 |
|
10521 |
|
10522 |
|
10523 |
|
10524 |
|
10525 | function treeForEachChild(tree, action) {
|
10526 | each(tree.node.children, (child, childTree) => {
|
10527 | action(new Tree(child, tree, childTree));
|
10528 | });
|
10529 | }
|
10530 |
|
10531 |
|
10532 |
|
10533 |
|
10534 |
|
10535 |
|
10536 |
|
10537 |
|
10538 |
|
10539 | function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
|
10540 | if (includeSelf && !childrenFirst) {
|
10541 | action(tree);
|
10542 | }
|
10543 | treeForEachChild(tree, child => {
|
10544 | treeForEachDescendant(child, action, true, childrenFirst);
|
10545 | });
|
10546 | if (includeSelf && childrenFirst) {
|
10547 | action(tree);
|
10548 | }
|
10549 | }
|
10550 |
|
10551 |
|
10552 |
|
10553 |
|
10554 |
|
10555 |
|
10556 |
|
10557 |
|
10558 | function treeForEachAncestor(tree, action, includeSelf) {
|
10559 | let node = includeSelf ? tree : tree.parent;
|
10560 | while (node !== null) {
|
10561 | if (action(node)) {
|
10562 | return true;
|
10563 | }
|
10564 | node = node.parent;
|
10565 | }
|
10566 | return false;
|
10567 | }
|
10568 |
|
10569 |
|
10570 |
|
10571 | function treeGetPath(tree) {
|
10572 | return new Path(tree.parent === null
|
10573 | ? tree.name
|
10574 | : treeGetPath(tree.parent) + '/' + tree.name);
|
10575 | }
|
10576 |
|
10577 |
|
10578 |
|
10579 | function treeUpdateParents(tree) {
|
10580 | if (tree.parent !== null) {
|
10581 | treeUpdateChild(tree.parent, tree.name, tree);
|
10582 | }
|
10583 | }
|
10584 |
|
10585 |
|
10586 |
|
10587 |
|
10588 |
|
10589 |
|
10590 | function treeUpdateChild(tree, childName, child) {
|
10591 | const childEmpty = treeIsEmpty(child);
|
10592 | const childExists = contains(tree.node.children, childName);
|
10593 | if (childEmpty && childExists) {
|
10594 | delete tree.node.children[childName];
|
10595 | tree.node.childCount--;
|
10596 | treeUpdateParents(tree);
|
10597 | }
|
10598 | else if (!childEmpty && !childExists) {
|
10599 | tree.node.children[childName] = child.node;
|
10600 | tree.node.childCount++;
|
10601 | treeUpdateParents(tree);
|
10602 | }
|
10603 | }
|
10604 |
|
10605 |
|
10606 |
|
10607 |
|
10608 |
|
10609 |
|
10610 |
|
10611 |
|
10612 |
|
10613 |
|
10614 |
|
10615 |
|
10616 |
|
10617 |
|
10618 |
|
10619 |
|
10620 |
|
10621 |
|
10622 |
|
10623 |
|
10624 | const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
|
10625 |
|
10626 |
|
10627 |
|
10628 |
|
10629 | const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
|
10630 |
|
10631 |
|
10632 |
|
10633 | const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
|
10634 | const isValidKey = function (key) {
|
10635 | return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
|
10636 | };
|
10637 | const isValidPathString = function (pathString) {
|
10638 | return (typeof pathString === 'string' &&
|
10639 | pathString.length !== 0 &&
|
10640 | !INVALID_PATH_REGEX_.test(pathString));
|
10641 | };
|
10642 | const isValidRootPathString = function (pathString) {
|
10643 | if (pathString) {
|
10644 |
|
10645 | pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
|
10646 | }
|
10647 | return isValidPathString(pathString);
|
10648 | };
|
10649 | const isValidPriority = function (priority) {
|
10650 | return (priority === null ||
|
10651 | typeof priority === 'string' ||
|
10652 | (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
|
10653 | (priority &&
|
10654 | typeof priority === 'object' &&
|
10655 |
|
10656 | contains(priority, '.sv')));
|
10657 | };
|
10658 |
|
10659 |
|
10660 |
|
10661 | const validateFirebaseDataArg = function (fnName, value, path, optional) {
|
10662 | if (optional && value === undefined) {
|
10663 | return;
|
10664 | }
|
10665 | validateFirebaseData(errorPrefix(fnName, 'value'), value, path);
|
10666 | };
|
10667 |
|
10668 |
|
10669 |
|
10670 | const validateFirebaseData = function (errorPrefix, data, path_) {
|
10671 | const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
|
10672 | if (data === undefined) {
|
10673 | throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
|
10674 | }
|
10675 | if (typeof data === 'function') {
|
10676 | throw new Error(errorPrefix +
|
10677 | 'contains a function ' +
|
10678 | validationPathToErrorString(path) +
|
10679 | ' with contents = ' +
|
10680 | data.toString());
|
10681 | }
|
10682 | if (isInvalidJSONNumber(data)) {
|
10683 | throw new Error(errorPrefix +
|
10684 | 'contains ' +
|
10685 | data.toString() +
|
10686 | ' ' +
|
10687 | validationPathToErrorString(path));
|
10688 | }
|
10689 |
|
10690 | if (typeof data === 'string' &&
|
10691 | data.length > MAX_LEAF_SIZE_ / 3 &&
|
10692 | stringLength(data) > MAX_LEAF_SIZE_) {
|
10693 | throw new Error(errorPrefix +
|
10694 | 'contains a string greater than ' +
|
10695 | MAX_LEAF_SIZE_ +
|
10696 | ' utf8 bytes ' +
|
10697 | validationPathToErrorString(path) +
|
10698 | " ('" +
|
10699 | data.substring(0, 50) +
|
10700 | "...')");
|
10701 | }
|
10702 |
|
10703 |
|
10704 | if (data && typeof data === 'object') {
|
10705 | let hasDotValue = false;
|
10706 | let hasActualChild = false;
|
10707 | each(data, (key, value) => {
|
10708 | if (key === '.value') {
|
10709 | hasDotValue = true;
|
10710 | }
|
10711 | else if (key !== '.priority' && key !== '.sv') {
|
10712 | hasActualChild = true;
|
10713 | if (!isValidKey(key)) {
|
10714 | throw new Error(errorPrefix +
|
10715 | ' contains an invalid key (' +
|
10716 | key +
|
10717 | ') ' +
|
10718 | validationPathToErrorString(path) +
|
10719 | '. Keys must be non-empty strings ' +
|
10720 | 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
|
10721 | }
|
10722 | }
|
10723 | validationPathPush(path, key);
|
10724 | validateFirebaseData(errorPrefix, value, path);
|
10725 | validationPathPop(path);
|
10726 | });
|
10727 | if (hasDotValue && hasActualChild) {
|
10728 | throw new Error(errorPrefix +
|
10729 | ' contains ".value" child ' +
|
10730 | validationPathToErrorString(path) +
|
10731 | ' in addition to actual children.');
|
10732 | }
|
10733 | }
|
10734 | };
|
10735 |
|
10736 |
|
10737 |
|
10738 | const validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
|
10739 | let i, curPath;
|
10740 | for (i = 0; i < mergePaths.length; i++) {
|
10741 | curPath = mergePaths[i];
|
10742 | const keys = pathSlice(curPath);
|
10743 | for (let j = 0; j < keys.length; j++) {
|
10744 | if (keys[j] === '.priority' && j === keys.length - 1) ;
|
10745 | else if (!isValidKey(keys[j])) {
|
10746 | throw new Error(errorPrefix +
|
10747 | 'contains an invalid key (' +
|
10748 | keys[j] +
|
10749 | ') in path ' +
|
10750 | curPath.toString() +
|
10751 | '. Keys must be non-empty strings ' +
|
10752 | 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
|
10753 | }
|
10754 | }
|
10755 | }
|
10756 |
|
10757 |
|
10758 |
|
10759 | mergePaths.sort(pathCompare);
|
10760 | let prevPath = null;
|
10761 | for (i = 0; i < mergePaths.length; i++) {
|
10762 | curPath = mergePaths[i];
|
10763 | if (prevPath !== null && pathContains(prevPath, curPath)) {
|
10764 | throw new Error(errorPrefix +
|
10765 | 'contains a path ' +
|
10766 | prevPath.toString() +
|
10767 | ' that is ancestor of another path ' +
|
10768 | curPath.toString());
|
10769 | }
|
10770 | prevPath = curPath;
|
10771 | }
|
10772 | };
|
10773 |
|
10774 |
|
10775 |
|
10776 |
|
10777 | const validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
|
10778 | if (optional && data === undefined) {
|
10779 | return;
|
10780 | }
|
10781 | const errorPrefix$1 = errorPrefix(fnName, 'values');
|
10782 | if (!(data && typeof data === 'object') || Array.isArray(data)) {
|
10783 | throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');
|
10784 | }
|
10785 | const mergePaths = [];
|
10786 | each(data, (key, value) => {
|
10787 | const curPath = new Path(key);
|
10788 | validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));
|
10789 | if (pathGetBack(curPath) === '.priority') {
|
10790 | if (!isValidPriority(value)) {
|
10791 | throw new Error(errorPrefix$1 +
|
10792 | "contains an invalid value for '" +
|
10793 | curPath.toString() +
|
10794 | "', which must be a valid " +
|
10795 | 'Firebase priority (a string, finite number, server value, or null).');
|
10796 | }
|
10797 | }
|
10798 | mergePaths.push(curPath);
|
10799 | });
|
10800 | validateFirebaseMergePaths(errorPrefix$1, mergePaths);
|
10801 | };
|
10802 | const validatePriority = function (fnName, priority, optional) {
|
10803 | if (optional && priority === undefined) {
|
10804 | return;
|
10805 | }
|
10806 | if (isInvalidJSONNumber(priority)) {
|
10807 | throw new Error(errorPrefix(fnName, 'priority') +
|
10808 | 'is ' +
|
10809 | priority.toString() +
|
10810 | ', but must be a valid Firebase priority (a string, finite number, ' +
|
10811 | 'server value, or null).');
|
10812 | }
|
10813 |
|
10814 | if (!isValidPriority(priority)) {
|
10815 | throw new Error(errorPrefix(fnName, 'priority') +
|
10816 | 'must be a valid Firebase priority ' +
|
10817 | '(a string, finite number, server value, or null).');
|
10818 | }
|
10819 | };
|
10820 | const validateKey = function (fnName, argumentName, key, optional) {
|
10821 | if (optional && key === undefined) {
|
10822 | return;
|
10823 | }
|
10824 | if (!isValidKey(key)) {
|
10825 | throw new Error(errorPrefix(fnName, argumentName) +
|
10826 | 'was an invalid key = "' +
|
10827 | key +
|
10828 | '". Firebase keys must be non-empty strings and ' +
|
10829 | 'can\'t contain ".", "#", "$", "/", "[", or "]").');
|
10830 | }
|
10831 | };
|
10832 |
|
10833 |
|
10834 |
|
10835 | const validatePathString = function (fnName, argumentName, pathString, optional) {
|
10836 | if (optional && pathString === undefined) {
|
10837 | return;
|
10838 | }
|
10839 | if (!isValidPathString(pathString)) {
|
10840 | throw new Error(errorPrefix(fnName, argumentName) +
|
10841 | 'was an invalid path = "' +
|
10842 | pathString +
|
10843 | '". Paths must be non-empty strings and ' +
|
10844 | 'can\'t contain ".", "#", "$", "[", or "]"');
|
10845 | }
|
10846 | };
|
10847 | const validateRootPathString = function (fnName, argumentName, pathString, optional) {
|
10848 | if (pathString) {
|
10849 |
|
10850 | pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
|
10851 | }
|
10852 | validatePathString(fnName, argumentName, pathString, optional);
|
10853 | };
|
10854 |
|
10855 |
|
10856 |
|
10857 | const validateWritablePath = function (fnName, path) {
|
10858 | if (pathGetFront(path) === '.info') {
|
10859 | throw new Error(fnName + " failed = Can't modify data under /.info/");
|
10860 | }
|
10861 | };
|
10862 | const validateUrl = function (fnName, parsedUrl) {
|
10863 |
|
10864 | const pathString = parsedUrl.path.toString();
|
10865 | if (!(typeof parsedUrl.repoInfo.host === 'string') ||
|
10866 | parsedUrl.repoInfo.host.length === 0 ||
|
10867 | (!isValidKey(parsedUrl.repoInfo.namespace) &&
|
10868 | parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
|
10869 | (pathString.length !== 0 && !isValidRootPathString(pathString))) {
|
10870 | throw new Error(errorPrefix(fnName, 'url') +
|
10871 | 'must be a valid firebase URL and ' +
|
10872 | 'the path can\'t contain ".", "#", "$", "[", or "]".');
|
10873 | }
|
10874 | };
|
10875 |
|
10876 |
|
10877 |
|
10878 |
|
10879 |
|
10880 |
|
10881 |
|
10882 |
|
10883 |
|
10884 |
|
10885 |
|
10886 |
|
10887 |
|
10888 |
|
10889 |
|
10890 |
|
10891 |
|
10892 |
|
10893 |
|
10894 |
|
10895 |
|
10896 |
|
10897 |
|
10898 |
|
10899 |
|
10900 |
|
10901 |
|
10902 |
|
10903 |
|
10904 |
|
10905 | class EventQueue {
|
10906 | constructor() {
|
10907 | this.eventLists_ = [];
|
10908 | |
10909 |
|
10910 |
|
10911 | this.recursionDepth_ = 0;
|
10912 | }
|
10913 | }
|
10914 |
|
10915 |
|
10916 |
|
10917 | function eventQueueQueueEvents(eventQueue, eventDataList) {
|
10918 |
|
10919 | let currList = null;
|
10920 | for (let i = 0; i < eventDataList.length; i++) {
|
10921 | const data = eventDataList[i];
|
10922 | const path = data.getPath();
|
10923 | if (currList !== null && !pathEquals(path, currList.path)) {
|
10924 | eventQueue.eventLists_.push(currList);
|
10925 | currList = null;
|
10926 | }
|
10927 | if (currList === null) {
|
10928 | currList = { events: [], path };
|
10929 | }
|
10930 | currList.events.push(data);
|
10931 | }
|
10932 | if (currList) {
|
10933 | eventQueue.eventLists_.push(currList);
|
10934 | }
|
10935 | }
|
10936 |
|
10937 |
|
10938 |
|
10939 |
|
10940 |
|
10941 |
|
10942 |
|
10943 |
|
10944 |
|
10945 | function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
|
10946 | eventQueueQueueEvents(eventQueue, eventDataList);
|
10947 | eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));
|
10948 | }
|
10949 |
|
10950 |
|
10951 |
|
10952 |
|
10953 |
|
10954 |
|
10955 |
|
10956 |
|
10957 |
|
10958 | function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
|
10959 | eventQueueQueueEvents(eventQueue, eventDataList);
|
10960 | eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||
|
10961 | pathContains(changedPath, eventPath));
|
10962 | }
|
10963 | function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
|
10964 | eventQueue.recursionDepth_++;
|
10965 | let sentAll = true;
|
10966 | for (let i = 0; i < eventQueue.eventLists_.length; i++) {
|
10967 | const eventList = eventQueue.eventLists_[i];
|
10968 | if (eventList) {
|
10969 | const eventPath = eventList.path;
|
10970 | if (predicate(eventPath)) {
|
10971 | eventListRaise(eventQueue.eventLists_[i]);
|
10972 | eventQueue.eventLists_[i] = null;
|
10973 | }
|
10974 | else {
|
10975 | sentAll = false;
|
10976 | }
|
10977 | }
|
10978 | }
|
10979 | if (sentAll) {
|
10980 | eventQueue.eventLists_ = [];
|
10981 | }
|
10982 | eventQueue.recursionDepth_--;
|
10983 | }
|
10984 |
|
10985 |
|
10986 |
|
10987 | function eventListRaise(eventList) {
|
10988 | for (let i = 0; i < eventList.events.length; i++) {
|
10989 | const eventData = eventList.events[i];
|
10990 | if (eventData !== null) {
|
10991 | eventList.events[i] = null;
|
10992 | const eventFn = eventData.getEventRunner();
|
10993 | if (logger) {
|
10994 | log('event: ' + eventData.toString());
|
10995 | }
|
10996 | exceptionGuard(eventFn);
|
10997 | }
|
10998 | }
|
10999 | }
|
11000 |
|
11001 |
|
11002 |
|
11003 |
|
11004 |
|
11005 |
|
11006 |
|
11007 |
|
11008 |
|
11009 |
|
11010 |
|
11011 |
|
11012 |
|
11013 |
|
11014 |
|
11015 |
|
11016 |
|
11017 | const INTERRUPT_REASON = 'repo_interrupt';
|
11018 |
|
11019 |
|
11020 |
|
11021 |
|
11022 |
|
11023 | const MAX_TRANSACTION_RETRIES = 25;
|
11024 |
|
11025 |
|
11026 |
|
11027 | class Repo {
|
11028 | constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
|
11029 | this.repoInfo_ = repoInfo_;
|
11030 | this.forceRestClient_ = forceRestClient_;
|
11031 | this.authTokenProvider_ = authTokenProvider_;
|
11032 | this.appCheckProvider_ = appCheckProvider_;
|
11033 | this.dataUpdateCount = 0;
|
11034 | this.statsListener_ = null;
|
11035 | this.eventQueue_ = new EventQueue();
|
11036 | this.nextWriteId_ = 1;
|
11037 | this.interceptServerDataCallback_ = null;
|
11038 |
|
11039 | this.onDisconnect_ = newSparseSnapshotTree();
|
11040 |
|
11041 | this.transactionQueueTree_ = new Tree();
|
11042 |
|
11043 | this.persistentConnection_ = null;
|
11044 |
|
11045 | this.key = this.repoInfo_.toURLString();
|
11046 | }
|
11047 | |
11048 |
|
11049 |
|
11050 | toString() {
|
11051 | return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
|
11052 | }
|
11053 | }
|
11054 | function repoStart(repo, appId, authOverride) {
|
11055 | repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
|
11056 | if (repo.forceRestClient_ || beingCrawled()) {
|
11057 | repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
|
11058 | repoOnDataUpdate(repo, pathString, data, isMerge, tag);
|
11059 | }, repo.authTokenProvider_, repo.appCheckProvider_);
|
11060 |
|
11061 | setTimeout(() => repoOnConnectStatus(repo, true), 0);
|
11062 | }
|
11063 | else {
|
11064 |
|
11065 | if (typeof authOverride !== 'undefined' && authOverride !== null) {
|
11066 | if (typeof authOverride !== 'object') {
|
11067 | throw new Error('Only objects are supported for option databaseAuthVariableOverride');
|
11068 | }
|
11069 | try {
|
11070 | stringify(authOverride);
|
11071 | }
|
11072 | catch (e) {
|
11073 | throw new Error('Invalid authOverride provided: ' + e);
|
11074 | }
|
11075 | }
|
11076 | repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
|
11077 | repoOnDataUpdate(repo, pathString, data, isMerge, tag);
|
11078 | }, (connectStatus) => {
|
11079 | repoOnConnectStatus(repo, connectStatus);
|
11080 | }, (updates) => {
|
11081 | repoOnServerInfoUpdate(repo, updates);
|
11082 | }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
|
11083 | repo.server_ = repo.persistentConnection_;
|
11084 | }
|
11085 | repo.authTokenProvider_.addTokenChangeListener(token => {
|
11086 | repo.server_.refreshAuthToken(token);
|
11087 | });
|
11088 | repo.appCheckProvider_.addTokenChangeListener(result => {
|
11089 | repo.server_.refreshAppCheckToken(result.token);
|
11090 | });
|
11091 |
|
11092 |
|
11093 | repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
|
11094 |
|
11095 | repo.infoData_ = new SnapshotHolder();
|
11096 | repo.infoSyncTree_ = new SyncTree({
|
11097 | startListening: (query, tag, currentHashFn, onComplete) => {
|
11098 | let infoEvents = [];
|
11099 | const node = repo.infoData_.getNode(query._path);
|
11100 |
|
11101 |
|
11102 | if (!node.isEmpty()) {
|
11103 | infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
|
11104 | setTimeout(() => {
|
11105 | onComplete('ok');
|
11106 | }, 0);
|
11107 | }
|
11108 | return infoEvents;
|
11109 | },
|
11110 | stopListening: () => { }
|
11111 | });
|
11112 | repoUpdateInfo(repo, 'connected', false);
|
11113 | repo.serverSyncTree_ = new SyncTree({
|
11114 | startListening: (query, tag, currentHashFn, onComplete) => {
|
11115 | repo.server_.listen(query, currentHashFn, tag, (status, data) => {
|
11116 | const events = onComplete(status, data);
|
11117 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
|
11118 | });
|
11119 |
|
11120 | return [];
|
11121 | },
|
11122 | stopListening: (query, tag) => {
|
11123 | repo.server_.unlisten(query, tag);
|
11124 | }
|
11125 | });
|
11126 | }
|
11127 |
|
11128 |
|
11129 |
|
11130 | function repoServerTime(repo) {
|
11131 | const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
|
11132 | const offset = offsetNode.val() || 0;
|
11133 | return new Date().getTime() + offset;
|
11134 | }
|
11135 |
|
11136 |
|
11137 |
|
11138 | function repoGenerateServerValues(repo) {
|
11139 | return generateWithValues({
|
11140 | timestamp: repoServerTime(repo)
|
11141 | });
|
11142 | }
|
11143 |
|
11144 |
|
11145 |
|
11146 | function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
|
11147 |
|
11148 | repo.dataUpdateCount++;
|
11149 | const path = new Path(pathString);
|
11150 | data = repo.interceptServerDataCallback_
|
11151 | ? repo.interceptServerDataCallback_(pathString, data)
|
11152 | : data;
|
11153 | let events = [];
|
11154 | if (tag) {
|
11155 | if (isMerge) {
|
11156 | const taggedChildren = map(data, (raw) => nodeFromJSON(raw));
|
11157 | events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
|
11158 | }
|
11159 | else {
|
11160 | const taggedSnap = nodeFromJSON(data);
|
11161 | events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
|
11162 | }
|
11163 | }
|
11164 | else if (isMerge) {
|
11165 | const changedChildren = map(data, (raw) => nodeFromJSON(raw));
|
11166 | events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
|
11167 | }
|
11168 | else {
|
11169 | const snap = nodeFromJSON(data);
|
11170 | events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
|
11171 | }
|
11172 | let affectedPath = path;
|
11173 | if (events.length > 0) {
|
11174 |
|
11175 |
|
11176 | affectedPath = repoRerunTransactions(repo, path);
|
11177 | }
|
11178 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
|
11179 | }
|
11180 | function repoOnConnectStatus(repo, connectStatus) {
|
11181 | repoUpdateInfo(repo, 'connected', connectStatus);
|
11182 | if (connectStatus === false) {
|
11183 | repoRunOnDisconnectEvents(repo);
|
11184 | }
|
11185 | }
|
11186 | function repoOnServerInfoUpdate(repo, updates) {
|
11187 | each(updates, (key, value) => {
|
11188 | repoUpdateInfo(repo, key, value);
|
11189 | });
|
11190 | }
|
11191 | function repoUpdateInfo(repo, pathString, value) {
|
11192 | const path = new Path('/.info/' + pathString);
|
11193 | const newNode = nodeFromJSON(value);
|
11194 | repo.infoData_.updateSnapshot(path, newNode);
|
11195 | const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
|
11196 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
|
11197 | }
|
11198 | function repoGetNextWriteId(repo) {
|
11199 | return repo.nextWriteId_++;
|
11200 | }
|
11201 |
|
11202 |
|
11203 |
|
11204 |
|
11205 |
|
11206 |
|
11207 |
|
11208 |
|
11209 |
|
11210 |
|
11211 |
|
11212 |
|
11213 |
|
11214 |
|
11215 |
|
11216 | function repoGetValue(repo, query) {
|
11217 |
|
11218 | const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
|
11219 | if (cached != null) {
|
11220 | return Promise.resolve(cached);
|
11221 | }
|
11222 | return repo.server_.get(query).then(payload => {
|
11223 | const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
|
11224 |
|
11225 | if (query._queryParams.loadsAllData()) {
|
11226 | syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
|
11227 | }
|
11228 | else {
|
11229 |
|
11230 |
|
11231 |
|
11232 |
|
11233 | const tag = syncTreeRegisterQuery(repo.serverSyncTree_, query);
|
11234 | syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
|
11235 |
|
11236 |
|
11237 | }
|
11238 | const cancels = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, null);
|
11239 | if (cancels.length > 0) {
|
11240 | repoLog(repo, 'unexpected cancel events in repoGetValue');
|
11241 | }
|
11242 | return node;
|
11243 | }, err => {
|
11244 | repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);
|
11245 | return Promise.reject(new Error(err));
|
11246 | });
|
11247 | }
|
11248 | function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
|
11249 | repoLog(repo, 'set', {
|
11250 | path: path.toString(),
|
11251 | value: newVal,
|
11252 | priority: newPriority
|
11253 | });
|
11254 |
|
11255 |
|
11256 | const serverValues = repoGenerateServerValues(repo);
|
11257 | const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
|
11258 | const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
|
11259 | const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
|
11260 | const writeId = repoGetNextWriteId(repo);
|
11261 | const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
|
11262 | eventQueueQueueEvents(repo.eventQueue_, events);
|
11263 | repo.server_.put(path.toString(), newNodeUnresolved.val( true), (status, errorReason) => {
|
11264 | const success = status === 'ok';
|
11265 | if (!success) {
|
11266 | warn('set at ' + path + ' failed: ' + status);
|
11267 | }
|
11268 | const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
|
11269 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
|
11270 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11271 | });
|
11272 | const affectedPath = repoAbortTransactions(repo, path);
|
11273 | repoRerunTransactions(repo, affectedPath);
|
11274 |
|
11275 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
|
11276 | }
|
11277 | function repoUpdate(repo, path, childrenToMerge, onComplete) {
|
11278 | repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
|
11279 |
|
11280 | let empty = true;
|
11281 | const serverValues = repoGenerateServerValues(repo);
|
11282 | const changedChildren = {};
|
11283 | each(childrenToMerge, (changedKey, changedValue) => {
|
11284 | empty = false;
|
11285 | changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
|
11286 | });
|
11287 | if (!empty) {
|
11288 | const writeId = repoGetNextWriteId(repo);
|
11289 | const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);
|
11290 | eventQueueQueueEvents(repo.eventQueue_, events);
|
11291 | repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {
|
11292 | const success = status === 'ok';
|
11293 | if (!success) {
|
11294 | warn('update at ' + path + ' failed: ' + status);
|
11295 | }
|
11296 | const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
|
11297 | const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
|
11298 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
|
11299 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11300 | });
|
11301 | each(childrenToMerge, (changedPath) => {
|
11302 | const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
|
11303 | repoRerunTransactions(repo, affectedPath);
|
11304 | });
|
11305 |
|
11306 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
|
11307 | }
|
11308 | else {
|
11309 | log("update() called with empty data. Don't do anything.");
|
11310 | repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
|
11311 | }
|
11312 | }
|
11313 |
|
11314 |
|
11315 |
|
11316 | function repoRunOnDisconnectEvents(repo) {
|
11317 | repoLog(repo, 'onDisconnectEvents');
|
11318 | const serverValues = repoGenerateServerValues(repo);
|
11319 | const resolvedOnDisconnectTree = newSparseSnapshotTree();
|
11320 | sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
|
11321 | const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
|
11322 | sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
|
11323 | });
|
11324 | let events = [];
|
11325 | sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
|
11326 | events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
|
11327 | const affectedPath = repoAbortTransactions(repo, path);
|
11328 | repoRerunTransactions(repo, affectedPath);
|
11329 | });
|
11330 | repo.onDisconnect_ = newSparseSnapshotTree();
|
11331 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
|
11332 | }
|
11333 | function repoOnDisconnectCancel(repo, path, onComplete) {
|
11334 | repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {
|
11335 | if (status === 'ok') {
|
11336 | sparseSnapshotTreeForget(repo.onDisconnect_, path);
|
11337 | }
|
11338 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11339 | });
|
11340 | }
|
11341 | function repoOnDisconnectSet(repo, path, value, onComplete) {
|
11342 | const newNode = nodeFromJSON(value);
|
11343 | repo.server_.onDisconnectPut(path.toString(), newNode.val( true), (status, errorReason) => {
|
11344 | if (status === 'ok') {
|
11345 | sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
|
11346 | }
|
11347 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11348 | });
|
11349 | }
|
11350 | function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
|
11351 | const newNode = nodeFromJSON(value, priority);
|
11352 | repo.server_.onDisconnectPut(path.toString(), newNode.val( true), (status, errorReason) => {
|
11353 | if (status === 'ok') {
|
11354 | sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
|
11355 | }
|
11356 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11357 | });
|
11358 | }
|
11359 | function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
|
11360 | if (isEmpty(childrenToMerge)) {
|
11361 | log("onDisconnect().update() called with empty data. Don't do anything.");
|
11362 | repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
|
11363 | return;
|
11364 | }
|
11365 | repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {
|
11366 | if (status === 'ok') {
|
11367 | each(childrenToMerge, (childName, childNode) => {
|
11368 | const newChildNode = nodeFromJSON(childNode);
|
11369 | sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
|
11370 | });
|
11371 | }
|
11372 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11373 | });
|
11374 | }
|
11375 | function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
|
11376 | let events;
|
11377 | if (pathGetFront(query._path) === '.info') {
|
11378 | events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
|
11379 | }
|
11380 | else {
|
11381 | events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
|
11382 | }
|
11383 | eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
|
11384 | }
|
11385 | function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
|
11386 |
|
11387 |
|
11388 | let events;
|
11389 | if (pathGetFront(query._path) === '.info') {
|
11390 | events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
|
11391 | }
|
11392 | else {
|
11393 | events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
|
11394 | }
|
11395 | eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
|
11396 | }
|
11397 | function repoInterrupt(repo) {
|
11398 | if (repo.persistentConnection_) {
|
11399 | repo.persistentConnection_.interrupt(INTERRUPT_REASON);
|
11400 | }
|
11401 | }
|
11402 | function repoResume(repo) {
|
11403 | if (repo.persistentConnection_) {
|
11404 | repo.persistentConnection_.resume(INTERRUPT_REASON);
|
11405 | }
|
11406 | }
|
11407 | function repoLog(repo, ...varArgs) {
|
11408 | let prefix = '';
|
11409 | if (repo.persistentConnection_) {
|
11410 | prefix = repo.persistentConnection_.id + ':';
|
11411 | }
|
11412 | log(prefix, ...varArgs);
|
11413 | }
|
11414 | function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
|
11415 | if (callback) {
|
11416 | exceptionGuard(() => {
|
11417 | if (status === 'ok') {
|
11418 | callback(null);
|
11419 | }
|
11420 | else {
|
11421 | const code = (status || 'error').toUpperCase();
|
11422 | let message = code;
|
11423 | if (errorReason) {
|
11424 | message += ': ' + errorReason;
|
11425 | }
|
11426 | const error = new Error(message);
|
11427 |
|
11428 | error.code = code;
|
11429 | callback(error);
|
11430 | }
|
11431 | });
|
11432 | }
|
11433 | }
|
11434 |
|
11435 |
|
11436 |
|
11437 |
|
11438 |
|
11439 |
|
11440 |
|
11441 |
|
11442 |
|
11443 |
|
11444 |
|
11445 | function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
|
11446 | repoLog(repo, 'transaction on ' + path);
|
11447 |
|
11448 | const transaction = {
|
11449 | path,
|
11450 | update: transactionUpdate,
|
11451 | onComplete,
|
11452 |
|
11453 | status: null,
|
11454 |
|
11455 |
|
11456 | order: LUIDGenerator(),
|
11457 |
|
11458 | applyLocally,
|
11459 |
|
11460 | retryCount: 0,
|
11461 |
|
11462 | unwatcher,
|
11463 |
|
11464 | abortReason: null,
|
11465 | currentWriteId: null,
|
11466 | currentInputSnapshot: null,
|
11467 | currentOutputSnapshotRaw: null,
|
11468 | currentOutputSnapshotResolved: null
|
11469 | };
|
11470 |
|
11471 | const currentState = repoGetLatestState(repo, path, undefined);
|
11472 | transaction.currentInputSnapshot = currentState;
|
11473 | const newVal = transaction.update(currentState.val());
|
11474 | if (newVal === undefined) {
|
11475 |
|
11476 | transaction.unwatcher();
|
11477 | transaction.currentOutputSnapshotRaw = null;
|
11478 | transaction.currentOutputSnapshotResolved = null;
|
11479 | if (transaction.onComplete) {
|
11480 | transaction.onComplete(null, false, transaction.currentInputSnapshot);
|
11481 | }
|
11482 | }
|
11483 | else {
|
11484 | validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
|
11485 |
|
11486 | transaction.status = 0 ;
|
11487 | const queueNode = treeSubTree(repo.transactionQueueTree_, path);
|
11488 | const nodeQueue = treeGetValue(queueNode) || [];
|
11489 | nodeQueue.push(transaction);
|
11490 | treeSetValue(queueNode, nodeQueue);
|
11491 |
|
11492 |
|
11493 |
|
11494 |
|
11495 | let priorityForNode;
|
11496 | if (typeof newVal === 'object' &&
|
11497 | newVal !== null &&
|
11498 | contains(newVal, '.priority')) {
|
11499 |
|
11500 | priorityForNode = safeGet(newVal, '.priority');
|
11501 | assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
|
11502 | 'Priority must be a valid string, finite number, server value, or null.');
|
11503 | }
|
11504 | else {
|
11505 | const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
|
11506 | ChildrenNode.EMPTY_NODE;
|
11507 | priorityForNode = currentNode.getPriority().val();
|
11508 | }
|
11509 | const serverValues = repoGenerateServerValues(repo);
|
11510 | const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
|
11511 | const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
|
11512 | transaction.currentOutputSnapshotRaw = newNodeUnresolved;
|
11513 | transaction.currentOutputSnapshotResolved = newNode;
|
11514 | transaction.currentWriteId = repoGetNextWriteId(repo);
|
11515 | const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
|
11516 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
|
11517 | repoSendReadyTransactions(repo, repo.transactionQueueTree_);
|
11518 | }
|
11519 | }
|
11520 |
|
11521 |
|
11522 |
|
11523 | function repoGetLatestState(repo, path, excludeSets) {
|
11524 | return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
|
11525 | ChildrenNode.EMPTY_NODE);
|
11526 | }
|
11527 |
|
11528 |
|
11529 |
|
11530 |
|
11531 |
|
11532 |
|
11533 |
|
11534 |
|
11535 |
|
11536 | function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
|
11537 |
|
11538 | if (!node) {
|
11539 | repoPruneCompletedTransactionsBelowNode(repo, node);
|
11540 | }
|
11541 | if (treeGetValue(node)) {
|
11542 | const queue = repoBuildTransactionQueue(repo, node);
|
11543 | assert(queue.length > 0, 'Sending zero length transaction queue');
|
11544 | const allRun = queue.every((transaction) => transaction.status === 0 );
|
11545 |
|
11546 | if (allRun) {
|
11547 | repoSendTransactionQueue(repo, treeGetPath(node), queue);
|
11548 | }
|
11549 | }
|
11550 | else if (treeHasChildren(node)) {
|
11551 | treeForEachChild(node, childNode => {
|
11552 | repoSendReadyTransactions(repo, childNode);
|
11553 | });
|
11554 | }
|
11555 | }
|
11556 |
|
11557 |
|
11558 |
|
11559 |
|
11560 |
|
11561 |
|
11562 |
|
11563 | function repoSendTransactionQueue(repo, path, queue) {
|
11564 |
|
11565 | const setsToIgnore = queue.map(txn => {
|
11566 | return txn.currentWriteId;
|
11567 | });
|
11568 | const latestState = repoGetLatestState(repo, path, setsToIgnore);
|
11569 | let snapToSend = latestState;
|
11570 | const latestHash = latestState.hash();
|
11571 | for (let i = 0; i < queue.length; i++) {
|
11572 | const txn = queue[i];
|
11573 | assert(txn.status === 0 , 'tryToSendTransactionQueue_: items in queue should all be run.');
|
11574 | txn.status = 1 ;
|
11575 | txn.retryCount++;
|
11576 | const relativePath = newRelativePath(path, txn.path);
|
11577 |
|
11578 | snapToSend = snapToSend.updateChild(relativePath , txn.currentOutputSnapshotRaw);
|
11579 | }
|
11580 | const dataToSend = snapToSend.val(true);
|
11581 | const pathToSend = path;
|
11582 |
|
11583 | repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
|
11584 | repoLog(repo, 'transaction put response', {
|
11585 | path: pathToSend.toString(),
|
11586 | status
|
11587 | });
|
11588 | let events = [];
|
11589 | if (status === 'ok') {
|
11590 |
|
11591 |
|
11592 |
|
11593 | const callbacks = [];
|
11594 | for (let i = 0; i < queue.length; i++) {
|
11595 | queue[i].status = 2 ;
|
11596 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
|
11597 | if (queue[i].onComplete) {
|
11598 |
|
11599 |
|
11600 | callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));
|
11601 | }
|
11602 | queue[i].unwatcher();
|
11603 | }
|
11604 |
|
11605 | repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
|
11606 |
|
11607 | repoSendReadyTransactions(repo, repo.transactionQueueTree_);
|
11608 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
|
11609 |
|
11610 | for (let i = 0; i < callbacks.length; i++) {
|
11611 | exceptionGuard(callbacks[i]);
|
11612 | }
|
11613 | }
|
11614 | else {
|
11615 |
|
11616 | if (status === 'datastale') {
|
11617 | for (let i = 0; i < queue.length; i++) {
|
11618 | if (queue[i].status === 3 ) {
|
11619 | queue[i].status = 4 ;
|
11620 | }
|
11621 | else {
|
11622 | queue[i].status = 0 ;
|
11623 | }
|
11624 | }
|
11625 | }
|
11626 | else {
|
11627 | warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
|
11628 | for (let i = 0; i < queue.length; i++) {
|
11629 | queue[i].status = 4 ;
|
11630 | queue[i].abortReason = status;
|
11631 | }
|
11632 | }
|
11633 | repoRerunTransactions(repo, path);
|
11634 | }
|
11635 | }, latestHash);
|
11636 | }
|
11637 |
|
11638 |
|
11639 |
|
11640 |
|
11641 |
|
11642 |
|
11643 |
|
11644 |
|
11645 |
|
11646 |
|
11647 |
|
11648 | function repoRerunTransactions(repo, changedPath) {
|
11649 | const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
|
11650 | const path = treeGetPath(rootMostTransactionNode);
|
11651 | const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
|
11652 | repoRerunTransactionQueue(repo, queue, path);
|
11653 | return path;
|
11654 | }
|
11655 |
|
11656 |
|
11657 |
|
11658 |
|
11659 |
|
11660 |
|
11661 |
|
11662 | function repoRerunTransactionQueue(repo, queue, path) {
|
11663 | if (queue.length === 0) {
|
11664 | return;
|
11665 | }
|
11666 |
|
11667 |
|
11668 |
|
11669 | const callbacks = [];
|
11670 | let events = [];
|
11671 |
|
11672 | const txnsToRerun = queue.filter(q => {
|
11673 | return q.status === 0 ;
|
11674 | });
|
11675 | const setsToIgnore = txnsToRerun.map(q => {
|
11676 | return q.currentWriteId;
|
11677 | });
|
11678 | for (let i = 0; i < queue.length; i++) {
|
11679 | const transaction = queue[i];
|
11680 | const relativePath = newRelativePath(path, transaction.path);
|
11681 | let abortTransaction = false, abortReason;
|
11682 | assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
|
11683 | if (transaction.status === 4 ) {
|
11684 | abortTransaction = true;
|
11685 | abortReason = transaction.abortReason;
|
11686 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
|
11687 | }
|
11688 | else if (transaction.status === 0 ) {
|
11689 | if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
|
11690 | abortTransaction = true;
|
11691 | abortReason = 'maxretry';
|
11692 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
|
11693 | }
|
11694 | else {
|
11695 |
|
11696 | const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
|
11697 | transaction.currentInputSnapshot = currentNode;
|
11698 | const newData = queue[i].update(currentNode.val());
|
11699 | if (newData !== undefined) {
|
11700 | validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
|
11701 | let newDataNode = nodeFromJSON(newData);
|
11702 | const hasExplicitPriority = typeof newData === 'object' &&
|
11703 | newData != null &&
|
11704 | contains(newData, '.priority');
|
11705 | if (!hasExplicitPriority) {
|
11706 |
|
11707 | newDataNode = newDataNode.updatePriority(currentNode.getPriority());
|
11708 | }
|
11709 | const oldWriteId = transaction.currentWriteId;
|
11710 | const serverValues = repoGenerateServerValues(repo);
|
11711 | const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
|
11712 | transaction.currentOutputSnapshotRaw = newDataNode;
|
11713 | transaction.currentOutputSnapshotResolved = newNodeResolved;
|
11714 | transaction.currentWriteId = repoGetNextWriteId(repo);
|
11715 |
|
11716 | setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
|
11717 | events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
|
11718 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
|
11719 | }
|
11720 | else {
|
11721 | abortTransaction = true;
|
11722 | abortReason = 'nodata';
|
11723 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
|
11724 | }
|
11725 | }
|
11726 | }
|
11727 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
|
11728 | events = [];
|
11729 | if (abortTransaction) {
|
11730 |
|
11731 | queue[i].status = 2 ;
|
11732 |
|
11733 |
|
11734 |
|
11735 | (function (unwatcher) {
|
11736 | setTimeout(unwatcher, Math.floor(0));
|
11737 | })(queue[i].unwatcher);
|
11738 | if (queue[i].onComplete) {
|
11739 | if (abortReason === 'nodata') {
|
11740 | callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));
|
11741 | }
|
11742 | else {
|
11743 | callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));
|
11744 | }
|
11745 | }
|
11746 | }
|
11747 | }
|
11748 |
|
11749 | repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
|
11750 |
|
11751 | for (let i = 0; i < callbacks.length; i++) {
|
11752 | exceptionGuard(callbacks[i]);
|
11753 | }
|
11754 |
|
11755 | repoSendReadyTransactions(repo, repo.transactionQueueTree_);
|
11756 | }
|
11757 |
|
11758 |
|
11759 |
|
11760 |
|
11761 |
|
11762 |
|
11763 |
|
11764 |
|
11765 | function repoGetAncestorTransactionNode(repo, path) {
|
11766 | let front;
|
11767 |
|
11768 |
|
11769 | let transactionNode = repo.transactionQueueTree_;
|
11770 | front = pathGetFront(path);
|
11771 | while (front !== null && treeGetValue(transactionNode) === undefined) {
|
11772 | transactionNode = treeSubTree(transactionNode, front);
|
11773 | path = pathPopFront(path);
|
11774 | front = pathGetFront(path);
|
11775 | }
|
11776 | return transactionNode;
|
11777 | }
|
11778 |
|
11779 |
|
11780 |
|
11781 |
|
11782 |
|
11783 |
|
11784 |
|
11785 | function repoBuildTransactionQueue(repo, transactionNode) {
|
11786 |
|
11787 | const transactionQueue = [];
|
11788 | repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
|
11789 |
|
11790 | transactionQueue.sort((a, b) => a.order - b.order);
|
11791 | return transactionQueue;
|
11792 | }
|
11793 | function repoAggregateTransactionQueuesForNode(repo, node, queue) {
|
11794 | const nodeQueue = treeGetValue(node);
|
11795 | if (nodeQueue) {
|
11796 | for (let i = 0; i < nodeQueue.length; i++) {
|
11797 | queue.push(nodeQueue[i]);
|
11798 | }
|
11799 | }
|
11800 | treeForEachChild(node, child => {
|
11801 | repoAggregateTransactionQueuesForNode(repo, child, queue);
|
11802 | });
|
11803 | }
|
11804 |
|
11805 |
|
11806 |
|
11807 | function repoPruneCompletedTransactionsBelowNode(repo, node) {
|
11808 | const queue = treeGetValue(node);
|
11809 | if (queue) {
|
11810 | let to = 0;
|
11811 | for (let from = 0; from < queue.length; from++) {
|
11812 | if (queue[from].status !== 2 ) {
|
11813 | queue[to] = queue[from];
|
11814 | to++;
|
11815 | }
|
11816 | }
|
11817 | queue.length = to;
|
11818 | treeSetValue(node, queue.length > 0 ? queue : undefined);
|
11819 | }
|
11820 | treeForEachChild(node, childNode => {
|
11821 | repoPruneCompletedTransactionsBelowNode(repo, childNode);
|
11822 | });
|
11823 | }
|
11824 |
|
11825 |
|
11826 |
|
11827 |
|
11828 |
|
11829 |
|
11830 |
|
11831 | function repoAbortTransactions(repo, path) {
|
11832 | const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
|
11833 | const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
|
11834 | treeForEachAncestor(transactionNode, (node) => {
|
11835 | repoAbortTransactionsOnNode(repo, node);
|
11836 | });
|
11837 | repoAbortTransactionsOnNode(repo, transactionNode);
|
11838 | treeForEachDescendant(transactionNode, (node) => {
|
11839 | repoAbortTransactionsOnNode(repo, node);
|
11840 | });
|
11841 | return affectedPath;
|
11842 | }
|
11843 |
|
11844 |
|
11845 |
|
11846 |
|
11847 |
|
11848 | function repoAbortTransactionsOnNode(repo, node) {
|
11849 | const queue = treeGetValue(node);
|
11850 | if (queue) {
|
11851 |
|
11852 |
|
11853 |
|
11854 | const callbacks = [];
|
11855 |
|
11856 |
|
11857 | let events = [];
|
11858 | let lastSent = -1;
|
11859 | for (let i = 0; i < queue.length; i++) {
|
11860 | if (queue[i].status === 3 ) ;
|
11861 | else if (queue[i].status === 1 ) {
|
11862 | assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
|
11863 | lastSent = i;
|
11864 |
|
11865 | queue[i].status = 3 ;
|
11866 | queue[i].abortReason = 'set';
|
11867 | }
|
11868 | else {
|
11869 | assert(queue[i].status === 0 , 'Unexpected transaction status in abort');
|
11870 |
|
11871 | queue[i].unwatcher();
|
11872 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
|
11873 | if (queue[i].onComplete) {
|
11874 | callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
|
11875 | }
|
11876 | }
|
11877 | }
|
11878 | if (lastSent === -1) {
|
11879 |
|
11880 | treeSetValue(node, undefined);
|
11881 | }
|
11882 | else {
|
11883 |
|
11884 | queue.length = lastSent + 1;
|
11885 | }
|
11886 |
|
11887 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
|
11888 | for (let i = 0; i < callbacks.length; i++) {
|
11889 | exceptionGuard(callbacks[i]);
|
11890 | }
|
11891 | }
|
11892 | }
|
11893 |
|
11894 |
|
11895 |
|
11896 |
|
11897 |
|
11898 |
|
11899 |
|
11900 |
|
11901 |
|
11902 |
|
11903 |
|
11904 |
|
11905 |
|
11906 |
|
11907 |
|
11908 |
|
11909 |
|
11910 | function decodePath(pathString) {
|
11911 | let pathStringDecoded = '';
|
11912 | const pieces = pathString.split('/');
|
11913 | for (let i = 0; i < pieces.length; i++) {
|
11914 | if (pieces[i].length > 0) {
|
11915 | let piece = pieces[i];
|
11916 | try {
|
11917 | piece = decodeURIComponent(piece.replace(/\+/g, ' '));
|
11918 | }
|
11919 | catch (e) { }
|
11920 | pathStringDecoded += '/' + piece;
|
11921 | }
|
11922 | }
|
11923 | return pathStringDecoded;
|
11924 | }
|
11925 |
|
11926 |
|
11927 |
|
11928 | function decodeQuery(queryString) {
|
11929 | const results = {};
|
11930 | if (queryString.charAt(0) === '?') {
|
11931 | queryString = queryString.substring(1);
|
11932 | }
|
11933 | for (const segment of queryString.split('&')) {
|
11934 | if (segment.length === 0) {
|
11935 | continue;
|
11936 | }
|
11937 | const kv = segment.split('=');
|
11938 | if (kv.length === 2) {
|
11939 | results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
|
11940 | }
|
11941 | else {
|
11942 | warn(`Invalid query segment '${segment}' in query '${queryString}'`);
|
11943 | }
|
11944 | }
|
11945 | return results;
|
11946 | }
|
11947 | const parseRepoInfo = function (dataURL, nodeAdmin) {
|
11948 | const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
|
11949 | if (parsedUrl.domain === 'firebase.com') {
|
11950 | fatal(parsedUrl.host +
|
11951 | ' is no longer supported. ' +
|
11952 | 'Please use <YOUR FIREBASE>.firebaseio.com instead');
|
11953 | }
|
11954 |
|
11955 | if ((!namespace || namespace === 'undefined') &&
|
11956 | parsedUrl.domain !== 'localhost') {
|
11957 | fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
|
11958 | }
|
11959 | if (!parsedUrl.secure) {
|
11960 | warnIfPageIsSecure();
|
11961 | }
|
11962 | const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
|
11963 | return {
|
11964 | repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
|
11965 | '',
|
11966 | namespace !== parsedUrl.subdomain),
|
11967 | path: new Path(parsedUrl.pathString)
|
11968 | };
|
11969 | };
|
11970 | const parseDatabaseURL = function (dataURL) {
|
11971 |
|
11972 | let host = '', domain = '', subdomain = '', pathString = '', namespace = '';
|
11973 |
|
11974 | let secure = true, scheme = 'https', port = 443;
|
11975 |
|
11976 | if (typeof dataURL === 'string') {
|
11977 |
|
11978 | let colonInd = dataURL.indexOf('//');
|
11979 | if (colonInd >= 0) {
|
11980 | scheme = dataURL.substring(0, colonInd - 1);
|
11981 | dataURL = dataURL.substring(colonInd + 2);
|
11982 | }
|
11983 |
|
11984 | let slashInd = dataURL.indexOf('/');
|
11985 | if (slashInd === -1) {
|
11986 | slashInd = dataURL.length;
|
11987 | }
|
11988 | let questionMarkInd = dataURL.indexOf('?');
|
11989 | if (questionMarkInd === -1) {
|
11990 | questionMarkInd = dataURL.length;
|
11991 | }
|
11992 | host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
|
11993 | if (slashInd < questionMarkInd) {
|
11994 |
|
11995 | pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
|
11996 | }
|
11997 | const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
|
11998 |
|
11999 | colonInd = host.indexOf(':');
|
12000 | if (colonInd >= 0) {
|
12001 | secure = scheme === 'https' || scheme === 'wss';
|
12002 | port = parseInt(host.substring(colonInd + 1), 10);
|
12003 | }
|
12004 | else {
|
12005 | colonInd = host.length;
|
12006 | }
|
12007 | const hostWithoutPort = host.slice(0, colonInd);
|
12008 | if (hostWithoutPort.toLowerCase() === 'localhost') {
|
12009 | domain = 'localhost';
|
12010 | }
|
12011 | else if (hostWithoutPort.split('.').length <= 2) {
|
12012 | domain = hostWithoutPort;
|
12013 | }
|
12014 | else {
|
12015 |
|
12016 | const dotInd = host.indexOf('.');
|
12017 | subdomain = host.substring(0, dotInd).toLowerCase();
|
12018 | domain = host.substring(dotInd + 1);
|
12019 |
|
12020 | namespace = subdomain;
|
12021 | }
|
12022 |
|
12023 | if ('ns' in queryParams) {
|
12024 | namespace = queryParams['ns'];
|
12025 | }
|
12026 | }
|
12027 | return {
|
12028 | host,
|
12029 | port,
|
12030 | domain,
|
12031 | subdomain,
|
12032 | secure,
|
12033 | scheme,
|
12034 | pathString,
|
12035 | namespace
|
12036 | };
|
12037 | };
|
12038 |
|
12039 |
|
12040 |
|
12041 |
|
12042 |
|
12043 |
|
12044 |
|
12045 |
|
12046 |
|
12047 |
|
12048 |
|
12049 |
|
12050 |
|
12051 |
|
12052 |
|
12053 |
|
12054 |
|
12055 |
|
12056 |
|
12057 |
|
12058 | class DataEvent {
|
12059 | |
12060 |
|
12061 |
|
12062 |
|
12063 |
|
12064 |
|
12065 | constructor(eventType, eventRegistration, snapshot, prevName) {
|
12066 | this.eventType = eventType;
|
12067 | this.eventRegistration = eventRegistration;
|
12068 | this.snapshot = snapshot;
|
12069 | this.prevName = prevName;
|
12070 | }
|
12071 | getPath() {
|
12072 | const ref = this.snapshot.ref;
|
12073 | if (this.eventType === 'value') {
|
12074 | return ref._path;
|
12075 | }
|
12076 | else {
|
12077 | return ref.parent._path;
|
12078 | }
|
12079 | }
|
12080 | getEventType() {
|
12081 | return this.eventType;
|
12082 | }
|
12083 | getEventRunner() {
|
12084 | return this.eventRegistration.getEventRunner(this);
|
12085 | }
|
12086 | toString() {
|
12087 | return (this.getPath().toString() +
|
12088 | ':' +
|
12089 | this.eventType +
|
12090 | ':' +
|
12091 | stringify(this.snapshot.exportVal()));
|
12092 | }
|
12093 | }
|
12094 | class CancelEvent {
|
12095 | constructor(eventRegistration, error, path) {
|
12096 | this.eventRegistration = eventRegistration;
|
12097 | this.error = error;
|
12098 | this.path = path;
|
12099 | }
|
12100 | getPath() {
|
12101 | return this.path;
|
12102 | }
|
12103 | getEventType() {
|
12104 | return 'cancel';
|
12105 | }
|
12106 | getEventRunner() {
|
12107 | return this.eventRegistration.getEventRunner(this);
|
12108 | }
|
12109 | toString() {
|
12110 | return this.path.toString() + ':cancel';
|
12111 | }
|
12112 | }
|
12113 |
|
12114 |
|
12115 |
|
12116 |
|
12117 |
|
12118 |
|
12119 |
|
12120 |
|
12121 |
|
12122 |
|
12123 |
|
12124 |
|
12125 |
|
12126 |
|
12127 |
|
12128 |
|
12129 |
|
12130 |
|
12131 |
|
12132 |
|
12133 |
|
12134 |
|
12135 |
|
12136 | class CallbackContext {
|
12137 | constructor(snapshotCallback, cancelCallback) {
|
12138 | this.snapshotCallback = snapshotCallback;
|
12139 | this.cancelCallback = cancelCallback;
|
12140 | }
|
12141 | onValue(expDataSnapshot, previousChildName) {
|
12142 | this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
|
12143 | }
|
12144 | onCancel(error) {
|
12145 | assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
|
12146 | return this.cancelCallback.call(null, error);
|
12147 | }
|
12148 | get hasCancelCallback() {
|
12149 | return !!this.cancelCallback;
|
12150 | }
|
12151 | matches(other) {
|
12152 | return (this.snapshotCallback === other.snapshotCallback ||
|
12153 | (this.snapshotCallback.userCallback !== undefined &&
|
12154 | this.snapshotCallback.userCallback ===
|
12155 | other.snapshotCallback.userCallback &&
|
12156 | this.snapshotCallback.context === other.snapshotCallback.context));
|
12157 | }
|
12158 | }
|
12159 |
|
12160 |
|
12161 |
|
12162 |
|
12163 |
|
12164 |
|
12165 |
|
12166 |
|
12167 |
|
12168 |
|
12169 |
|
12170 |
|
12171 |
|
12172 |
|
12173 |
|
12174 |
|
12175 |
|
12176 |
|
12177 |
|
12178 |
|
12179 |
|
12180 |
|
12181 |
|
12182 |
|
12183 |
|
12184 |
|
12185 |
|
12186 |
|
12187 |
|
12188 |
|
12189 |
|
12190 |
|
12191 |
|
12192 |
|
12193 |
|
12194 |
|
12195 |
|
12196 | class OnDisconnect {
|
12197 |
|
12198 | constructor(_repo, _path) {
|
12199 | this._repo = _repo;
|
12200 | this._path = _path;
|
12201 | }
|
12202 | |
12203 |
|
12204 |
|
12205 |
|
12206 |
|
12207 |
|
12208 |
|
12209 |
|
12210 |
|
12211 |
|
12212 | cancel() {
|
12213 | const deferred = new Deferred();
|
12214 | repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));
|
12215 | return deferred.promise;
|
12216 | }
|
12217 | |
12218 |
|
12219 |
|
12220 |
|
12221 |
|
12222 |
|
12223 | remove() {
|
12224 | validateWritablePath('OnDisconnect.remove', this._path);
|
12225 | const deferred = new Deferred();
|
12226 | repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));
|
12227 | return deferred.promise;
|
12228 | }
|
12229 | |
12230 |
|
12231 |
|
12232 |
|
12233 |
|
12234 |
|
12235 |
|
12236 |
|
12237 |
|
12238 |
|
12239 |
|
12240 |
|
12241 |
|
12242 |
|
12243 |
|
12244 |
|
12245 |
|
12246 |
|
12247 |
|
12248 | set(value) {
|
12249 | validateWritablePath('OnDisconnect.set', this._path);
|
12250 | validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
|
12251 | const deferred = new Deferred();
|
12252 | repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));
|
12253 | return deferred.promise;
|
12254 | }
|
12255 | |
12256 |
|
12257 |
|
12258 |
|
12259 |
|
12260 |
|
12261 |
|
12262 |
|
12263 |
|
12264 |
|
12265 | setWithPriority(value, priority) {
|
12266 | validateWritablePath('OnDisconnect.setWithPriority', this._path);
|
12267 | validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
|
12268 | validatePriority('OnDisconnect.setWithPriority', priority, false);
|
12269 | const deferred = new Deferred();
|
12270 | repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));
|
12271 | return deferred.promise;
|
12272 | }
|
12273 | |
12274 |
|
12275 |
|
12276 |
|
12277 |
|
12278 |
|
12279 |
|
12280 |
|
12281 |
|
12282 |
|
12283 |
|
12284 |
|
12285 |
|
12286 |
|
12287 |
|
12288 |
|
12289 | update(values) {
|
12290 | validateWritablePath('OnDisconnect.update', this._path);
|
12291 | validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
|
12292 | const deferred = new Deferred();
|
12293 | repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));
|
12294 | return deferred.promise;
|
12295 | }
|
12296 | }
|
12297 |
|
12298 |
|
12299 |
|
12300 |
|
12301 |
|
12302 |
|
12303 |
|
12304 |
|
12305 |
|
12306 |
|
12307 |
|
12308 |
|
12309 |
|
12310 |
|
12311 |
|
12312 |
|
12313 |
|
12314 |
|
12315 |
|
12316 |
|
12317 | class QueryImpl {
|
12318 | |
12319 |
|
12320 |
|
12321 | constructor(_repo, _path, _queryParams, _orderByCalled) {
|
12322 | this._repo = _repo;
|
12323 | this._path = _path;
|
12324 | this._queryParams = _queryParams;
|
12325 | this._orderByCalled = _orderByCalled;
|
12326 | }
|
12327 | get key() {
|
12328 | if (pathIsEmpty(this._path)) {
|
12329 | return null;
|
12330 | }
|
12331 | else {
|
12332 | return pathGetBack(this._path);
|
12333 | }
|
12334 | }
|
12335 | get ref() {
|
12336 | return new ReferenceImpl(this._repo, this._path);
|
12337 | }
|
12338 | get _queryIdentifier() {
|
12339 | const obj = queryParamsGetQueryObject(this._queryParams);
|
12340 | const id = ObjectToUniqueKey(obj);
|
12341 | return id === '{}' ? 'default' : id;
|
12342 | }
|
12343 | |
12344 |
|
12345 |
|
12346 | get _queryObject() {
|
12347 | return queryParamsGetQueryObject(this._queryParams);
|
12348 | }
|
12349 | isEqual(other) {
|
12350 | other = getModularInstance(other);
|
12351 | if (!(other instanceof QueryImpl)) {
|
12352 | return false;
|
12353 | }
|
12354 | const sameRepo = this._repo === other._repo;
|
12355 | const samePath = pathEquals(this._path, other._path);
|
12356 | const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
|
12357 | return sameRepo && samePath && sameQueryIdentifier;
|
12358 | }
|
12359 | toJSON() {
|
12360 | return this.toString();
|
12361 | }
|
12362 | toString() {
|
12363 | return this._repo.toString() + pathToUrlEncodedString(this._path);
|
12364 | }
|
12365 | }
|
12366 |
|
12367 |
|
12368 |
|
12369 | function validateNoPreviousOrderByCall(query, fnName) {
|
12370 | if (query._orderByCalled === true) {
|
12371 | throw new Error(fnName + ": You can't combine multiple orderBy calls.");
|
12372 | }
|
12373 | }
|
12374 |
|
12375 |
|
12376 |
|
12377 | function validateQueryEndpoints(params) {
|
12378 | let startNode = null;
|
12379 | let endNode = null;
|
12380 | if (params.hasStart()) {
|
12381 | startNode = params.getIndexStartValue();
|
12382 | }
|
12383 | if (params.hasEnd()) {
|
12384 | endNode = params.getIndexEndValue();
|
12385 | }
|
12386 | if (params.getIndex() === KEY_INDEX) {
|
12387 | const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
|
12388 | 'startAt(), endAt(), or equalTo().';
|
12389 | const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
|
12390 | 'endAt(), endBefore(), or equalTo() must be a string.';
|
12391 | if (params.hasStart()) {
|
12392 | const startName = params.getIndexStartName();
|
12393 | if (startName !== MIN_NAME) {
|
12394 | throw new Error(tooManyArgsError);
|
12395 | }
|
12396 | else if (typeof startNode !== 'string') {
|
12397 | throw new Error(wrongArgTypeError);
|
12398 | }
|
12399 | }
|
12400 | if (params.hasEnd()) {
|
12401 | const endName = params.getIndexEndName();
|
12402 | if (endName !== MAX_NAME) {
|
12403 | throw new Error(tooManyArgsError);
|
12404 | }
|
12405 | else if (typeof endNode !== 'string') {
|
12406 | throw new Error(wrongArgTypeError);
|
12407 | }
|
12408 | }
|
12409 | }
|
12410 | else if (params.getIndex() === PRIORITY_INDEX) {
|
12411 | if ((startNode != null && !isValidPriority(startNode)) ||
|
12412 | (endNode != null && !isValidPriority(endNode))) {
|
12413 | throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
|
12414 | 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
|
12415 | '(null, a number, or a string).');
|
12416 | }
|
12417 | }
|
12418 | else {
|
12419 | assert(params.getIndex() instanceof PathIndex ||
|
12420 | params.getIndex() === VALUE_INDEX, 'unknown index type.');
|
12421 | if ((startNode != null && typeof startNode === 'object') ||
|
12422 | (endNode != null && typeof endNode === 'object')) {
|
12423 | throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
|
12424 | 'equalTo() cannot be an object.');
|
12425 | }
|
12426 | }
|
12427 | }
|
12428 |
|
12429 |
|
12430 |
|
12431 | function validateLimit(params) {
|
12432 | if (params.hasStart() &&
|
12433 | params.hasEnd() &&
|
12434 | params.hasLimit() &&
|
12435 | !params.hasAnchoredLimit()) {
|
12436 | throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
|
12437 | 'limitToFirst() or limitToLast() instead.');
|
12438 | }
|
12439 | }
|
12440 |
|
12441 |
|
12442 |
|
12443 | class ReferenceImpl extends QueryImpl {
|
12444 |
|
12445 | constructor(repo, path) {
|
12446 | super(repo, path, new QueryParams(), false);
|
12447 | }
|
12448 | get parent() {
|
12449 | const parentPath = pathParent(this._path);
|
12450 | return parentPath === null
|
12451 | ? null
|
12452 | : new ReferenceImpl(this._repo, parentPath);
|
12453 | }
|
12454 | get root() {
|
12455 | let ref = this;
|
12456 | while (ref.parent !== null) {
|
12457 | ref = ref.parent;
|
12458 | }
|
12459 | return ref;
|
12460 | }
|
12461 | }
|
12462 |
|
12463 |
|
12464 |
|
12465 |
|
12466 |
|
12467 |
|
12468 |
|
12469 |
|
12470 |
|
12471 |
|
12472 |
|
12473 |
|
12474 |
|
12475 |
|
12476 | class DataSnapshot {
|
12477 | |
12478 |
|
12479 |
|
12480 |
|
12481 |
|
12482 |
|
12483 | constructor(_node,
|
12484 | /**
|
12485 | * The location of this DataSnapshot.
|
12486 | */
|
12487 | ref, _index) {
|
12488 | this._node = _node;
|
12489 | this.ref = ref;
|
12490 | this._index = _index;
|
12491 | }
|
12492 | |
12493 |
|
12494 |
|
12495 |
|
12496 |
|
12497 |
|
12498 |
|
12499 |
|
12500 | get priority() {
|
12501 |
|
12502 | return this._node.getPriority().val();
|
12503 | }
|
12504 | |
12505 |
|
12506 |
|
12507 |
|
12508 |
|
12509 |
|
12510 |
|
12511 |
|
12512 |
|
12513 | get key() {
|
12514 | return this.ref.key;
|
12515 | }
|
12516 |
|
12517 | get size() {
|
12518 | return this._node.numChildren();
|
12519 | }
|
12520 | |
12521 |
|
12522 |
|
12523 |
|
12524 |
|
12525 |
|
12526 |
|
12527 |
|
12528 |
|
12529 |
|
12530 |
|
12531 |
|
12532 | child(path) {
|
12533 | const childPath = new Path(path);
|
12534 | const childRef = child(this.ref, path);
|
12535 | return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
|
12536 | }
|
12537 | |
12538 |
|
12539 |
|
12540 |
|
12541 | exists() {
|
12542 | return !this._node.isEmpty();
|
12543 | }
|
12544 | |
12545 |
|
12546 |
|
12547 |
|
12548 |
|
12549 |
|
12550 |
|
12551 |
|
12552 |
|
12553 |
|
12554 | exportVal() {
|
12555 | return this._node.val(true);
|
12556 | }
|
12557 | |
12558 |
|
12559 |
|
12560 |
|
12561 |
|
12562 |
|
12563 |
|
12564 |
|
12565 |
|
12566 |
|
12567 |
|
12568 |
|
12569 |
|
12570 |
|
12571 |
|
12572 |
|
12573 |
|
12574 |
|
12575 | forEach(action) {
|
12576 | if (this._node.isLeafNode()) {
|
12577 | return false;
|
12578 | }
|
12579 | const childrenNode = this._node;
|
12580 |
|
12581 | return !!childrenNode.forEachChild(this._index, (key, node) => {
|
12582 | return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
|
12583 | });
|
12584 | }
|
12585 | |
12586 |
|
12587 |
|
12588 |
|
12589 |
|
12590 |
|
12591 |
|
12592 | hasChild(path) {
|
12593 | const childPath = new Path(path);
|
12594 | return !this._node.getChild(childPath).isEmpty();
|
12595 | }
|
12596 | |
12597 |
|
12598 |
|
12599 |
|
12600 |
|
12601 |
|
12602 |
|
12603 |
|
12604 |
|
12605 |
|
12606 |
|
12607 |
|
12608 | hasChildren() {
|
12609 | if (this._node.isLeafNode()) {
|
12610 | return false;
|
12611 | }
|
12612 | else {
|
12613 | return !this._node.isEmpty();
|
12614 | }
|
12615 | }
|
12616 | |
12617 |
|
12618 |
|
12619 | toJSON() {
|
12620 | return this.exportVal();
|
12621 | }
|
12622 | |
12623 |
|
12624 |
|
12625 |
|
12626 |
|
12627 |
|
12628 |
|
12629 |
|
12630 |
|
12631 |
|
12632 |
|
12633 |
|
12634 | val() {
|
12635 | return this._node.val();
|
12636 | }
|
12637 | }
|
12638 |
|
12639 |
|
12640 |
|
12641 |
|
12642 |
|
12643 |
|
12644 |
|
12645 |
|
12646 |
|
12647 |
|
12648 |
|
12649 |
|
12650 |
|
12651 |
|
12652 | function ref(db, path) {
|
12653 | db = getModularInstance(db);
|
12654 | db._checkNotDeleted('ref');
|
12655 | return path !== undefined ? child(db._root, path) : db._root;
|
12656 | }
|
12657 |
|
12658 |
|
12659 |
|
12660 |
|
12661 |
|
12662 |
|
12663 |
|
12664 |
|
12665 |
|
12666 |
|
12667 |
|
12668 |
|
12669 |
|
12670 |
|
12671 |
|
12672 |
|
12673 | function refFromURL(db, url) {
|
12674 | db = getModularInstance(db);
|
12675 | db._checkNotDeleted('refFromURL');
|
12676 | const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
|
12677 | validateUrl('refFromURL', parsedURL);
|
12678 | const repoInfo = parsedURL.repoInfo;
|
12679 | if (!db._repo.repoInfo_.isCustomHost() &&
|
12680 | repoInfo.host !== db._repo.repoInfo_.host) {
|
12681 | fatal('refFromURL' +
|
12682 | ': Host name does not match the current database: ' +
|
12683 | '(found ' +
|
12684 | repoInfo.host +
|
12685 | ' but expected ' +
|
12686 | db._repo.repoInfo_.host +
|
12687 | ')');
|
12688 | }
|
12689 | return ref(db, parsedURL.path.toString());
|
12690 | }
|
12691 |
|
12692 |
|
12693 |
|
12694 |
|
12695 |
|
12696 |
|
12697 |
|
12698 |
|
12699 |
|
12700 |
|
12701 |
|
12702 | function child(parent, path) {
|
12703 | parent = getModularInstance(parent);
|
12704 | if (pathGetFront(parent._path) === null) {
|
12705 | validateRootPathString('child', 'path', path, false);
|
12706 | }
|
12707 | else {
|
12708 | validatePathString('child', 'path', path, false);
|
12709 | }
|
12710 | return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
|
12711 | }
|
12712 |
|
12713 |
|
12714 |
|
12715 |
|
12716 |
|
12717 |
|
12718 |
|
12719 | function onDisconnect(ref) {
|
12720 | ref = getModularInstance(ref);
|
12721 | return new OnDisconnect(ref._repo, ref._path);
|
12722 | }
|
12723 |
|
12724 |
|
12725 |
|
12726 |
|
12727 |
|
12728 |
|
12729 |
|
12730 |
|
12731 |
|
12732 |
|
12733 |
|
12734 |
|
12735 |
|
12736 |
|
12737 |
|
12738 |
|
12739 |
|
12740 |
|
12741 |
|
12742 |
|
12743 |
|
12744 |
|
12745 |
|
12746 | function push(parent, value) {
|
12747 | parent = getModularInstance(parent);
|
12748 | validateWritablePath('push', parent._path);
|
12749 | validateFirebaseDataArg('push', value, parent._path, true);
|
12750 | const now = repoServerTime(parent._repo);
|
12751 | const name = nextPushId(now);
|
12752 |
|
12753 |
|
12754 |
|
12755 |
|
12756 |
|
12757 |
|
12758 | const thennablePushRef = child(parent, name);
|
12759 | const pushRef = child(parent, name);
|
12760 | let promise;
|
12761 | if (value != null) {
|
12762 | promise = set(pushRef, value).then(() => pushRef);
|
12763 | }
|
12764 | else {
|
12765 | promise = Promise.resolve(pushRef);
|
12766 | }
|
12767 | thennablePushRef.then = promise.then.bind(promise);
|
12768 | thennablePushRef.catch = promise.then.bind(promise, undefined);
|
12769 | return thennablePushRef;
|
12770 | }
|
12771 |
|
12772 |
|
12773 |
|
12774 |
|
12775 |
|
12776 |
|
12777 |
|
12778 |
|
12779 |
|
12780 |
|
12781 |
|
12782 |
|
12783 |
|
12784 |
|
12785 | function remove(ref) {
|
12786 | validateWritablePath('remove', ref._path);
|
12787 | return set(ref, null);
|
12788 | }
|
12789 | /**
|
12790 | * Writes data to this Database location.
|
12791 | *
|
12792 | * This will overwrite any data at this location and all child locations.
|
12793 | *
|
12794 | * The effect of the write will be visible immediately, and the corresponding
|
12795 | * events ("value", "child_added", etc.) will be triggered. Synchronization of
|
12796 | * the data to the Firebase servers will also be started, and the returned
|
12797 | * Promise will resolve when complete. If provided, the `onComplete` callback
|
12798 | * will be called asynchronously after synchronization has finished.
|
12799 | *
|
12800 | * Passing `null` for the new value is equivalent to calling `remove()`; namely,
|
12801 | * all data at this location and all child locations will be deleted.
|
12802 | *
|
12803 | * `set()` will remove any priority stored at this location, so if priority is
|
12804 | * meant to be preserved, you need to use `setWithPriority()` instead.
|
12805 | *
|
12806 | * Note that modifying data with `set()` will cancel any pending transactions
|
12807 | * at that location, so extreme care should be taken if mixing `set()` and
|
12808 | * `transaction()` to modify the same data.
|
12809 | *
|
12810 | * A single `set()` will generate a single "value" event at the location where
|
12811 | * the `set()` was performed.
|
12812 | *
|
12813 | * @param ref - The location to write to.
|
12814 | * @param value - The value to be written (string, number, boolean, object,
|
12815 | * array, or null).
|
12816 | * @returns Resolves when write to server is complete.
|
12817 | */
|
12818 | function set(ref, value) {
|
12819 | ref = getModularInstance(ref);
|
12820 | validateWritablePath('set', ref._path);
|
12821 | validateFirebaseDataArg('set', value, ref._path, false);
|
12822 | const deferred = new Deferred();
|
12823 | repoSetWithPriority(ref._repo, ref._path, value,
|
12824 | null, deferred.wrapCallback(() => { }));
|
12825 | return deferred.promise;
|
12826 | }
|
12827 |
|
12828 |
|
12829 |
|
12830 |
|
12831 |
|
12832 |
|
12833 |
|
12834 |
|
12835 |
|
12836 |
|
12837 |
|
12838 |
|
12839 | function setPriority(ref, priority) {
|
12840 | ref = getModularInstance(ref);
|
12841 | validateWritablePath('setPriority', ref._path);
|
12842 | validatePriority('setPriority', priority, false);
|
12843 | const deferred = new Deferred();
|
12844 | repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));
|
12845 | return deferred.promise;
|
12846 | }
|
12847 |
|
12848 |
|
12849 |
|
12850 |
|
12851 |
|
12852 |
|
12853 |
|
12854 |
|
12855 |
|
12856 |
|
12857 |
|
12858 |
|
12859 |
|
12860 |
|
12861 |
|
12862 | function setWithPriority(ref, value, priority) {
|
12863 | validateWritablePath('setWithPriority', ref._path);
|
12864 | validateFirebaseDataArg('setWithPriority', value, ref._path, false);
|
12865 | validatePriority('setWithPriority', priority, false);
|
12866 | if (ref.key === '.length' || ref.key === '.keys') {
|
12867 | throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
|
12868 | }
|
12869 | const deferred = new Deferred();
|
12870 | repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));
|
12871 | return deferred.promise;
|
12872 | }
|
12873 |
|
12874 |
|
12875 |
|
12876 |
|
12877 |
|
12878 |
|
12879 |
|
12880 |
|
12881 |
|
12882 |
|
12883 |
|
12884 |
|
12885 |
|
12886 |
|
12887 |
|
12888 |
|
12889 |
|
12890 |
|
12891 |
|
12892 |
|
12893 |
|
12894 |
|
12895 |
|
12896 |
|
12897 |
|
12898 |
|
12899 |
|
12900 |
|
12901 |
|
12902 |
|
12903 |
|
12904 |
|
12905 |
|
12906 |
|
12907 |
|
12908 | function update(ref, values) {
|
12909 | validateFirebaseMergeDataArg('update', values, ref._path, false);
|
12910 | const deferred = new Deferred();
|
12911 | repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));
|
12912 | return deferred.promise;
|
12913 | }
|
12914 |
|
12915 |
|
12916 |
|
12917 |
|
12918 |
|
12919 |
|
12920 |
|
12921 |
|
12922 | function get(query) {
|
12923 | query = getModularInstance(query);
|
12924 | return repoGetValue(query._repo, query).then(node => {
|
12925 | return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
|
12926 | });
|
12927 | }
|
12928 |
|
12929 |
|
12930 |
|
12931 | class ValueEventRegistration {
|
12932 | constructor(callbackContext) {
|
12933 | this.callbackContext = callbackContext;
|
12934 | }
|
12935 | respondsTo(eventType) {
|
12936 | return eventType === 'value';
|
12937 | }
|
12938 | createEvent(change, query) {
|
12939 | const index = query._queryParams.getIndex();
|
12940 | return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
|
12941 | }
|
12942 | getEventRunner(eventData) {
|
12943 | if (eventData.getEventType() === 'cancel') {
|
12944 | return () => this.callbackContext.onCancel(eventData.error);
|
12945 | }
|
12946 | else {
|
12947 | return () => this.callbackContext.onValue(eventData.snapshot, null);
|
12948 | }
|
12949 | }
|
12950 | createCancelEvent(error, path) {
|
12951 | if (this.callbackContext.hasCancelCallback) {
|
12952 | return new CancelEvent(this, error, path);
|
12953 | }
|
12954 | else {
|
12955 | return null;
|
12956 | }
|
12957 | }
|
12958 | matches(other) {
|
12959 | if (!(other instanceof ValueEventRegistration)) {
|
12960 | return false;
|
12961 | }
|
12962 | else if (!other.callbackContext || !this.callbackContext) {
|
12963 |
|
12964 | return true;
|
12965 | }
|
12966 | else {
|
12967 | return other.callbackContext.matches(this.callbackContext);
|
12968 | }
|
12969 | }
|
12970 | hasAnyCallback() {
|
12971 | return this.callbackContext !== null;
|
12972 | }
|
12973 | }
|
12974 |
|
12975 |
|
12976 |
|
12977 | class ChildEventRegistration {
|
12978 | constructor(eventType, callbackContext) {
|
12979 | this.eventType = eventType;
|
12980 | this.callbackContext = callbackContext;
|
12981 | }
|
12982 | respondsTo(eventType) {
|
12983 | let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
|
12984 | eventToCheck =
|
12985 | eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
|
12986 | return this.eventType === eventToCheck;
|
12987 | }
|
12988 | createCancelEvent(error, path) {
|
12989 | if (this.callbackContext.hasCancelCallback) {
|
12990 | return new CancelEvent(this, error, path);
|
12991 | }
|
12992 | else {
|
12993 | return null;
|
12994 | }
|
12995 | }
|
12996 | createEvent(change, query) {
|
12997 | assert(change.childName != null, 'Child events should have a childName.');
|
12998 | const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
|
12999 | const index = query._queryParams.getIndex();
|
13000 | return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
|
13001 | }
|
13002 | getEventRunner(eventData) {
|
13003 | if (eventData.getEventType() === 'cancel') {
|
13004 | return () => this.callbackContext.onCancel(eventData.error);
|
13005 | }
|
13006 | else {
|
13007 | return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
|
13008 | }
|
13009 | }
|
13010 | matches(other) {
|
13011 | if (other instanceof ChildEventRegistration) {
|
13012 | return (this.eventType === other.eventType &&
|
13013 | (!this.callbackContext ||
|
13014 | !other.callbackContext ||
|
13015 | this.callbackContext.matches(other.callbackContext)));
|
13016 | }
|
13017 | return false;
|
13018 | }
|
13019 | hasAnyCallback() {
|
13020 | return !!this.callbackContext;
|
13021 | }
|
13022 | }
|
13023 | function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
|
13024 | let cancelCallback;
|
13025 | if (typeof cancelCallbackOrListenOptions === 'object') {
|
13026 | cancelCallback = undefined;
|
13027 | options = cancelCallbackOrListenOptions;
|
13028 | }
|
13029 | if (typeof cancelCallbackOrListenOptions === 'function') {
|
13030 | cancelCallback = cancelCallbackOrListenOptions;
|
13031 | }
|
13032 | if (options && options.onlyOnce) {
|
13033 | const userCallback = callback;
|
13034 | const onceCallback = (dataSnapshot, previousChildName) => {
|
13035 | repoRemoveEventCallbackForQuery(query._repo, query, container);
|
13036 | userCallback(dataSnapshot, previousChildName);
|
13037 | };
|
13038 | onceCallback.userCallback = callback.userCallback;
|
13039 | onceCallback.context = callback.context;
|
13040 | callback = onceCallback;
|
13041 | }
|
13042 | const callbackContext = new CallbackContext(callback, cancelCallback || undefined);
|
13043 | const container = eventType === 'value'
|
13044 | ? new ValueEventRegistration(callbackContext)
|
13045 | : new ChildEventRegistration(eventType, callbackContext);
|
13046 | repoAddEventCallbackForQuery(query._repo, query, container);
|
13047 | return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
|
13048 | }
|
13049 | function onValue(query, callback, cancelCallbackOrListenOptions, options) {
|
13050 | return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
|
13051 | }
|
13052 | function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
|
13053 | return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
|
13054 | }
|
13055 | function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
|
13056 | return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
|
13057 | }
|
13058 | function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
|
13059 | return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
|
13060 | }
|
13061 | function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
|
13062 | return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
|
13063 | }
|
13064 |
|
13065 |
|
13066 |
|
13067 |
|
13068 |
|
13069 |
|
13070 |
|
13071 |
|
13072 |
|
13073 |
|
13074 |
|
13075 |
|
13076 |
|
13077 |
|
13078 |
|
13079 |
|
13080 |
|
13081 |
|
13082 |
|
13083 |
|
13084 |
|
13085 |
|
13086 |
|
13087 |
|
13088 | function off(query, eventType, callback) {
|
13089 | let container = null;
|
13090 | const expCallback = callback ? new CallbackContext(callback) : null;
|
13091 | if (eventType === 'value') {
|
13092 | container = new ValueEventRegistration(expCallback);
|
13093 | }
|
13094 | else if (eventType) {
|
13095 | container = new ChildEventRegistration(eventType, expCallback);
|
13096 | }
|
13097 | repoRemoveEventCallbackForQuery(query._repo, query, container);
|
13098 | }
|
13099 |
|
13100 |
|
13101 |
|
13102 |
|
13103 |
|
13104 |
|
13105 |
|
13106 |
|
13107 |
|
13108 |
|
13109 | class QueryConstraint {
|
13110 | }
|
13111 | class QueryEndAtConstraint extends QueryConstraint {
|
13112 | constructor(_value, _key) {
|
13113 | super();
|
13114 | this._value = _value;
|
13115 | this._key = _key;
|
13116 | }
|
13117 | _apply(query) {
|
13118 | validateFirebaseDataArg('endAt', this._value, query._path, true);
|
13119 | const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
|
13120 | validateLimit(newParams);
|
13121 | validateQueryEndpoints(newParams);
|
13122 | if (query._queryParams.hasEnd()) {
|
13123 | throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
|
13124 | 'endBefore or equalTo).');
|
13125 | }
|
13126 | return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
|
13127 | }
|
13128 | }
|
13129 |
|
13130 |
|
13131 |
|
13132 |
|
13133 |
|
13134 |
|
13135 |
|
13136 |
|
13137 |
|
13138 |
|
13139 |
|
13140 |
|
13141 |
|
13142 |
|
13143 |
|
13144 |
|
13145 |
|
13146 |
|
13147 |
|
13148 |
|
13149 |
|
13150 |
|
13151 |
|
13152 | function endAt(value, key) {
|
13153 | validateKey('endAt', 'key', key, true);
|
13154 | return new QueryEndAtConstraint(value, key);
|
13155 | }
|
13156 | class QueryEndBeforeConstraint extends QueryConstraint {
|
13157 | constructor(_value, _key) {
|
13158 | super();
|
13159 | this._value = _value;
|
13160 | this._key = _key;
|
13161 | }
|
13162 | _apply(query) {
|
13163 | validateFirebaseDataArg('endBefore', this._value, query._path, false);
|
13164 | const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
|
13165 | validateLimit(newParams);
|
13166 | validateQueryEndpoints(newParams);
|
13167 | if (query._queryParams.hasEnd()) {
|
13168 | throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
|
13169 | 'endBefore or equalTo).');
|
13170 | }
|
13171 | return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
|
13172 | }
|
13173 | }
|
13174 |
|
13175 |
|
13176 |
|
13177 |
|
13178 |
|
13179 |
|
13180 |
|
13181 |
|
13182 |
|
13183 |
|
13184 |
|
13185 |
|
13186 |
|
13187 |
|
13188 |
|
13189 |
|
13190 |
|
13191 |
|
13192 |
|
13193 | function endBefore(value, key) {
|
13194 | validateKey('endBefore', 'key', key, true);
|
13195 | return new QueryEndBeforeConstraint(value, key);
|
13196 | }
|
13197 | class QueryStartAtConstraint extends QueryConstraint {
|
13198 | constructor(_value, _key) {
|
13199 | super();
|
13200 | this._value = _value;
|
13201 | this._key = _key;
|
13202 | }
|
13203 | _apply(query) {
|
13204 | validateFirebaseDataArg('startAt', this._value, query._path, true);
|
13205 | const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
|
13206 | validateLimit(newParams);
|
13207 | validateQueryEndpoints(newParams);
|
13208 | if (query._queryParams.hasStart()) {
|
13209 | throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
|
13210 | 'startBefore or equalTo).');
|
13211 | }
|
13212 | return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
|
13213 | }
|
13214 | }
|
13215 |
|
13216 |
|
13217 |
|
13218 |
|
13219 |
|
13220 |
|
13221 |
|
13222 |
|
13223 |
|
13224 |
|
13225 |
|
13226 |
|
13227 |
|
13228 |
|
13229 |
|
13230 |
|
13231 |
|
13232 |
|
13233 |
|
13234 |
|
13235 |
|
13236 |
|
13237 | function startAt(value = null, key) {
|
13238 | validateKey('startAt', 'key', key, true);
|
13239 | return new QueryStartAtConstraint(value, key);
|
13240 | }
|
13241 | class QueryStartAfterConstraint extends QueryConstraint {
|
13242 | constructor(_value, _key) {
|
13243 | super();
|
13244 | this._value = _value;
|
13245 | this._key = _key;
|
13246 | }
|
13247 | _apply(query) {
|
13248 | validateFirebaseDataArg('startAfter', this._value, query._path, false);
|
13249 | const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
|
13250 | validateLimit(newParams);
|
13251 | validateQueryEndpoints(newParams);
|
13252 | if (query._queryParams.hasStart()) {
|
13253 | throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
|
13254 | 'startAfter, or equalTo).');
|
13255 | }
|
13256 | return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
|
13257 | }
|
13258 | }
|
13259 |
|
13260 |
|
13261 |
|
13262 |
|
13263 |
|
13264 |
|
13265 |
|
13266 |
|
13267 |
|
13268 |
|
13269 |
|
13270 |
|
13271 |
|
13272 |
|
13273 |
|
13274 |
|
13275 |
|
13276 |
|
13277 | function startAfter(value, key) {
|
13278 | validateKey('startAfter', 'key', key, true);
|
13279 | return new QueryStartAfterConstraint(value, key);
|
13280 | }
|
13281 | class QueryLimitToFirstConstraint extends QueryConstraint {
|
13282 | constructor(_limit) {
|
13283 | super();
|
13284 | this._limit = _limit;
|
13285 | }
|
13286 | _apply(query) {
|
13287 | if (query._queryParams.hasLimit()) {
|
13288 | throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
|
13289 | 'or limitToLast).');
|
13290 | }
|
13291 | return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
|
13292 | }
|
13293 | }
|
13294 |
|
13295 |
|
13296 |
|
13297 |
|
13298 |
|
13299 |
|
13300 |
|
13301 |
|
13302 |
|
13303 |
|
13304 |
|
13305 |
|
13306 |
|
13307 |
|
13308 |
|
13309 |
|
13310 |
|
13311 |
|
13312 | function limitToFirst(limit) {
|
13313 | if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
|
13314 | throw new Error('limitToFirst: First argument must be a positive integer.');
|
13315 | }
|
13316 | return new QueryLimitToFirstConstraint(limit);
|
13317 | }
|
13318 | class QueryLimitToLastConstraint extends QueryConstraint {
|
13319 | constructor(_limit) {
|
13320 | super();
|
13321 | this._limit = _limit;
|
13322 | }
|
13323 | _apply(query) {
|
13324 | if (query._queryParams.hasLimit()) {
|
13325 | throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
|
13326 | 'or limitToLast).');
|
13327 | }
|
13328 | return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
|
13329 | }
|
13330 | }
|
13331 |
|
13332 |
|
13333 |
|
13334 |
|
13335 |
|
13336 |
|
13337 |
|
13338 |
|
13339 |
|
13340 |
|
13341 |
|
13342 |
|
13343 |
|
13344 |
|
13345 |
|
13346 |
|
13347 |
|
13348 |
|
13349 | function limitToLast(limit) {
|
13350 | if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
|
13351 | throw new Error('limitToLast: First argument must be a positive integer.');
|
13352 | }
|
13353 | return new QueryLimitToLastConstraint(limit);
|
13354 | }
|
13355 | class QueryOrderByChildConstraint extends QueryConstraint {
|
13356 | constructor(_path) {
|
13357 | super();
|
13358 | this._path = _path;
|
13359 | }
|
13360 | _apply(query) {
|
13361 | validateNoPreviousOrderByCall(query, 'orderByChild');
|
13362 | const parsedPath = new Path(this._path);
|
13363 | if (pathIsEmpty(parsedPath)) {
|
13364 | throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
|
13365 | }
|
13366 | const index = new PathIndex(parsedPath);
|
13367 | const newParams = queryParamsOrderBy(query._queryParams, index);
|
13368 | validateQueryEndpoints(newParams);
|
13369 | return new QueryImpl(query._repo, query._path, newParams,
|
13370 | true);
|
13371 | }
|
13372 | }
|
13373 |
|
13374 |
|
13375 |
|
13376 |
|
13377 |
|
13378 |
|
13379 |
|
13380 |
|
13381 |
|
13382 |
|
13383 |
|
13384 |
|
13385 |
|
13386 |
|
13387 |
|
13388 |
|
13389 |
|
13390 | function orderByChild(path) {
|
13391 | if (path === '$key') {
|
13392 | throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
|
13393 | }
|
13394 | else if (path === '$priority') {
|
13395 | throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
|
13396 | }
|
13397 | else if (path === '$value') {
|
13398 | throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
|
13399 | }
|
13400 | validatePathString('orderByChild', 'path', path, false);
|
13401 | return new QueryOrderByChildConstraint(path);
|
13402 | }
|
13403 | class QueryOrderByKeyConstraint extends QueryConstraint {
|
13404 | _apply(query) {
|
13405 | validateNoPreviousOrderByCall(query, 'orderByKey');
|
13406 | const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
|
13407 | validateQueryEndpoints(newParams);
|
13408 | return new QueryImpl(query._repo, query._path, newParams,
|
13409 | true);
|
13410 | }
|
13411 | }
|
13412 |
|
13413 |
|
13414 |
|
13415 |
|
13416 |
|
13417 |
|
13418 |
|
13419 |
|
13420 | function orderByKey() {
|
13421 | return new QueryOrderByKeyConstraint();
|
13422 | }
|
13423 | class QueryOrderByPriorityConstraint extends QueryConstraint {
|
13424 | _apply(query) {
|
13425 | validateNoPreviousOrderByCall(query, 'orderByPriority');
|
13426 | const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
|
13427 | validateQueryEndpoints(newParams);
|
13428 | return new QueryImpl(query._repo, query._path, newParams,
|
13429 | true);
|
13430 | }
|
13431 | }
|
13432 |
|
13433 |
|
13434 |
|
13435 |
|
13436 |
|
13437 |
|
13438 |
|
13439 |
|
13440 | function orderByPriority() {
|
13441 | return new QueryOrderByPriorityConstraint();
|
13442 | }
|
13443 | class QueryOrderByValueConstraint extends QueryConstraint {
|
13444 | _apply(query) {
|
13445 | validateNoPreviousOrderByCall(query, 'orderByValue');
|
13446 | const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
|
13447 | validateQueryEndpoints(newParams);
|
13448 | return new QueryImpl(query._repo, query._path, newParams,
|
13449 | true);
|
13450 | }
|
13451 | }
|
13452 |
|
13453 |
|
13454 |
|
13455 |
|
13456 |
|
13457 |
|
13458 |
|
13459 |
|
13460 |
|
13461 | function orderByValue() {
|
13462 | return new QueryOrderByValueConstraint();
|
13463 | }
|
13464 | class QueryEqualToValueConstraint extends QueryConstraint {
|
13465 | constructor(_value, _key) {
|
13466 | super();
|
13467 | this._value = _value;
|
13468 | this._key = _key;
|
13469 | }
|
13470 | _apply(query) {
|
13471 | validateFirebaseDataArg('equalTo', this._value, query._path, false);
|
13472 | if (query._queryParams.hasStart()) {
|
13473 | throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
|
13474 | 'equalTo).');
|
13475 | }
|
13476 | if (query._queryParams.hasEnd()) {
|
13477 | throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
|
13478 | 'equalTo).');
|
13479 | }
|
13480 | return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
|
13481 | }
|
13482 | }
|
13483 |
|
13484 |
|
13485 |
|
13486 |
|
13487 |
|
13488 |
|
13489 |
|
13490 |
|
13491 |
|
13492 |
|
13493 |
|
13494 |
|
13495 |
|
13496 |
|
13497 |
|
13498 |
|
13499 |
|
13500 |
|
13501 |
|
13502 |
|
13503 |
|
13504 |
|
13505 |
|
13506 | function equalTo(value, key) {
|
13507 | validateKey('equalTo', 'key', key, true);
|
13508 | return new QueryEqualToValueConstraint(value, key);
|
13509 | }
|
13510 |
|
13511 |
|
13512 |
|
13513 |
|
13514 |
|
13515 |
|
13516 |
|
13517 |
|
13518 |
|
13519 | function query(query, ...queryConstraints) {
|
13520 | let queryImpl = getModularInstance(query);
|
13521 | for (const constraint of queryConstraints) {
|
13522 | queryImpl = constraint._apply(queryImpl);
|
13523 | }
|
13524 | return queryImpl;
|
13525 | }
|
13526 |
|
13527 |
|
13528 |
|
13529 |
|
13530 |
|
13531 |
|
13532 | syncPointSetReferenceConstructor(ReferenceImpl);
|
13533 | syncTreeSetReferenceConstructor(ReferenceImpl);
|
13534 |
|
13535 |
|
13536 |
|
13537 |
|
13538 |
|
13539 |
|
13540 |
|
13541 |
|
13542 |
|
13543 |
|
13544 |
|
13545 |
|
13546 |
|
13547 |
|
13548 |
|
13549 |
|
13550 |
|
13551 |
|
13552 |
|
13553 |
|
13554 |
|
13555 |
|
13556 |
|
13557 |
|
13558 |
|
13559 | const FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
|
13560 |
|
13561 |
|
13562 |
|
13563 | const repos = {};
|
13564 |
|
13565 |
|
13566 |
|
13567 | let useRestClient = false;
|
13568 |
|
13569 |
|
13570 |
|
13571 | function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
|
13572 | repo.repoInfo_ = new RepoInfo(`${host}:${port}`,
|
13573 | false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
|
13574 | if (tokenProvider) {
|
13575 | repo.authTokenProvider_ = tokenProvider;
|
13576 | }
|
13577 | }
|
13578 |
|
13579 |
|
13580 |
|
13581 |
|
13582 | function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
|
13583 | let dbUrl = url || app.options.databaseURL;
|
13584 | if (dbUrl === undefined) {
|
13585 | if (!app.options.projectId) {
|
13586 | fatal("Can't determine Firebase Database URL. Be sure to include " +
|
13587 | ' a Project ID when calling firebase.initializeApp().');
|
13588 | }
|
13589 | log('Using default host for project ', app.options.projectId);
|
13590 | dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
|
13591 | }
|
13592 | let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
|
13593 | let repoInfo = parsedUrl.repoInfo;
|
13594 | let isEmulator;
|
13595 | let dbEmulatorHost = undefined;
|
13596 | if (typeof process !== 'undefined' && process.env) {
|
13597 | dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
|
13598 | }
|
13599 | if (dbEmulatorHost) {
|
13600 | isEmulator = true;
|
13601 | dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
|
13602 | parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
|
13603 | repoInfo = parsedUrl.repoInfo;
|
13604 | }
|
13605 | else {
|
13606 | isEmulator = !parsedUrl.repoInfo.secure;
|
13607 | }
|
13608 | const authTokenProvider = nodeAdmin && isEmulator
|
13609 | ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
|
13610 | : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
|
13611 | validateUrl('Invalid Firebase Database URL', parsedUrl);
|
13612 | if (!pathIsEmpty(parsedUrl.path)) {
|
13613 | fatal('Database URL must point to the root of a Firebase Database ' +
|
13614 | '(not including a child path).');
|
13615 | }
|
13616 | const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
|
13617 | return new Database(repo, app);
|
13618 | }
|
13619 |
|
13620 |
|
13621 |
|
13622 |
|
13623 | function repoManagerDeleteRepo(repo, appName) {
|
13624 | const appRepos = repos[appName];
|
13625 |
|
13626 | if (!appRepos || appRepos[repo.key] !== repo) {
|
13627 | fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
|
13628 | }
|
13629 | repoInterrupt(repo);
|
13630 | delete appRepos[repo.key];
|
13631 | }
|
13632 |
|
13633 |
|
13634 |
|
13635 |
|
13636 |
|
13637 |
|
13638 |
|
13639 | function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
|
13640 | let appRepos = repos[app.name];
|
13641 | if (!appRepos) {
|
13642 | appRepos = {};
|
13643 | repos[app.name] = appRepos;
|
13644 | }
|
13645 | let repo = appRepos[repoInfo.toURLString()];
|
13646 | if (repo) {
|
13647 | fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
|
13648 | }
|
13649 | repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
|
13650 | appRepos[repoInfo.toURLString()] = repo;
|
13651 | return repo;
|
13652 | }
|
13653 |
|
13654 |
|
13655 |
|
13656 | function repoManagerForceRestClient(forceRestClient) {
|
13657 | useRestClient = forceRestClient;
|
13658 | }
|
13659 |
|
13660 |
|
13661 |
|
13662 | class Database {
|
13663 |
|
13664 | constructor(_repoInternal,
|
13665 | /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
|
13666 | app) {
|
13667 | this._repoInternal = _repoInternal;
|
13668 | this.app = app;
|
13669 |
|
13670 | this['type'] = 'database';
|
13671 |
|
13672 | this._instanceStarted = false;
|
13673 | }
|
13674 | get _repo() {
|
13675 | if (!this._instanceStarted) {
|
13676 | repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
|
13677 | this._instanceStarted = true;
|
13678 | }
|
13679 | return this._repoInternal;
|
13680 | }
|
13681 | get _root() {
|
13682 | if (!this._rootInternal) {
|
13683 | this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
|
13684 | }
|
13685 | return this._rootInternal;
|
13686 | }
|
13687 | _delete() {
|
13688 | if (this._rootInternal !== null) {
|
13689 | repoManagerDeleteRepo(this._repo, this.app.name);
|
13690 | this._repoInternal = null;
|
13691 | this._rootInternal = null;
|
13692 | }
|
13693 | return Promise.resolve();
|
13694 | }
|
13695 | _checkNotDeleted(apiName) {
|
13696 | if (this._rootInternal === null) {
|
13697 | fatal('Cannot call ' + apiName + ' on a deleted database.');
|
13698 | }
|
13699 | }
|
13700 | }
|
13701 | function checkTransportInit() {
|
13702 | if (TransportManager.IS_TRANSPORT_INITIALIZED) {
|
13703 | warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
|
13704 | }
|
13705 | }
|
13706 |
|
13707 |
|
13708 |
|
13709 | function forceWebSockets() {
|
13710 | checkTransportInit();
|
13711 | BrowserPollConnection.forceDisallow();
|
13712 | }
|
13713 |
|
13714 |
|
13715 |
|
13716 | function forceLongPolling() {
|
13717 | checkTransportInit();
|
13718 | WebSocketConnection.forceDisallow();
|
13719 | BrowserPollConnection.forceAllow();
|
13720 | }
|
13721 |
|
13722 |
|
13723 |
|
13724 |
|
13725 |
|
13726 |
|
13727 |
|
13728 |
|
13729 |
|
13730 |
|
13731 |
|
13732 |
|
13733 | function getDatabase(app = getApp(), url) {
|
13734 | return _getProvider(app, 'database').getImmediate({
|
13735 | identifier: url
|
13736 | });
|
13737 | }
|
13738 |
|
13739 |
|
13740 |
|
13741 |
|
13742 |
|
13743 |
|
13744 |
|
13745 |
|
13746 |
|
13747 |
|
13748 |
|
13749 | function connectDatabaseEmulator(db, host, port, options = {}) {
|
13750 | db = getModularInstance(db);
|
13751 | db._checkNotDeleted('useEmulator');
|
13752 | if (db._instanceStarted) {
|
13753 | fatal('Cannot call useEmulator() after instance has already been initialized.');
|
13754 | }
|
13755 | const repo = db._repoInternal;
|
13756 | let tokenProvider = undefined;
|
13757 | if (repo.repoInfo_.nodeAdmin) {
|
13758 | if (options.mockUserToken) {
|
13759 | fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
|
13760 | }
|
13761 | tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
|
13762 | }
|
13763 | else if (options.mockUserToken) {
|
13764 | const token = typeof options.mockUserToken === 'string'
|
13765 | ? options.mockUserToken
|
13766 | : createMockUserToken(options.mockUserToken, db.app.options.projectId);
|
13767 | tokenProvider = new EmulatorTokenProvider(token);
|
13768 | }
|
13769 |
|
13770 | repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
|
13771 | }
|
13772 |
|
13773 |
|
13774 |
|
13775 |
|
13776 |
|
13777 |
|
13778 |
|
13779 |
|
13780 |
|
13781 |
|
13782 |
|
13783 |
|
13784 |
|
13785 |
|
13786 |
|
13787 |
|
13788 |
|
13789 |
|
13790 |
|
13791 |
|
13792 |
|
13793 | function goOffline(db) {
|
13794 | db = getModularInstance(db);
|
13795 | db._checkNotDeleted('goOffline');
|
13796 | repoInterrupt(db._repo);
|
13797 | }
|
13798 |
|
13799 |
|
13800 |
|
13801 |
|
13802 |
|
13803 |
|
13804 |
|
13805 |
|
13806 |
|
13807 |
|
13808 |
|
13809 | function goOnline(db) {
|
13810 | db = getModularInstance(db);
|
13811 | db._checkNotDeleted('goOnline');
|
13812 | repoResume(db._repo);
|
13813 | }
|
13814 | function enableLogging(logger, persistent) {
|
13815 | enableLogging$1(logger, persistent);
|
13816 | }
|
13817 |
|
13818 |
|
13819 |
|
13820 |
|
13821 |
|
13822 |
|
13823 |
|
13824 |
|
13825 |
|
13826 |
|
13827 |
|
13828 |
|
13829 |
|
13830 |
|
13831 |
|
13832 |
|
13833 |
|
13834 | function registerDatabase(variant) {
|
13835 | setSDKVersion(SDK_VERSION$1);
|
13836 | _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {
|
13837 | const app = container.getProvider('app').getImmediate();
|
13838 | const authProvider = container.getProvider('auth-internal');
|
13839 | const appCheckProvider = container.getProvider('app-check-internal');
|
13840 | return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
|
13841 | }, "PUBLIC" ).setMultipleInstances(true));
|
13842 | registerVersion(name, version, variant);
|
13843 |
|
13844 | registerVersion(name, version, 'esm2017');
|
13845 | }
|
13846 |
|
13847 |
|
13848 |
|
13849 |
|
13850 |
|
13851 |
|
13852 |
|
13853 |
|
13854 |
|
13855 |
|
13856 |
|
13857 |
|
13858 |
|
13859 |
|
13860 |
|
13861 |
|
13862 |
|
13863 | const SERVER_TIMESTAMP = {
|
13864 | '.sv': 'timestamp'
|
13865 | };
|
13866 |
|
13867 |
|
13868 |
|
13869 |
|
13870 |
|
13871 | function serverTimestamp() {
|
13872 | return SERVER_TIMESTAMP;
|
13873 | }
|
13874 |
|
13875 |
|
13876 |
|
13877 |
|
13878 |
|
13879 |
|
13880 |
|
13881 | function increment(delta) {
|
13882 | return {
|
13883 | '.sv': {
|
13884 | 'increment': delta
|
13885 | }
|
13886 | };
|
13887 | }
|
13888 |
|
13889 |
|
13890 |
|
13891 |
|
13892 |
|
13893 |
|
13894 |
|
13895 |
|
13896 |
|
13897 |
|
13898 |
|
13899 |
|
13900 |
|
13901 |
|
13902 |
|
13903 |
|
13904 |
|
13905 |
|
13906 |
|
13907 |
|
13908 | class TransactionResult {
|
13909 |
|
13910 | constructor(
|
13911 | /** Whether the transaction was successfully committed. */
|
13912 | committed,
|
13913 | /** The resulting data snapshot. */
|
13914 | snapshot) {
|
13915 | this.committed = committed;
|
13916 | this.snapshot = snapshot;
|
13917 | }
|
13918 |
|
13919 | toJSON() {
|
13920 | return { committed: this.committed, snapshot: this.snapshot.toJSON() };
|
13921 | }
|
13922 | }
|
13923 |
|
13924 |
|
13925 |
|
13926 |
|
13927 |
|
13928 |
|
13929 |
|
13930 |
|
13931 |
|
13932 |
|
13933 |
|
13934 |
|
13935 |
|
13936 |
|
13937 |
|
13938 |
|
13939 |
|
13940 |
|
13941 |
|
13942 |
|
13943 |
|
13944 |
|
13945 |
|
13946 |
|
13947 |
|
13948 |
|
13949 |
|
13950 |
|
13951 |
|
13952 |
|
13953 |
|
13954 |
|
13955 |
|
13956 |
|
13957 |
|
13958 |
|
13959 |
|
13960 | function runTransaction(ref,
|
13961 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
13962 | transactionUpdate, options) {
|
13963 | var _a;
|
13964 | ref = getModularInstance(ref);
|
13965 | validateWritablePath('Reference.transaction', ref._path);
|
13966 | if (ref.key === '.length' || ref.key === '.keys') {
|
13967 | throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
|
13968 | }
|
13969 | const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
|
13970 | const deferred = new Deferred();
|
13971 | const promiseComplete = (error, committed, node) => {
|
13972 | let dataSnapshot = null;
|
13973 | if (error) {
|
13974 | deferred.reject(error);
|
13975 | }
|
13976 | else {
|
13977 | dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
|
13978 | deferred.resolve(new TransactionResult(committed, dataSnapshot));
|
13979 | }
|
13980 | };
|
13981 |
|
13982 | const unwatcher = onValue(ref, () => { });
|
13983 | repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
|
13984 | return deferred.promise;
|
13985 | }
|
13986 |
|
13987 |
|
13988 |
|
13989 |
|
13990 |
|
13991 |
|
13992 |
|
13993 |
|
13994 |
|
13995 |
|
13996 |
|
13997 |
|
13998 |
|
13999 |
|
14000 |
|
14001 |
|
14002 |
|
14003 | PersistentConnection;
|
14004 |
|
14005 | PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
|
14006 | this.sendRequest('q', { p: pathString }, onComplete);
|
14007 | };
|
14008 |
|
14009 | PersistentConnection.prototype.echo = function (data, onEcho) {
|
14010 | this.sendRequest('echo', { d: data }, onEcho);
|
14011 | };
|
14012 |
|
14013 | Connection;
|
14014 |
|
14015 |
|
14016 |
|
14017 | const hijackHash = function (newHash) {
|
14018 | const oldPut = PersistentConnection.prototype.put;
|
14019 | PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
|
14020 | if (hash !== undefined) {
|
14021 | hash = newHash();
|
14022 | }
|
14023 | oldPut.call(this, pathString, data, onComplete, hash);
|
14024 | };
|
14025 | return function () {
|
14026 | PersistentConnection.prototype.put = oldPut;
|
14027 | };
|
14028 | };
|
14029 | RepoInfo;
|
14030 |
|
14031 |
|
14032 |
|
14033 |
|
14034 | const forceRestClient = function (forceRestClient) {
|
14035 | repoManagerForceRestClient(forceRestClient);
|
14036 | };
|
14037 |
|
14038 |
|
14039 |
|
14040 |
|
14041 |
|
14042 |
|
14043 | registerDatabase();
|
14044 |
|
14045 | 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 };
|
14046 | //# sourceMappingURL=index.esm2017.js.map
|