Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(211)

Side by Side Diff: lib/src/firebase/firebase-debug.js

Issue 1418513006: update elements and fix some bugs (Closed) Base URL: git@github.com:dart-lang/polymer_elements.git@master
Patch Set: code review updates Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « lib/src/firebase/firebase.js ('k') | lib/src/ga-api-utils/build/ga-api-utils.js » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 /*! @license Firebase v2.2.9 1 /*! @license Firebase v2.3.1
2 License: https://www.firebase.com/terms/terms-of-service.html */ 2 License: https://www.firebase.com/terms/terms-of-service.html */
3 (function(ns) { 3 (function(ns) {
4 ns.wrapper = function(goog, fb) { 4 ns.wrapper = function(goog, fb) {
5 // Prevents closure from trying (and failing) to retrieve a deps.js file. 5 // Prevents closure from trying (and failing) to retrieve a deps.js file.
6 var CLOSURE_NO_DEPS = true; 6 var CLOSURE_NO_DEPS = true;
7 7
8 // Sets CLIENT_VERSION manually, since we can't use a closure --define with WHITESPACE_ONLY compilation. 8 // Sets CLIENT_VERSION manually, since we can't use a closure --define with WHITESPACE_ONLY compilation.
9 var CLIENT_VERSION = '2.2.9'; 9 var CLIENT_VERSION = '2.3.1';
10 var COMPILED = false; 10 var COMPILED = false;
11 var goog = goog || {}; 11 var goog = goog || {};
12 goog.global = this; 12 goog.global = this;
13 goog.global.CLOSURE_UNCOMPILED_DEFINES; 13 goog.global.CLOSURE_UNCOMPILED_DEFINES;
14 goog.global.CLOSURE_DEFINES; 14 goog.global.CLOSURE_DEFINES;
15 goog.isDef = function(val) { 15 goog.isDef = function(val) {
16 return val !== void 0; 16 return val !== void 0;
17 }; 17 };
18 goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) { 18 goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
19 var parts = name.split("."); 19 var parts = name.split(".");
(...skipping 4105 matching lines...) Expand 10 before | Expand all | Expand 10 after
4125 } 4125 }
4126 childrenNode.forEachChild(fb.core.snap.PriorityIndex, function(childName, ch ildNode) { 4126 childrenNode.forEachChild(fb.core.snap.PriorityIndex, function(childName, ch ildNode) {
4127 var newChildNode = fb.core.util.ServerValues.resolveDeferredValueSnapshot( childNode, serverValues); 4127 var newChildNode = fb.core.util.ServerValues.resolveDeferredValueSnapshot( childNode, serverValues);
4128 if (newChildNode !== childNode) { 4128 if (newChildNode !== childNode) {
4129 newNode = newNode.updateImmediateChild(childName, newChildNode); 4129 newNode = newNode.updateImmediateChild(childName, newChildNode);
4130 } 4130 }
4131 }); 4131 });
4132 return newNode; 4132 return newNode;
4133 } 4133 }
4134 }; 4134 };
4135 goog.provide("fb.core.util.Path");
4136 goog.provide("fb.core.util.ValidationPath");
4137 fb.core.util.Path = goog.defineClass(null, {constructor:function(pathOrString, o pt_pieceNum) {
4138 if (arguments.length == 1) {
4139 this.pieces_ = pathOrString.split("/");
4140 var copyTo = 0;
4141 for (var i = 0;i < this.pieces_.length;i++) {
4142 if (this.pieces_[i].length > 0) {
4143 this.pieces_[copyTo] = this.pieces_[i];
4144 copyTo++;
4145 }
4146 }
4147 this.pieces_.length = copyTo;
4148 this.pieceNum_ = 0;
4149 } else {
4150 this.pieces_ = pathOrString;
4151 this.pieceNum_ = opt_pieceNum;
4152 }
4153 }, getFront:function() {
4154 if (this.pieceNum_ >= this.pieces_.length) {
4155 return null;
4156 }
4157 return this.pieces_[this.pieceNum_];
4158 }, getLength:function() {
4159 return this.pieces_.length - this.pieceNum_;
4160 }, popFront:function() {
4161 var pieceNum = this.pieceNum_;
4162 if (pieceNum < this.pieces_.length) {
4163 pieceNum++;
4164 }
4165 return new fb.core.util.Path(this.pieces_, pieceNum);
4166 }, getBack:function() {
4167 if (this.pieceNum_ < this.pieces_.length) {
4168 return this.pieces_[this.pieces_.length - 1];
4169 }
4170 return null;
4171 }, toString:function() {
4172 var pathString = "";
4173 for (var i = this.pieceNum_;i < this.pieces_.length;i++) {
4174 if (this.pieces_[i] !== "") {
4175 pathString += "/" + this.pieces_[i];
4176 }
4177 }
4178 return pathString || "/";
4179 }, toUrlEncodedString:function() {
4180 var pathString = "";
4181 for (var i = this.pieceNum_;i < this.pieces_.length;i++) {
4182 if (this.pieces_[i] !== "") {
4183 pathString += "/" + goog.string.urlEncode(this.pieces_[i]);
4184 }
4185 }
4186 return pathString || "/";
4187 }, slice:function(opt_begin) {
4188 var begin = opt_begin || 0;
4189 return this.pieces_.slice(this.pieceNum_ + begin);
4190 }, parent:function() {
4191 if (this.pieceNum_ >= this.pieces_.length) {
4192 return null;
4193 }
4194 var pieces = [];
4195 for (var i = this.pieceNum_;i < this.pieces_.length - 1;i++) {
4196 pieces.push(this.pieces_[i]);
4197 }
4198 return new fb.core.util.Path(pieces, 0);
4199 }, child:function(childPathObj) {
4200 var pieces = [];
4201 for (var i = this.pieceNum_;i < this.pieces_.length;i++) {
4202 pieces.push(this.pieces_[i]);
4203 }
4204 if (childPathObj instanceof fb.core.util.Path) {
4205 for (i = childPathObj.pieceNum_;i < childPathObj.pieces_.length;i++) {
4206 pieces.push(childPathObj.pieces_[i]);
4207 }
4208 } else {
4209 var childPieces = childPathObj.split("/");
4210 for (i = 0;i < childPieces.length;i++) {
4211 if (childPieces[i].length > 0) {
4212 pieces.push(childPieces[i]);
4213 }
4214 }
4215 }
4216 return new fb.core.util.Path(pieces, 0);
4217 }, isEmpty:function() {
4218 return this.pieceNum_ >= this.pieces_.length;
4219 }, statics:{relativePath:function(outerPath, innerPath) {
4220 var outer = outerPath.getFront(), inner = innerPath.getFront();
4221 if (outer === null) {
4222 return innerPath;
4223 } else {
4224 if (outer === inner) {
4225 return fb.core.util.Path.relativePath(outerPath.popFront(), innerPath.popF ront());
4226 } else {
4227 throw new Error("INTERNAL ERROR: innerPath (" + innerPath + ") is not with in " + "outerPath (" + outerPath + ")");
4228 }
4229 }
4230 }}, equals:function(other) {
4231 if (this.getLength() !== other.getLength()) {
4232 return false;
4233 }
4234 for (var i = this.pieceNum_, j = other.pieceNum_;i <= this.pieces_.length;i++, j++) {
4235 if (this.pieces_[i] !== other.pieces_[j]) {
4236 return false;
4237 }
4238 }
4239 return true;
4240 }, contains:function(other) {
4241 var i = this.pieceNum_;
4242 var j = other.pieceNum_;
4243 if (this.getLength() > other.getLength()) {
4244 return false;
4245 }
4246 while (i < this.pieces_.length) {
4247 if (this.pieces_[i] !== other.pieces_[j]) {
4248 return false;
4249 }
4250 ++i;
4251 ++j;
4252 }
4253 return true;
4254 }});
4255 fb.core.util.Path.Empty = new fb.core.util.Path("");
4256 fb.core.util.ValidationPath = goog.defineClass(null, {constructor:function(path, errorPrefix) {
4257 this.parts_ = path.slice();
4258 this.byteLength_ = Math.max(1, this.parts_.length);
4259 this.errorPrefix_ = errorPrefix;
4260 for (var i = 0;i < this.parts_.length;i++) {
4261 this.byteLength_ += fb.util.utf8.stringLength(this.parts_[i]);
4262 }
4263 this.checkValid_();
4264 }, statics:{MAX_PATH_DEPTH:32, MAX_PATH_LENGTH_BYTES:768}, push:function(child) {
4265 if (this.parts_.length > 0) {
4266 this.byteLength_ += 1;
4267 }
4268 this.parts_.push(child);
4269 this.byteLength_ += fb.util.utf8.stringLength(child);
4270 this.checkValid_();
4271 }, pop:function() {
4272 var last = this.parts_.pop();
4273 this.byteLength_ -= fb.util.utf8.stringLength(last);
4274 if (this.parts_.length > 0) {
4275 this.byteLength_ -= 1;
4276 }
4277 }, checkValid_:function() {
4278 if (this.byteLength_ > fb.core.util.ValidationPath.MAX_PATH_LENGTH_BYTES) {
4279 throw new Error(this.errorPrefix_ + "has a key path longer than " + fb.core. util.ValidationPath.MAX_PATH_LENGTH_BYTES + " bytes (" + this.byteLength_ + ")." );
4280 }
4281 if (this.parts_.length > fb.core.util.ValidationPath.MAX_PATH_DEPTH) {
4282 throw new Error(this.errorPrefix_ + "path specified exceeds the maximum dept h that can be written (" + fb.core.util.ValidationPath.MAX_PATH_DEPTH + ") or ob ject contains a cycle " + this.toErrorString());
4283 }
4284 }, toErrorString:function() {
4285 if (this.parts_.length == 0) {
4286 return "";
4287 }
4288 return "in property '" + this.parts_.join(".") + "'";
4289 }});
4290 goog.provide("fb.core.storage.MemoryStorage"); 4135 goog.provide("fb.core.storage.MemoryStorage");
4291 goog.require("fb.util.obj"); 4136 goog.require("fb.util.obj");
4292 goog.scope(function() { 4137 goog.scope(function() {
4293 var obj = fb.util.obj; 4138 var obj = fb.util.obj;
4294 fb.core.storage.MemoryStorage = function() { 4139 fb.core.storage.MemoryStorage = function() {
4295 this.cache_ = {}; 4140 this.cache_ = {};
4296 }; 4141 };
4297 var MemoryStorage = fb.core.storage.MemoryStorage; 4142 var MemoryStorage = fb.core.storage.MemoryStorage;
4298 MemoryStorage.prototype.set = function(key, value) { 4143 MemoryStorage.prototype.set = function(key, value) {
4299 if (value == null) { 4144 if (value == null) {
(...skipping 88 matching lines...) Expand 10 before | Expand all | Expand 10 after
4388 return this.domain !== "firebaseio.com" && this.domain !== "firebaseio-demo.co m"; 4233 return this.domain !== "firebaseio.com" && this.domain !== "firebaseio-demo.co m";
4389 }; 4234 };
4390 fb.core.RepoInfo.prototype.updateHost = function(newHost) { 4235 fb.core.RepoInfo.prototype.updateHost = function(newHost) {
4391 if (newHost !== this.internalHost) { 4236 if (newHost !== this.internalHost) {
4392 this.internalHost = newHost; 4237 this.internalHost = newHost;
4393 if (this.isCacheableHost()) { 4238 if (this.isCacheableHost()) {
4394 fb.core.storage.PersistentStorage.set("host:" + this.host, this.internalHo st); 4239 fb.core.storage.PersistentStorage.set("host:" + this.host, this.internalHo st);
4395 } 4240 }
4396 } 4241 }
4397 }; 4242 };
4243 fb.core.RepoInfo.prototype.connectionURL = function(type, params) {
4244 fb.core.util.assert(typeof type === "string", "typeof type must == string");
4245 fb.core.util.assert(typeof params === "object", "typeof params must == object" );
4246 var connURL;
4247 if (type === fb.realtime.Constants.WEBSOCKET) {
4248 connURL = (this.secure ? "wss://" : "ws://") + this.internalHost + "/.ws?";
4249 } else {
4250 if (type === fb.realtime.Constants.LONG_POLLING) {
4251 connURL = (this.secure ? "https://" : "http://") + this.internalHost + "/. lp?";
4252 } else {
4253 throw new Error("Unknown connection type: " + type);
4254 }
4255 }
4256 if (this.needsQueryParam()) {
4257 params["ns"] = this.namespace;
4258 }
4259 var pairs = [];
4260 goog.object.forEach(params, function(element, index, obj) {
4261 pairs.push(index + "=" + element);
4262 });
4263 return connURL + pairs.join("&");
4264 };
4398 fb.core.RepoInfo.prototype.toString = function() { 4265 fb.core.RepoInfo.prototype.toString = function() {
4399 var str = (this.secure ? "https://" : "http://") + this.host; 4266 var str = (this.secure ? "https://" : "http://") + this.host;
4400 if (this.persistenceKey) { 4267 if (this.persistenceKey) {
4401 str += "<" + this.persistenceKey + ">"; 4268 str += "<" + this.persistenceKey + ">";
4402 } 4269 }
4403 return str; 4270 return str;
4404 }; 4271 };
4405 goog.provide("fb.core.util"); 4272 goog.provide("fb.core.util");
4406 goog.require("fb.constants"); 4273 goog.require("fb.constants");
4407 goog.require("fb.core.RepoInfo"); 4274 goog.require("fb.core.RepoInfo");
(...skipping 1067 matching lines...) Expand 10 before | Expand all | Expand 10 after
5475 }; 5342 };
5476 fb.core.view.ViewProcessor = function(filter) { 5343 fb.core.view.ViewProcessor = function(filter) {
5477 this.filter_ = filter; 5344 this.filter_ = filter;
5478 }; 5345 };
5479 fb.core.view.ViewProcessor.prototype.assertIndexed = function(viewCache) { 5346 fb.core.view.ViewProcessor.prototype.assertIndexed = function(viewCache) {
5480 fb.core.util.assert(viewCache.getEventCache().getNode().isIndexed(this.filter_ .getIndex()), "Event snap not indexed"); 5347 fb.core.util.assert(viewCache.getEventCache().getNode().isIndexed(this.filter_ .getIndex()), "Event snap not indexed");
5481 fb.core.util.assert(viewCache.getServerCache().getNode().isIndexed(this.filter _.getIndex()), "Server snap not indexed"); 5348 fb.core.util.assert(viewCache.getServerCache().getNode().isIndexed(this.filter _.getIndex()), "Server snap not indexed");
5482 }; 5349 };
5483 fb.core.view.ViewProcessor.prototype.applyOperation = function(oldViewCache, ope ration, writesCache, optCompleteCache) { 5350 fb.core.view.ViewProcessor.prototype.applyOperation = function(oldViewCache, ope ration, writesCache, optCompleteCache) {
5484 var accumulator = new fb.core.view.ChildChangeAccumulator; 5351 var accumulator = new fb.core.view.ChildChangeAccumulator;
5485 var newViewCache, constrainNode; 5352 var newViewCache, filterServerNode;
5486 if (operation.type === fb.core.OperationType.OVERWRITE) { 5353 if (operation.type === fb.core.OperationType.OVERWRITE) {
5487 var overwrite = (operation); 5354 var overwrite = (operation);
5488 if (overwrite.source.fromUser) { 5355 if (overwrite.source.fromUser) {
5489 newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, over write.snap, writesCache, optCompleteCache, accumulator); 5356 newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, over write.snap, writesCache, optCompleteCache, accumulator);
5490 } else { 5357 } else {
5491 fb.core.util.assert(overwrite.source.fromServer, "Unknown source."); 5358 fb.core.util.assert(overwrite.source.fromServer, "Unknown source.");
5492 constrainNode = overwrite.source.tagged; 5359 filterServerNode = overwrite.source.tagged || oldViewCache.getServerCache( ).isFiltered() && !overwrite.path.isEmpty();
5493 newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, ov erwrite.snap, writesCache, optCompleteCache, constrainNode, accumulator); 5360 newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, ov erwrite.snap, writesCache, optCompleteCache, filterServerNode, accumulator);
5494 } 5361 }
5495 } else { 5362 } else {
5496 if (operation.type === fb.core.OperationType.MERGE) { 5363 if (operation.type === fb.core.OperationType.MERGE) {
5497 var merge = (operation); 5364 var merge = (operation);
5498 if (merge.source.fromUser) { 5365 if (merge.source.fromUser) {
5499 newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.chil dren, writesCache, optCompleteCache, accumulator); 5366 newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.chil dren, writesCache, optCompleteCache, accumulator);
5500 } else { 5367 } else {
5501 fb.core.util.assert(merge.source.fromServer, "Unknown source."); 5368 fb.core.util.assert(merge.source.fromServer, "Unknown source.");
5502 constrainNode = merge.source.tagged; 5369 filterServerNode = merge.source.tagged || oldViewCache.getServerCache(). isFiltered();
5503 newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.ch ildren, writesCache, optCompleteCache, constrainNode, accumulator); 5370 newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.ch ildren, writesCache, optCompleteCache, filterServerNode, accumulator);
5504 } 5371 }
5505 } else { 5372 } else {
5506 if (operation.type === fb.core.OperationType.ACK_USER_WRITE) { 5373 if (operation.type === fb.core.OperationType.ACK_USER_WRITE) {
5507 var ackUserWrite = (operation); 5374 var ackUserWrite = (operation);
5508 if (!ackUserWrite.revert) { 5375 if (!ackUserWrite.revert) {
5509 newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ack UserWrite.affectedTree, writesCache, optCompleteCache, accumulator); 5376 newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ack UserWrite.affectedTree, writesCache, optCompleteCache, accumulator);
5510 } else { 5377 } else {
5511 newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, optCompleteCache, accumulator); 5378 newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, optCompleteCache, accumulator);
5512 } 5379 }
5513 } else { 5380 } else {
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
5579 if (newEventChild != null) { 5446 if (newEventChild != null) {
5580 newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), child Key, newEventChild, childChangePath, source, accumulator); 5447 newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), child Key, newEventChild, childChangePath, source, accumulator);
5581 } else { 5448 } else {
5582 newEventCache = oldEventSnap.getNode(); 5449 newEventCache = oldEventSnap.getNode();
5583 } 5450 }
5584 } 5451 }
5585 } 5452 }
5586 return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitiali zed() || changePath.isEmpty(), this.filter_.filtersNodes()); 5453 return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitiali zed() || changePath.isEmpty(), this.filter_.filtersNodes());
5587 } 5454 }
5588 }; 5455 };
5589 fb.core.view.ViewProcessor.prototype.applyServerOverwrite_ = function(oldViewCac he, changePath, changedSnap, writesCache, optCompleteCache, constrainServerNode, accumulator) { 5456 fb.core.view.ViewProcessor.prototype.applyServerOverwrite_ = function(oldViewCac he, changePath, changedSnap, writesCache, optCompleteCache, filterServerNode, ac cumulator) {
5590 var oldServerSnap = oldViewCache.getServerCache(); 5457 var oldServerSnap = oldViewCache.getServerCache();
5591 var newServerCache; 5458 var newServerCache;
5592 var serverFilter = constrainServerNode ? this.filter_ : this.filter_.getIndexe dFilter(); 5459 var serverFilter = filterServerNode ? this.filter_ : this.filter_.getIndexedFi lter();
5593 if (changePath.isEmpty()) { 5460 if (changePath.isEmpty()) {
5594 newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), change dSnap, null); 5461 newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), change dSnap, null);
5595 } else { 5462 } else {
5596 if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) { 5463 if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
5597 var newServerNode = oldServerSnap.getNode().updateChild(changePath, change dSnap); 5464 var newServerNode = oldServerSnap.getNode().updateChild(changePath, change dSnap);
5598 newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newS erverNode, null); 5465 newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newS erverNode, null);
5599 } else { 5466 } else {
5600 var childKey = changePath.getFront(); 5467 var childKey = changePath.getFront();
5601 if (!oldServerSnap.isCompleteForPath(changePath) && changePath.getLength() > 1) { 5468 if (!oldServerSnap.isCompleteForPath(changePath) && changePath.getLength() > 1) {
5602 return oldViewCache; 5469 return oldViewCache;
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
5674 } 5541 }
5675 }); 5542 });
5676 return curViewCache; 5543 return curViewCache;
5677 }; 5544 };
5678 fb.core.view.ViewProcessor.prototype.applyMerge_ = function(node, merge) { 5545 fb.core.view.ViewProcessor.prototype.applyMerge_ = function(node, merge) {
5679 merge.foreach(function(relativePath, childNode) { 5546 merge.foreach(function(relativePath, childNode) {
5680 node = node.updateChild(relativePath, childNode); 5547 node = node.updateChild(relativePath, childNode);
5681 }); 5548 });
5682 return node; 5549 return node;
5683 }; 5550 };
5684 fb.core.view.ViewProcessor.prototype.applyServerMerge_ = function(viewCache, pat h, changedChildren, writesCache, serverCache, constrainServerNode, accumulator) { 5551 fb.core.view.ViewProcessor.prototype.applyServerMerge_ = function(viewCache, pat h, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
5685 if (viewCache.getServerCache().getNode().isEmpty() && !viewCache.getServerCach e().isFullyInitialized()) { 5552 if (viewCache.getServerCache().getNode().isEmpty() && !viewCache.getServerCach e().isFullyInitialized()) {
5686 return viewCache; 5553 return viewCache;
5687 } 5554 }
5688 var curViewCache = viewCache; 5555 var curViewCache = viewCache;
5689 var viewMergeTree; 5556 var viewMergeTree;
5690 if (path.isEmpty()) { 5557 if (path.isEmpty()) {
5691 viewMergeTree = changedChildren; 5558 viewMergeTree = changedChildren;
5692 } else { 5559 } else {
5693 viewMergeTree = fb.core.util.ImmutableTree.Empty.setTree(path, changedChildr en); 5560 viewMergeTree = fb.core.util.ImmutableTree.Empty.setTree(path, changedChildr en);
5694 } 5561 }
5695 var serverNode = viewCache.getServerCache().getNode(); 5562 var serverNode = viewCache.getServerCache().getNode();
5696 var self = this; 5563 var self = this;
5697 viewMergeTree.children.inorderTraversal(function(childKey, childTree) { 5564 viewMergeTree.children.inorderTraversal(function(childKey, childTree) {
5698 if (serverNode.hasChild(childKey)) { 5565 if (serverNode.hasChild(childKey)) {
5699 var serverChild = viewCache.getServerCache().getNode().getImmediateChild(c hildKey); 5566 var serverChild = viewCache.getServerCache().getNode().getImmediateChild(c hildKey);
5700 var newChild = self.applyMerge_(serverChild, childTree); 5567 var newChild = self.applyMerge_(serverChild, childTree);
5701 curViewCache = self.applyServerOverwrite_(curViewCache, new fb.core.util.P ath(childKey), newChild, writesCache, serverCache, constrainServerNode, accumula tor); 5568 curViewCache = self.applyServerOverwrite_(curViewCache, new fb.core.util.P ath(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator );
5702 } 5569 }
5703 }); 5570 });
5704 viewMergeTree.children.inorderTraversal(function(childKey, childMergeTree) { 5571 viewMergeTree.children.inorderTraversal(function(childKey, childMergeTree) {
5705 var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(chil dKey) && childMergeTree.value == null; 5572 var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(chil dKey) && childMergeTree.value == null;
5706 if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) { 5573 if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
5707 var serverChild = viewCache.getServerCache().getNode().getImmediateChild(c hildKey); 5574 var serverChild = viewCache.getServerCache().getNode().getImmediateChild(c hildKey);
5708 var newChild = self.applyMerge_(serverChild, childMergeTree); 5575 var newChild = self.applyMerge_(serverChild, childMergeTree);
5709 curViewCache = self.applyServerOverwrite_(curViewCache, new fb.core.util.P ath(childKey), newChild, writesCache, serverCache, constrainServerNode, accumula tor); 5576 curViewCache = self.applyServerOverwrite_(curViewCache, new fb.core.util.P ath(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator );
5710 } 5577 }
5711 }); 5578 });
5712 return curViewCache; 5579 return curViewCache;
5713 }; 5580 };
5714 fb.core.view.ViewProcessor.prototype.ackUserWrite_ = function(viewCache, ackPath , affectedTree, writesCache, optCompleteCache, accumulator) { 5581 fb.core.view.ViewProcessor.prototype.ackUserWrite_ = function(viewCache, ackPath , affectedTree, writesCache, optCompleteCache, accumulator) {
5715 if (writesCache.shadowingWrite(ackPath) != null) { 5582 if (writesCache.shadowingWrite(ackPath) != null) {
5716 return viewCache; 5583 return viewCache;
5717 } 5584 }
5585 var filterServerNode = viewCache.getServerCache().isFiltered();
5718 var serverCache = viewCache.getServerCache(); 5586 var serverCache = viewCache.getServerCache();
5719 if (affectedTree.value != null) { 5587 if (affectedTree.value != null) {
5720 if (ackPath.isEmpty() && serverCache.isFullyInitialized() || serverCache.isC ompleteForPath(ackPath)) { 5588 if (ackPath.isEmpty() && serverCache.isFullyInitialized() || serverCache.isC ompleteForPath(ackPath)) {
5721 return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode( ).getChild(ackPath), writesCache, optCompleteCache, false, accumulator); 5589 return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode( ).getChild(ackPath), writesCache, optCompleteCache, filterServerNode, accumulato r);
5722 } else { 5590 } else {
5723 if (ackPath.isEmpty()) { 5591 if (ackPath.isEmpty()) {
5724 var changedChildren = (fb.core.util.ImmutableTree.Empty); 5592 var changedChildren = (fb.core.util.ImmutableTree.Empty);
5725 serverCache.getNode().forEachChild(fb.core.snap.KeyIndex, function(name, node) { 5593 serverCache.getNode().forEachChild(fb.core.snap.KeyIndex, function(name, node) {
5726 changedChildren = changedChildren.set(new fb.core.util.Path(name), nod e); 5594 changedChildren = changedChildren.set(new fb.core.util.Path(name), nod e);
5727 }); 5595 });
5728 return this.applyServerMerge_(viewCache, ackPath, changedChildren, write sCache, optCompleteCache, false, accumulator); 5596 return this.applyServerMerge_(viewCache, ackPath, changedChildren, write sCache, optCompleteCache, filterServerNode, accumulator);
5729 } else { 5597 } else {
5730 return viewCache; 5598 return viewCache;
5731 } 5599 }
5732 } 5600 }
5733 } else { 5601 } else {
5734 var changedChildren = (fb.core.util.ImmutableTree.Empty); 5602 var changedChildren = (fb.core.util.ImmutableTree.Empty);
5735 affectedTree.foreach(function(mergePath, value) { 5603 affectedTree.foreach(function(mergePath, value) {
5736 var serverCachePath = ackPath.child(mergePath); 5604 var serverCachePath = ackPath.child(mergePath);
5737 if (serverCache.isCompleteForPath(serverCachePath)) { 5605 if (serverCache.isCompleteForPath(serverCachePath)) {
5738 changedChildren = changedChildren.set(mergePath, serverCache.getNode().g etChild(serverCachePath)); 5606 changedChildren = changedChildren.set(mergePath, serverCache.getNode().g etChild(serverCachePath));
5739 } 5607 }
5740 }); 5608 });
5741 return this.applyServerMerge_(viewCache, ackPath, changedChildren, writesCac he, optCompleteCache, false, accumulator); 5609 return this.applyServerMerge_(viewCache, ackPath, changedChildren, writesCac he, optCompleteCache, filterServerNode, accumulator);
5742 } 5610 }
5743 }; 5611 };
5744 fb.core.view.ViewProcessor.prototype.revertUserWrite_ = function(viewCache, path , writesCache, optCompleteServerCache, accumulator) { 5612 fb.core.view.ViewProcessor.prototype.revertUserWrite_ = function(viewCache, path , writesCache, optCompleteServerCache, accumulator) {
5745 var complete; 5613 var complete;
5746 if (writesCache.shadowingWrite(path) != null) { 5614 if (writesCache.shadowingWrite(path) != null) {
5747 return viewCache; 5615 return viewCache;
5748 } else { 5616 } else {
5749 var source = new fb.core.view.WriteTreeCompleteChildSource(writesCache, view Cache, optCompleteServerCache); 5617 var source = new fb.core.view.WriteTreeCompleteChildSource(writesCache, view Cache, optCompleteServerCache);
5750 var oldEventCache = viewCache.getEventCache().getNode(); 5618 var oldEventCache = viewCache.getEventCache().getNode();
5751 var newEventCache; 5619 var newEventCache;
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
5785 complete = viewCache.getServerCache().isFullyInitialized() || writesCache.sh adowingWrite(fb.core.util.Path.Empty) != null; 5653 complete = viewCache.getServerCache().isFullyInitialized() || writesCache.sh adowingWrite(fb.core.util.Path.Empty) != null;
5786 return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filte rsNodes()); 5654 return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filte rsNodes());
5787 } 5655 }
5788 }; 5656 };
5789 fb.core.view.ViewProcessor.prototype.listenComplete_ = function(viewCache, path, writesCache, serverCache, accumulator) { 5657 fb.core.view.ViewProcessor.prototype.listenComplete_ = function(viewCache, path, writesCache, serverCache, accumulator) {
5790 var oldServerNode = viewCache.getServerCache(); 5658 var oldServerNode = viewCache.getServerCache();
5791 var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServ erNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered()); 5659 var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServ erNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());
5792 return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCach e, fb.core.view.NO_COMPLETE_CHILD_SOURCE, accumulator); 5660 return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCach e, fb.core.view.NO_COMPLETE_CHILD_SOURCE, accumulator);
5793 }; 5661 };
5794 goog.provide("fb.core.snap.Index"); 5662 goog.provide("fb.core.snap.Index");
5663 goog.provide("fb.core.snap.KeyIndex");
5664 goog.provide("fb.core.snap.PathIndex");
5795 goog.provide("fb.core.snap.PriorityIndex"); 5665 goog.provide("fb.core.snap.PriorityIndex");
5796 goog.provide("fb.core.snap.SubKeyIndex"); 5666 goog.provide("fb.core.snap.ValueIndex");
5797 goog.require("fb.core.snap.comparators");
5798 goog.require("fb.core.util"); 5667 goog.require("fb.core.util");
5799 fb.core.snap.Index = function() { 5668 fb.core.snap.Index = function() {
5800 }; 5669 };
5801 fb.core.snap.Index.FallbackType; 5670 fb.core.snap.Index.FallbackType;
5802 fb.core.snap.Index.Fallback = {}; 5671 fb.core.snap.Index.Fallback = {};
5803 fb.core.snap.Index.prototype.compare = goog.abstractMethod; 5672 fb.core.snap.Index.prototype.compare = goog.abstractMethod;
5804 fb.core.snap.Index.prototype.isDefinedOn = goog.abstractMethod; 5673 fb.core.snap.Index.prototype.isDefinedOn = goog.abstractMethod;
5805 fb.core.snap.Index.prototype.getCompare = function() { 5674 fb.core.snap.Index.prototype.getCompare = function() {
5806 return goog.bind(this.compare, this); 5675 return goog.bind(this.compare, this);
5807 }; 5676 };
5808 fb.core.snap.Index.prototype.indexedValueChanged = function(oldNode, newNode) { 5677 fb.core.snap.Index.prototype.indexedValueChanged = function(oldNode, newNode) {
5809 var oldWrapped = new fb.core.snap.NamedNode(fb.core.util.MIN_NAME, oldNode); 5678 var oldWrapped = new fb.core.snap.NamedNode(fb.core.util.MIN_NAME, oldNode);
5810 var newWrapped = new fb.core.snap.NamedNode(fb.core.util.MIN_NAME, newNode); 5679 var newWrapped = new fb.core.snap.NamedNode(fb.core.util.MIN_NAME, newNode);
5811 return this.compare(oldWrapped, newWrapped) !== 0; 5680 return this.compare(oldWrapped, newWrapped) !== 0;
5812 }; 5681 };
5813 fb.core.snap.Index.prototype.minPost = function() { 5682 fb.core.snap.Index.prototype.minPost = function() {
5814 return fb.core.snap.NamedNode.MIN; 5683 return fb.core.snap.NamedNode.MIN;
5815 }; 5684 };
5816 fb.core.snap.Index.prototype.maxPost = goog.abstractMethod; 5685 fb.core.snap.Index.prototype.maxPost = goog.abstractMethod;
5817 fb.core.snap.Index.prototype.makePost = goog.abstractMethod; 5686 fb.core.snap.Index.prototype.makePost = goog.abstractMethod;
5818 fb.core.snap.Index.prototype.toString = goog.abstractMethod; 5687 fb.core.snap.Index.prototype.toString = goog.abstractMethod;
5819 fb.core.snap.SubKeyIndex = function(indexKey) { 5688 fb.core.snap.PathIndex = function(indexPath) {
5820 fb.core.snap.Index.call(this); 5689 fb.core.snap.Index.call(this);
5821 this.indexKey_ = indexKey; 5690 fb.core.util.assert(!indexPath.isEmpty() && indexPath.getFront() !== ".priorit y", "Can't create PathIndex with empty path or .priority key");
5691 this.indexPath_ = indexPath;
5822 }; 5692 };
5823 goog.inherits(fb.core.snap.SubKeyIndex, fb.core.snap.Index); 5693 goog.inherits(fb.core.snap.PathIndex, fb.core.snap.Index);
5824 fb.core.snap.SubKeyIndex.prototype.extractChild = function(snap) { 5694 fb.core.snap.PathIndex.prototype.extractChild = function(snap) {
5825 return snap.getImmediateChild(this.indexKey_); 5695 return snap.getChild(this.indexPath_);
5826 }; 5696 };
5827 fb.core.snap.SubKeyIndex.prototype.isDefinedOn = function(node) { 5697 fb.core.snap.PathIndex.prototype.isDefinedOn = function(node) {
5828 return!node.getImmediateChild(this.indexKey_).isEmpty(); 5698 return!node.getChild(this.indexPath_).isEmpty();
5829 }; 5699 };
5830 fb.core.snap.SubKeyIndex.prototype.compare = function(a, b) { 5700 fb.core.snap.PathIndex.prototype.compare = function(a, b) {
5831 var aChild = this.extractChild(a.node); 5701 var aChild = this.extractChild(a.node);
5832 var bChild = this.extractChild(b.node); 5702 var bChild = this.extractChild(b.node);
5833 var indexCmp = aChild.compareTo(bChild); 5703 var indexCmp = aChild.compareTo(bChild);
5834 if (indexCmp === 0) { 5704 if (indexCmp === 0) {
5835 return fb.core.util.nameCompare(a.name, b.name); 5705 return fb.core.util.nameCompare(a.name, b.name);
5836 } else { 5706 } else {
5837 return indexCmp; 5707 return indexCmp;
5838 } 5708 }
5839 }; 5709 };
5840 fb.core.snap.SubKeyIndex.prototype.makePost = function(indexValue, name) { 5710 fb.core.snap.PathIndex.prototype.makePost = function(indexValue, name) {
5841 var valueNode = fb.core.snap.NodeFromJSON(indexValue); 5711 var valueNode = fb.core.snap.NodeFromJSON(indexValue);
5842 var node = fb.core.snap.EMPTY_NODE.updateImmediateChild(this.indexKey_, valueN ode); 5712 var node = fb.core.snap.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
5843 return new fb.core.snap.NamedNode(name, node); 5713 return new fb.core.snap.NamedNode(name, node);
5844 }; 5714 };
5845 fb.core.snap.SubKeyIndex.prototype.maxPost = function() { 5715 fb.core.snap.PathIndex.prototype.maxPost = function() {
5846 var node = fb.core.snap.EMPTY_NODE.updateImmediateChild(this.indexKey_, fb.cor e.snap.MAX_NODE); 5716 var node = fb.core.snap.EMPTY_NODE.updateChild(this.indexPath_, fb.core.snap.M AX_NODE);
5847 return new fb.core.snap.NamedNode(fb.core.util.MAX_NAME, node); 5717 return new fb.core.snap.NamedNode(fb.core.util.MAX_NAME, node);
5848 }; 5718 };
5849 fb.core.snap.SubKeyIndex.prototype.toString = function() { 5719 fb.core.snap.PathIndex.prototype.toString = function() {
5850 return this.indexKey_; 5720 return this.indexPath_.slice().join("/");
5851 }; 5721 };
5852 fb.core.snap.PriorityIndex_ = function() { 5722 fb.core.snap.PriorityIndex_ = function() {
5853 fb.core.snap.Index.call(this); 5723 fb.core.snap.Index.call(this);
5854 }; 5724 };
5855 goog.inherits(fb.core.snap.PriorityIndex_, fb.core.snap.Index); 5725 goog.inherits(fb.core.snap.PriorityIndex_, fb.core.snap.Index);
5856 fb.core.snap.PriorityIndex_.prototype.compare = function(a, b) { 5726 fb.core.snap.PriorityIndex_.prototype.compare = function(a, b) {
5857 var aPriority = a.node.getPriority(); 5727 var aPriority = a.node.getPriority();
5858 var bPriority = b.node.getPriority(); 5728 var bPriority = b.node.getPriority();
5859 var indexCmp = aPriority.compareTo(bPriority); 5729 var indexCmp = aPriority.compareTo(bPriority);
5860 if (indexCmp === 0) { 5730 if (indexCmp === 0) {
(...skipping 287 matching lines...) Expand 10 before | Expand all | Expand 10 after
6148 var orderBy; 6018 var orderBy;
6149 if (this.index_ === fb.core.snap.PriorityIndex) { 6019 if (this.index_ === fb.core.snap.PriorityIndex) {
6150 orderBy = REST_CONSTANTS.PRIORITY_INDEX; 6020 orderBy = REST_CONSTANTS.PRIORITY_INDEX;
6151 } else { 6021 } else {
6152 if (this.index_ === fb.core.snap.ValueIndex) { 6022 if (this.index_ === fb.core.snap.ValueIndex) {
6153 orderBy = REST_CONSTANTS.VALUE_INDEX; 6023 orderBy = REST_CONSTANTS.VALUE_INDEX;
6154 } else { 6024 } else {
6155 if (this.index_ === fb.core.snap.KeyIndex) { 6025 if (this.index_ === fb.core.snap.KeyIndex) {
6156 orderBy = REST_CONSTANTS.KEY_INDEX; 6026 orderBy = REST_CONSTANTS.KEY_INDEX;
6157 } else { 6027 } else {
6158 fb.core.util.assert(this.index_ instanceof fb.core.snap.SubKeyIndex, "Un recognized index type!"); 6028 fb.core.util.assert(this.index_ instanceof fb.core.snap.PathIndex, "Unre cognized index type!");
6159 orderBy = this.index_.toString(); 6029 orderBy = this.index_.toString();
6160 } 6030 }
6161 } 6031 }
6162 } 6032 }
6163 qs[REST_CONSTANTS.ORDER_BY] = fb.util.json.stringify(orderBy); 6033 qs[REST_CONSTANTS.ORDER_BY] = fb.util.json.stringify(orderBy);
6164 if (this.startSet_) { 6034 if (this.startSet_) {
6165 qs[REST_CONSTANTS.START_AT] = fb.util.json.stringify(this.indexStartValue_); 6035 qs[REST_CONSTANTS.START_AT] = fb.util.json.stringify(this.indexStartValue_);
6166 if (this.startNameSet_) { 6036 if (this.startNameSet_) {
6167 qs[REST_CONSTANTS.START_AT] += "," + fb.util.json.stringify(this.indexStar tName_); 6037 qs[REST_CONSTANTS.START_AT] += "," + fb.util.json.stringify(this.indexStar tName_);
6168 } 6038 }
(...skipping 996 matching lines...) Expand 10 before | Expand all | Expand 10 after
7165 xhr.open("GET", url, true); 7035 xhr.open("GET", url, true);
7166 xhr.send(); 7036 xhr.send();
7167 }, statics:{getListenId_:function(query, opt_tag) { 7037 }, statics:{getListenId_:function(query, opt_tag) {
7168 if (goog.isDef(opt_tag)) { 7038 if (goog.isDef(opt_tag)) {
7169 return "tag$" + opt_tag; 7039 return "tag$" + opt_tag;
7170 } else { 7040 } else {
7171 fb.core.util.assert(query.getQueryParams().isDefault(), "should have a tag i f it's not a default query."); 7041 fb.core.util.assert(query.getQueryParams().isDefault(), "should have a tag i f it's not a default query.");
7172 return query.path.toString(); 7042 return query.path.toString();
7173 } 7043 }
7174 }}}); 7044 }}});
7045 goog.provide("fb.core.util.EventEmitter");
7046 goog.require("fb.core.util");
7047 goog.require("goog.array");
7048 fb.core.util.EventEmitter = goog.defineClass(null, {constructor:function(allowed Events) {
7049 fb.core.util.assert(goog.isArray(allowedEvents) && allowedEvents.length > 0, " Requires a non-empty array");
7050 this.allowedEvents_ = allowedEvents;
7051 this.listeners_ = {};
7052 }, getInitialEvent:goog.abstractMethod, trigger:function(eventType, var_args) {
7053 var listeners = goog.array.clone(this.listeners_[eventType] || []);
7054 for (var i = 0;i < listeners.length;i++) {
7055 listeners[i].callback.apply(listeners[i].context, Array.prototype.slice.call (arguments, 1));
7056 }
7057 }, on:function(eventType, callback, context) {
7058 this.validateEventType_(eventType);
7059 this.listeners_[eventType] = this.listeners_[eventType] || [];
7060 this.listeners_[eventType].push({callback:callback, context:context});
7061 var eventData = this.getInitialEvent(eventType);
7062 if (eventData) {
7063 callback.apply(context, eventData);
7064 }
7065 }, off:function(eventType, callback, context) {
7066 this.validateEventType_(eventType);
7067 var listeners = this.listeners_[eventType] || [];
7068 for (var i = 0;i < listeners.length;i++) {
7069 if (listeners[i].callback === callback && (!context || context === listeners [i].context)) {
7070 listeners.splice(i, 1);
7071 return;
7072 }
7073 }
7074 }, validateEventType_:function(eventType) {
7075 fb.core.util.assert(goog.array.find(this.allowedEvents_, function(et) {
7076 return et === eventType;
7077 }), "Unknown event: " + eventType);
7078 }});
7079 goog.provide("fb.core.util.nextPushId");
7080 goog.require("fb.core.util");
7081 fb.core.util.nextPushId = function() {
7082 var PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuv wxyz";
7083 var lastPushTime = 0;
7084 var lastRandChars = [];
7085 return function(now) {
7086 var duplicateTime = now === lastPushTime;
7087 lastPushTime = now;
7088 var timeStampChars = new Array(8);
7089 for (var i = 7;i >= 0;i--) {
7090 timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
7091 now = Math.floor(now / 64);
7092 }
7093 fb.core.util.assert(now === 0, "Cannot push at time == 0");
7094 var id = timeStampChars.join("");
7095 if (!duplicateTime) {
7096 for (i = 0;i < 12;i++) {
7097 lastRandChars[i] = Math.floor(Math.random() * 64);
7098 }
7099 } else {
7100 for (i = 11;i >= 0 && lastRandChars[i] === 63;i--) {
7101 lastRandChars[i] = 0;
7102 }
7103 lastRandChars[i]++;
7104 }
7105 for (i = 0;i < 12;i++) {
7106 id += PUSH_CHARS.charAt(lastRandChars[i]);
7107 }
7108 fb.core.util.assert(id.length === 20, "nextPushId: Length should be 20.");
7109 return id;
7110 };
7111 }();
7112 goog.provide("fb.core.util.OnlineMonitor");
7113 goog.require("fb.core.util");
7114 goog.require("fb.core.util.EventEmitter");
7115 fb.core.util.OnlineMonitor = goog.defineClass(fb.core.util.EventEmitter, {constr uctor:function() {
7116 fb.core.util.EventEmitter.call(this, ["online"]);
7117 this.online_ = true;
7118 if (typeof window !== "undefined" && typeof window.addEventListener !== "undef ined") {
7119 var self = this;
7120 window.addEventListener("online", function() {
7121 if (!self.online_) {
7122 self.online_ = true;
7123 self.trigger("online", true);
7124 }
7125 }, false);
7126 window.addEventListener("offline", function() {
7127 if (self.online_) {
7128 self.online_ = false;
7129 self.trigger("online", false);
7130 }
7131 }, false);
7132 }
7133 }, getInitialEvent:function(eventType) {
7134 fb.core.util.assert(eventType === "online", "Unknown event type: " + eventType );
7135 return[this.online_];
7136 }, currentlyOnline:function() {
7137 return this.online_;
7138 }});
7139 goog.addSingletonGetter(fb.core.util.OnlineMonitor);
7140 goog.provide("fb.core.util.VisibilityMonitor");
7141 goog.require("fb.core.util");
7142 goog.require("fb.core.util.EventEmitter");
7143 fb.core.util.VisibilityMonitor = goog.defineClass(fb.core.util.EventEmitter, {co nstructor:function() {
7144 fb.core.util.EventEmitter.call(this, ["visible"]);
7145 var hidden, visibilityChange;
7146 if (typeof document !== "undefined" && typeof document.addEventListener !== "u ndefined") {
7147 if (typeof document["hidden"] !== "undefined") {
7148 visibilityChange = "visibilitychange";
7149 hidden = "hidden";
7150 } else {
7151 if (typeof document["mozHidden"] !== "undefined") {
7152 visibilityChange = "mozvisibilitychange";
7153 hidden = "mozHidden";
7154 } else {
7155 if (typeof document["msHidden"] !== "undefined") {
7156 visibilityChange = "msvisibilitychange";
7157 hidden = "msHidden";
7158 } else {
7159 if (typeof document["webkitHidden"] !== "undefined") {
7160 visibilityChange = "webkitvisibilitychange";
7161 hidden = "webkitHidden";
7162 }
7163 }
7164 }
7165 }
7166 }
7167 this.visible_ = true;
7168 if (visibilityChange) {
7169 var self = this;
7170 document.addEventListener(visibilityChange, function() {
7171 var visible = !document[hidden];
7172 if (visible !== self.visible_) {
7173 self.visible_ = visible;
7174 self.trigger("visible", visible);
7175 }
7176 }, false);
7177 }
7178 }, getInitialEvent:function(eventType) {
7179 fb.core.util.assert(eventType === "visible", "Unknown event type: " + eventTyp e);
7180 return[this.visible_];
7181 }});
7182 goog.addSingletonGetter(fb.core.util.VisibilityMonitor);
7183 goog.provide("fb.core.util.Path");
7184 goog.provide("fb.core.util.ValidationPath");
7185 goog.require("fb.core.util");
7186 goog.require("fb.util.utf8");
7187 goog.require("goog.string");
7188 fb.core.util.Path = goog.defineClass(null, {constructor:function(pathOrString, o pt_pieceNum) {
7189 if (arguments.length == 1) {
7190 this.pieces_ = pathOrString.split("/");
7191 var copyTo = 0;
7192 for (var i = 0;i < this.pieces_.length;i++) {
7193 if (this.pieces_[i].length > 0) {
7194 this.pieces_[copyTo] = this.pieces_[i];
7195 copyTo++;
7196 }
7197 }
7198 this.pieces_.length = copyTo;
7199 this.pieceNum_ = 0;
7200 } else {
7201 this.pieces_ = pathOrString;
7202 this.pieceNum_ = opt_pieceNum;
7203 }
7204 }, getFront:function() {
7205 if (this.pieceNum_ >= this.pieces_.length) {
7206 return null;
7207 }
7208 return this.pieces_[this.pieceNum_];
7209 }, getLength:function() {
7210 return this.pieces_.length - this.pieceNum_;
7211 }, popFront:function() {
7212 var pieceNum = this.pieceNum_;
7213 if (pieceNum < this.pieces_.length) {
7214 pieceNum++;
7215 }
7216 return new fb.core.util.Path(this.pieces_, pieceNum);
7217 }, getBack:function() {
7218 if (this.pieceNum_ < this.pieces_.length) {
7219 return this.pieces_[this.pieces_.length - 1];
7220 }
7221 return null;
7222 }, toString:function() {
7223 var pathString = "";
7224 for (var i = this.pieceNum_;i < this.pieces_.length;i++) {
7225 if (this.pieces_[i] !== "") {
7226 pathString += "/" + this.pieces_[i];
7227 }
7228 }
7229 return pathString || "/";
7230 }, toUrlEncodedString:function() {
7231 var pathString = "";
7232 for (var i = this.pieceNum_;i < this.pieces_.length;i++) {
7233 if (this.pieces_[i] !== "") {
7234 pathString += "/" + goog.string.urlEncode(this.pieces_[i]);
7235 }
7236 }
7237 return pathString || "/";
7238 }, slice:function(opt_begin) {
7239 var begin = opt_begin || 0;
7240 return this.pieces_.slice(this.pieceNum_ + begin);
7241 }, parent:function() {
7242 if (this.pieceNum_ >= this.pieces_.length) {
7243 return null;
7244 }
7245 var pieces = [];
7246 for (var i = this.pieceNum_;i < this.pieces_.length - 1;i++) {
7247 pieces.push(this.pieces_[i]);
7248 }
7249 return new fb.core.util.Path(pieces, 0);
7250 }, child:function(childPathObj) {
7251 var pieces = [];
7252 for (var i = this.pieceNum_;i < this.pieces_.length;i++) {
7253 pieces.push(this.pieces_[i]);
7254 }
7255 if (childPathObj instanceof fb.core.util.Path) {
7256 for (i = childPathObj.pieceNum_;i < childPathObj.pieces_.length;i++) {
7257 pieces.push(childPathObj.pieces_[i]);
7258 }
7259 } else {
7260 var childPieces = childPathObj.split("/");
7261 for (i = 0;i < childPieces.length;i++) {
7262 if (childPieces[i].length > 0) {
7263 pieces.push(childPieces[i]);
7264 }
7265 }
7266 }
7267 return new fb.core.util.Path(pieces, 0);
7268 }, isEmpty:function() {
7269 return this.pieceNum_ >= this.pieces_.length;
7270 }, statics:{relativePath:function(outerPath, innerPath) {
7271 var outer = outerPath.getFront(), inner = innerPath.getFront();
7272 if (outer === null) {
7273 return innerPath;
7274 } else {
7275 if (outer === inner) {
7276 return fb.core.util.Path.relativePath(outerPath.popFront(), innerPath.popF ront());
7277 } else {
7278 throw new Error("INTERNAL ERROR: innerPath (" + innerPath + ") is not with in " + "outerPath (" + outerPath + ")");
7279 }
7280 }
7281 }, comparePaths:function(left, right) {
7282 var leftKeys = left.slice();
7283 var rightKeys = right.slice();
7284 for (var i = 0;i < leftKeys.length && i < rightKeys.length;i++) {
7285 var cmp = fb.core.util.nameCompare(leftKeys[i], rightKeys[i]);
7286 if (cmp !== 0) {
7287 return cmp;
7288 }
7289 }
7290 if (leftKeys.length === rightKeys.length) {
7291 return 0;
7292 }
7293 return leftKeys.length < rightKeys.length ? -1 : 1;
7294 }}, equals:function(other) {
7295 if (this.getLength() !== other.getLength()) {
7296 return false;
7297 }
7298 for (var i = this.pieceNum_, j = other.pieceNum_;i <= this.pieces_.length;i++, j++) {
7299 if (this.pieces_[i] !== other.pieces_[j]) {
7300 return false;
7301 }
7302 }
7303 return true;
7304 }, contains:function(other) {
7305 var i = this.pieceNum_;
7306 var j = other.pieceNum_;
7307 if (this.getLength() > other.getLength()) {
7308 return false;
7309 }
7310 while (i < this.pieces_.length) {
7311 if (this.pieces_[i] !== other.pieces_[j]) {
7312 return false;
7313 }
7314 ++i;
7315 ++j;
7316 }
7317 return true;
7318 }});
7319 fb.core.util.Path.Empty = new fb.core.util.Path("");
7320 fb.core.util.ValidationPath = goog.defineClass(null, {constructor:function(path, errorPrefix) {
7321 this.parts_ = path.slice();
7322 this.byteLength_ = Math.max(1, this.parts_.length);
7323 this.errorPrefix_ = errorPrefix;
7324 for (var i = 0;i < this.parts_.length;i++) {
7325 this.byteLength_ += fb.util.utf8.stringLength(this.parts_[i]);
7326 }
7327 this.checkValid_();
7328 }, statics:{MAX_PATH_DEPTH:32, MAX_PATH_LENGTH_BYTES:768}, push:function(child) {
7329 if (this.parts_.length > 0) {
7330 this.byteLength_ += 1;
7331 }
7332 this.parts_.push(child);
7333 this.byteLength_ += fb.util.utf8.stringLength(child);
7334 this.checkValid_();
7335 }, pop:function() {
7336 var last = this.parts_.pop();
7337 this.byteLength_ -= fb.util.utf8.stringLength(last);
7338 if (this.parts_.length > 0) {
7339 this.byteLength_ -= 1;
7340 }
7341 }, checkValid_:function() {
7342 if (this.byteLength_ > fb.core.util.ValidationPath.MAX_PATH_LENGTH_BYTES) {
7343 throw new Error(this.errorPrefix_ + "has a key path longer than " + fb.core. util.ValidationPath.MAX_PATH_LENGTH_BYTES + " bytes (" + this.byteLength_ + ")." );
7344 }
7345 if (this.parts_.length > fb.core.util.ValidationPath.MAX_PATH_DEPTH) {
7346 throw new Error(this.errorPrefix_ + "path specified exceeds the maximum dept h that can be written (" + fb.core.util.ValidationPath.MAX_PATH_DEPTH + ") or ob ject contains a cycle " + this.toErrorString());
7347 }
7348 }, toErrorString:function() {
7349 if (this.parts_.length == 0) {
7350 return "";
7351 }
7352 return "in property '" + this.parts_.join(".") + "'";
7353 }});
7175 goog.provide("fb.core.util.ImmutableTree"); 7354 goog.provide("fb.core.util.ImmutableTree");
7176 goog.require("fb.core.util"); 7355 goog.require("fb.core.util");
7177 goog.require("fb.core.util.Path"); 7356 goog.require("fb.core.util.Path");
7178 goog.require("fb.core.util.SortedMap"); 7357 goog.require("fb.core.util.SortedMap");
7179 goog.require("fb.util.json"); 7358 goog.require("fb.util.json");
7180 goog.require("fb.util.obj"); 7359 goog.require("fb.util.obj");
7181 goog.require("goog.object"); 7360 goog.require("goog.object");
7182 fb.core.util.ImmutableTree = goog.defineClass(null, {constructor:function(value, opt_children) { 7361 fb.core.util.ImmutableTree = goog.defineClass(null, {constructor:function(value, opt_children) {
7183 this.value = value; 7362 this.value = value;
7184 this.children = opt_children || fb.core.util.ImmutableTree.EmptyChildren_; 7363 this.children = opt_children || fb.core.util.ImmutableTree.EmptyChildren_;
(...skipping 941 matching lines...) Expand 10 before | Expand all | Expand 10 after
8126 var covered = this.syncPointTree_.findOnPath(path, function(relativePath, pa rentSyncPoint) { 8305 var covered = this.syncPointTree_.findOnPath(path, function(relativePath, pa rentSyncPoint) {
8127 return parentSyncPoint.hasCompleteView(); 8306 return parentSyncPoint.hasCompleteView();
8128 }); 8307 });
8129 if (removingDefault && !covered) { 8308 if (removingDefault && !covered) {
8130 var subtree = this.syncPointTree_.subtree(path); 8309 var subtree = this.syncPointTree_.subtree(path);
8131 if (!subtree.isEmpty()) { 8310 if (!subtree.isEmpty()) {
8132 var newViews = this.collectDistinctViewsForSubTree_(subtree); 8311 var newViews = this.collectDistinctViewsForSubTree_(subtree);
8133 for (var i = 0;i < newViews.length;++i) { 8312 for (var i = 0;i < newViews.length;++i) {
8134 var view = newViews[i], newQuery = view.getQuery(); 8313 var view = newViews[i], newQuery = view.getQuery();
8135 var listener = this.createListenerForView_(view); 8314 var listener = this.createListenerForView_(view);
8136 this.listenProvider_.startListening(newQuery, this.tagForQuery_(newQue ry), listener.hashFn, listener.onComplete); 8315 this.listenProvider_.startListening(this.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);
8137 } 8316 }
8138 } else { 8317 } else {
8139 } 8318 }
8140 } 8319 }
8141 if (!covered && removed.length > 0 && !cancelError) { 8320 if (!covered && removed.length > 0 && !cancelError) {
8142 if (removingDefault) { 8321 if (removingDefault) {
8143 var defaultTag = null; 8322 var defaultTag = null;
8144 this.listenProvider_.stopListening(query, defaultTag); 8323 this.listenProvider_.stopListening(this.queryForListening_(query), defau ltTag);
8145 } else { 8324 } else {
8146 var self = this; 8325 var self = this;
8147 goog.array.forEach(removed, function(queryToRemove) { 8326 goog.array.forEach(removed, function(queryToRemove) {
8148 var queryIdToRemove = queryToRemove.queryIdentifier(); 8327 var queryIdToRemove = queryToRemove.queryIdentifier();
8149 var tagToRemove = self.queryToTagMap_[self.makeQueryKey_(queryToRemove )]; 8328 var tagToRemove = self.queryToTagMap_[self.makeQueryKey_(queryToRemove )];
8150 self.listenProvider_.stopListening(queryToRemove, tagToRemove); 8329 self.listenProvider_.stopListening(self.queryForListening_(queryToRemo ve), tagToRemove);
8151 }); 8330 });
8152 } 8331 }
8153 } 8332 }
8154 this.removeTags_(removed); 8333 this.removeTags_(removed);
8155 } else { 8334 } else {
8156 } 8335 }
8157 return cancelEvents; 8336 return cancelEvents;
8158 }; 8337 };
8159 fb.core.SyncTree.prototype.calcCompleteEventCache = function(path, writeIdsToExc lude) { 8338 fb.core.SyncTree.prototype.calcCompleteEventCache = function(path, writeIdsToExc lude) {
8160 var includeHiddenSets = true; 8339 var includeHiddenSets = true;
(...skipping 28 matching lines...) Expand all
8189 for (var j = 0;j < queries.length;++j) { 8368 for (var j = 0;j < queries.length;++j) {
8190 var removedQuery = queries[j]; 8369 var removedQuery = queries[j];
8191 if (!removedQuery.getQueryParams().loadsAllData()) { 8370 if (!removedQuery.getQueryParams().loadsAllData()) {
8192 var removedQueryKey = this.makeQueryKey_(removedQuery); 8371 var removedQueryKey = this.makeQueryKey_(removedQuery);
8193 var removedQueryTag = this.queryToTagMap_[removedQueryKey]; 8372 var removedQueryTag = this.queryToTagMap_[removedQueryKey];
8194 delete this.queryToTagMap_[removedQueryKey]; 8373 delete this.queryToTagMap_[removedQueryKey];
8195 delete this.tagToQueryMap_["_" + removedQueryTag]; 8374 delete this.tagToQueryMap_["_" + removedQueryTag];
8196 } 8375 }
8197 } 8376 }
8198 }; 8377 };
8378 fb.core.SyncTree.prototype.queryForListening_ = function(query) {
8379 if (query.getQueryParams().loadsAllData() && !query.getQueryParams().isDefault ()) {
8380 return(query.ref());
8381 } else {
8382 return query;
8383 }
8384 };
8199 fb.core.SyncTree.prototype.setupListener_ = function(query, view) { 8385 fb.core.SyncTree.prototype.setupListener_ = function(query, view) {
8200 var path = query.path; 8386 var path = query.path;
8201 var tag = this.tagForQuery_(query); 8387 var tag = this.tagForQuery_(query);
8202 var listener = this.createListenerForView_(view); 8388 var listener = this.createListenerForView_(view);
8203 var events = this.listenProvider_.startListening(query, tag, listener.hashFn, listener.onComplete); 8389 var events = this.listenProvider_.startListening(this.queryForListening_(query ), tag, listener.hashFn, listener.onComplete);
8204 var subtree = this.syncPointTree_.subtree(path); 8390 var subtree = this.syncPointTree_.subtree(path);
8205 if (tag) { 8391 if (tag) {
8206 fb.core.util.assert(!subtree.value.hasCompleteView(), "If we're adding a que ry, it shouldn't be shadowed"); 8392 fb.core.util.assert(!subtree.value.hasCompleteView(), "If we're adding a que ry, it shouldn't be shadowed");
8207 } else { 8393 } else {
8208 var queriesToStop = subtree.fold(function(relativePath, maybeChildSyncPoint, childMap) { 8394 var queriesToStop = subtree.fold(function(relativePath, maybeChildSyncPoint, childMap) {
8209 if (!relativePath.isEmpty() && maybeChildSyncPoint && maybeChildSyncPoint. hasCompleteView()) { 8395 if (!relativePath.isEmpty() && maybeChildSyncPoint && maybeChildSyncPoint. hasCompleteView()) {
8210 return[maybeChildSyncPoint.getCompleteView().getQuery()]; 8396 return[maybeChildSyncPoint.getCompleteView().getQuery()];
8211 } else { 8397 } else {
8212 var queries = []; 8398 var queries = [];
8213 if (maybeChildSyncPoint) { 8399 if (maybeChildSyncPoint) {
8214 queries = queries.concat(goog.array.map(maybeChildSyncPoint.getQueryVi ews(), function(view) { 8400 queries = queries.concat(goog.array.map(maybeChildSyncPoint.getQueryVi ews(), function(view) {
8215 return view.getQuery(); 8401 return view.getQuery();
8216 })); 8402 }));
8217 } 8403 }
8218 goog.object.forEach(childMap, function(childQueries) { 8404 goog.object.forEach(childMap, function(childQueries) {
8219 queries = queries.concat(childQueries); 8405 queries = queries.concat(childQueries);
8220 }); 8406 });
8221 return queries; 8407 return queries;
8222 } 8408 }
8223 }); 8409 });
8224 for (var i = 0;i < queriesToStop.length;++i) { 8410 for (var i = 0;i < queriesToStop.length;++i) {
8225 var queryToStop = queriesToStop[i]; 8411 var queryToStop = queriesToStop[i];
8226 this.listenProvider_.stopListening(queryToStop, this.tagForQuery_(queryToS top)); 8412 this.listenProvider_.stopListening(this.queryForListening_(queryToStop), t his.tagForQuery_(queryToStop));
8227 } 8413 }
8228 } 8414 }
8229 return events; 8415 return events;
8230 }; 8416 };
8231 fb.core.SyncTree.prototype.createListenerForView_ = function(view) { 8417 fb.core.SyncTree.prototype.createListenerForView_ = function(view) {
8232 var self = this; 8418 var self = this;
8233 var query = view.getQuery(); 8419 var query = view.getQuery();
8234 var tag = this.tagForQuery_(query); 8420 var tag = this.tagForQuery_(query);
8235 return{hashFn:function() { 8421 return{hashFn:function() {
8236 var cache = view.getServerCache() || fb.core.snap.EMPTY_NODE; 8422 var cache = view.getServerCache() || fb.core.snap.EMPTY_NODE;
(...skipping 170 matching lines...) Expand 10 before | Expand all | Expand 10 after
8407 this.node_.childCount--; 8593 this.node_.childCount--;
8408 this.updateParents_(); 8594 this.updateParents_();
8409 } else { 8595 } else {
8410 if (!childEmpty && !childExists) { 8596 if (!childEmpty && !childExists) {
8411 this.node_.children[childName] = child.node_; 8597 this.node_.children[childName] = child.node_;
8412 this.node_.childCount++; 8598 this.node_.childCount++;
8413 this.updateParents_(); 8599 this.updateParents_();
8414 } 8600 }
8415 } 8601 }
8416 }}); 8602 }});
8417 goog.provide("fb.core.util.EventEmitter");
8418 goog.require("fb.core.util");
8419 goog.require("goog.array");
8420 fb.core.util.EventEmitter = goog.defineClass(null, {constructor:function(allowed Events) {
8421 fb.core.util.assert(goog.isArray(allowedEvents) && allowedEvents.length > 0, " Requires a non-empty array");
8422 this.allowedEvents_ = allowedEvents;
8423 this.listeners_ = {};
8424 }, getInitialEvent:goog.abstractMethod, trigger:function(eventType, var_args) {
8425 var listeners = this.listeners_[eventType] || [];
8426 for (var i = 0;i < listeners.length;i++) {
8427 listeners[i].callback.apply(listeners[i].context, Array.prototype.slice.call (arguments, 1));
8428 }
8429 }, on:function(eventType, callback, context) {
8430 this.validateEventType_(eventType);
8431 this.listeners_[eventType] = this.listeners_[eventType] || [];
8432 this.listeners_[eventType].push({callback:callback, context:context});
8433 var eventData = this.getInitialEvent(eventType);
8434 if (eventData) {
8435 callback.apply(context, eventData);
8436 }
8437 }, off:function(eventType, callback, context) {
8438 this.validateEventType_(eventType);
8439 var listeners = this.listeners_[eventType] || [];
8440 for (var i = 0;i < listeners.length;i++) {
8441 if (listeners[i].callback === callback && (!context || context === listeners [i].context)) {
8442 listeners.splice(i, 1);
8443 return;
8444 }
8445 }
8446 }, validateEventType_:function(eventType) {
8447 fb.core.util.assert(goog.array.find(this.allowedEvents_, function(et) {
8448 return et === eventType;
8449 }), "Unknown event: " + eventType);
8450 }});
8451 goog.provide("fb.core.util.nextPushId");
8452 goog.require("fb.core.util");
8453 fb.core.util.nextPushId = function() {
8454 var PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuv wxyz";
8455 var lastPushTime = 0;
8456 var lastRandChars = [];
8457 return function(now) {
8458 var duplicateTime = now === lastPushTime;
8459 lastPushTime = now;
8460 var timeStampChars = new Array(8);
8461 for (var i = 7;i >= 0;i--) {
8462 timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
8463 now = Math.floor(now / 64);
8464 }
8465 fb.core.util.assert(now === 0, "Cannot push at time == 0");
8466 var id = timeStampChars.join("");
8467 if (!duplicateTime) {
8468 for (i = 0;i < 12;i++) {
8469 lastRandChars[i] = Math.floor(Math.random() * 64);
8470 }
8471 } else {
8472 for (i = 11;i >= 0 && lastRandChars[i] === 63;i--) {
8473 lastRandChars[i] = 0;
8474 }
8475 lastRandChars[i]++;
8476 }
8477 for (i = 0;i < 12;i++) {
8478 id += PUSH_CHARS.charAt(lastRandChars[i]);
8479 }
8480 fb.core.util.assert(id.length === 20, "nextPushId: Length should be 20.");
8481 return id;
8482 };
8483 }();
8484 goog.provide("fb.core.util.OnlineMonitor");
8485 goog.require("fb.core.util");
8486 goog.require("fb.core.util.EventEmitter");
8487 fb.core.util.OnlineMonitor = goog.defineClass(fb.core.util.EventEmitter, {constr uctor:function() {
8488 fb.core.util.EventEmitter.call(this, ["online"]);
8489 this.online_ = true;
8490 if (typeof window !== "undefined" && typeof window.addEventListener !== "undef ined") {
8491 var self = this;
8492 window.addEventListener("online", function() {
8493 if (!self.online_) {
8494 self.online_ = true;
8495 self.trigger("online", true);
8496 }
8497 }, false);
8498 window.addEventListener("offline", function() {
8499 if (self.online_) {
8500 self.online_ = false;
8501 self.trigger("online", false);
8502 }
8503 }, false);
8504 }
8505 }, getInitialEvent:function(eventType) {
8506 fb.core.util.assert(eventType === "online", "Unknown event type: " + eventType );
8507 return[this.online_];
8508 }, currentlyOnline:function() {
8509 return this.online_;
8510 }});
8511 goog.addSingletonGetter(fb.core.util.OnlineMonitor);
8512 goog.provide("fb.core.util.VisibilityMonitor");
8513 goog.require("fb.core.util");
8514 goog.require("fb.core.util.EventEmitter");
8515 fb.core.util.VisibilityMonitor = goog.defineClass(fb.core.util.EventEmitter, {co nstructor:function() {
8516 fb.core.util.EventEmitter.call(this, ["visible"]);
8517 var hidden, visibilityChange;
8518 if (typeof document !== "undefined" && typeof document.addEventListener !== "u ndefined") {
8519 if (typeof document["hidden"] !== "undefined") {
8520 visibilityChange = "visibilitychange";
8521 hidden = "hidden";
8522 } else {
8523 if (typeof document["mozHidden"] !== "undefined") {
8524 visibilityChange = "mozvisibilitychange";
8525 hidden = "mozHidden";
8526 } else {
8527 if (typeof document["msHidden"] !== "undefined") {
8528 visibilityChange = "msvisibilitychange";
8529 hidden = "msHidden";
8530 } else {
8531 if (typeof document["webkitHidden"] !== "undefined") {
8532 visibilityChange = "webkitvisibilitychange";
8533 hidden = "webkitHidden";
8534 }
8535 }
8536 }
8537 }
8538 }
8539 this.visible_ = true;
8540 if (visibilityChange) {
8541 var self = this;
8542 document.addEventListener(visibilityChange, function() {
8543 var visible = !document[hidden];
8544 if (visible !== self.visible_) {
8545 self.visible_ = visible;
8546 self.trigger("visible", visible);
8547 }
8548 }, false);
8549 }
8550 }, getInitialEvent:function(eventType) {
8551 fb.core.util.assert(eventType === "visible", "Unknown event type: " + eventTyp e);
8552 return[this.visible_];
8553 }});
8554 goog.addSingletonGetter(fb.core.util.VisibilityMonitor);
8555 goog.provide("fb.core.util.validation"); 8603 goog.provide("fb.core.util.validation");
8556 goog.require("fb.core.util"); 8604 goog.require("fb.core.util");
8557 goog.require("fb.core.util.Path"); 8605 goog.require("fb.core.util.Path");
8558 goog.require("fb.core.util.ValidationPath"); 8606 goog.require("fb.core.util.ValidationPath");
8559 goog.require("fb.util.obj"); 8607 goog.require("fb.util.obj");
8560 goog.require("fb.util.utf8"); 8608 goog.require("fb.util.utf8");
8561 goog.require("fb.util.validation"); 8609 goog.require("fb.util.validation");
8562 fb.core.util.validation = {INVALID_KEY_REGEX_:/[\[\].#$\/\u0000-\u001F\u007F]/, INVALID_PATH_REGEX_:/[\[\].#$\u0000-\u001F\u007F]/, VALID_AUTH_PROVIDER:/^[a-zA- Z][a-zA-Z._\-+]+$/, MAX_LEAF_SIZE_:10 * 1024 * 1024, isValidKey:function(key) { 8610 fb.core.util.validation = {INVALID_KEY_REGEX_:/[\[\].#$\/\u0000-\u001F\u007F]/, INVALID_PATH_REGEX_:/[\[\].#$\u0000-\u001F\u007F]/, VALID_AUTH_PROVIDER:/^[a-zA- Z][a-zA-Z._\-+]+$/, MAX_LEAF_SIZE_:10 * 1024 * 1024, isValidKey:function(key) {
8563 return goog.isString(key) && key.length !== 0 && !fb.core.util.validation.INVA LID_KEY_REGEX_.test(key); 8611 return goog.isString(key) && key.length !== 0 && !fb.core.util.validation.INVA LID_KEY_REGEX_.test(key);
8564 }, isValidPathString:function(pathString) { 8612 }, isValidPathString:function(pathString) {
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
8605 } 8653 }
8606 } 8654 }
8607 path.push(key); 8655 path.push(key);
8608 fb.core.util.validation.validateFirebaseData(errorPrefix, value, path); 8656 fb.core.util.validation.validateFirebaseData(errorPrefix, value, path);
8609 path.pop(); 8657 path.pop();
8610 }); 8658 });
8611 if (hasDotValue && hasActualChild) { 8659 if (hasDotValue && hasActualChild) {
8612 throw new Error(errorPrefix + ' contains ".value" child ' + path.toErrorSt ring() + " in addition to actual children."); 8660 throw new Error(errorPrefix + ' contains ".value" child ' + path.toErrorSt ring() + " in addition to actual children.");
8613 } 8661 }
8614 } 8662 }
8663 }, validateFirebaseMergePaths:function(errorPrefix, mergePaths) {
8664 var i, curPath;
8665 for (i = 0;i < mergePaths.length;i++) {
8666 curPath = mergePaths[i];
8667 var keys = curPath.slice();
8668 for (var j = 0;j < keys.length;j++) {
8669 if (keys[j] === ".priority" && j === keys.length - 1) {
8670 } else {
8671 if (!fb.core.util.validation.isValidKey(keys[j])) {
8672 throw new Error(errorPrefix + "contains an invalid key (" + keys[j] + ") in path " + curPath.toString() + ". Keys must be non-empty strings " + 'and c an\'t contain ".", "#", "$", "/", "[", or "]"');
8673 }
8674 }
8675 }
8676 }
8677 mergePaths.sort(fb.core.util.Path.comparePaths);
8678 var prevPath = null;
8679 for (i = 0;i < mergePaths.length;i++) {
8680 curPath = mergePaths[i];
8681 if (prevPath !== null && prevPath.contains(curPath)) {
8682 throw new Error(errorPrefix + "contains a path " + prevPath.toString() + " that is ancestor of another path " + curPath.toString());
8683 }
8684 prevPath = curPath;
8685 }
8615 }, validateFirebaseMergeDataArg:function(fnName, argumentNumber, data, path, opt ional) { 8686 }, validateFirebaseMergeDataArg:function(fnName, argumentNumber, data, path, opt ional) {
8616 if (optional && !goog.isDef(data)) { 8687 if (optional && !goog.isDef(data)) {
8617 return; 8688 return;
8618 } 8689 }
8690 var errorPrefix = fb.util.validation.errorPrefix(fnName, argumentNumber, optio nal);
8619 if (!goog.isObject(data) || goog.isArray(data)) { 8691 if (!goog.isObject(data) || goog.isArray(data)) {
8620 throw new Error(fb.util.validation.errorPrefix(fnName, argumentNumber, optio nal) + " must be an Object containing " + "the children to replace."); 8692 throw new Error(errorPrefix + " must be an object containing the children to replace.");
8621 } 8693 }
8622 if (fb.util.obj.contains(data, ".value")) { 8694 var mergePaths = [];
8623 throw new Error(fb.util.validation.errorPrefix(fnName, argumentNumber, optio nal) + ' must not contain ".value". ' + "To overwrite with a leaf value, just u se .set() instead."); 8695 fb.util.obj.foreach(data, function(key, value) {
8624 } 8696 var curPath = new fb.core.util.Path(key);
8625 fb.core.util.validation.validateFirebaseDataArg(fnName, argumentNumber, data, path, optional); 8697 fb.core.util.validation.validateFirebaseData(errorPrefix, value, path.child( curPath));
8698 if (curPath.getBack() === ".priority") {
8699 if (!fb.core.util.validation.isValidPriority(value)) {
8700 throw new Error(errorPrefix + "contains an invalid value for '" + curPat h.toString() + "', which must be a valid " + "Firebase priority (a string, finit e number, server value, or null).");
8701 }
8702 }
8703 mergePaths.push(curPath);
8704 });
8705 fb.core.util.validation.validateFirebaseMergePaths(errorPrefix, mergePaths);
8626 }, validatePriority:function(fnName, argumentNumber, priority, optional) { 8706 }, validatePriority:function(fnName, argumentNumber, priority, optional) {
8627 if (optional && !goog.isDef(priority)) { 8707 if (optional && !goog.isDef(priority)) {
8628 return; 8708 return;
8629 } 8709 }
8630 if (fb.core.util.isInvalidJSONNumber(priority)) { 8710 if (fb.core.util.isInvalidJSONNumber(priority)) {
8631 throw new Error(fb.util.validation.errorPrefix(fnName, argumentNumber, optio nal) + "is " + priority.toString() + ", but must be a valid Firebase priority (a string, finite number, " + "server value, or null)."); 8711 throw new Error(fb.util.validation.errorPrefix(fnName, argumentNumber, optio nal) + "is " + priority.toString() + ", but must be a valid Firebase priority (a string, finite number, " + "server value, or null).");
8632 } 8712 }
8633 if (!fb.core.util.validation.isValidPriority(priority)) { 8713 if (!fb.core.util.validation.isValidPriority(priority)) {
8634 throw new Error(fb.util.validation.errorPrefix(fnName, argumentNumber, optio nal) + "must be a valid Firebase priority " + "(a string, finite number, server value, or null)."); 8714 throw new Error(fb.util.validation.errorPrefix(fnName, argumentNumber, optio nal) + "must be a valid Firebase priority " + "(a string, finite number, server value, or null).");
8635 } 8715 }
(...skipping 1304 matching lines...) Expand 10 before | Expand all | Expand 10 after
9940 }; 10020 };
9941 fb.realtime.Transport.prototype.start = function() { 10021 fb.realtime.Transport.prototype.start = function() {
9942 }; 10022 };
9943 fb.realtime.Transport.prototype.close = function() { 10023 fb.realtime.Transport.prototype.close = function() {
9944 }; 10024 };
9945 fb.realtime.Transport.prototype.send = function(data) { 10025 fb.realtime.Transport.prototype.send = function(data) {
9946 }; 10026 };
9947 fb.realtime.Transport.prototype.bytesReceived; 10027 fb.realtime.Transport.prototype.bytesReceived;
9948 fb.realtime.Transport.prototype.bytesSent; 10028 fb.realtime.Transport.prototype.bytesSent;
9949 goog.provide("fb.realtime.Constants"); 10029 goog.provide("fb.realtime.Constants");
9950 fb.realtime.Constants = {PROTOCOL_VERSION:"5", VERSION_PARAM:"v", SESSION_PARAM: "s", REFERER_PARAM:"r", FORGE_REF:"f", FORGE_DOMAIN:"firebaseio.com"}; 10030 fb.realtime.Constants = {PROTOCOL_VERSION:"5", VERSION_PARAM:"v", TRANSPORT_SESS ION_PARAM:"s", REFERER_PARAM:"r", FORGE_REF:"f", FORGE_DOMAIN:"firebaseio.com", LAST_SESSION_PARAM:"ls", WEBSOCKET:"websocket", LONG_POLLING:"long_polling"};
9951 goog.provide("fb.realtime.polling.PacketReceiver"); 10031 goog.provide("fb.realtime.polling.PacketReceiver");
9952 fb.realtime.polling.PacketReceiver = function(onMessage) { 10032 fb.realtime.polling.PacketReceiver = function(onMessage) {
9953 this.onMessage_ = onMessage; 10033 this.onMessage_ = onMessage;
9954 this.pendingResponses = []; 10034 this.pendingResponses = [];
9955 this.currentResponseNum = 0; 10035 this.currentResponseNum = 0;
9956 this.closeAfterResponse = -1; 10036 this.closeAfterResponse = -1;
9957 this.onClose = null; 10037 this.onClose = null;
9958 }; 10038 };
9959 fb.realtime.polling.PacketReceiver.prototype.closeAfter = function(responseNum, callback) { 10039 fb.realtime.polling.PacketReceiver.prototype.closeAfter = function(responseNum, callback) {
9960 this.closeAfterResponse = responseNum; 10040 this.closeAfterResponse = responseNum;
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
10008 var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = "seg"; 10088 var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = "seg";
10009 var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = "ts"; 10089 var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = "ts";
10010 var FIREBASE_LONGPOLL_DATA_PARAM = "d"; 10090 var FIREBASE_LONGPOLL_DATA_PARAM = "d";
10011 var FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = "disconn"; 10091 var FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = "disconn";
10012 var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = "dframe"; 10092 var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = "dframe";
10013 var MAX_URL_DATA_SIZE = 1870; 10093 var MAX_URL_DATA_SIZE = 1870;
10014 var SEG_HEADER_SIZE = 30; 10094 var SEG_HEADER_SIZE = 30;
10015 var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE; 10095 var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
10016 var KEEPALIVE_REQUEST_INTERVAL = 25E3; 10096 var KEEPALIVE_REQUEST_INTERVAL = 25E3;
10017 var LP_CONNECT_TIMEOUT = 3E4; 10097 var LP_CONNECT_TIMEOUT = 3E4;
10018 fb.realtime.BrowserPollConnection = function(connId, repoInfo, sessionId) { 10098 fb.realtime.BrowserPollConnection = function(connId, repoInfo, opt_transportSess ionId, opt_lastSessionId) {
10019 this.connId = connId; 10099 this.connId = connId;
10020 this.log_ = fb.core.util.logWrapper(connId); 10100 this.log_ = fb.core.util.logWrapper(connId);
10021 this.repoInfo = repoInfo; 10101 this.repoInfo = repoInfo;
10022 this.bytesSent = 0; 10102 this.bytesSent = 0;
10023 this.bytesReceived = 0; 10103 this.bytesReceived = 0;
10024 this.stats_ = fb.core.stats.StatsManager.getCollection(repoInfo); 10104 this.stats_ = fb.core.stats.StatsManager.getCollection(repoInfo);
10025 this.sessionId = sessionId; 10105 this.transportSessionId = opt_transportSessionId;
10026 this.everConnected_ = false; 10106 this.everConnected_ = false;
10107 this.lastSessionId = opt_lastSessionId;
10027 this.urlFn = function(params) { 10108 this.urlFn = function(params) {
10028 if (repoInfo.needsQueryParam()) { 10109 return repoInfo.connectionURL(fb.realtime.Constants.LONG_POLLING, params);
10029 params["ns"] = repoInfo.namespace;
10030 }
10031 var pairs = [];
10032 for (var k in params) {
10033 if (params.hasOwnProperty(k)) {
10034 pairs.push(k + "=" + params[k]);
10035 }
10036 }
10037 return(repoInfo.secure ? "https://" : "http://") + repoInfo.internalHost + " /.lp?" + pairs.join("&");
10038 }; 10110 };
10039 }; 10111 };
10040 fb.realtime.BrowserPollConnection.prototype.open = function(onMessage, onDisconn ect) { 10112 fb.realtime.BrowserPollConnection.prototype.open = function(onMessage, onDisconn ect) {
10041 this.curSegmentNum = 0; 10113 this.curSegmentNum = 0;
10042 this.onDisconnect_ = onDisconnect; 10114 this.onDisconnect_ = onDisconnect;
10043 this.myPacketOrderer = new fb.realtime.polling.PacketReceiver(onMessage); 10115 this.myPacketOrderer = new fb.realtime.polling.PacketReceiver(onMessage);
10044 this.isClosed_ = false; 10116 this.isClosed_ = false;
10045 var self = this; 10117 var self = this;
10046 this.connectTimeoutTimer_ = setTimeout(function() { 10118 this.connectTimeoutTimer_ = setTimeout(function() {
10047 self.log_("Timed out trying to connect."); 10119 self.log_("Timed out trying to connect.");
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
10085 }, function() { 10157 }, function() {
10086 self.onClosed_(); 10158 self.onClosed_();
10087 }, self.urlFn); 10159 }, self.urlFn);
10088 var urlParams = {}; 10160 var urlParams = {};
10089 urlParams[FIREBASE_LONGPOLL_START_PARAM] = "t"; 10161 urlParams[FIREBASE_LONGPOLL_START_PARAM] = "t";
10090 urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 1E8); 10162 urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 1E8);
10091 if (self.scriptTagHolder.uniqueCallbackIdentifier) { 10163 if (self.scriptTagHolder.uniqueCallbackIdentifier) {
10092 urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = self.scriptTagHolder.uniq ueCallbackIdentifier; 10164 urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = self.scriptTagHolder.uniq ueCallbackIdentifier;
10093 } 10165 }
10094 urlParams[fb.realtime.Constants.VERSION_PARAM] = fb.realtime.Constants.PROTO COL_VERSION; 10166 urlParams[fb.realtime.Constants.VERSION_PARAM] = fb.realtime.Constants.PROTO COL_VERSION;
10095 if (self.sessionId) { 10167 if (self.transportSessionId) {
10096 urlParams[fb.realtime.Constants.SESSION_PARAM] = self.sessionId; 10168 urlParams[fb.realtime.Constants.TRANSPORT_SESSION_PARAM] = self.transportS essionId;
10169 }
10170 if (self.lastSessionId) {
10171 urlParams[fb.realtime.Constants.LAST_SESSION_PARAM] = self.lastSessionId;
10097 } 10172 }
10098 if (!NODE_CLIENT && typeof location !== "undefined" && location.href && loca tion.href.indexOf(fb.realtime.Constants.FORGE_DOMAIN) !== -1) { 10173 if (!NODE_CLIENT && typeof location !== "undefined" && location.href && loca tion.href.indexOf(fb.realtime.Constants.FORGE_DOMAIN) !== -1) {
10099 urlParams[fb.realtime.Constants.REFERER_PARAM] = fb.realtime.Constants.FOR GE_REF; 10174 urlParams[fb.realtime.Constants.REFERER_PARAM] = fb.realtime.Constants.FOR GE_REF;
10100 } 10175 }
10101 var connectURL = self.urlFn(urlParams); 10176 var connectURL = self.urlFn(urlParams);
10102 self.log_("Connecting via long-poll to " + connectURL); 10177 self.log_("Connecting via long-poll to " + connectURL);
10103 self.scriptTagHolder.addTag(connectURL, function() { 10178 self.scriptTagHolder.addTag(connectURL, function() {
10104 }); 10179 });
10105 }); 10180 });
10106 }; 10181 };
(...skipping 294 matching lines...) Expand 10 before | Expand all | Expand 10 after
10401 fb.WebSocket = require("faye-websocket")["Client"]; 10476 fb.WebSocket = require("faye-websocket")["Client"];
10402 } else { 10477 } else {
10403 if (typeof MozWebSocket !== "undefined") { 10478 if (typeof MozWebSocket !== "undefined") {
10404 fb.WebSocket = MozWebSocket; 10479 fb.WebSocket = MozWebSocket;
10405 } else { 10480 } else {
10406 if (typeof WebSocket !== "undefined") { 10481 if (typeof WebSocket !== "undefined") {
10407 fb.WebSocket = WebSocket; 10482 fb.WebSocket = WebSocket;
10408 } 10483 }
10409 } 10484 }
10410 } 10485 }
10411 fb.realtime.WebSocketConnection = function(connId, repoInfo, sessionId) { 10486 fb.realtime.WebSocketConnection = function(connId, repoInfo, opt_transportSessio nId, opt_lastSessionId) {
10412 this.connId = connId; 10487 this.connId = connId;
10413 this.log_ = fb.core.util.logWrapper(this.connId); 10488 this.log_ = fb.core.util.logWrapper(this.connId);
10414 this.keepaliveTimer = null; 10489 this.keepaliveTimer = null;
10415 this.frames = null; 10490 this.frames = null;
10416 this.totalFrames = 0; 10491 this.totalFrames = 0;
10417 this.bytesSent = 0; 10492 this.bytesSent = 0;
10418 this.bytesReceived = 0; 10493 this.bytesReceived = 0;
10419 this.stats_ = fb.core.stats.StatsManager.getCollection(repoInfo); 10494 this.stats_ = fb.core.stats.StatsManager.getCollection(repoInfo);
10420 this.connURL = (repoInfo.secure ? "wss://" : "ws://") + repoInfo.internalHost + "/.ws?" + fb.realtime.Constants.VERSION_PARAM + "=" + fb.realtime.Constants.PR OTOCOL_VERSION; 10495 this.connURL = this.connectionURL_(repoInfo, opt_transportSessionId, opt_lastS essionId);
10496 };
10497 fb.realtime.WebSocketConnection.prototype.connectionURL_ = function(repoInfo, op t_transportSessionId, opt_lastSessionId) {
10498 var urlParams = {};
10499 urlParams[fb.realtime.Constants.VERSION_PARAM] = fb.realtime.Constants.PROTOCO L_VERSION;
10421 if (!NODE_CLIENT && typeof location !== "undefined" && location.href && locati on.href.indexOf(fb.realtime.Constants.FORGE_DOMAIN) !== -1) { 10500 if (!NODE_CLIENT && typeof location !== "undefined" && location.href && locati on.href.indexOf(fb.realtime.Constants.FORGE_DOMAIN) !== -1) {
10422 this.connURL = this.connURL + "&" + fb.realtime.Constants.REFERER_PARAM + "= " + fb.realtime.Constants.FORGE_REF; 10501 urlParams[fb.realtime.Constants.REFERER_PARAM] = fb.realtime.Constants.FORGE _REF;
10423 } 10502 }
10424 if (repoInfo.needsQueryParam()) { 10503 if (opt_transportSessionId) {
10425 this.connURL = this.connURL + "&ns=" + repoInfo.namespace; 10504 urlParams[fb.realtime.Constants.TRANSPORT_SESSION_PARAM] = opt_transportSess ionId;
10426 } 10505 }
10427 if (sessionId) { 10506 if (opt_lastSessionId) {
10428 this.connURL = this.connURL + "&" + fb.realtime.Constants.SESSION_PARAM + "= " + sessionId; 10507 urlParams[fb.realtime.Constants.LAST_SESSION_PARAM] = opt_lastSessionId;
10429 } 10508 }
10509 return repoInfo.connectionURL(fb.realtime.Constants.WEBSOCKET, urlParams);
10430 }; 10510 };
10431 fb.realtime.WebSocketConnection.prototype.open = function(onMess, onDisconn) { 10511 fb.realtime.WebSocketConnection.prototype.open = function(onMess, onDisconn) {
10432 this.onDisconnect = onDisconn; 10512 this.onDisconnect = onDisconn;
10433 this.onMessage = onMess; 10513 this.onMessage = onMess;
10434 this.log_("Websocket connecting to " + this.connURL); 10514 this.log_("Websocket connecting to " + this.connURL);
10435 this.everConnected_ = false; 10515 this.everConnected_ = false;
10436 fb.core.storage.PersistentStorage.set("previous_websocket_failure", true); 10516 fb.core.storage.PersistentStorage.set("previous_websocket_failure", true);
10437 try { 10517 try {
10438 if (NODE_CLIENT) { 10518 if (NODE_CLIENT) {
10439 var options = {"headers":{"User-Agent":"Firebase/" + fb.realtime.Constants .PROTOCOL_VERSION + "/" + CLIENT_VERSION + "/" + process.platform + "/Node"}}; 10519 var options = {"headers":{"User-Agent":"Firebase/" + fb.realtime.Constants .PROTOCOL_VERSION + "/" + CLIENT_VERSION + "/" + process.platform + "/Node"}};
(...skipping 208 matching lines...) Expand 10 before | Expand all | Expand 10 after
10648 var MESSAGE_TYPE = "t"; 10728 var MESSAGE_TYPE = "t";
10649 var MESSAGE_DATA = "d"; 10729 var MESSAGE_DATA = "d";
10650 var CONTROL_SHUTDOWN = "s"; 10730 var CONTROL_SHUTDOWN = "s";
10651 var CONTROL_RESET = "r"; 10731 var CONTROL_RESET = "r";
10652 var CONTROL_ERROR = "e"; 10732 var CONTROL_ERROR = "e";
10653 var CONTROL_PONG = "o"; 10733 var CONTROL_PONG = "o";
10654 var SWITCH_ACK = "a"; 10734 var SWITCH_ACK = "a";
10655 var END_TRANSMISSION = "n"; 10735 var END_TRANSMISSION = "n";
10656 var PING = "p"; 10736 var PING = "p";
10657 var SERVER_HELLO = "h"; 10737 var SERVER_HELLO = "h";
10658 fb.realtime.Connection = function(connId, repoInfo, onMessage, onReady, onDiscon nect, onKill) { 10738 fb.realtime.Connection = function(connId, repoInfo, onMessage, onReady, onDiscon nect, onKill, lastSessionId) {
10659 this.id = connId; 10739 this.id = connId;
10660 this.log_ = fb.core.util.logWrapper("c:" + this.id + ":"); 10740 this.log_ = fb.core.util.logWrapper("c:" + this.id + ":");
10661 this.onMessage_ = onMessage; 10741 this.onMessage_ = onMessage;
10662 this.onReady_ = onReady; 10742 this.onReady_ = onReady;
10663 this.onDisconnect_ = onDisconnect; 10743 this.onDisconnect_ = onDisconnect;
10664 this.onKill_ = onKill; 10744 this.onKill_ = onKill;
10665 this.repoInfo_ = repoInfo; 10745 this.repoInfo_ = repoInfo;
10666 this.pendingDataMessages = []; 10746 this.pendingDataMessages = [];
10667 this.connectionCount = 0; 10747 this.connectionCount = 0;
10668 this.transportManager_ = new fb.realtime.TransportManager(repoInfo); 10748 this.transportManager_ = new fb.realtime.TransportManager(repoInfo);
10669 this.state_ = REALTIME_STATE_CONNECTING; 10749 this.state_ = REALTIME_STATE_CONNECTING;
10750 this.lastSessionId = lastSessionId;
10670 this.log_("Connection created"); 10751 this.log_("Connection created");
10671 this.start_(); 10752 this.start_();
10672 }; 10753 };
10673 fb.realtime.Connection.prototype.start_ = function() { 10754 fb.realtime.Connection.prototype.start_ = function() {
10674 var conn = this.transportManager_.initialTransport(); 10755 var conn = this.transportManager_.initialTransport();
10675 this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_); 10756 this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this .lastSessionId);
10676 this.primaryResponsesRequired_ = conn["responsesRequiredToBeHealthy"] || 0; 10757 this.primaryResponsesRequired_ = conn["responsesRequiredToBeHealthy"] || 0;
10677 var onMessageReceived = this.connReceiver_(this.conn_); 10758 var onMessageReceived = this.connReceiver_(this.conn_);
10678 var onConnectionLost = this.disconnReceiver_(this.conn_); 10759 var onConnectionLost = this.disconnReceiver_(this.conn_);
10679 this.tx_ = this.conn_; 10760 this.tx_ = this.conn_;
10680 this.rx_ = this.conn_; 10761 this.rx_ = this.conn_;
10681 this.secondaryConn_ = null; 10762 this.secondaryConn_ = null;
10682 this.isHealthy_ = false; 10763 this.isHealthy_ = false;
10683 var self = this; 10764 var self = this;
10684 setTimeout(function() { 10765 setTimeout(function() {
10685 self.conn_ && self.conn_.open(onMessageReceived, onConnectionLost); 10766 self.conn_ && self.conn_.open(onMessageReceived, onConnectionLost);
(...skipping 226 matching lines...) Expand 10 before | Expand all | Expand 10 after
10912 } else { 10993 } else {
10913 this.closeConnections_(); 10994 this.closeConnections_();
10914 this.start_(); 10995 this.start_();
10915 } 10996 }
10916 }; 10997 };
10917 fb.realtime.Connection.prototype.onConnectionEstablished_ = function(conn, times tamp) { 10998 fb.realtime.Connection.prototype.onConnectionEstablished_ = function(conn, times tamp) {
10918 this.log_("Realtime connection established."); 10999 this.log_("Realtime connection established.");
10919 this.conn_ = conn; 11000 this.conn_ = conn;
10920 this.state_ = REALTIME_STATE_CONNECTED; 11001 this.state_ = REALTIME_STATE_CONNECTED;
10921 if (this.onReady_) { 11002 if (this.onReady_) {
10922 this.onReady_(timestamp); 11003 this.onReady_(timestamp, this.sessionId);
10923 this.onReady_ = null; 11004 this.onReady_ = null;
10924 } 11005 }
10925 var self = this; 11006 var self = this;
10926 if (this.primaryResponsesRequired_ === 0) { 11007 if (this.primaryResponsesRequired_ === 0) {
10927 this.log_("Primary connection is healthy."); 11008 this.log_("Primary connection is healthy.");
10928 this.isHealthy_ = true; 11009 this.isHealthy_ = true;
10929 } else { 11010 } else {
10930 setTimeout(function() { 11011 setTimeout(function() {
10931 self.sendPingOnPrimaryIfNecessary_(); 11012 self.sendPingOnPrimaryIfNecessary_();
10932 }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS)); 11013 }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
(...skipping 93 matching lines...) Expand 10 before | Expand all | Expand 10 after
11026 this.outstandingPutCount_ = 0; 11107 this.outstandingPutCount_ = 0;
11027 this.onDisconnectRequestQueue_ = []; 11108 this.onDisconnectRequestQueue_ = [];
11028 this.connected_ = false; 11109 this.connected_ = false;
11029 this.reconnectDelay_ = RECONNECT_MIN_DELAY; 11110 this.reconnectDelay_ = RECONNECT_MIN_DELAY;
11030 this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT; 11111 this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
11031 this.onDataUpdate_ = onDataUpdate; 11112 this.onDataUpdate_ = onDataUpdate;
11032 this.onConnectStatus_ = onConnectStatus; 11113 this.onConnectStatus_ = onConnectStatus;
11033 this.onServerInfoUpdate_ = onServerInfoUpdate; 11114 this.onServerInfoUpdate_ = onServerInfoUpdate;
11034 this.repoInfo_ = repoInfo; 11115 this.repoInfo_ = repoInfo;
11035 this.securityDebugCallback_ = null; 11116 this.securityDebugCallback_ = null;
11117 this.lastSessionId = null;
11036 this.realtime_ = null; 11118 this.realtime_ = null;
11037 this.credential_ = null; 11119 this.credential_ = null;
11038 this.establishConnectionTimer_ = null; 11120 this.establishConnectionTimer_ = null;
11039 this.visible_ = false; 11121 this.visible_ = false;
11040 this.requestCBHash_ = {}; 11122 this.requestCBHash_ = {};
11041 this.requestNumber_ = 0; 11123 this.requestNumber_ = 0;
11042 this.firstConnection_ = true; 11124 this.firstConnection_ = true;
11043 this.lastConnectionAttemptTime_ = null; 11125 this.lastConnectionAttemptTime_ = null;
11044 this.lastConnectionEstablishedTime_ = null; 11126 this.lastConnectionEstablishedTime_ = null;
11045 this.scheduleConnect_(0); 11127 this.scheduleConnect_(0);
11046 fb.core.util.VisibilityMonitor.getInstance().on("visible", this.onVisible_, th is); 11128 fb.core.util.VisibilityMonitor.getInstance().on("visible", this.onVisible_, th is);
11047 if (repoInfo.host.indexOf("fblocal") === -1) { 11129 if (repoInfo.host.indexOf("fblocal") === -1) {
11048 fb.core.util.OnlineMonitor.getInstance().on("online", this.onOnline_, this); 11130 fb.core.util.OnlineMonitor.getInstance().on("online", this.onOnline_, this);
11049 } 11131 }
11050 }, statics:{nextPersistentConnectionId_:0, nextConnectionId_:0}, sendRequest:fun ction(action, body, onResponse) { 11132 }, statics:{nextPersistentConnectionId_:0, nextConnectionId_:0}, sendRequest:fun ction(action, body, onResponse) {
11051 var curReqNum = ++this.requestNumber_; 11133 var curReqNum = ++this.requestNumber_;
11052 var msg = {"r":curReqNum, "a":action, "b":body}; 11134 var msg = {"r":curReqNum, "a":action, "b":body};
11053 this.log_(fb.util.json.stringify(msg)); 11135 this.log_(fb.util.json.stringify(msg));
11054 fb.core.util.assert(this.connected_, "sendRequest call when we're not connecte d not allowed."); 11136 fb.core.util.assert(this.connected_, "sendRequest call when we're not connecte d not allowed.");
11055 this.realtime_.sendRequest(msg); 11137 this.realtime_.sendRequest(msg);
11056 if (onResponse) { 11138 if (onResponse) {
11057 this.requestCBHash_[curReqNum] = onResponse; 11139 this.requestCBHash_[curReqNum] = onResponse;
11058 } 11140 }
11059 }, listen:function(query, currentHashFn, tag, onComplete) { 11141 }, listen:function(query, currentHashFn, tag, onComplete) {
11060 var queryId = query.queryIdentifier(); 11142 var queryId = query.queryIdentifier();
11061 var pathString = query.path.toString(); 11143 var pathString = query.path.toString();
11062 this.log_("Listen called for " + pathString + " " + queryId); 11144 this.log_("Listen called for " + pathString + " " + queryId);
11063 this.listens_[pathString] = this.listens_[pathString] || {}; 11145 this.listens_[pathString] = this.listens_[pathString] || {};
11146 fb.core.util.assert(query.getQueryParams().isDefault() || !query.getQueryParam s().loadsAllData(), "listen() called for non-default but complete query");
11064 fb.core.util.assert(!this.listens_[pathString][queryId], "listen() called twic e for same path/queryId."); 11147 fb.core.util.assert(!this.listens_[pathString][queryId], "listen() called twic e for same path/queryId.");
11065 var listenSpec = {onComplete:onComplete, hashFn:currentHashFn, query:query, ta g:tag}; 11148 var listenSpec = {onComplete:onComplete, hashFn:currentHashFn, query:query, ta g:tag};
11066 this.listens_[pathString][queryId] = listenSpec; 11149 this.listens_[pathString][queryId] = listenSpec;
11067 if (this.connected_) { 11150 if (this.connected_) {
11068 this.sendListen_(listenSpec); 11151 this.sendListen_(listenSpec);
11069 } 11152 }
11070 }, sendListen_:function(listenSpec) { 11153 }, sendListen_:function(listenSpec) {
11071 var query = listenSpec.query; 11154 var query = listenSpec.query;
11072 var pathString = query.path.toString(); 11155 var pathString = query.path.toString();
11073 var queryId = query.queryIdentifier(); 11156 var queryId = query.queryIdentifier();
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after
11144 if (status !== "ok" && authdata.cancelCallback) { 11227 if (status !== "ok" && authdata.cancelCallback) {
11145 authdata.cancelCallback(status, data); 11228 authdata.cancelCallback(status, data);
11146 } 11229 }
11147 } 11230 }
11148 }); 11231 });
11149 } 11232 }
11150 }, unlisten:function(query, tag) { 11233 }, unlisten:function(query, tag) {
11151 var pathString = query.path.toString(); 11234 var pathString = query.path.toString();
11152 var queryId = query.queryIdentifier(); 11235 var queryId = query.queryIdentifier();
11153 this.log_("Unlisten called for " + pathString + " " + queryId); 11236 this.log_("Unlisten called for " + pathString + " " + queryId);
11237 fb.core.util.assert(query.getQueryParams().isDefault() || !query.getQueryParam s().loadsAllData(), "unlisten() called for non-default but complete query");
11154 var listen = this.removeListen_(pathString, queryId); 11238 var listen = this.removeListen_(pathString, queryId);
11155 if (listen && this.connected_) { 11239 if (listen && this.connected_) {
11156 this.sendUnlisten_(pathString, queryId, query.queryObject(), tag); 11240 this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);
11157 } 11241 }
11158 }, sendUnlisten_:function(pathString, queryId, queryObj, tag) { 11242 }, sendUnlisten_:function(pathString, queryId, queryObj, tag) {
11159 this.log_("Unlisten on " + pathString + " for " + queryId); 11243 this.log_("Unlisten on " + pathString + " for " + queryId);
11160 var self = this; 11244 var self = this;
11161 var req = {"p":pathString}; 11245 var req = {"p":pathString};
11162 var action = "n"; 11246 var action = "n";
11163 if (tag) { 11247 if (tag) {
(...skipping 110 matching lines...) Expand 10 before | Expand all | Expand 10 after
11274 } else { 11358 } else {
11275 if (action === "sd") { 11359 if (action === "sd") {
11276 this.onSecurityDebugPacket_(body); 11360 this.onSecurityDebugPacket_(body);
11277 } else { 11361 } else {
11278 fb.core.util.error("Unrecognized action received from server: " + fb .util.json.stringify(action) + "\nAre you using the latest client?"); 11362 fb.core.util.error("Unrecognized action received from server: " + fb .util.json.stringify(action) + "\nAre you using the latest client?");
11279 } 11363 }
11280 } 11364 }
11281 } 11365 }
11282 } 11366 }
11283 } 11367 }
11284 }, onReady_:function(timestamp) { 11368 }, onReady_:function(timestamp, sessionId) {
11285 this.log_("connection ready"); 11369 this.log_("connection ready");
11286 this.connected_ = true; 11370 this.connected_ = true;
11287 this.lastConnectionEstablishedTime_ = (new Date).getTime(); 11371 this.lastConnectionEstablishedTime_ = (new Date).getTime();
11288 this.handleTimestamp_(timestamp); 11372 this.handleTimestamp_(timestamp);
11373 this.lastSessionId = sessionId;
11289 if (this.firstConnection_) { 11374 if (this.firstConnection_) {
11290 this.sendConnectStats_(); 11375 this.sendConnectStats_();
11291 } 11376 }
11292 this.restoreState_(); 11377 this.restoreState_();
11293 this.firstConnection_ = false; 11378 this.firstConnection_ = false;
11294 this.onConnectStatus_(true); 11379 this.onConnectStatus_(true);
11295 }, scheduleConnect_:function(timeout) { 11380 }, scheduleConnect_:function(timeout) {
11296 fb.core.util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?"); 11381 fb.core.util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
11297 if (this.establishConnectionTimer_) { 11382 if (this.establishConnectionTimer_) {
11298 clearTimeout(this.establishConnectionTimer_); 11383 clearTimeout(this.establishConnectionTimer_);
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
11355 }, establishConnection_:function() { 11440 }, establishConnection_:function() {
11356 if (this.shouldReconnect_()) { 11441 if (this.shouldReconnect_()) {
11357 this.log_("Making a connection attempt"); 11442 this.log_("Making a connection attempt");
11358 this.lastConnectionAttemptTime_ = (new Date).getTime(); 11443 this.lastConnectionAttemptTime_ = (new Date).getTime();
11359 this.lastConnectionEstablishedTime_ = null; 11444 this.lastConnectionEstablishedTime_ = null;
11360 var onDataMessage = goog.bind(this.onDataMessage_, this); 11445 var onDataMessage = goog.bind(this.onDataMessage_, this);
11361 var onReady = goog.bind(this.onReady_, this); 11446 var onReady = goog.bind(this.onReady_, this);
11362 var onDisconnect = goog.bind(this.onRealtimeDisconnect_, this); 11447 var onDisconnect = goog.bind(this.onRealtimeDisconnect_, this);
11363 var connId = this.id + ":" + fb.core.PersistentConnection.nextConnectionId_+ +; 11448 var connId = this.id + ":" + fb.core.PersistentConnection.nextConnectionId_+ +;
11364 var self = this; 11449 var self = this;
11450 var lastSessionId = this.lastSessionId;
11365 this.realtime_ = new fb.realtime.Connection(connId, this.repoInfo_, onDataMe ssage, onReady, onDisconnect, function(reason) { 11451 this.realtime_ = new fb.realtime.Connection(connId, this.repoInfo_, onDataMe ssage, onReady, onDisconnect, function(reason) {
11366 fb.core.util.warn(reason + " (" + self.repoInfo_.toString() + ")"); 11452 fb.core.util.warn(reason + " (" + self.repoInfo_.toString() + ")");
11367 self.killed_ = true; 11453 self.killed_ = true;
11368 }); 11454 }, lastSessionId);
11369 } 11455 }
11370 }, interrupt:function() { 11456 }, interrupt:function() {
11371 this.interrupted_ = true; 11457 this.interrupted_ = true;
11372 if (this.realtime_) { 11458 if (this.realtime_) {
11373 this.realtime_.close(); 11459 this.realtime_.close();
11374 } else { 11460 } else {
11375 if (this.establishConnectionTimer_) { 11461 if (this.establishConnectionTimer_) {
11376 clearTimeout(this.establishConnectionTimer_); 11462 clearTimeout(this.establishConnectionTimer_);
11377 this.establishConnectionTimer_ = null; 11463 this.establishConnectionTimer_ = null;
11378 } 11464 }
(...skipping 995 matching lines...) Expand 10 before | Expand all | Expand 10 after
12374 throw new Error(wrongArgTypeError); 12460 throw new Error(wrongArgTypeError);
12375 } 12461 }
12376 } 12462 }
12377 } 12463 }
12378 } else { 12464 } else {
12379 if (params.getIndex() === fb.core.snap.PriorityIndex) { 12465 if (params.getIndex() === fb.core.snap.PriorityIndex) {
12380 if (startNode != null && !fb.core.util.validation.isValidPriority(startNod e) || endNode != null && !fb.core.util.validation.isValidPriority(endNode)) { 12466 if (startNode != null && !fb.core.util.validation.isValidPriority(startNod e) || endNode != null && !fb.core.util.validation.isValidPriority(endNode)) {
12381 throw new Error("Query: When ordering by priority, the first argument pa ssed to startAt(), " + "endAt(), or equalTo() must be a valid priority value (nu ll, a number, or a string)."); 12467 throw new Error("Query: When ordering by priority, the first argument pa ssed to startAt(), " + "endAt(), or equalTo() must be a valid priority value (nu ll, a number, or a string).");
12382 } 12468 }
12383 } else { 12469 } else {
12384 fb.core.util.assert(params.getIndex() instanceof fb.core.snap.SubKeyIndex || params.getIndex() === fb.core.snap.ValueIndex, "unknown index type."); 12470 fb.core.util.assert(params.getIndex() instanceof fb.core.snap.PathIndex || params.getIndex() === fb.core.snap.ValueIndex, "unknown index type.");
12385 if (startNode != null && typeof startNode === "object" || endNode != null && typeof endNode === "object") { 12471 if (startNode != null && typeof startNode === "object" || endNode != null && typeof endNode === "object") {
12386 throw new Error("Query: First argument passed to startAt(), endAt(), or equalTo() cannot be " + "an object."); 12472 throw new Error("Query: First argument passed to startAt(), endAt(), or equalTo() cannot be " + "an object.");
12387 } 12473 }
12388 } 12474 }
12389 } 12475 }
12390 }, validateLimit_:function(params) { 12476 }, validateLimit_:function(params) {
12391 if (params.hasStart() && params.hasEnd() && params.hasLimit() && !params.hasAn choredLimit()) { 12477 if (params.hasStart() && params.hasEnd() && params.hasLimit() && !params.hasAn choredLimit()) {
12392 throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use l imitToFirst() or limitToLast() instead."); 12478 throw new Error("Query: Can't combine startAt(), endAt(), and limit(). Use l imitToFirst() or limitToLast() instead.");
12393 } 12479 }
12394 }, validateNoPreviousOrderByCall_:function(fnName) { 12480 }, validateNoPreviousOrderByCall_:function(fnName) {
(...skipping 86 matching lines...) Expand 10 before | Expand all | Expand 10 after
12481 return new fb.api.Query(this.repo, this.path, this.queryParams_.limitToFirst(l imit), this.orderByCalled_); 12567 return new fb.api.Query(this.repo, this.path, this.queryParams_.limitToFirst(l imit), this.orderByCalled_);
12482 }, limitToLast:function(limit) { 12568 }, limitToLast:function(limit) {
12483 fb.util.validation.validateArgCount("Query.limitToLast", 1, 1, arguments.lengt h); 12569 fb.util.validation.validateArgCount("Query.limitToLast", 1, 1, arguments.lengt h);
12484 if (!goog.isNumber(limit) || Math.floor(limit) !== limit || limit <= 0) { 12570 if (!goog.isNumber(limit) || Math.floor(limit) !== limit || limit <= 0) {
12485 throw new Error("Query.limitToLast: First argument must be a positive intege r."); 12571 throw new Error("Query.limitToLast: First argument must be a positive intege r.");
12486 } 12572 }
12487 if (this.queryParams_.hasLimit()) { 12573 if (this.queryParams_.hasLimit()) {
12488 throw new Error("Query.limitToLast: Limit was already set (by another call t o limit, " + "limitToFirst, or limitToLast)."); 12574 throw new Error("Query.limitToLast: Limit was already set (by another call t o limit, " + "limitToFirst, or limitToLast).");
12489 } 12575 }
12490 return new fb.api.Query(this.repo, this.path, this.queryParams_.limitToLast(li mit), this.orderByCalled_); 12576 return new fb.api.Query(this.repo, this.path, this.queryParams_.limitToLast(li mit), this.orderByCalled_);
12491 }, orderByChild:function(key) { 12577 }, orderByChild:function(path) {
12492 fb.util.validation.validateArgCount("Query.orderByChild", 1, 1, arguments.leng th); 12578 fb.util.validation.validateArgCount("Query.orderByChild", 1, 1, arguments.leng th);
12493 if (key === "$key") { 12579 if (path === "$key") {
12494 throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKe y() instead.'); 12580 throw new Error('Query.orderByChild: "$key" is invalid. Use Query.orderByKe y() instead.');
12495 } else { 12581 } else {
12496 if (key === "$priority") { 12582 if (path === "$priority") {
12497 throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.or derByPriority() instead.'); 12583 throw new Error('Query.orderByChild: "$priority" is invalid. Use Query.or derByPriority() instead.');
12498 } else { 12584 } else {
12499 if (key === "$value") { 12585 if (path === "$value") {
12500 throw new Error('Query.orderByChild: "$value" is invalid. Use Query.ord erByValue() instead.'); 12586 throw new Error('Query.orderByChild: "$value" is invalid. Use Query.ord erByValue() instead.');
12501 } 12587 }
12502 } 12588 }
12503 } 12589 }
12504 fb.core.util.validation.validateKey("Query.orderByChild", 1, key, false); 12590 fb.core.util.validation.validatePathString("Query.orderByChild", 1, path, fals e);
12505 this.validateNoPreviousOrderByCall_("Query.orderByChild"); 12591 this.validateNoPreviousOrderByCall_("Query.orderByChild");
12506 var index = new fb.core.snap.SubKeyIndex(key); 12592 var parsedPath = new fb.core.util.Path(path);
12593 if (parsedPath.isEmpty()) {
12594 throw new Error("Query.orderByChild: cannot pass in empty path. Use Query.o rderByValue() instead.");
12595 }
12596 var index = new fb.core.snap.PathIndex(parsedPath);
12507 var newParams = this.queryParams_.orderBy(index); 12597 var newParams = this.queryParams_.orderBy(index);
12508 this.validateQueryEndpoints_(newParams); 12598 this.validateQueryEndpoints_(newParams);
12509 return new fb.api.Query(this.repo, this.path, newParams, true); 12599 return new fb.api.Query(this.repo, this.path, newParams, true);
12510 }, orderByKey:function() { 12600 }, orderByKey:function() {
12511 fb.util.validation.validateArgCount("Query.orderByKey", 0, 0, arguments.length ); 12601 fb.util.validation.validateArgCount("Query.orderByKey", 0, 0, arguments.length );
12512 this.validateNoPreviousOrderByCall_("Query.orderByKey"); 12602 this.validateNoPreviousOrderByCall_("Query.orderByKey");
12513 var newParams = this.queryParams_.orderBy(fb.core.snap.KeyIndex); 12603 var newParams = this.queryParams_.orderBy(fb.core.snap.KeyIndex);
12514 this.validateQueryEndpoints_(newParams); 12604 this.validateQueryEndpoints_(newParams);
12515 return new fb.api.Query(this.repo, this.path, newParams, true); 12605 return new fb.api.Query(this.repo, this.path, newParams, true);
12516 }, orderByPriority:function() { 12606 }, orderByPriority:function() {
(...skipping 418 matching lines...) Expand 10 before | Expand all | Expand 10 after
12935 this.repo.auth.resetPassword(params, onComplete); 13025 this.repo.auth.resetPassword(params, onComplete);
12936 }}); 13026 }});
12937 if (NODE_CLIENT) { 13027 if (NODE_CLIENT) {
12938 module["exports"] = Firebase; 13028 module["exports"] = Firebase;
12939 } 13029 }
12940 ; 13030 ;
12941 } 13031 }
12942 ns.wrapper(ns.goog, ns.fb); 13032 ns.wrapper(ns.goog, ns.fb);
12943 }({goog:{}, fb:{}})); 13033 }({goog:{}, fb:{}}));
12944 13034
OLDNEW
« no previous file with comments | « lib/src/firebase/firebase.js ('k') | lib/src/ga-api-utils/build/ga-api-utils.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698