Skip to content

Instantly share code, notes, and snippets.

@develar
Created April 18, 2013 16:11
Show Gist options
  • Save develar/5413991 to your computer and use it in GitHub Desktop.
Save develar/5413991 to your computer and use it in GitHub Desktop.
wef
This file has been truncated, but you can view the full file.
s.sslPass;\n }\n\n // Set up logger if any set\n this.logger = this.options.logger != null\n && (typeof this.options.logger.debug == 'function')\n && (typeof this.options.logger.error == 'function')\n && (typeof this.options.logger.log == 'function')\n ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};\n\n // Just keeps list of events we allow\n this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]};\n // Internal state of server connection\n this._serverState = 'disconnected';\n // this._timeout = false;\n // Contains state information about server connection\n this._state = {'runtimeStats': {'queryStats':new RunningStats()}};\n // Do we record server stats or not\n this.recordQueryStats = false;\n};\n\n/**\n * @ignore\n */\ninherits(Server, Base);\n\n//\n// Deprecated, USE ReadPreferences class\n//\nServer.READ_PRIMARY = ReadPreference.PRIMARY;\nServer.READ_SECONDARY = ReadPreference.SECONDARY_PREFERRED;\nServer.READ_SECONDARY_ONLY = ReadPreference.SECONDARY;\n\n/**\n * Always ourselves\n * @ignore\n */\nServer.prototype.setReadPreference = function() {}\n\n/**\n * @ignore\n */\nServer.prototype.isMongos = function() {\n return this.isMasterDoc != null && this.isMasterDoc['msg'] == \"isdbgrid\" ? true : false;\n}\n\n/**\n * @ignore\n */\nServer.prototype._isUsed = function() {\n return this._used;\n}\n\n/**\n * @ignore\n */\nServer.prototype.close = function(callback) {\n // Remove all local listeners\n this.removeAllListeners();\n\n if(this.connectionPool != null) {\n // Remove all the listeners on the pool so it does not fire messages all over the place\n this.connectionPool.removeAllEventListeners();\n // Close the connection if it's open\n this.connectionPool.stop(true);\n }\n\n // Set server status as disconnected\n this._serverState = 'disconnected';\n // Peform callback if present\n if(typeof callback === 'function') callback(null);\n};\n\n/**\n * @ignore\n */\nServer.prototype.isConnected = function() {\n return this._serverState == 'connected';\n}\n\n/**\n * @ignore\n */\nServer.prototype.allServerInstances = function() {\n return [this];\n}\n\n/**\n * @ignore\n */\nServer.prototype.isSetMember = function() {\n return this.replicasetInstance != null || this.mongosInstance != null;\n}\n\n/**\n * Assigns a replica set to this `server`.\n *\n * @param {ReplSet} replset\n * @ignore\n */\nServer.prototype.assignReplicaSet = function (replset) {\n this.replicasetInstance = replset;\n this.inheritReplSetOptionsFrom(replset);\n this.enableRecordQueryStats(replset.recordQueryStats);\n}\n\n/**\n * Takes needed options from `replset` and overwrites\n * our own options.\n *\n * @param {ReplSet} replset\n * @ignore\n */\nServer.prototype.inheritReplSetOptionsFrom = function (replset) {\n this.socketOptions = {};\n this.socketOptions.connectTimeoutMS = replset._connectTimeoutMS;\n\n if(replset.ssl) {\n // Set ssl on\n this.socketOptions.ssl = true;\n // Set ssl validation\n this.socketOptions.sslValidate = replset.sslValidate == null ? false : replset.sslValidate;\n // Set the ssl certificate authority (array of Buffer/String keys)\n this.socketOptions.sslCA = Array.isArray(replset.sslCA) ? replset.sslCA : null;\n // Set certificate to present\n this.socketOptions.sslCert = replset.sslCert;\n // Set certificate to present\n this.socketOptions.sslKey = replset.sslKey;\n // Password to unlock private key\n this.socketOptions.sslPass = replset.sslPass;\n }\n\n // If a socket option object exists clone it\n if(utils.isObject(replset.socketOptions)) {\n var keys = Object.keys(replset.socketOptions);\n for(var i = 0; i < keys.length; i++)\n this.socketOptions[keys[i]] = replset.socketOptions[keys[i]];\n }\n}\n\n/**\n * Opens this server connection.\n *\n * @ignore\n */\nServer.prototype.connect = function(dbInstance, options, callback) {\n if('function' === typeof options) callback = options, options = {};\n if(options == null) options = {};\n if(!('function' === typeof callback)) callback = null;\n\n // Currently needed to work around problems with multiple connections in a pool with ssl\n // TODO fix if possible\n if(this.ssl == true) {\n // Set up socket options for ssl\n this.socketOptions.ssl = true;\n // Set ssl validation\n this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate;\n // Set the ssl certificate authority (array of Buffer/String keys)\n this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null;\n // Set certificate to present\n this.socketOptions.sslCert = this.sslCert;\n // Set certificate to present\n this.socketOptions.sslKey = this.sslKey;\n // Password to unlock private key\n this.socketOptions.sslPass = this.sslPass;\n }\n\n // Let's connect\n var server = this;\n // Let's us override the main receiver of events\n var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this;\n // Save reference to dbInstance\n this.db = dbInstance; // `db` property matches ReplSet and Mongos\n this.dbInstances = [dbInstance];\n\n // Force connection pool if there is one\n if(server.connectionPool) server.connectionPool.stop();\n\n // Set server state to connecting\n this._serverState = 'connecting';\n // Ensure dbInstance can do a slave query if it's set\n dbInstance.slaveOk = this.slaveOk ? this.slaveOk : dbInstance.slaveOk;\n // Create connection Pool instance with the current BSON serializer\n var connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions);\n // If ssl is not enabled don't wait between the pool connections\n if(this.ssl == null || !this.ssl) connectionPool._timeToWait = null;\n // Set logger on pool\n connectionPool.logger = this.logger;\n\n // Set up a new pool using default settings\n server.connectionPool = connectionPool;\n\n // Set basic parameters passed in\n var returnIsMasterResults = options.returnIsMasterResults == null ? false : options.returnIsMasterResults;\n\n // Create a default connect handler, overriden when using replicasets\n var connectCallback = function(err, reply) {\n // ensure no callbacks get called twice\n var internalCallback = callback;\n callback = null;\n // If something close down the connection and removed the callback before\n // proxy killed connection etc, ignore the erorr as close event was isssued\n if(err != null && internalCallback == null) return;\n // Internal callback\n if(err != null) return internalCallback(err, null, server);\n server.master = reply.documents[0].ismaster == 1 ? true : false;\n server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize);\n server.connectionPool.setMaxMessageSizeBytes(reply.documents[0].maxMessageSizeBytes);\n // Set server as connected\n server.connected = true;\n // Save document returned so we can query it\n server.isMasterDoc = reply.documents[0];\n\n // Emit open event\n _emitAcrossAllDbInstances(server, eventReceiver, \"open\", null, returnIsMasterResults ? reply : dbInstance, null);\n\n // If we have it set to returnIsMasterResults\n if(returnIsMasterResults) {\n internalCallback(null, reply, server);\n } else {\n internalCallback(null, dbInstance, server);\n }\n };\n\n // Let's us override the main connect callback\n var connectHandler = options.connectHandler == null ? connectCallback : options.connectHandler;\n\n // Set up on connect method\n connectionPool.on(\"poolReady\", function() {\n // Create db command and Add the callback to the list of callbacks by the request id (mapping outgoing messages to correct callbacks)\n var db_command = DbCommand.NcreateIsMasterCommand(dbInstance, dbInstance.databaseName);\n // Check out a reader from the pool\n var connection = connectionPool.checkoutConnection();\n // Set server state to connEcted\n server._serverState = 'connected';\n\n // Register handler for messages\n server._registerHandler(db_command, false, connection, connectHandler);\n\n // Write the command out\n connection.write(db_command);\n })\n\n // Set up item connection\n connectionPool.on(\"message\", function(message) {\n // Attempt to parse the message\n try {\n // Create a new mongo reply\n var mongoReply = new MongoReply()\n // Parse the header\n mongoReply.parseHeader(message, connectionPool.bson)\n\n // If message size is not the same as the buffer size\n // something went terribly wrong somewhere\n if(mongoReply.messageLength != message.length) {\n // Emit the error\n if(eventReceiver.listeners(\"error\") && eventReceiver.listeners(\"error\").length > 0) eventReceiver.emit(\"error\", new Error(\"bson length is different from message length\"), server);\n // Remove all listeners\n server.removeAllListeners();\n } else {\n var startDate = new Date().getTime();\n\n // Callback instance\n var callbackInfo = server._findHandler(mongoReply.responseTo.toString());\n\n // The command executed another request, log the handler again under that request id\n if(mongoReply.requestId > 0 && mongoReply.cursorId.toString() != \"0\" \n && callbackInfo && callbackInfo.info && callbackInfo.info.exhaust) {\n server._reRegisterHandler(mongoReply.requestId, callbackInfo);\n }\n\n // Only execute callback if we have a caller\n // chained is for findAndModify as it does not respect write concerns\n if(callbackInfo && callbackInfo.callback && callbackInfo.info && Array.isArray(callbackInfo.info.chained)) {\n // Check if callback has already been fired (missing chain command)\n var chained = callbackInfo.info.chained;\n var numberOfFoundCallbacks = 0;\n for(var i = 0; i < chained.length; i++) {\n if(server._hasHandler(chained[i])) numberOfFoundCallbacks++;\n }\n\n // If we have already fired then clean up rest of chain and move on\n if(numberOfFoundCallbacks != chained.length) {\n for(var i = 0; i < chained.length; i++) {\n server._removeHandler(chained[i]);\n }\n\n // Just return from function\n return;\n }\n\n // Parse the body\n mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) {\n if(err != null) {\n // If pool connection is already closed\n if(server._serverState === 'disconnected') return;\n // Set server state to disconnected\n server._serverState = 'disconnected';\n // Remove all listeners and close the connection pool\n server.removeAllListeners();\n connectionPool.stop(true);\n\n // If we have a callback return the error\n if(typeof callback === 'function') {\n // ensure no callbacks get called twice\n var internalCallback = callback;\n callback = null;\n // Perform callback\n internalCallback(new Error(\"connection closed due to parseError\"), null, server);\n } else if(server.isSetMember()) {\n if(server.listeners(\"parseError\") && server.listeners(\"parseError\").length > 0) server.emit(\"parseError\", new Error(\"connection closed due to parseError\"), server);\n } else {\n if(eventReceiver.listeners(\"parseError\") && eventReceiver.listeners(\"parseError\").length > 0) eventReceiver.emit(\"parseError\", new Error(\"connection closed due to parseError\"), server);\n }\n\n // If we are a single server connection fire errors correctly\n if(!server.isSetMember()) {\n // Fire all callback errors\n server.__executeAllCallbacksWithError(new Error(\"connection closed due to parseError\"));\n // Emit error\n _emitAcrossAllDbInstances(server, eventReceiver, \"parseError\", server, null, true);\n }\n // Short cut\n return;\n }\n\n // Fetch the callback\n var callbackInfo = server._findHandler(mongoReply.responseTo.toString());\n // If we have an error let's execute the callback and clean up all other\n // chained commands\n var firstResult = mongoReply && mongoReply.documents;\n\n // Check for an error, if we have one let's trigger the callback and clean up\n // The chained callbacks\n if(firstResult[0].err != null || firstResult[0].errmsg != null) {\n // Trigger the callback for the error\n server._callHandler(mongoReply.responseTo, mongoReply, null);\n } else {\n var chainedIds = callbackInfo.info.chained;\n\n if(chainedIds.length > 0 && chainedIds[chainedIds.length - 1] == mongoReply.responseTo) {\n // Cleanup all other chained calls\n chainedIds.pop();\n // Remove listeners\n for(var i = 0; i < chainedIds.length; i++) server._removeHandler(chainedIds[i]);\n // Call the handler\n server._callHandler(mongoReply.responseTo, callbackInfo.info.results.shift(), null);\n } else{\n // Add the results to all the results\n for(var i = 0; i < chainedIds.length; i++) {\n var handler = server._findHandler(chainedIds[i]);\n // Check if we have an object, if it's the case take the current object commands and\n // and add this one\n if(handler.info != null) {\n handler.info.results = Array.isArray(callbackInfo.info.results) ? callbackInfo.info.results : [];\n handler.info.results.push(mongoReply);\n }\n }\n }\n }\n });\n } else if(callbackInfo && callbackInfo.callback && callbackInfo.info) {\n // Parse the body\n mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) {\n if(err != null) {\n // If pool connection is already closed\n if(server._serverState === 'disconnected') return;\n // Set server state to disconnected\n server._serverState = 'disconnected';\n // Remove all listeners and close the connection pool\n server.removeAllListeners();\n connectionPool.stop(true);\n\n // If we have a callback return the error\n if(typeof callback === 'function') {\n // ensure no callbacks get called twice\n var internalCallback = callback;\n callback = null;\n // Perform callback\n internalCallback(new Error(\"connection closed due to parseError\"), null, server);\n } else if(server.isSetMember()) {\n if(server.listeners(\"parseError\") && server.listeners(\"parseError\").length > 0) server.emit(\"parseError\", new Error(\"connection closed due to parseError\"), server);\n } else {\n if(eventReceiver.listeners(\"parseError\") && eventReceiver.listeners(\"parseError\").length > 0) eventReceiver.emit(\"parseError\", new Error(\"connection closed due to parseError\"), server);\n }\n\n // If we are a single server connection fire errors correctly\n if(!server.isSetMember()) {\n // Fire all callback errors\n server.__executeAllCallbacksWithError(new Error(\"connection closed due to parseError\"));\n // Emit error\n _emitAcrossAllDbInstances(server, eventReceiver, \"parseError\", server, null, true);\n }\n // Short cut\n return;\n }\n\n // Let's record the stats info if it's enabled\n if(server.recordQueryStats == true && server._state['runtimeStats'] != null\n && server._state.runtimeStats['queryStats'] instanceof RunningStats) {\n // Add data point to the running statistics object\n server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start);\n }\n\n server._callHandler(mongoReply.responseTo, mongoReply, null);\n });\n }\n }\n } catch (err) {\n // Throw error in next tick\n processor(function() {\n throw err;\n })\n }\n });\n\n // Handle timeout\n connectionPool.on(\"timeout\", function(err) {\n // If pool connection is already closed\n if(server._serverState === 'disconnected') return;\n // Set server state to disconnected\n server._serverState = 'disconnected';\n // If we have a callback return the error\n if(typeof callback === 'function') {\n // ensure no callbacks get called twice\n var internalCallback = callback;\n callback = null;\n // Perform callback\n internalCallback(err, null, server);\n } else if(server.isSetMember()) {\n if(server.listeners(\"timeout\") && server.listeners(\"timeout\").length > 0) server.emit(\"timeout\", err, server);\n } else {\n if(eventReceiver.listeners(\"timeout\") && eventReceiver.listeners(\"timeout\").length > 0) eventReceiver.emit(\"timeout\", err, server);\n }\n\n // If we are a single server connection fire errors correctly\n if(!server.isSetMember()) {\n // Fire all callback errors\n server.__executeAllCallbacksWithError(err);\n // Emit error\n _emitAcrossAllDbInstances(server, eventReceiver, \"timeout\", err, server, true);\n }\n });\n\n // Handle errors\n connectionPool.on(\"error\", function(message, connection, error_options) {\n // If pool connection is already closed\n if(server._serverState === 'disconnected') return;\n // Set server state to disconnected\n server._serverState = 'disconnected';\n // Error message\n var error_message = new Error(message && message.err ? message.err : message);\n // Error message coming from ssl\n if(error_options && error_options.ssl) error_message.ssl = true;\n // If we have a callback return the error\n if(typeof callback === 'function') {\n // ensure no callbacks get called twice\n var internalCallback = callback;\n callback = null;\n // Perform callback\n internalCallback(error_message, null, server);\n } else if(server.isSetMember()) {\n if(server.listeners(\"error\") && server.listeners(\"error\").length > 0) server.emit(\"error\", error_message, server);\n } else {\n if(eventReceiver.listeners(\"error\") && eventReceiver.listeners(\"error\").length > 0) eventReceiver.emit(\"error\", error_message, server);\n }\n\n // If we are a single server connection fire errors correctly\n if(!server.isSetMember()) {\n // Fire all callback errors\n server.__executeAllCallbacksWithError(error_message);\n // Emit error\n _emitAcrossAllDbInstances(server, eventReceiver, \"error\", error_message, server, true);\n }\n });\n\n // Handle close events\n connectionPool.on(\"close\", function() {\n // If pool connection is already closed\n if(server._serverState === 'disconnected') return;\n // Set server state to disconnected\n server._serverState = 'disconnected';\n // If we have a callback return the error\n if(typeof callback == 'function') {\n // ensure no callbacks get called twice\n var internalCallback = callback;\n callback = null;\n // Perform callback\n internalCallback(new Error(\"connection closed\"), null, server);\n } else if(server.isSetMember()) {\n if(server.listeners(\"close\") && server.listeners(\"close\").length > 0) server.emit(\"close\", new Error(\"connection closed\"), server);\n } else {\n if(eventReceiver.listeners(\"close\") && eventReceiver.listeners(\"close\").length > 0) eventReceiver.emit(\"close\", new Error(\"connection closed\"), server);\n }\n\n // If we are a single server connection fire errors correctly\n if(!server.isSetMember()) {\n // Fire all callback errors\n server.__executeAllCallbacksWithError(new Error(\"connection closed\"));\n // Emit error\n _emitAcrossAllDbInstances(server, eventReceiver, \"close\", server, null, true);\n }\n });\n\n // If we have a parser error we are in an unknown state, close everything and emit\n // error\n connectionPool.on(\"parseError\", function(message) {\n // If pool connection is already closed\n if(server._serverState === 'disconnected') return;\n // Set server state to disconnected\n server._serverState = 'disconnected';\n // If we have a callback return the error\n if(typeof callback === 'function') {\n // ensure no callbacks get called twice\n var internalCallback = callback;\n callback = null;\n // Perform callback\n internalCallback(new Error(\"connection closed due to parseError\"), null, server);\n } else if(server.isSetMember()) {\n if(server.listeners(\"parseError\") && server.listeners(\"parseError\").length > 0) server.emit(\"parseError\", new Error(\"connection closed due to parseError\"), server);\n } else {\n if(eventReceiver.listeners(\"parseError\") && eventReceiver.listeners(\"parseError\").length > 0) eventReceiver.emit(\"parseError\", new Error(\"connection closed due to parseError\"), server);\n }\n\n // If we are a single server connection fire errors correctly\n if(!server.isSetMember()) {\n // Fire all callback errors\n server.__executeAllCallbacksWithError(new Error(\"connection closed due to parseError\"));\n // Emit error\n _emitAcrossAllDbInstances(server, eventReceiver, \"parseError\", server, null, true);\n }\n });\n\n // Boot up connection poole, pass in a locator of callbacks\n connectionPool.start();\n}\n\n/**\n * @ignore\n */\nvar _emitAcrossAllDbInstances = function(server, filterDb, event, message, object, resetConnection) {\n // Emit close event across all db instances sharing the sockets\n var allServerInstances = server.allServerInstances();\n // Fetch the first server instance\n var serverInstance = allServerInstances[0];\n // For all db instances signal all db instances\n if(Array.isArray(serverInstance.dbInstances) && serverInstance.dbInstances.length >= 1) {\n\t for(var i = 0; i < serverInstance.dbInstances.length; i++) {\n var dbInstance = serverInstance.dbInstances[i];\n // Set the parent\n if(resetConnection && typeof dbInstance.openCalled != 'undefined')\n dbInstance.openCalled = false;\n // Check if it's our current db instance and skip if it is\n if(filterDb == null || filterDb.databaseName !== dbInstance.databaseName || filterDb.tag !== dbInstance.tag) {\n // Only emit if there is a listener\n if(dbInstance.listeners(event).length > 0)\n \t dbInstance.emit(event, message, object);\n }\n }\n }\n}\n\n/**\n * @ignore\n */\nServer.prototype.allRawConnections = function() {\n return this.connectionPool.getAllConnections();\n}\n\n/**\n * Check if a writer can be provided\n * @ignore\n */\nvar canCheckoutWriter = function(self, read) {\n // We cannot write to an arbiter or secondary server\n if(self.isMasterDoc['arbiterOnly'] == true) {\n return new Error(\"Cannot write to an arbiter\");\n } if(self.isMasterDoc['secondary'] == true) {\n return new Error(\"Cannot write to a secondary\");\n } else if(read == true && self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc['ismaster'] == true) {\n return new Error(\"Cannot read from primary when secondary only specified\");\n }\n\n // Return no error\n return null;\n}\n\n/**\n * @ignore\n */\nServer.prototype.checkoutWriter = function(read) {\n if(read == true) return this.connectionPool.checkoutConnection();\n // Check if are allowed to do a checkout (if we try to use an arbiter f.ex)\n var result = canCheckoutWriter(this, read);\n // If the result is null check out a writer\n if(result == null && this.connectionPool != null) {\n return this.connectionPool.checkoutConnection();\n } else if(result == null) {\n return null;\n } else {\n return result;\n }\n}\n\n/**\n * Check if a reader can be provided\n * @ignore\n */\nvar canCheckoutReader = function(self) {\n // We cannot write to an arbiter or secondary server\n if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) {\n return new Error(\"Cannot write to an arbiter\");\n } else if(self._readPreference != null) {\n // If the read preference is Primary and the instance is not a master return an error\n if((self._readPreference == ReadPreference.PRIMARY) && self.isMasterDoc['ismaster'] != true) {\n return new Error(\"Read preference is Server.PRIMARY and server is not master\");\n } else if(self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc['ismaster'] == true) {\n return new Error(\"Cannot read from primary when secondary only specified\");\n }\n }\n\n // Return no error\n return null;\n}\n\n/**\n * @ignore\n */\nServer.prototype.checkoutReader = function() {\n // Check if are allowed to do a checkout (if we try to use an arbiter f.ex)\n var result = canCheckoutReader(this);\n // If the result is null check out a writer\n if(result == null && this.connectionPool != null) {\n return this.connectionPool.checkoutConnection();\n } else if(result == null) {\n return null;\n } else {\n return result;\n }\n}\n\n/**\n * @ignore\n */\nServer.prototype.enableRecordQueryStats = function(enable) {\n this.recordQueryStats = enable;\n}\n\n/**\n * Internal statistics object used for calculating average and standard devitation on\n * running queries\n * @ignore\n */\nvar RunningStats = function() {\n var self = this;\n this.m_n = 0;\n this.m_oldM = 0.0;\n this.m_oldS = 0.0;\n this.m_newM = 0.0;\n this.m_newS = 0.0;\n\n // Define getters\n Object.defineProperty(this, \"numDataValues\", { enumerable: true\n , get: function () { return this.m_n; }\n });\n\n Object.defineProperty(this, \"mean\", { enumerable: true\n , get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; }\n });\n\n Object.defineProperty(this, \"variance\", { enumerable: true\n , get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); }\n });\n\n Object.defineProperty(this, \"standardDeviation\", { enumerable: true\n , get: function () { return Math.sqrt(this.variance); }\n });\n\n Object.defineProperty(this, \"sScore\", { enumerable: true\n , get: function () {\n var bottom = this.mean + this.standardDeviation;\n if(bottom == 0) return 0;\n return ((2 * this.mean * this.standardDeviation)/(bottom));\n }\n });\n}\n\n/**\n * @ignore\n */\nRunningStats.prototype.push = function(x) {\n // Update the number of samples\n this.m_n = this.m_n + 1;\n // See Knuth TAOCP vol 2, 3rd edition, page 232\n if(this.m_n == 1) {\n this.m_oldM = this.m_newM = x;\n this.m_oldS = 0.0;\n } else {\n this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n;\n this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM);\n\n // set up for next iteration\n this.m_oldM = this.m_newM;\n this.m_oldS = this.m_newS;\n }\n}\n\n/**\n * @ignore\n */\nObject.defineProperty(Server.prototype, \"autoReconnect\", { enumerable: true\n , get: function () {\n return this.options['auto_reconnect'] == null ? false : this.options['auto_reconnect'];\n }\n});\n\n/**\n * @ignore\n */\nObject.defineProperty(Server.prototype, \"connection\", { enumerable: true\n , get: function () {\n return this.internalConnection;\n }\n , set: function(connection) {\n this.internalConnection = connection;\n }\n});\n\n/**\n * @ignore\n */\nObject.defineProperty(Server.prototype, \"master\", { enumerable: true\n , get: function () {\n return this.internalMaster;\n }\n , set: function(value) {\n this.internalMaster = value;\n }\n});\n\n/**\n * @ignore\n */\nObject.defineProperty(Server.prototype, \"primary\", { enumerable: true\n , get: function () {\n return this;\n }\n});\n\n/**\n * Getter for query Stats\n * @ignore\n */\nObject.defineProperty(Server.prototype, \"queryStats\", { enumerable: true\n , get: function () {\n return this._state.runtimeStats.queryStats;\n }\n});\n\n/**\n * @ignore\n */\nObject.defineProperty(Server.prototype, \"runtimeStats\", { enumerable: true\n , get: function () {\n return this._state.runtimeStats;\n }\n});\n\n/**\n * Get Read Preference method\n * @ignore\n */\nObject.defineProperty(Server.prototype, \"readPreference\", { enumerable: true\n , get: function () {\n if(this._readPreference == null && this.readSecondary) {\n return Server.READ_SECONDARY;\n } else if(this._readPreference == null && !this.readSecondary) {\n return Server.READ_PRIMARY;\n } else {\n return this._readPreference;\n }\n }\n});\n\n/**\n * @ignore\n */\nexports.Server = Server;\n\n});","sourceLength":35119,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js (lines: 907)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":516,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[283]}}
{"seq":178,"request_seq":516,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js","id":283,"lineOffset":0,"columnOffset":0,"lineCount":146,"source":"(function (exports, require, module, __filename, __dirname) { var Long = require('bson').Long\n , timers = require('timers');\n\n// Set processor, setImmediate if 0.10 otherwise nextTick\nvar processor = timers.setImmediate ? timers.setImmediate : process.nextTick;\nprocessor = process.nextTick\n\n/**\n Reply message from mongo db\n**/\nvar MongoReply = exports.MongoReply = function() {\n this.documents = [];\n this.index = 0;\n};\n\nMongoReply.prototype.parseHeader = function(binary_reply, bson) {\n // Unpack the standard header first\n this.messageLength = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n this.index = this.index + 4;\n // Fetch the request id for this reply\n this.requestId = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n this.index = this.index + 4;\n // Fetch the id of the request that triggered the response\n this.responseTo = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n // Skip op-code field\n this.index = this.index + 4 + 4;\n // Unpack the reply message\n this.responseFlag = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n this.index = this.index + 4;\n // Unpack the cursor id (a 64 bit long integer)\n var low_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n this.index = this.index + 4;\n var high_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n this.index = this.index + 4;\n this.cursorId = new Long(low_bits, high_bits);\n // Unpack the starting from\n this.startingFrom = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n this.index = this.index + 4;\n // Unpack the number of objects returned\n this.numberReturned = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n this.index = this.index + 4;\n}\n\nMongoReply.prototype.parseBody = function(binary_reply, bson, raw, callback) {\n raw = raw == null ? false : raw;\n // Just set a doc limit for deserializing\n var docLimitSize = 1024*20;\n\n // If our message length is very long, let's switch to process.nextTick for messages\n if(this.messageLength > docLimitSize) {\n var batchSize = this.numberReturned;\n this.documents = new Array(this.numberReturned);\n\n // Just walk down until we get a positive number >= 1\n for(var i = 50; i > 0; i--) {\n if((this.numberReturned/i) >= 1) {\n batchSize = i;\n break;\n }\n }\n\n // Actual main creator of the processFunction setting internal state to control the flow\n var parseFunction = function(_self, _binary_reply, _batchSize, _numberReturned) {\n var object_index = 0;\n // Internal loop process that will use nextTick to ensure we yield some time\n var processFunction = function() {\n // Adjust batchSize if we have less results left than batchsize\n if((_numberReturned - object_index) < _batchSize) {\n _batchSize = _numberReturned - object_index;\n }\n\n // If raw just process the entries\n if(raw) {\n // Iterate over the batch\n for(var i = 0; i < _batchSize; i++) {\n // Are we done ?\n if(object_index <= _numberReturned) {\n // Read the size of the bson object\n var bsonObjectSize = _binary_reply[_self.index] | _binary_reply[_self.index + 1] << 8 | _binary_reply[_self.index + 2] << 16 | _binary_reply[_self.index + 3] << 24;\n // If we are storing the raw responses to pipe straight through\n _self.documents[object_index] = binary_reply.slice(_self.index, _self.index + bsonObjectSize);\n // Adjust binary index to point to next block of binary bson data\n _self.index = _self.index + bsonObjectSize;\n // Update number of docs parsed\n object_index = object_index + 1;\n }\n }\n } else {\n try {\n // Parse documents\n _self.index = bson.deserializeStream(binary_reply, _self.index, _batchSize, _self.documents, object_index);\n // Adjust index\n object_index = object_index + _batchSize;\n } catch (err) {\n return callback(err);\n }\n }\n\n // If we hav more documents process NextTick\n if(object_index < _numberReturned) {\n processor(processFunction);\n } else {\n callback(null);\n }\n }\n\n // Return the process function\n return processFunction;\n }(this, binary_reply, batchSize, this.numberReturned)();\n } else {\n try {\n // Let's unpack all the bson documents, deserialize them and store them\n for(var object_index = 0; object_index < this.numberReturned; object_index++) {\n // Read the size of the bson object\n var bsonObjectSize = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;\n // If we are storing the raw responses to pipe straight through\n if(raw) {\n // Deserialize the object and add to the documents array\n this.documents.push(binary_reply.slice(this.index, this.index + bsonObjectSize));\n } else {\n // Deserialize the object and add to the documents array\n this.documents.push(bson.deserialize(binary_reply.slice(this.index, this.index + bsonObjectSize)));\n }\n // Adjust binary index to point to next block of binary bson data\n this.index = this.index + bsonObjectSize;\n }\n } catch(err) {\n return callback(err);\n }\n\n // No error return\n callback(null);\n }\n}\n\nMongoReply.prototype.is_error = function(){\n if(this.documents.length == 1) {\n return this.documents[0].ok == 1 ? false : true;\n }\n return false;\n};\n\nMongoReply.prototype.error_message = function() {\n return this.documents.length == 1 && this.documents[0].ok == 1 ? '' : this.documents[0].errmsg;\n};\n});","sourceLength":6460,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js (lines: 146)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":517,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[286]}}
{"seq":179,"request_seq":517,"type":"response","command":"scripts","success":true,"body":[{"handle":7,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js","id":286,"lineOffset":0,"columnOffset":0,"lineCount":295,"source":"(function (exports, require, module, __filename, __dirname) { var utils = require('./connection_utils'),\n inherits = require('util').inherits,\n net = require('net'),\n timers = require('timers'),\n EventEmitter = require('events').EventEmitter,\n inherits = require('util').inherits,\n MongoReply = require(\"../responses/mongo_reply\").MongoReply,\n Connection = require(\"./connection\").Connection;\n\n// Set processor, setImmediate if 0.10 otherwise nextTick\nvar processor = timers.setImmediate ? timers.setImmediate : process.nextTick;\nprocessor = process.nextTick\n\nvar ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) {\n if(typeof host !== 'string') {\n throw new Error(\"host must be specified [\" + host + \"]\");\n }\n\n // Set up event emitter\n EventEmitter.call(this);\n\n // Keep all options for the socket in a specific collection allowing the user to specify the\n // Wished upon socket connection parameters\n this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {};\n this.socketOptions.host = host;\n this.socketOptions.port = port;\n this.socketOptions.domainSocket = false;\n this.bson = bson;\n // PoolSize is always + 1 for special reserved \"measurment\" socket (like ping, stats etc)\n this.poolSize = poolSize;\n this.minPoolSize = Math.floor(this.poolSize / 2) + 1;\n\n // Check if the host is a socket\n if(host.match(/^\\//)) {\n this.socketOptions.domainSocket = true;\n } else if(typeof port === 'string') {\n try { \n port = parseInt(port, 10); \n } catch(err) { \n new Error(\"port must be specified or valid integer[\" + port + \"]\"); \n }\n } else if(typeof port !== 'number') {\n throw new Error(\"port must be specified [\" + port + \"]\");\n }\n\n // Set default settings for the socket options\n utils.setIntegerParameter(this.socketOptions, 'timeout', 0);\n // Delay before writing out the data to the server\n utils.setBooleanParameter(this.socketOptions, 'noDelay', true);\n // Delay before writing out the data to the server\n utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0);\n // Set the encoding of the data read, default is binary == null\n utils.setStringParameter(this.socketOptions, 'encoding', null);\n // Allows you to set a throttling bufferSize if you need to stop overflows\n utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0);\n\n // Internal structures\n this.openConnections = [];\n // Assign connection id's\n this.connectionId = 0;\n\n // Current index for selection of pool connection\n this.currentConnectionIndex = 0;\n // The pool state\n this._poolState = 'disconnected';\n // timeout control\n this._timeout = false;\n // Time to wait between connections for the pool\n this._timeToWait = 10;\n}\n\ninherits(ConnectionPool, EventEmitter);\n\nConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) {\n if(maxBsonSize == null){\n maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE;\n }\n\n for(var i = 0; i < this.openConnections.length; i++) {\n this.openConnections[i].maxBsonSize = maxBsonSize;\n }\n}\n\nConnectionPool.prototype.setMaxMessageSizeBytes = function(maxMessageSizeBytes) {\n if(maxMessageSizeBytes == null){\n maxMessageSizeBytes = Connection.DEFAULT_MAX_MESSAGE_SIZE;\n }\n\n for(var i = 0; i < this.openConnections.length; i++) {\n this.openConnections[i].maxMessageSizeBytes = maxMessageSizeBytes;\n }\n}\n\n// Start a function\nvar _connect = function(_self) {\n // return new function() {\n // Create a new connection instance\n var connection = new Connection(_self.connectionId++, _self.socketOptions);\n // Set logger on pool\n connection.logger = _self.logger;\n // Connect handler\n connection.on(\"connect\", function(err, connection) {\n // Add connection to list of open connections\n _self.openConnections.push(connection);\n // If the number of open connections is equal to the poolSize signal ready pool\n if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') {\n // Set connected\n _self._poolState = 'connected';\n // Emit pool ready\n _self.emit(\"poolReady\");\n } else if(_self.openConnections.length < _self.poolSize) {\n // Wait a little bit of time to let the close event happen if the server closes the connection\n // so we don't leave hanging connections around\n if(typeof _self._timeToWait == 'number') {\n setTimeout(function() {\n // If we are still connecting (no close events fired in between start another connection)\n if(_self._poolState == 'connecting') {\n _connect(_self);\n }\n }, _self._timeToWait);\n } else {\n processor(function() {\n // If we are still connecting (no close events fired in between start another connection)\n if(_self._poolState == 'connecting') {\n _connect(_self);\n }\n });\n }\n }\n });\n\n var numberOfErrors = 0\n\n // Error handler\n connection.on(\"error\", function(err, connection, error_options) {\n numberOfErrors++;\n // If we are already disconnected ignore the event\n if(_self._poolState != 'disconnected' && _self.listeners(\"error\").length > 0) {\n _self.emit(\"error\", err, connection, error_options);\n }\n\n // Close the connection\n connection.close();\n // Set pool as disconnected\n _self._poolState = 'disconnected';\n // Stop the pool\n _self.stop();\n });\n\n // Close handler\n connection.on(\"close\", function() {\n // If we are already disconnected ignore the event\n if(_self._poolState !== 'disconnected' && _self.listeners(\"close\").length > 0) {\n _self.emit(\"close\");\n }\n\n // Set disconnected\n _self._poolState = 'disconnected';\n // Stop\n _self.stop();\n });\n\n // Timeout handler\n connection.on(\"timeout\", function(err, connection) {\n // If we are already disconnected ignore the event\n if(_self._poolState !== 'disconnected' && _self.listeners(\"timeout\").length > 0) {\n _self.emit(\"timeout\", err);\n }\n\n // Close the connection\n connection.close();\n // Set disconnected\n _self._poolState = 'disconnected';\n _self.stop();\n });\n\n // Parse error, needs a complete shutdown of the pool\n connection.on(\"parseError\", function() {\n // If we are already disconnected ignore the event\n if(_self._poolState !== 'disconnected' && _self.listeners(\"parseError\").length > 0) {\n _self.emit(\"parseError\", new Error(\"parseError occured\"));\n }\n\n // Set disconnected\n _self._poolState = 'disconnected';\n _self.stop();\n });\n\n connection.on(\"message\", function(message) {\n _self.emit(\"message\", message);\n });\n\n // Start connection in the next tick\n connection.start();\n // }();\n}\n\n\n// Start method, will throw error if no listeners are available\n// Pass in an instance of the listener that contains the api for\n// finding callbacks for a given message etc.\nConnectionPool.prototype.start = function() {\n var markerDate = new Date().getTime();\n var self = this;\n\n if(this.listeners(\"poolReady\").length == 0) {\n throw \"pool must have at least one listener ready that responds to the [poolReady] event\";\n }\n\n // Set pool state to connecting\n this._poolState = 'connecting';\n this._timeout = false;\n\n _connect(self);\n}\n\n// Restart a connection pool (on a close the pool might be in a wrong state)\nConnectionPool.prototype.restart = function() {\n // Close all connections\n this.stop(false);\n // Now restart the pool\n this.start();\n}\n\n// Stop the connections in the pool\nConnectionPool.prototype.stop = function(removeListeners) {\n removeListeners = removeListeners == null ? true : removeListeners;\n // Set disconnected\n this._poolState = 'disconnected';\n\n // Clear all listeners if specified\n if(removeListeners) {\n this.removeAllEventListeners();\n }\n\n // Close all connections\n for(var i = 0; i < this.openConnections.length; i++) {\n this.openConnections[i].close();\n }\n\n // Clean up\n this.openConnections = [];\n}\n\n// Check the status of the connection\nConnectionPool.prototype.isConnected = function() {\n return this._poolState === 'connected';\n}\n\n// Checkout a connection from the pool for usage, or grab a specific pool instance\nConnectionPool.prototype.checkoutConnection = function(id) {\n var index = (this.currentConnectionIndex++ % (this.openConnections.length));\n var connection = this.openConnections[index];\n return connection;\n}\n\nConnectionPool.prototype.getAllConnections = function() {\n return this.openConnections;\n}\n\n// Remove all non-needed event listeners\nConnectionPool.prototype.removeAllEventListeners = function() {\n this.removeAllListeners(\"close\");\n this.removeAllListeners(\"error\");\n this.removeAllListeners(\"timeout\");\n this.removeAllListeners(\"connect\");\n this.removeAllListeners(\"end\");\n this.removeAllListeners(\"parseError\");\n this.removeAllListeners(\"message\");\n this.removeAllListeners(\"poolReady\");\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n});","sourceLength":9095,"scriptType":2,"compilationType":0,"context":{"ref":6},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js (lines: 295)"}],"refs":[{"handle":6,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":518,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[289]}}
{"seq":180,"request_seq":518,"type":"response","command":"scripts","success":true,"body":[{"handle":9,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js","id":289,"lineOffset":0,"columnOffset":0,"lineCount":170,"source":"(function (exports, require, module, __filename, __dirname) { var EventEmitter = require('events').EventEmitter\n , inherits = require('util').inherits;\n\n/**\n * Internal class for callback storage\n * @ignore\n */\nvar CallbackStore = function() {\n // Make class an event emitter\n EventEmitter.call(this);\n // Add a info about call variable\n this._notReplied = {};\n}\n\n/**\n * @ignore\n */\ninherits(CallbackStore, EventEmitter);\n\nvar Base = function Base() { \n EventEmitter.call(this);\n\n // Callback store is part of connection specification\n if(Base._callBackStore == null) {\n Base._callBackStore = new CallbackStore();\n }\n \n // this._callBackStore = Base._callBackStore;\n this._callBackStore = new CallbackStore();\n}\n\n/**\n * @ignore\n */\ninherits(Base, EventEmitter);\n\n/**\n * Fire all the errors\n * @ignore\n */\nBase.prototype.__executeAllCallbacksWithError = function(err) {\n // Check all callbacks\n var keys = Object.keys(this._callBackStore._notReplied);\n // For each key check if it's a callback that needs to be returned\n for(var j = 0; j < keys.length; j++) {\n var info = this._callBackStore._notReplied[keys[j]];\n // Check if we have a chained command (findAndModify)\n if(info && info['chained'] && Array.isArray(info['chained']) && info['chained'].length > 0) {\n var chained = info['chained'];\n // Only callback once and the last one is the right one\n var finalCallback = chained.pop();\n // Emit only the last event\n this._callBackStore.emit(finalCallback, err, null);\n\n // Put back the final callback to ensure we don't call all commands in the chain\n chained.push(finalCallback);\n\n // Remove all chained callbacks\n for(var i = 0; i < chained.length; i++) {\n delete this._callBackStore._notReplied[chained[i]];\n }\n } else {\n this._callBackStore.emit(keys[j], err, null);\n }\n }\n}\n\n/**\n * Register a handler\n * @ignore\n * @api private\n */\nBase.prototype._registerHandler = function(db_command, raw, connection, exhaust, callback) {\n // If we have an array of commands, chain them\n var chained = Array.isArray(db_command);\n\n // Check if we have exhausted\n if(typeof exhaust == 'function') {\n callback = exhaust;\n exhaust = false;\n }\n\n // If they are chained we need to add a special handler situation\n if(chained) {\n // List off chained id's\n var chainedIds = [];\n // Add all id's\n for(var i = 0; i < db_command.length; i++) chainedIds.push(db_command[i].getRequestId().toString());\n // Register all the commands together\n for(var i = 0; i < db_command.length; i++) {\n var command = db_command[i];\n // Add the callback to the store\n this._callBackStore.once(command.getRequestId(), callback);\n // Add the information about the reply\n this._callBackStore._notReplied[command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, chained:chainedIds, connection:connection, exhaust:false};\n }\n } else {\n // Add the callback to the list of handlers\n this._callBackStore.once(db_command.getRequestId(), callback);\n // Add the information about the reply\n this._callBackStore._notReplied[db_command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, connection:connection, exhaust:exhaust};\n }\n}\n\n/**\n * Re-Register a handler, on the cursor id f.ex\n * @ignore\n * @api private\n */\nBase.prototype._reRegisterHandler = function(newId, object, callback) {\n // Add the callback to the list of handlers\n this._callBackStore.once(newId, object.callback.listener);\n // Add the information about the reply\n this._callBackStore._notReplied[newId] = object.info;\n}\n\n/**\n *\n * @ignore\n * @api private\n */\nBase.prototype._callHandler = function(id, document, err) {\n // If there is a callback peform it\n if(this._callBackStore.listeners(id).length >= 1) {\n // Get info object\n var info = this._callBackStore._notReplied[id];\n // Delete the current object\n delete this._callBackStore._notReplied[id];\n // Emit to the callback of the object\n this._callBackStore.emit(id, err, document, info.connection);\n }\n}\n\n/**\n *\n * @ignore\n * @api private\n */\nBase.prototype._hasHandler = function(id) {\n // If there is a callback peform it\n return this._callBackStore.listeners(id).length >= 1;\n}\n\n/**\n *\n * @ignore\n * @api private\n */\nBase.prototype._removeHandler = function(id) {\n // Remove the information\n if(this._callBackStore._notReplied[id] != null) delete this._callBackStore._notReplied[id];\n // Remove the callback if it's registered\n this._callBackStore.removeAllListeners(id);\n // Force cleanup _events, node.js seems to set it as a null value\n if(this._callBackStore._events != null) delete this._callBackStore._events[id];\n}\n\n/**\n *\n * @ignore\n * @api private\n */\nBase.prototype._findHandler = function(id) {\n var info = this._callBackStore._notReplied[id];\n // Return the callback\n return {info:info, callback:(this._callBackStore.listeners(id).length >= 1) ? this._callBackStore.listeners(id)[0] : null}\n}\n\nexports.Base = Base;\n});","sourceLength":5060,"scriptType":2,"compilationType":0,"context":{"ref":8},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/base.js (lines: 170)"}],"refs":[{"handle":8,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":519,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[292]}}
{"seq":181,"request_seq":519,"type":"response","command":"scripts","success":true,"body":[{"handle":11,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js","id":292,"lineOffset":0,"columnOffset":0,"lineCount":358,"source":"(function (exports, require, module, __filename, __dirname) { var ReadPreference = require('./read_preference').ReadPreference\n , Base = require('./base').Base\n , inherits = require('util').inherits;\n\n/**\n * Mongos constructor provides a connection to a mongos proxy including failover to additional servers\n *\n * Options\n * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))\n * - **ha** {Boolean, default:true}, turn on high availability, attempts to reconnect to down proxies\n * - **haInterval** {Number, default:2000}, time between each replicaset status check.\n *\n * @class Represents a Mongos connection with failover to backup proxies\n * @param {Array} list of mongos server objects\n * @param {Object} [options] additional options for the mongos connection\n */\nvar Mongos = function Mongos(servers, options) {\n // Set up basic\n if(!(this instanceof Mongos))\n return new Mongos(servers, options);\n\n // Set up event emitter\n Base.call(this);\n\n // Throw error on wrong setup\n if(servers == null || !Array.isArray(servers) || servers.length == 0)\n throw new Error(\"At least one mongos proxy must be in the array\");\n\n // Ensure we have at least an empty options object\n this.options = options == null ? {} : options;\n // Set default connection pool options\n this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};\n // Enabled ha\n this.haEnabled = this.options['ha'] == null ? true : this.options['ha'];\n // How often are we checking for new servers in the replicaset\n this.mongosStatusCheckInterval = this.options['haInterval'] == null ? 2000 : this.options['haInterval'];\n // Save all the server connections\n this.servers = servers;\n // Servers we need to attempt reconnect with\n this.downServers = [];\n // Just contains the current lowest ping time and server\n this.lowestPingTimeServer = null;\n this.lowestPingTime = 0;\n\n // Connection timeout\n this._connectTimeoutMS = this.socketOptions.connectTimeoutMS\n ? this.socketOptions.connectTimeoutMS\n : 1000;\n\n // Add options to servers\n for(var i = 0; i < this.servers.length; i++) {\n var server = this.servers[i];\n server._callBackStore = this._callBackStore;\n // Default empty socket options object\n var socketOptions = {host: server.host, port: server.port};\n // If a socket option object exists clone it\n if(this.socketOptions != null) {\n var keys = Object.keys(this.socketOptions);\n for(var k = 0; k < keys.length;k++) socketOptions[keys[i]] = this.socketOptions[keys[i]];\n }\n // Set socket options\n server.socketOptions = socketOptions;\n }\n}\n\n/**\n * @ignore\n */\ninherits(Mongos, Base);\n\n/**\n * @ignore\n */\nMongos.prototype.isMongos = function() {\n return true;\n}\n\n/**\n * @ignore\n */\nMongos.prototype.connect = function(db, options, callback) {\n if('function' === typeof options) callback = options, options = {};\n if(options == null) options = {};\n if(!('function' === typeof callback)) callback = null;\n var self = this;\n\n // Keep reference to parent\n this.db = db;\n // Set server state to connecting\n this._serverState = 'connecting';\n // Number of total servers that need to initialized (known servers)\n this._numberOfServersLeftToInitialize = this.servers.length;\n // Default to the first proxy server as the first one to use\n this._currentMongos = this.servers[0];\n\n // Connect handler\n var connectHandler = function(_server) {\n return function(err, result) {\n self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1;\n\n if(self._numberOfServersLeftToInitialize == 0) {\n // Start ha function if it exists\n if(self.haEnabled) {\n // Setup the ha process\n self._replicasetTimeoutId = setTimeout(self.mongosCheckFunction, self.mongosStatusCheckInterval);\n }\n\n // Set the mongos to connected\n self._serverState = \"connected\";\n // Emit the open event\n self.db.emit(\"open\", null, self.db);\n // Callback\n callback(null, self.db);\n }\n }\n };\n\n // Error handler\n var errorOrCloseHandler = function(_server) {\n return function(err, result) {\n // Create current mongos comparision\n var currentUrl = self._currentMongos.host + \":\" + self._currentMongos.port;\n var serverUrl = this.host + \":\" + this.port;\n // We need to check if the server that closed is the actual current proxy we are using, otherwise\n // just ignore\n if(currentUrl == serverUrl) {\n // Remove the server from the list\n if(self.servers.indexOf(_server) != -1) {\n self.servers.splice(self.servers.indexOf(_server), 1);\n }\n\n // Pick the next one on the list if there is one\n for(var i = 0; i < self.servers.length; i++) {\n // Grab the server out of the array (making sure there is no servers in the list if none available)\n var server = self.servers[i];\n // Generate url for comparision\n var serverUrl = server.host + \":\" + server.port;\n // It's not the current one and connected set it as the current db\n if(currentUrl != serverUrl && server.isConnected()) {\n self._currentMongos = server;\n break;\n }\n }\n }\n\n // Ensure we don't store the _server twice\n if(self.downServers.indexOf(_server) == -1) {\n // Add the server instances\n self.downServers.push(_server);\n }\n }\n }\n\n // Mongo function\n this.mongosCheckFunction = function() {\n // If we have down servers let's attempt a reconnect\n if(self.downServers.length > 0) {\n var numberOfServersLeft = self.downServers.length;\n // Attempt to reconnect\n for(var i = 0; i < self.downServers.length; i++) {\n var downServer = self.downServers.pop();\n \n // Configuration\n var options = {\n slaveOk: true,\n poolSize: 1,\n socketOptions: { connectTimeoutMS: self._connectTimeoutMS },\n returnIsMasterResults: true\n } \n\n // Attemp to reconnect\n downServer.connect(self.db, options, function(_server) {\n // Return a function to check for the values\n return function(err, result) {\n // Adjust the number of servers left\n numberOfServersLeft = numberOfServersLeft - 1;\n\n if(err != null) {\n self.downServers.push(_server);\n } else {\n // Add server event handlers\n _server.on(\"close\", errorOrCloseHandler(_server));\n _server.on(\"error\", errorOrCloseHandler(_server));\n // Add to list of servers\n self.servers.push(_server);\n }\n\n if(numberOfServersLeft <= 0) {\n // Perfom another ha\n self._replicasetTimeoutId = setTimeout(self.mongosCheckFunction, self.mongosStatusCheckInterval);\n }\n }\n }(downServer));\n }\n } else if(self.servers.length > 0) {\n var numberOfServersLeft = self.servers.length;\n var _s = new Date().getTime()\n\n // Else let's perform a ping command\n for(var i = 0; i < self.servers.length; i++) {\n var executePing = function(_server) {\n // Get a read connection\n var _connection = _server.checkoutReader();\n // Execute ping command\n self.db.command({ping:1}, {failFast:true, connection:_connection}, function(err, result) {\n var pingTime = new Date().getTime() - _s;\n // If no server set set the first one, otherwise check\n // the lowest ping time and assign the server if it's got a lower ping time\n if(self.lowestPingTimeServer == null) {\n self.lowestPingTimeServer = _server;\n self.lowestPingTime = pingTime;\n self._currentMongos = _server;\n } else if(self.lowestPingTime > pingTime\n && (_server.host != self.lowestPingTimeServer.host || _server.port != self.lowestPingTimeServer.port)) {\n self.lowestPingTimeServer = _server;\n self.lowestPingTime = pingTime;\n self._currentMongos = _server;\n }\n\n // Number of servers left\n numberOfServersLeft = numberOfServersLeft - 1;\n // All active mongos's pinged\n if(numberOfServersLeft == 0) {\n // Perfom another ha\n self._replicasetTimeoutId = setTimeout(self.mongosCheckFunction, self.mongosStatusCheckInterval);\n }\n })\n }\n \n // Execute the function\n executePing(self.servers[i]);\n }\n } else {\n self._replicasetTimeoutId = setTimeout(self.mongosCheckFunction, self.mongosStatusCheckInterval);\n }\n }\n\n // Connect all the server instances\n for(var i = 0; i < this.servers.length; i++) {\n // Get the connection\n var server = this.servers[i];\n server.mongosInstance = this;\n // Add server event handlers\n server.on(\"close\", errorOrCloseHandler(server));\n server.on(\"timeout\", errorOrCloseHandler(server));\n server.on(\"error\", errorOrCloseHandler(server));\n // Configuration\n var options = {\n slaveOk: true,\n poolSize: 1,\n socketOptions: { connectTimeoutMS: self._connectTimeoutMS },\n returnIsMasterResults: true\n } \n\n // Connect the instance\n server.connect(self.db, options, connectHandler(server));\n }\n}\n\n/**\n * @ignore\n * Just return the currently picked active connection\n */\nMongos.prototype.allServerInstances = function() {\n return this.servers;\n}\n\n/**\n * Always ourselves\n * @ignore\n */\nMongos.prototype.setReadPreference = function() {}\n\n/**\n * @ignore\n */\nMongos.prototype.allRawConnections = function() {\n // Neeed to build a complete list of all raw connections, start with master server\n var allConnections = [];\n // Add all connections\n for(var i = 0; i < this.servers.length; i++) {\n allConnections = allConnections.concat(this.servers[i].allRawConnections());\n }\n\n // Return all the conections\n return allConnections;\n}\n\n/**\n * @ignore\n */\nMongos.prototype.isConnected = function() {\n return this._serverState == \"connected\";\n}\n\n/**\n * @ignore\n */\nMongos.prototype.checkoutWriter = function() {\n // No current mongo, just pick first server\n if(this._currentMongos == null && this.servers.length > 0) {\n return this.servers[0].checkoutWriter();\n }\n return this._currentMongos.checkoutWriter();\n}\n\n/**\n * @ignore\n */\nMongos.prototype.checkoutReader = function(read) {\n // If we have a read preference object unpack it\n if(typeof read == 'object' && read['_type'] == 'ReadPreference') {\n // Validate if the object is using a valid mode\n if(!read.isValid()) throw new Error(\"Illegal readPreference mode specified, \" + read.mode);\n } else if(!ReadPreference.isValid(read)) {\n throw new Error(\"Illegal readPreference mode specified, \" + read);\n }\n\n // No current mongo, just pick first server\n if(this._currentMongos == null && this.servers.length > 0) {\n return this.servers[0].checkoutReader();\n }\n return this._currentMongos.checkoutReader();\n}\n\n/**\n * @ignore\n */\nMongos.prototype.close = function(callback) {\n var self = this;\n // Set server status as disconnected\n this._serverState = 'disconnected';\n // Number of connections to close\n var numberOfConnectionsToClose = self.servers.length;\n // If we have a ha process running kill it\n if(self._replicasetTimeoutId != null) clearTimeout(self._replicasetTimeoutId);\n // Close all proxy connections\n for(var i = 0; i < self.servers.length; i++) {\n self.servers[i].close(function(err, result) {\n numberOfConnectionsToClose = numberOfConnectionsToClose - 1;\n // Callback if we have one defined\n if(numberOfConnectionsToClose == 0 && typeof callback == 'function') {\n callback(null);\n }\n });\n }\n}\n\n/**\n * @ignore\n * Return the used state\n */\nMongos.prototype._isUsed = function() {\n return this._used;\n}\n\nexports.Mongos = Mongos;\n});","sourceLength":12132,"scriptType":2,"compilationType":0,"context":{"ref":10},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/mongos.js (lines: 358)"}],"refs":[{"handle":10,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":520,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[295]}}
{"seq":182,"request_seq":520,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set.js","id":295,"lineOffset":0,"columnOffset":0,"lineCount":1473,"source":"(function (exports, require, module, __filename, __dirname) { var Connection = require('./connection').Connection, \n ReadPreference = require('./read_preference').ReadPreference,\n DbCommand = require('../commands/db_command').DbCommand,\n MongoReply = require('../responses/mongo_reply').MongoReply,\n debug = require('util').debug,\n inherits = require('util').inherits,\n inspect = require('util').inspect,\n Server = require('./server').Server,\n PingStrategy = require('./strategies/ping_strategy').PingStrategy,\n StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy,\n Base = require('./base').Base;\n\nconst STATE_STARTING_PHASE_1 = 0;\nconst STATE_PRIMARY = 1;\nconst STATE_SECONDARY = 2;\nconst STATE_RECOVERING = 3;\nconst STATE_FATAL_ERROR = 4;\nconst STATE_STARTING_PHASE_2 = 5;\nconst STATE_UNKNOWN = 6;\nconst STATE_ARBITER = 7;\nconst STATE_DOWN = 8;\nconst STATE_ROLLBACK = 9;\n\n/**\n * ReplSet constructor provides replicaset functionality\n *\n * Options\n * - **ha** {Boolean, default:true}, turn on high availability.\n * - **haInterval** {Number, default:2000}, time between each replicaset status check.\n * - **reconnectWait** {Number, default:1000}, time to wait in miliseconds before attempting reconnect.\n * - **retries** {Number, default:30}, number of times to attempt a replicaset reconnect.\n * - **rs_name** {String}, the name of the replicaset to connect to.\n * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))\n * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * - **strategy** {String, default:'ping'}, selection strategy for reads choose between (ping, statistical and none, default is ping)\n * - **secondaryAcceptableLatencyMS** {Number, default:15}, sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms)\n * - **connectArbiter** {Boolean, default:false}, sets if the driver should connect to arbiters or not.\n * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**.\n * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support)\n * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)\n * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)\n * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)\n * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)\n * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)\n *\n * @class Represents a Replicaset Configuration\n * @param {Array} list of server objects participating in the replicaset.\n * @param {Object} [options] additional options for the replicaset connection.\n */\nvar ReplSet = exports.ReplSet = function(servers, options) {\n this.count = 0;\n\n // Set up basic\n if(!(this instanceof ReplSet))\n return new ReplSet(servers, options);\n\n // Set up event emitter\n Base.call(this);\n\n // Ensure no Mongos's\n for(var i = 0; i < servers.length; i++) {\n if(!(servers[i] instanceof Server)) throw new Error(\"list of servers must be of type Server\");\n }\n\n // Just reference for simplicity\n var self = this;\n // Contains the master server entry\n this.options = options == null ? {} : options;\n this.reconnectWait = this.options[\"reconnectWait\"] != null ? this.options[\"reconnectWait\"] : 1000;\n this.retries = this.options[\"retries\"] != null ? this.options[\"retries\"] : 30;\n this.replicaSet = this.options[\"rs_name\"];\n\n // Are we allowing reads from secondaries ?\n this.readSecondary = this.options[\"read_secondary\"];\n this.slaveOk = true;\n this.closedConnectionCount = 0;\n this._used = false;\n\n // Connect arbiters ?\n this.connectArbiter = this.options.connectArbiter == null ? false : this.options.connectArbiter;\n\n // Default poolSize for new server instances\n this.poolSize = this.options.poolSize == null ? 5 : this.options.poolSize;\n this._currentServerChoice = 0;\n\n // Set up ssl connections\n this.ssl = this.options.ssl == null ? false : this.options.ssl;\n // Set ssl validation\n this.sslValidate = this.options.sslValidate == null ? false : this.options.sslValidate;\n // Set the ssl certificate authority (array of Buffer/String keys)\n this.sslCA = Array.isArray(this.options.sslCA) ? this.options.sslCA : null;\n // Certificate to present to the server\n this.sslCert = this.options.sslCert;\n // Certificate private key if in separate file\n this.sslKey = this.options.sslKey;\n // Password to unlock private key\n this.sslPass = this.options.sslPass;\n\n // Ensure we are not trying to validate with no list of certificates\n if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) {\n throw new Error(\"The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate\");\n }\n\n // Internal state of server connection\n this._serverState = 'disconnected';\n // Read preference\n this._readPreference = null;\n // HA running\n this._haRunning = false;\n // Do we record server stats or not\n this.recordQueryStats = false;\n // Update health try server\n this.updateHealthServerTry = 0;\n\n // Get the readPreference\n var readPreference = this.options['readPreference'];\n\n // Validate correctness of Read preferences\n if(readPreference != null) {\n if(readPreference != ReadPreference.PRIMARY && readPreference != ReadPreference.PRIMARY_PREFERRED\n && readPreference != ReadPreference.SECONDARY && readPreference != ReadPreference.SECONDARY_PREFERRED\n && readPreference != ReadPreference.NEAREST && typeof readPreference != 'object' && readPreference['_type'] != 'ReadPreference') {\n throw new Error(\"Illegal readPreference mode specified, \" + readPreference);\n }\n\n this._readPreference = readPreference;\n } else {\n this._readPreference = null;\n }\n\n // Ensure read_secondary is set correctly\n if(!this.readSecondary)\n this.readSecondary = this._readPreference == ReadPreference.PRIMARY \n || this._readPreference == false \n || this._readPreference == null ? false : true;\n\n // Ensure correct slave set\n if(this.readSecondary) this.slaveOk = true;\n\n // Strategy for picking a secondary\n this.secondaryAcceptableLatencyMS = this.options['secondaryAcceptableLatencyMS'] == null ? 15 : this.options['secondaryAcceptableLatencyMS'];\n this.strategy = this.options['strategy'];\n // Make sure strategy is one of the two allowed\n if(this.strategy != null && (this.strategy != 'ping' && this.strategy != 'statistical' && this.strategy != 'none')) \n throw new Error(\"Only ping or statistical strategies allowed\"); \n if(this.strategy == null) this.strategy = 'ping';\n // Let's set up our strategy object for picking secodaries\n if(this.strategy == 'ping') {\n // Create a new instance\n this.strategyInstance = new PingStrategy(this, this.secondaryAcceptableLatencyMS);\n } else if(this.strategy == 'statistical') {\n // Set strategy as statistical\n this.strategyInstance = new StatisticsStrategy(this);\n // Add enable query information\n this.enableRecordQueryStats(true);\n }\n\n // Set logger if strategy exists\n if(this.strategyInstance) this.strategyInstance.logger = this.logger;\n\n // Set default connection pool options\n this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};\n\n // Set up logger if any set\n this.logger = this.options.logger != null\n && (typeof this.options.logger.debug == 'function')\n && (typeof this.options.logger.error == 'function')\n && (typeof this.options.logger.debug == 'function')\n ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};\n\n // Ensure all the instances are of type server and auto_reconnect is false\n if(!Array.isArray(servers) || servers.length == 0) {\n throw Error(\"The parameter must be an array of servers and contain at least one server\");\n } else if(Array.isArray(servers) || servers.length > 0) {\n var count = 0;\n servers.forEach(function(server) {\n if(server instanceof Server) count = count + 1;\n // Ensure no server has reconnect on\n server.options.auto_reconnect = false;\n // Set up ssl options\n server.ssl = self.ssl;\n server.sslValidate = self.sslValidate;\n server.sslCA = self.sslCA;\n server.sslCert = self.sslCert;\n server.sslKey = self.sslKey;\n server.sslPass = self.sslPass;\n server.poolSize = self.poolSize;\n // Set callback store\n server._callBackStore = self._callBackStore;\n });\n\n if(count < servers.length) {\n throw Error(\"All server entries must be of type Server\");\n } else {\n this.servers = servers;\n }\n }\n\n // var deduplicate list\n var uniqueServers = {};\n // De-duplicate any servers in the seed list\n for(var i = 0; i < this.servers.length; i++) {\n var server = this.servers[i];\n // If server does not exist set it\n if(uniqueServers[server.host + \":\" + server.port] == null) {\n uniqueServers[server.host + \":\" + server.port] = server;\n }\n }\n\n // Let's set the deduplicated list of servers\n this.servers = [];\n // Add the servers\n for(var key in uniqueServers) {\n this.servers.push(uniqueServers[key]);\n }\n\n // Enabled ha\n this.haEnabled = this.options['ha'] == null ? true : this.options['ha'];\n this._haServer = null;\n // How often are we checking for new servers in the replicaset\n this.replicasetStatusCheckInterval = this.options['haInterval'] == null ? 5000 : this.options['haInterval'];\n\n // Connection timeout\n this._connectTimeoutMS = this.socketOptions.connectTimeoutMS\n ? this.socketOptions.connectTimeoutMS\n : 1000;\n // Socket connection timeout\n this._socketTimeoutMS = this.socketOptions.socketTimeoutMS\n ? this.socketOptions.socketTimeoutMS\n : (this.replicasetStatusCheckInterval + 1000);\n};\n\n/**\n * @ignore\n */\ninherits(ReplSet, Base);\n\n/**\n * @ignore\n */\n// Allow setting the read preference at the replicaset level\nReplSet.prototype.setReadPreference = function(preference) {\n // Set read preference\n this._readPreference = preference;\n // Ensure slaveOk is correct for secondaries read preference and tags\n if((this._readPreference == ReadPreference.SECONDARY_PREFERRED \n || this._readPreference == ReadPreference.SECONDARY\n || this._readPreference == ReadPreference.NEAREST)\n || (this._readPreference != null && typeof this._readPreference == 'object')) {\n this.slaveOk = true;\n }\n}\n\n/**\n * @ignore\n */\nReplSet.prototype._isUsed = function() {\n return this._used;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.isMongos = function() {\n return false;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.isConnected = function(read) {\n if(read == null || read == ReadPreference.PRIMARY || read == false)\n return this.primary != null && this._state.master != null && this._state.master.isConnected();\n\n if((read == ReadPreference.PRIMARY_PREFERRED || read == ReadPreference.SECONDARY_PREFERRED || read == ReadPreference.NEAREST)\n && ((this.primary != null && this._state.master != null && this._state.master.isConnected())\n || (this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0))) {\n return true;\n } else if(read == ReadPreference.SECONDARY) {\n return this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0;\n }\n\n // No valid connection return false\n return false;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.isSetMember = function() {\n return false;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.isPrimary = function(config) {\n return this.readSecondary && Object.keys(this._state.secondaries).length > 0 ? false : true;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.isReadPrimary = ReplSet.prototype.isPrimary;\n\n/**\n * @ignore\n */\nReplSet.prototype.allServerInstances = function() {\n var self = this;\n // If no state yet return empty\n if(!self._state) return [];\n // Close all the servers (concatenate entire list of servers first for ease)\n var allServers = self._state.master != null ? [self._state.master] : [];\n\n // Secondary keys\n var keys = Object.keys(self._state.secondaries);\n // Add all secondaries\n for(var i = 0; i < keys.length; i++) {\n allServers.push(self._state.secondaries[keys[i]]);\n }\n\n // Arbiter keys\n var keys = Object.keys(self._state.arbiters);\n // Add all arbiters\n for(var i = 0; i < keys.length; i++) {\n allServers.push(self._state.arbiters[keys[i]]);\n }\n\n // Passive keys\n var keys = Object.keys(self._state.passives);\n // Add all arbiters\n for(var i = 0; i < keys.length; i++) {\n allServers.push(self._state.passives[keys[i]]);\n }\n\n // Return complete list of all servers\n return allServers;\n}\n\n/**\n * Enables high availability pings.\n *\n * @ignore\n */\nReplSet.prototype._enableHA = function () {\n var self = this;\n self._haRunning = true;\n return check();\n\n function ping () {\n // We are disconnected stop pinging and close current connection if any\n if(\"disconnected\" == self._serverState) {\n if(self._haServer != null) self._haServer.close();\n return;\n }\n\n // Create a list of all servers we can send the ismaster command to\n var allServers = self._state.master != null ? [self._state.master] : [];\n\n // Secondary keys\n var keys = Object.keys(self._state.secondaries);\n // Add all secondaries\n for(var i = 0; i < keys.length; i++) {\n allServers.push(self._state.secondaries[keys[i]]);\n }\n\n // If no servers quit as are probably connecting\n if(allServers.length == 0) return;\n // Pick one of the servers \n self.updateHealthServerTry = self.updateHealthServerTry++ % allServers.length;\n var selectedServer = allServers[self.updateHealthServerTry];\n\n // If we have an active db instance\n if(self.dbInstances.length > 0) {\n var db = self.dbInstances[0];\n\n // We have an instance already\n if(self._haServer == null) {\n // Create a new master connection\n self._haServer = new Server(selectedServer.host, selectedServer.port, {\n auto_reconnect: false,\n returnIsMasterResults: true,\n slaveOk: true,\n poolSize: 1,\n socketOptions: { \n connectTimeoutMS: self._connectTimeoutMS,\n socketTimeoutMS: self._socketTimeoutMS\n },\n ssl: self.ssl,\n sslValidate: self.sslValidate,\n sslCA: self.sslCA,\n sslCert: self.sslCert,\n sslKey: self.sslKey,\n sslPass: self.sslPass\n });\n\n self._haServer._callBackStore = self._callBackStore;\n\n // Add error handlers\n self._haServer.on(\"close\", function() {\n if(self._haServer) self._haServer.close();\n self._haServer = null;\n }); \n\n self._haServer.on(\"error\", function() {\n if(self._haServer) self._haServer.close();\n self._haServer = null; \n });\n\n self._haServer.on(\"timeout\", function() {\n if(self._haServer) self._haServer.close();\n self._haServer = null; \n });\n\n // Connect using the new _server connection to not impact the driver\n // behavior on any errors we could possibly run into\n self._haServer.connect(db, function(err, result, _server) {\n if(\"disconnected\" == self._serverState) {\n if(_server && _server.close) _server.close(); \n self._haRunning = false;\n return;\n }\n \n if(err) {\n if(_server && _server.close) _server.close();\n return check();\n }\n\n executeMasterCommand(db, _server);\n }); \n } else {\n executeMasterCommand(db, self._haServer);\n }\n }\n }\n\n function executeMasterCommand(db, _server) {\n try {\n // Create is master command\n var cmd = DbCommand.createIsMasterCommand(db);\n // Execute is master command\n db._executeQueryCommand(cmd, {failFast:true, connection: _server.checkoutReader()}, function(err, res) {\n if(\"disconnected\" == self._serverState) {\n if(_server && _server.close) _server.close(); \n self._haRunning = false;\n self._haServer = null;\n return;\n }\n // If error let's set perform another check\n if(err) {\n // Force new server selection\n self._haServer = null;\n return check();\n }\n // Validate the replicaset \n self._validateReplicaset(res, db.auths, function() {\n check();\n }); \n }); \n } catch(err) {\n if(self._haServer) self._haServer.close();\n self._haServer = null;\n check();\n } \n }\n\n function check() {\n self._haTimer = setTimeout(ping, self.replicasetStatusCheckInterval);\n }\n}\n\n/**\n * @ignore\n */\nReplSet.prototype._validateReplicaset = function(result, auths, cb) {\n var self = this;\n var res = result.documents[0];\n\n // manage master node changes\n if(res.primary && self._state.master && self._state.master.name != res.primary) {\n // Delete master record so we can rediscover it\n delete self._state.addresses[self._state.master.name];\n\n // TODO existing issue? this seems to only work if\n // we already have a connection to the new primary.\n\n // Update information on new primary\n // add as master, remove from secondary\n var newMaster = self._state.addresses[res.primary];\n newMaster.isMasterDoc.ismaster = true;\n newMaster.isMasterDoc.secondary = false;\n self._state.master = newMaster;\n delete self._state.secondaries[res.primary];\n }\n\n // discover new hosts\n var hosts = [];\n\n for(var i = 0; i < res.hosts.length; ++i) {\n var host = res.hosts[i];\n if (host == res.me) continue;\n if (!(self._state.addresses[host] || ~hosts.indexOf(host))) {\n // we dont already have a connection to this host and aren't\n // already planning on connecting.\n hosts.push(host);\n }\n }\n\n connectTo(hosts, auths, self, cb);\n}\n\n/**\n * Create connections to all `hosts` firing `cb` after\n * connections are attempted for all `hosts`.\n *\n * @param {Array} hosts\n * @param {Array} [auths]\n * @param {ReplSet} replset\n * @param {Function} cb\n * @ignore\n */\nfunction connectTo(hosts, auths, replset, cb) {\n var pending = hosts.length;\n if (!pending) return cb();\n\n for(var i = 0; i < hosts.length; ++i) {\n connectToHost(hosts[i], auths, replset, handle);\n }\n\n function handle () {\n --pending;\n if (0 === pending) cb();\n }\n}\n\n/**\n * Attempts connection to `host` and authenticates with optional `auth`\n * for the given `replset` firing `cb` when finished.\n *\n * @param {String} host\n * @param {Array} auths\n * @param {ReplSet} replset\n * @param {Function} cb\n * @ignore\n */\nfunction connectToHost(host, auths, replset, cb) {\n var server = createServer(host, replset);\n\n var options = {\n returnIsMasterResults: true,\n eventReceiver: server\n }\n\n server.connect(replset.db, options, function(err, result) {\n var doc = result && result.documents && result.documents[0];\n\n if (err || !doc) {\n server.close();\n return cb(err, result, server);\n }\n\n if(!(doc.ismaster || doc.secondary || doc.arbiterOnly)) {\n server.close();\n return cb(null, result, server);\n }\n\n // if host is an arbiter, disconnect if not configured for it\n if(doc.arbiterOnly && !replset.connectArbiter) {\n server.close();\n return cb(null, result, server);\n }\n\n // create handler for successful connections\n var handleConnect = _connectHandler(replset, null, server);\n function complete () {\n handleConnect(err, result);\n cb();\n }\n\n // authenticate if necessary\n if(!(Array.isArray(auths) && auths.length > 0)) {\n return complete();\n }\n\n var pending = auths.length;\n\n var connections = server.allRawConnections();\n var pendingAuthConn = connections.length;\n for(var x = 0; x <connections.length; x++) {\n var connection = connections[x];\n var authDone = false; \n for(var i = 0; i < auths.length; i++) {\n var auth = auths[i];\n var options = { authdb: auth.authdb, connection: connection };\n var username = auth.username;\n var password = auth.password;\n replset.db.authenticate(username, password, options, function() {\n --pending;\n if(0 === pending) {\n authDone = true;\n --pendingAuthConn;\n if(0 === pendingAuthConn) {\n return complete();\n } \n }\n });\n }\n }\n });\n}\n\n/**\n * Creates a new server for the `replset` based on `host`.\n *\n * @param {String} host - host:port pair (localhost:27017)\n * @param {ReplSet} replset - the ReplSet instance\n * @return {Server}\n * @ignore\n */\nfunction createServer(host, replset) {\n // copy existing socket options to new server\n var socketOptions = {}\n if(replset.socketOptions) {\n var keys = Object.keys(replset.socketOptions);\n for(var k = 0; k < keys.length; k++) {\n socketOptions[keys[k]] = replset.socketOptions[keys[k]];\n }\n }\n\n var parts = host.split(/:/);\n if(1 === parts.length) {\n parts[1] = Connection.DEFAULT_PORT;\n }\n\n socketOptions.host = parts[0];\n socketOptions.port = parseInt(parts[1], 10);\n\n var serverOptions = {\n readPreference: replset._readPreference,\n socketOptions: socketOptions,\n poolSize: replset.poolSize,\n logger: replset.logger,\n auto_reconnect: false,\n ssl: replset.ssl,\n sslValidate: replset.sslValidate,\n sslCA: replset.sslCA,\n sslCert: replset.sslCert,\n sslKey: replset.sslKey,\n sslPass: replset.sslPass\n }\n\n var server = new Server(socketOptions.host, socketOptions.port, serverOptions);\n server._callBackStore = replset._callBackStore;\n server.replicasetInstance = replset;\n server.on(\"close\", _handler(\"close\", replset));\n server.on(\"error\", _handler(\"error\", replset));\n server.on(\"timeout\", _handler(\"timeout\", replset));\n return server;\n}\n\nvar _handler = function(event, self) {\n return function(err, server) { \n // Remove from all lists\n delete self._state.secondaries[server.name];\n delete self._state.arbiters[server.name];\n delete self._state.passives[server.name];\n delete self._state.addresses[server.name];\n\n // Execute all the callbacks with errors\n self.__executeAllCallbacksWithError(err);\n\n // If we have app listeners on close event\n if(self.db.listeners(event).length > 0) {\n self.db.emit(event, err);\n }\n\n // If it's the primary close all connections\n if(self._state.master \n && self._state.master.host == server.host\n && self._state.master.port == server.port) {\n // return self.close();\n self._state.master = null;\n }\n }\n}\n\nvar _connectHandler = function(self, candidateServers, instanceServer) {\n return function(err, result) {\n // If we have an ssl error store the error\n if(err && err.ssl) {\n self._sslError = err;\n }\n\n // We are disconnected stop attempting reconnect or connect\n if(self._serverState == 'disconnected') return instanceServer.close();\n\n // If no error handle isMaster\n if(err == null && result.documents[0].hosts != null) {\n // Fetch the isMaster command result\n var document = result.documents[0];\n // Break out the results\n var setName = document.setName;\n var isMaster = document.ismaster;\n var secondary = document.secondary;\n var passive = document.passive;\n var arbiterOnly = document.arbiterOnly;\n var hosts = Array.isArray(document.hosts) ? document.hosts : [];\n var arbiters = Array.isArray(document.arbiters) ? document.arbiters : [];\n var passives = Array.isArray(document.passives) ? document.passives : [];\n var tags = document.tags ? document.tags : {};\n var primary = document.primary;\n // Find the current server name and fallback if none\n var userProvidedServerString = instanceServer.host + \":\" + instanceServer.port;\n var me = document.me || userProvidedServerString;\n\n // Verify if the set name is the same otherwise shut down and return an error\n if(self.replicaSet == null) {\n self.replicaSet = setName;\n } else if(self.replicaSet != setName) {\n // Stop the set\n self.close();\n // Emit a connection error\n return self.emit(\"connectionError\",\n new Error(\"configured mongodb replicaset does not match provided replicaset [\" + setName + \"] != [\" + self.replicaSet + \"]\"))\n }\n\n // Make sure we have the right reference\n var oldServer = self._state.addresses[userProvidedServerString]\n if (oldServer && oldServer !== instanceServer) oldServer.close();\n delete self._state.addresses[userProvidedServerString];\n\n if (self._state.addresses[me] && self._state.addresses[me] !== instanceServer) {\n self._state.addresses[me].close();\n }\n\n self._state.addresses[me] = instanceServer;\n\n // Let's add the server to our list of server types\n if(secondary == true && (passive == false || passive == null)) {\n self._state.secondaries[me] = instanceServer;\n } else if(arbiterOnly == true) {\n self._state.arbiters[me] = instanceServer;\n } else if(secondary == true && passive == true) {\n self._state.passives[me] = instanceServer;\n } else if(isMaster == true) {\n self._state.master = instanceServer;\n } else if(isMaster == false && primary != null && self._state.addresses[primary]) {\n self._state.master = self._state.addresses[primary];\n }\n\n // Set the name\n instanceServer.name = me;\n // Add tag info\n instanceServer.tags = tags;\n\n // Add the handlers to the instance\n instanceServer.on(\"close\", _handler(\"close\", self));\n instanceServer.on(\"error\", _handler(\"error\", self));\n instanceServer.on(\"timeout\", _handler(\"timeout\", self));\n\n // Possible hosts\n var possibleHosts = Array.isArray(hosts) ? hosts.slice() : [];\n possibleHosts = Array.isArray(passives) ? possibleHosts.concat(passives) : possibleHosts;\n\n if(self.connectArbiter == true) {\n possibleHosts = Array.isArray(arbiters) ? possibleHosts.concat(arbiters) : possibleHosts;\n }\n\n if(Array.isArray(candidateServers)) {\n // Add any new candidate servers for connection\n for(var j = 0; j < possibleHosts.length; j++) {\n if(self._state.addresses[possibleHosts[j]] == null && possibleHosts[j] != null) {\n var parts = possibleHosts[j].split(/:/);\n if(parts.length == 1) {\n parts = [parts[0], Connection.DEFAULT_PORT];\n }\n\n // New candidate server\n var candidateServer = new Server(parts[0], parseInt(parts[1]));\n candidateServer._callBackStore = self._callBackStore;\n candidateServer.name = possibleHosts[j];\n candidateServer.ssl = self.ssl;\n candidateServer.sslValidate = self.sslValidate;\n candidateServer.sslCA = self.sslCA;\n candidateServer.sslCert = self.sslCert;\n candidateServer.sslKey = self.sslKey;\n candidateServer.sslPass = self.sslPass;\n\n // Set the candidate server\n self._state.addresses[possibleHosts[j]] = candidateServer;\n // Add the new server to the list of candidate servers\n candidateServers.push(candidateServer);\n }\n }\n }\n } else if(err != null || self._serverState == 'disconnected'){\n delete self._state.addresses[instanceServer.host + \":\" + instanceServer.port];\n // Remove it from the set\n instanceServer.close();\n }\n\n // Attempt to connect to the next server\n if(Array.isArray(candidateServers) && candidateServers.length > 0) {\n var server = candidateServers.pop();\n\n // Get server addresses\n var addresses = self._state.addresses;\n\n // Default empty socket options object\n var socketOptions = {};\n\n // Set fast connect timeout\n socketOptions['connectTimeoutMS'] = self._connectTimeoutMS;\n\n // If a socket option object exists clone it\n if(self.socketOptions != null && typeof self.socketOptions === 'object') {\n var keys = Object.keys(self.socketOptions);\n for(var j = 0; j < keys.length;j++) socketOptions[keys[j]] = self.socketOptions[keys[j]];\n }\n\n // If ssl is specified\n if(self.ssl) server.ssl = true;\n\n // Add host information to socket options\n socketOptions['host'] = server.host;\n socketOptions['port'] = server.port;\n server.socketOptions = socketOptions;\n server.replicasetInstance = self;\n server.enableRecordQueryStats(self.recordQueryStats);\n\n // Set the server\n if (addresses[server.host + \":\" + server.port] != server) {\n if (addresses[server.host + \":\" + server.port]) {\n // Close the connection before deleting\n addresses[server.host + \":\" + server.port].close();\n }\n delete addresses[server.host + \":\" + server.port];\n }\n\n addresses[server.host + \":\" + server.port] = server;\n // Connect\n server.connect(self.db, {returnIsMasterResults: true, eventReceiver:server}, _connectHandler(self, candidateServers, server));\n } else if(Array.isArray(candidateServers)) {\n // If we have no primary emit error\n if(self._state.master == null) {\n // Stop the set\n self.close();\n\n // If we have an ssl error send the message instead of no primary found\n if(self._sslError) {\n return self.emit(\"connectionError\", self._sslError);\n }\n\n // Emit a connection error\n return self.emit(\"connectionError\",\n new Error(\"no primary server found in set\"))\n } else{\n if(self.strategyInstance) {\n self.strategyInstance.start();\n }\n\n for(var i = 0; i < self.dbInstances.length; i++) self.dbInstances[i]._state = 'connected';\n self.emit(\"fullsetup\", null, self.db, self);\n self.emit(\"open\", null, self.db, self); \n }\n }\n }\n}\n\nvar _fullsetup_emitted = false;\n\n/**\n * Interval state object constructor\n *\n * @ignore\n */\nReplSet.State = function ReplSetState () {\n this.errorMessages = [];\n this.secondaries = {};\n this.addresses = {};\n this.arbiters = {};\n this.passives = {};\n this.members = [];\n this.errors = {};\n this.setName = null;\n this.master = null;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.connect = function(parent, options, callback) {\n var self = this;\n if('function' === typeof options) callback = options, options = {};\n if(options == null) options = {};\n if(!('function' === typeof callback)) callback = null;\n\n // Ensure it's all closed\n self.close();\n\n // Set connecting status\n this.db = parent;\n this._serverState = 'connecting';\n this._callbackList = [];\n\n this._state = new ReplSet.State();\n\n // Ensure parent can do a slave query if it's set\n parent.slaveOk = this.slaveOk\n ? this.slaveOk\n : parent.slaveOk;\n\n // Remove any listeners\n this.removeAllListeners(\"fullsetup\");\n this.removeAllListeners(\"connectionError\");\n\n // Add primary found event handler\n this.once(\"fullsetup\", function() {\n self._handleOnFullSetup(parent);\n\n // Callback\n if(typeof callback == 'function') {\n var internalCallback = callback;\n callback = null;\n internalCallback(null, parent, self);\n }\n });\n\n this.once(\"connectionError\", function(err) {\n self._serverState = 'disconnected';\n // Ensure it's all closed\n self.close();\n // Perform the callback\n if(typeof callback == 'function') {\n var internalCallback = callback;\n callback = null;\n internalCallback(err, parent, self);\n }\n });\n\n // Get server addresses\n var addresses = this._state.addresses;\n\n // De-duplicate any servers\n var server, key;\n for(var i = 0; i < this.servers.length; i++) {\n server = this.servers[i];\n key = server.host + \":\" + server.port;\n if(null == addresses[key]) {\n addresses[key] = server;\n }\n }\n\n // Get the list of servers that is deduplicated and start connecting\n var candidateServers = [];\n var keys = Object.keys(addresses);\n for(var i = 0; i < keys.length; i++) {\n server = addresses[keys[i]];\n server.assignReplicaSet(this);\n candidateServers.push(server);\n }\n\n // Let's connect to the first one on the list\n server = candidateServers.pop();\n var opts = {\n returnIsMasterResults: true,\n eventReceiver: server\n }\n\n server.connect(parent, opts, _connectHandler(self, candidateServers, server)); \n}\n\n/**\n * Handles the first `fullsetup` event of this ReplSet.\n *\n * @param {Db} parent\n * @ignore\n */\nReplSet.prototype._handleOnFullSetup = function (parent) {\n this._serverState = 'connected';\n for(var i = 0; i < this.dbInstances.length; i++) this.dbInstances[i]._state = 'connected';\n if(parent._state) parent._state = 'connected';\n // Emit the fullsetup and open event\n parent.emit(\"open\", null, this.db, this);\n parent.emit(\"fullsetup\", null, this.db, this);\n\n if(!this.haEnabled) return;\n if(this._haRunning) return;\n this._enableHA();\n}\n\n/**\n * Disables high availability pings.\n *\n * @ignore\n */\nReplSet.prototype._disableHA = function () {\n clearTimeout(this._haTimer);\n this._haTimer = undefined;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.checkoutWriter = function() {\n // Establish connection\n var connection = this._state.master != null ? this._state.master.checkoutWriter() : null;\n // Return the connection\n return connection;\n}\n\n/**\n * @ignore\n */\nvar pickFirstConnectedSecondary = function pickFirstConnectedSecondary(self, tags) {\n var keys = Object.keys(self._state.secondaries);\n var connection;\n\n // Find first available reader if any\n for(var i = 0; i < keys.length; i++) {\n connection = self._state.secondaries[keys[i]].checkoutReader();\n if(connection) return connection;\n }\n\n // If we still have a null, read from primary if it's not secondary only\n if(self._readPreference == ReadPreference.SECONDARY_PREFERRED) {\n connection = self._state.master.checkoutReader();\n if(connection) return connection;\n }\n\n var preferenceName = self._readPreference == ReadPreference.SECONDARY_PREFERRED\n ? 'secondary'\n : self._readPreference;\n\n return new Error(\"No replica set member available for query with ReadPreference \"\n + preferenceName + \" and tags \" + JSON.stringify(tags));\n}\n\n/**\n * @ignore\n */\nvar _pickFromTags = function(self, tags) {\n // If we have an array or single tag selection\n var tagObjects = Array.isArray(tags) ? tags : [tags];\n // Iterate over all tags until we find a candidate server\n for(var _i = 0; _i < tagObjects.length; _i++) {\n // Grab a tag object\n var tagObject = tagObjects[_i];\n // Matching keys\n var matchingKeys = Object.keys(tagObject);\n // Match all the servers that match the provdided tags\n var keys = Object.keys(self._state.secondaries);\n var candidateServers = [];\n\n for(var i = 0; i < keys.length; i++) {\n var server = self._state.secondaries[keys[i]];\n // If we have tags match\n if(server.tags != null) {\n var matching = true;\n // Ensure we have all the values\n for(var j = 0; j < matchingKeys.length; j++) {\n if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {\n matching = false;\n break;\n }\n }\n\n // If we have a match add it to the list of matching servers\n if(matching) {\n candidateServers.push(server);\n }\n }\n }\n\n // If we have a candidate server return\n if(candidateServers.length > 0) {\n if(this.strategyInstance) return this.strategyInstance.checkoutConnection(tags, candidateServers);\n // Set instance to return\n return candidateServers[Math.floor(Math.random() * candidateServers.length)].checkoutReader();\n }\n }\n\n // No connection found\n return null;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.checkoutReader = function(readPreference, tags) {\n var connection = null;\n\n // If we have a read preference object unpack it\n if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') {\n // Validate if the object is using a valid mode\n if(!readPreference.isValid()) throw new Error(\"Illegal readPreference mode specified, \" + readPreference.mode);\n // Set the tag\n tags = readPreference.tags;\n readPreference = readPreference.mode;\n } else if(typeof readPreference == 'object' && readPreference['_type'] != 'ReadPreference') {\n throw new Error(\"read preferences must be either a string or an instance of ReadPreference\");\n }\n\n // Set up our read Preference, allowing us to override the readPreference\n var finalReadPreference = readPreference != null ? readPreference : this._readPreference;\n finalReadPreference = finalReadPreference == true ? ReadPreference.SECONDARY_PREFERRED : finalReadPreference;\n finalReadPreference = finalReadPreference == null ? ReadPreference.PRIMARY : finalReadPreference;\n\n // If we are reading from a primary\n if(finalReadPreference == 'primary') {\n // If we provide a tags set send an error\n if(typeof tags == 'object' && tags != null) {\n return new Error(\"PRIMARY cannot be combined with tags\");\n }\n\n // If we provide a tags set send an error\n if(this._state.master == null) {\n return new Error(\"No replica set primary available for query with ReadPreference PRIMARY\");\n }\n\n // Checkout a writer\n return this.checkoutWriter();\n }\n\n // If we have specified to read from a secondary server grab a random one and read\n // from it, otherwise just pass the primary connection\n if((this.readSecondary || finalReadPreference == ReadPreference.SECONDARY_PREFERRED || finalReadPreference == ReadPreference.SECONDARY) && Object.keys(this._state.secondaries).length > 0) {\n // If we have tags, look for servers matching the specific tag\n if(this.strategyInstance != null) {\n // Only pick from secondaries\n var _secondaries = [];\n for(var key in this._state.secondaries) {\n _secondaries.push(this._state.secondaries[key]);\n }\n\n if(finalReadPreference == ReadPreference.SECONDARY) {\n // Check out the nearest from only the secondaries\n connection = this.strategyInstance.checkoutConnection(tags, _secondaries);\n } else {\n connection = this.strategyInstance.checkoutConnection(tags, _secondaries);\n // No candidate servers that match the tags, error\n if(connection == null || connection instanceof Error) {\n // No secondary server avilable, attemp to checkout a primary server\n connection = this.checkoutWriter();\n // If no connection return an error\n if(connection == null) {\n return new Error(\"No replica set members available for query\");\n }\n }\n }\n } else if(tags != null && typeof tags == 'object') {\n // Get connection\n connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {\n // No candidate servers that match the tags, error\n if(connection == null) {\n return new Error(\"No replica set members available for query\");\n }\n } else {\n connection = _roundRobin(this, tags);\n }\n } else if(finalReadPreference == ReadPreference.PRIMARY_PREFERRED) {\n // Check if there is a primary available and return that if possible\n connection = this.checkoutWriter();\n // If no connection available checkout a secondary\n if(connection == null) {\n // If we have tags, look for servers matching the specific tag\n if(tags != null && typeof tags == 'object') {\n // Get connection\n connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {\n // No candidate servers that match the tags, error\n if(connection == null) {\n return new Error(\"No replica set members available for query\");\n }\n } else {\n connection = _roundRobin(this, tags);\n }\n }\n } else if(finalReadPreference == ReadPreference.SECONDARY_PREFERRED) {\n // If we have tags, look for servers matching the specific tag\n if(this.strategyInstance != null) {\n connection = this.strategyInstance.checkoutConnection(tags);\n // No candidate servers that match the tags, error\n if(connection == null || connection instanceof Error) {\n // No secondary server avilable, attemp to checkout a primary server\n connection = this.checkoutWriter();\n // If no connection return an error\n if(connection == null) {\n var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;\n connection = new Error(\"No replica set member available for query with ReadPreference \" + preferenceName + \" and tags \" + JSON.stringify(tags));\n // return new Error(\"No replica set members available for query\");\n }\n }\n } else if(tags != null && typeof tags == 'object') {\n // Get connection\n connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {\n // No candidate servers that match the tags, error\n if(connection == null) {\n // No secondary server avilable, attemp to checkout a primary server\n connection = this.checkoutWriter();\n // If no connection return an error\n if(connection == null) {\n var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;\n connection = new Error(\"No replica set member available for query with ReadPreference \" + preferenceName + \" and tags \" + JSON.stringify(tags));\n // return new Error(\"No replica set members available for query\");\n }\n }\n }\n } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance != null) {\n connection = this.strategyInstance.checkoutConnection(tags);\n } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance == null) {\n return new Error(\"A strategy for calculating nearness must be enabled such as ping or statistical\");\n } else if(finalReadPreference == ReadPreference.SECONDARY && Object.keys(this._state.secondaries).length == 0) {\n if(tags != null && typeof tags == 'object') {\n var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;\n connection = new Error(\"No replica set member available for query with ReadPreference \" + preferenceName + \" and tags \" + JSON.stringify(tags));\n } else {\n connection = new Error(\"No replica set secondary available for query with ReadPreference SECONDARY\");\n }\n } else {\n connection = this.checkoutWriter();\n }\n\n // Return the connection\n return connection;\n}\n\n/**\n * Pick a secondary using round robin\n *\n * @ignore\n */\nfunction _roundRobin (replset, tags) {\n var keys = Object.keys(replset._state.secondaries);\n var key = keys[replset._currentServerChoice++ % keys.length];\n\n var conn = null != replset._state.secondaries[key]\n ? replset._state.secondaries[key].checkoutReader()\n : null;\n\n // If connection is null fallback to first available secondary\n if (null == conn) {\n conn = pickFirstConnectedSecondary(replset, tags);\n }\n\n return conn;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.allRawConnections = function() {\n // Neeed to build a complete list of all raw connections, start with master server\n var allConnections = [];\n if(this._state.master == null) return [];\n // Get connection object\n var allMasterConnections = this._state.master.connectionPool.getAllConnections();\n // Add all connections to list\n allConnections = allConnections.concat(allMasterConnections);\n // If we have read secondary let's add all secondary servers\n if(Object.keys(this._state.secondaries).length > 0) {\n // Get all the keys\n var keys = Object.keys(this._state.secondaries);\n // For each of the secondaries grab the connections\n for(var i = 0; i < keys.length; i++) {\n // Get connection object\n var secondaryPoolConnections = this._state.secondaries[keys[i]].connectionPool.getAllConnections();\n // Add all connections to list\n allConnections = allConnections.concat(secondaryPoolConnections);\n }\n }\n\n // Return all the conections\n return allConnections;\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.enableRecordQueryStats = function(enable) {\n // Set the global enable record query stats\n this.recordQueryStats = enable;\n // Ensure all existing servers already have the flag set, even if the\n // connections are up already or we have not connected yet\n if(this._state != null && this._state.addresses != null) {\n var keys = Object.keys(this._state.addresses);\n // Iterate over all server instances and set the enableRecordQueryStats flag\n for(var i = 0; i < keys.length; i++) {\n this._state.addresses[keys[i]].enableRecordQueryStats(enable);\n }\n } else if(Array.isArray(this.servers)) {\n for(var i = 0; i < this.servers.length; i++) {\n this.servers[i].enableRecordQueryStats(enable);\n }\n }\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.disconnect = function(callback) {\n this.close(callback);\n}\n\n/**\n * @ignore\n */\nReplSet.prototype.close = function(callback) {\n var self = this;\n // Disconnect\n this._serverState = 'disconnected';\n // Close all servers\n if(this._state && this._state.addresses) {\n var keys = Object.keys(this._state.addresses);\n // Iterate over all server instances\n for(var i = 0; i < keys.length; i++) {\n this._state.addresses[keys[i]].close();\n }\n }\n\n // If we have a strategy stop it\n if(this.strategyInstance) {\n this.strategyInstance.stop();\n }\n // Shut down HA if running connection\n if(this._haServer) this._haServer.close();\n\n // If it's a callback\n if(typeof callback == 'function') callback(null, null);\n}\n\n/**\n * Auto Reconnect property\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"autoReconnect\", { enumerable: true\n , get: function () {\n return true;\n }\n});\n\n/**\n * Get Read Preference method\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"readPreference\", { enumerable: true\n , get: function () {\n if(this._readPreference == null && this.readSecondary) {\n return ReadPreference.SECONDARY_PREFERRED;\n } else if(this._readPreference == null && !this.readSecondary) {\n return ReadPreference.PRIMARY;\n } else {\n return this._readPreference;\n }\n }\n});\n\n/**\n * Db Instances\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"dbInstances\", {enumerable:true\n , get: function() {\n var servers = this.allServerInstances();\n return servers.length > 0 ? servers[0].dbInstances : [];\n }\n})\n\n/**\n * Just make compatible with server.js\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"host\", { enumerable: true\n , get: function () {\n if (this.primary != null) return this.primary.host;\n }\n});\n\n/**\n * Just make compatible with server.js\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"port\", { enumerable: true\n , get: function () {\n if (this.primary != null) return this.primary.port;\n }\n});\n\n/**\n * Get status of read\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"read\", { enumerable: true\n , get: function () {\n return this.secondaries.length > 0 ? this.secondaries[0] : null;\n }\n});\n\n/**\n * Get list of secondaries\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"secondaries\", {enumerable: true\n , get: function() {\n var keys = Object.keys(this._state.secondaries);\n var array = new Array(keys.length);\n // Convert secondaries to array\n for(var i = 0; i < keys.length; i++) {\n array[i] = this._state.secondaries[keys[i]];\n }\n return array;\n }\n});\n\n/**\n * Get list of all secondaries including passives\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"allSecondaries\", {enumerable: true\n , get: function() {\n return this.secondaries.concat(this.passives);\n }\n});\n\n/**\n * Get list of arbiters\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"arbiters\", {enumerable: true\n , get: function() {\n var keys = Object.keys(this._state.arbiters);\n var array = new Array(keys.length);\n // Convert arbiters to array\n for(var i = 0; i < keys.length; i++) {\n array[i] = this._state.arbiters[keys[i]];\n }\n return array;\n }\n});\n\n/**\n * Get list of passives\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"passives\", {enumerable: true\n , get: function() {\n var keys = Object.keys(this._state.passives);\n var array = new Array(keys.length);\n // Convert arbiters to array\n for(var i = 0; i < keys.length; i++) {\n array[i] = this._state.passives[keys[i]];\n }\n return array;\n }\n});\n\n/**\n * Master connection property\n * @ignore\n */\nObject.defineProperty(ReplSet.prototype, \"primary\", { enumerable: true\n , get: function () {\n return this._state != null ? this._state.master : null;\n }\n});\n\n/**\n * @ignore\n */\n// Backward compatibility\nexports.ReplSetServers = ReplSet;\n\n});","sourceLength":50179,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/repl_set.js (lines: 1473)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":521,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[298]}}
{"seq":194,"request_seq":521,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/strategies/ping_strategy.js","id":298,"lineOffset":0,"columnOffset":0,"lineCount":292,"source":"(function (exports, require, module, __filename, __dirname) { var Server = require(\"../server\").Server\n , format = require('util').format;\n\n// The ping strategy uses pings each server and records the\n// elapsed time for the server so it can pick a server based on lowest\n// return time for the db command {ping:true}\nvar PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) {\n this.replicaset = replicaset;\n this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS;\n this.state = 'disconnected';\n this.pingInterval = 5000;\n // Class instance\n this.Db = require(\"../../db\").Db;\n // Active db connections\n this.dbs = {};\n // Logger api\n this.Logger = null;\n}\n\n// Starts any needed code\nPingStrategy.prototype.start = function(callback) {\n // already running?\n if ('connected' == this.state) return;\n\n this.state = 'connected';\n\n // Start ping server\n this._pingServer(callback);\n}\n\n// Stops and kills any processes running\nPingStrategy.prototype.stop = function(callback) {\n // Stop the ping process\n this.state = 'disconnected';\n\n // Stop all the server instances\n for(var key in this.dbs) {\n this.dbs[key].close();\n }\n\n // optional callback\n callback && callback(null, null);\n}\n\nPingStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) {\n // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS\n // Create a list of candidat servers, containing the primary if available\n var candidateServers = [];\n var self = this;\n\n // If we have not provided a list of candidate servers use the default setup\n if(!Array.isArray(secondaryCandidates)) {\n candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];\n // Add all the secondaries\n var keys = Object.keys(this.replicaset._state.secondaries);\n for(var i = 0; i < keys.length; i++) {\n candidateServers.push(this.replicaset._state.secondaries[keys[i]])\n }\n } else {\n candidateServers = secondaryCandidates;\n }\n\n // Final list of eligable server\n var finalCandidates = [];\n\n // If we have tags filter by tags\n if(tags != null && typeof tags == 'object') {\n // If we have an array or single tag selection\n var tagObjects = Array.isArray(tags) ? tags : [tags];\n // Iterate over all tags until we find a candidate server\n for(var _i = 0; _i < tagObjects.length; _i++) {\n // Grab a tag object\n var tagObject = tagObjects[_i];\n // Matching keys\n var matchingKeys = Object.keys(tagObject);\n // Remove any that are not tagged correctly\n for(var i = 0; i < candidateServers.length; i++) {\n var server = candidateServers[i];\n // If we have tags match\n if(server.tags != null) {\n var matching = true;\n\n // Ensure we have all the values\n for(var j = 0; j < matchingKeys.length; j++) {\n if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {\n matching = false;\n break;\n }\n }\n\n // If we have a match add it to the list of matching servers\n if(matching) {\n finalCandidates.push(server);\n }\n }\n }\n }\n } else {\n // Final array candidates\n var finalCandidates = candidateServers;\n }\n\n // Sort by ping time\n finalCandidates.sort(function(a, b) {\n return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs'];\n });\n\n if(0 === finalCandidates.length)\n return new Error(\"No replica set members available for query\");\n\n // find lowest server with a ping time\n var lowest = finalCandidates.filter(function (server) {\n return undefined != server.runtimeStats.pingMs;\n })[0];\n\n if(!lowest) {\n lowest = finalCandidates[0];\n }\n\n // convert to integer\n var lowestPing = lowest.runtimeStats.pingMs | 0;\n \n // determine acceptable latency\n var acceptable = lowestPing + this.secondaryAcceptableLatencyMS;\n\n // remove any server responding slower than acceptable\n var len = finalCandidates.length;\n while(len--) {\n if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) {\n finalCandidates.splice(len, 1);\n }\n }\n\n if(self.logger && self.logger.debug) { \n self.logger.debug(\"Ping strategy selection order for tags\", tags);\n finalCandidates.forEach(function(c) {\n self.logger.debug(format(\"%s:%s = %s ms\", c.host, c.port, c.runtimeStats['pingMs']), null);\n }) \n }\n\n // If no candidates available return an error\n if(finalCandidates.length == 0)\n return new Error(\"No replica set members available for query\");\n\n // Pick a random acceptable server\n var connection = finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();\n if(self.logger && self.logger.debug) { \n if(connection)\n self.logger.debug(\"picked server %s:%s\", connection.socketOptions.host, connection.socketOptions.port);\n }\n return connection;\n}\n\nPingStrategy.prototype._pingServer = function(callback) {\n var self = this;\n\n // Ping server function\n var pingFunction = function() {\n if(self.state == 'disconnected') return;\n\n // Create a list of all servers we can send the ismaster command to\n var allServers = self.replicaset._state.master != null ? [self.replicaset._state.master] : [];\n\n // Secondary keys\n var keys = Object.keys(self.replicaset._state.secondaries);\n // Add all secondaries\n for(var i = 0; i < keys.length; i++) {\n allServers.push(self.replicaset._state.secondaries[keys[i]]);\n }\n\n // Number of server entries\n var numberOfEntries = allServers.length;\n\n // We got keys\n for(var i = 0; i < allServers.length; i++) {\n\n // We got a server instance\n var server = allServers[i];\n\n // Create a new server object, avoid using internal connections as they might\n // be in an illegal state\n new function(serverInstance) {\n var _db = self.dbs[serverInstance.host + \":\" + serverInstance.port];\n // If we have a db\n if(_db != null) {\n // Startup time of the command\n var startTime = Date.now();\n\n // Execute ping command in own scope\n var _ping = function(__db, __serverInstance) {\n // Execute ping on this connection\n __db.executeDbCommand({ping:1}, {failFast:true}, function(err) {\n if(err) {\n delete self.dbs[__db.serverConfig.host + \":\" + __db.serverConfig.port];\n __db.close();\n return done();\n }\n\n if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {\n __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;\n }\n\n done();\n }); \n };\n // Ping\n _ping(_db, serverInstance);\n } else {\n // Create a new master connection\n var _server = new Server(serverInstance.host, serverInstance.port, {\n auto_reconnect: false,\n returnIsMasterResults: true,\n slaveOk: true,\n poolSize: 1,\n socketOptions: { connectTimeoutMS: self.replicaset._connectTimeoutMS },\n ssl: self.replicaset.ssl,\n sslValidate: self.replicaset.sslValidate,\n sslCA: self.replicaset.sslCA,\n sslCert: self.replicaset.sslCert,\n sslKey: self.replicaset.sslKey,\n sslPass: self.replicaset.sslPass\n });\n\n // Create Db instance \n var _db = new self.Db(self.replicaset.db.databaseName, _server, { safe: true });\n _db.on(\"close\", function() {\n delete self.dbs[this.serverConfig.host + \":\" + this.serverConfig.port];\n })\n\n var _ping = function(__db, __serverInstance) {\n if(self.state == 'disconnected') {\n self.stop();\n return;\n }\n\n __db.open(function(err, db) { \n if(self.state == 'disconnected' && __db != null) {\n return __db.close();\n }\n\n if(err) {\n delete self.dbs[__db.serverConfig.host + \":\" + __db.serverConfig.port];\n __db.close();\n return done();\n }\n\n // Save instance\n self.dbs[__db.serverConfig.host + \":\" + __db.serverConfig.port] = __db;\n\n // Startup time of the command\n var startTime = Date.now();\n\n // Execute ping on this connection\n __db.executeDbCommand({ping:1}, {failFast:true}, function(err) {\n if(err) {\n delete self.dbs[__db.serverConfig.host + \":\" + __db.serverConfig.port];\n __db.close();\n return done();\n }\n\n if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {\n __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;\n }\n\n done();\n });\n }); \n };\n\n _ping(_db, serverInstance);\n }\n\n function done() {\n // Adjust the number of checks\n numberOfEntries--;\n\n // If we are done with all results coming back trigger ping again\n if(0 === numberOfEntries && 'connected' == self.state) {\n setTimeout(pingFunction, self.pingInterval);\n }\n }\n }(server);\n }\n }\n\n // Start pingFunction\n pingFunction();\n\n callback && callback(null);\n}\n\n});","sourceLength":9617,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/strategies/ping_strategy.js (lines: 292)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":522,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[301]}}
{"seq":195,"request_seq":522,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/strategies/statistics_strategy.js","id":301,"lineOffset":0,"columnOffset":0,"lineCount":82,"source":"(function (exports, require, module, __filename, __dirname) { // The Statistics strategy uses the measure of each end-start time for each\n// query executed against the db to calculate the mean, variance and standard deviation\n// and pick the server which the lowest mean and deviation\nvar StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) {\n this.replicaset = replicaset;\n // Logger api\n this.Logger = null; \n}\n\n// Starts any needed code\nStatisticsStrategy.prototype.start = function(callback) {\n callback && callback(null, null);\n}\n\nStatisticsStrategy.prototype.stop = function(callback) {\n callback && callback(null, null);\n}\n\nStatisticsStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) {\n // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS\n // Create a list of candidat servers, containing the primary if available\n var candidateServers = [];\n\n // If we have not provided a list of candidate servers use the default setup\n if(!Array.isArray(secondaryCandidates)) {\n candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];\n // Add all the secondaries\n var keys = Object.keys(this.replicaset._state.secondaries);\n for(var i = 0; i < keys.length; i++) {\n candidateServers.push(this.replicaset._state.secondaries[keys[i]])\n }\n } else {\n candidateServers = secondaryCandidates;\n }\n\n // Final list of eligable server\n var finalCandidates = [];\n\n // If we have tags filter by tags\n if(tags != null && typeof tags == 'object') {\n // If we have an array or single tag selection\n var tagObjects = Array.isArray(tags) ? tags : [tags];\n // Iterate over all tags until we find a candidate server\n for(var _i = 0; _i < tagObjects.length; _i++) {\n // Grab a tag object\n var tagObject = tagObjects[_i];\n // Matching keys\n var matchingKeys = Object.keys(tagObject);\n // Remove any that are not tagged correctly\n for(var i = 0; i < candidateServers.length; i++) {\n var server = candidateServers[i];\n // If we have tags match\n if(server.tags != null) {\n var matching = true;\n\n // Ensure we have all the values\n for(var j = 0; j < matchingKeys.length; j++) {\n if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {\n matching = false;\n break;\n }\n }\n\n // If we have a match add it to the list of matching servers\n if(matching) {\n finalCandidates.push(server);\n }\n }\n }\n }\n } else {\n // Final array candidates\n var finalCandidates = candidateServers;\n }\n\n // If no candidates available return an error\n if(finalCandidates.length == 0) return new Error(\"No replica set members available for query\");\n // Pick a random server\n return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();\n}\n\n});","sourceLength":3037,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/strategies/statistics_strategy.js (lines: 82)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":523,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[304]}}
{"seq":196,"request_seq":523,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js","id":304,"lineOffset":0,"columnOffset":0,"lineCount":117,"source":"(function (exports, require, module, __filename, __dirname) { var Db = require('./db').Db;\n\n/**\n * Create a new MongoClient instance.\n *\n * Options\n * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write\n * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)\n * - **fsync**, (Boolean, default:false) write waits for fsync before returning\n * - **journal**, (Boolean, default:false) write waits for journal sync before returning\n * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * - **native_parser** {Boolean, default:false}, use c++ bson parser.\n * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client.\n * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.\n * - **serializeFunctions** {Boolean, default:false}, serialize functions.\n * - **raw** {Boolean, default:false}, peform operations using raw bson buffers.\n * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution.\n * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries.\n * - **numberOfRetries** {Number, default:5}, number of retries off connection.\n * \n * Deprecated Options \n * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.\n *\n * @class Represents a MongoClient\n * @param {Object} serverConfig server config object.\n * @param {Object} [options] additional options for the collection.\n */\nfunction MongoClient(serverConfig, options) {\n options = options == null ? {} : options;\n // If no write concern is set set the default to w:1\n if(options != null && !options.journal && !options.w && !options.fsync) {\n options.w = 1;\n }\n\n // The internal db instance we are wrapping\n this._db = new Db('test', serverConfig, options);\n}\n\n/**\n * Initialize the database connection.\n *\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the connected mongoclient or null if an error occured.\n * @return {null}\n * @api public\n */\nMongoClient.prototype.open = function(callback) {\n // Self reference\n var self = this;\n\n this._db.open(function(err, db) {\n if(err) return callback(err, null);\n callback(null, self);\n })\n}\n\n/**\n * Close the current db connection, including all the child db instances. Emits close event if no callback is provided.\n *\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the close method or null if an error occured.\n * @return {null}\n * @api public\n */\nMongoClient.prototype.close = function(callback) {\n this._db.close(callback);\n}\n\n/**\n * Create a new Db instance sharing the current socket connections.\n *\n * @param {String} dbName the name of the database we want to use.\n * @return {Db} a db instance using the new database.\n * @api public\n */\nMongoClient.prototype.db = function(dbName) {\n return this._db.db(dbName);\n}\n\n/**\n * Connect to MongoDB using a url as documented at\n *\n * docs.mongodb.org/manual/reference/connection-string/\n *\n * Options\n * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication\n * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor**\n * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor**\n * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor**\n * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor**\n *\n * @param {String} url connection url for MongoDB.\n * @param {Object} [options] optional options for insert command\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.\n * @return {null}\n * @api public\n */\nMongoClient.connect = function(url, options, callback) {\n if(typeof options == 'function') {\n callback = options;\n options = {};\n }\n\n Db.connect(url, options, function(err, db) {\n if(err) return callback(err, null);\n\n if(db.options !== null && !db.options.safe && !db.options.journal \n && !db.options.w && !db.options.fsync && typeof db.options.w != 'number'\n && (db.options.safe == false && url.indexOf(\"safe=\") == -1)) {\n db.options.w = 1;\n }\n\n // Return the db\n callback(null, db);\n });\n}\n\nexports.MongoClient = MongoClient;\n});","sourceLength":5278,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/mongo_client.js (lines: 117)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":524,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[307]}}
{"seq":197,"request_seq":524,"type":"response","command":"scripts","success":true,"body":[{"handle":7,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js","id":307,"lineOffset":0,"columnOffset":0,"lineCount":2149,"source":"(function (exports, require, module, __filename, __dirname) { /**\n * Module dependencies.\n * @ignore\n */\nvar QueryCommand = require('./commands/query_command').QueryCommand,\n DbCommand = require('./commands/db_command').DbCommand,\n MongoReply = require('./responses/mongo_reply').MongoReply,\n Admin = require('./admin').Admin,\n Collection = require('./collection').Collection,\n Server = require('./connection/server').Server,\n ReplSet = require('./connection/repl_set').ReplSet,\n ReadPreference = require('./connection/read_preference').ReadPreference,\n Mongos = require('./connection/mongos').Mongos,\n Cursor = require('./cursor').Cursor,\n EventEmitter = require('events').EventEmitter,\n inherits = require('util').inherits,\n crypto = require('crypto'),\n timers = require('timers'),\n utils = require('./utils'),\n parse = require('./connection/url_parser').parse;\n\n// Set processor, setImmediate if 0.10 otherwise nextTick\nvar processor = timers.setImmediate ? timers.setImmediate : process.nextTick;\nprocessor = process.nextTick\n\n/**\n * Create a new Db instance.\n *\n * Options\n * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write\n * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)\n * - **fsync**, (Boolean, default:false) write waits for fsync before returning\n * - **journal**, (Boolean, default:false) write waits for journal sync before returning\n * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * - **native_parser** {Boolean, default:false}, use c++ bson parser.\n * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client.\n * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.\n * - **serializeFunctions** {Boolean, default:false}, serialize functions.\n * - **raw** {Boolean, default:false}, peform operations using raw bson buffers.\n * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution.\n * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries.\n * - **numberOfRetries** {Number, default:5}, number of retries off connection.\n * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**.\n * \n * Deprecated Options \n * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.\n *\n * @class Represents a Db\n * @param {String} databaseName name of the database.\n * @param {Object} serverConfig server config object.\n * @param {Object} [options] additional options for the collection.\n */\nfunction Db(databaseName, serverConfig, options) {\n if(!(this instanceof Db)) return new Db(databaseName, serverConfig, options);\n\n EventEmitter.call(this);\n this.databaseName = databaseName;\n this.serverConfig = serverConfig;\n this.options = options == null ? {} : options;\n // State to check against if the user force closed db\n this._applicationClosed = false;\n // Fetch the override flag if any\n var overrideUsedFlag = this.options['override_used_flag'] == null ? false : this.options['override_used_flag'];\n\n // Verify that nobody is using this config\n if(!overrideUsedFlag && this.serverConfig != null && typeof this.serverConfig == 'object' && this.serverConfig._isUsed && this.serverConfig._isUsed()) { \n throw new Error(\"A Server or ReplSet instance cannot be shared across multiple Db instances\");\n } else if(!overrideUsedFlag && typeof this.serverConfig == 'object'){\n // Set being used\n this.serverConfig._used = true;\n }\n\n // Ensure we have a valid db name\n validateDatabaseName(databaseName);\n\n // Contains all the connections for the db\n try {\n this.native_parser = this.options.native_parser;\n // The bson lib\n var bsonLib = this.bsonLib = this.options.native_parser ? require('bson').BSONNative : require('bson').BSONPure;\n // Fetch the serializer object\n var BSON = bsonLib.BSON;\n // Create a new instance\n this.bson = new BSON([bsonLib.Long, bsonLib.ObjectID, bsonLib.Binary, bsonLib.Code, bsonLib.DBRef, bsonLib.Symbol, bsonLib.Double, bsonLib.Timestamp, bsonLib.MaxKey, bsonLib.MinKey]);\n // Backward compatibility to access types\n this.bson_deserializer = bsonLib;\n this.bson_serializer = bsonLib;\n } catch (err) {\n // If we tried to instantiate the native driver\n var msg = \"Native bson parser not compiled, please compile \"\n + \"or avoid using native_parser=true\";\n throw Error(msg);\n }\n\n // Internal state of the server\n this._state = 'disconnected';\n\n this.pkFactory = this.options.pk == null ? bsonLib.ObjectID : this.options.pk;\n this.forceServerObjectId = this.options.forceServerObjectId != null ? this.options.forceServerObjectId : false;\n\n // Added safe\n this.safe = this.options.safe == null ? false : this.options.safe; \n\n // If we have not specified a \"safe mode\" we just print a warning to the console\n if(this.options.safe == null && this.options.w == null && this.options.journal == null && this.options.fsync == null) {\n console.log(\"========================================================================================\");\n console.log(\"= Please ensure that you set the default write concern for the database by setting =\");\n console.log(\"= one of the options =\");\n console.log(\"= =\");\n console.log(\"= w: (value of > -1 or the string 'majority'), where < 1 means =\");\n console.log(\"= no write acknowlegement =\");\n console.log(\"= journal: true/false, wait for flush to journal before acknowlegement =\");\n console.log(\"= fsync: true/false, wait for flush to file system before acknowlegement =\");\n console.log(\"= =\");\n console.log(\"= For backward compatibility safe is still supported and =\");\n console.log(\"= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =\");\n console.log(\"= the default value is false which means the driver receives does not =\");\n console.log(\"= return the information of the success/error of the insert/update/remove =\");\n console.log(\"= =\");\n console.log(\"= ex: new Db(new Server('localhost', 27017), {safe:false}) =\");\n console.log(\"= =\");\n console.log(\"= http://www.mongodb.org/display/DOCS/getLastError+Command =\");\n console.log(\"= =\");\n console.log(\"= The default of no acknowlegement will change in the very near future =\");\n console.log(\"= =\");\n console.log(\"= This message will disappear when the default safe is set on the driver Db =\");\n console.log(\"========================================================================================\");\n }\n\n // Internal states variables\n this.notReplied ={};\n this.isInitializing = true;\n this.auths = [];\n this.openCalled = false;\n\n // Command queue, keeps a list of incoming commands that need to be executed once the connection is up\n this.commands = [];\n\n // Set up logger\n this.logger = this.options.logger != null\n && (typeof this.options.logger.debug == 'function')\n && (typeof this.options.logger.error == 'function')\n && (typeof this.options.logger.log == 'function')\n ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};\n // Allow slaveOk\n this.slaveOk = this.options[\"slave_ok\"] == null ? false : this.options[\"slave_ok\"];\n\n var self = this;\n // Associate the logger with the server config\n this.serverConfig.logger = this.logger;\n if(this.serverConfig.strategyInstance) this.serverConfig.strategyInstance.logger = this.logger;\n this.tag = new Date().getTime();\n // Just keeps list of events we allow\n this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[]};\n\n // Controls serialization options\n this.serializeFunctions = this.options.serializeFunctions != null ? this.options.serializeFunctions : false;\n\n // Raw mode\n this.raw = this.options.raw != null ? this.options.raw : false;\n\n // Record query stats\n this.recordQueryStats = this.options.recordQueryStats != null ? this.options.recordQueryStats : false;\n\n // If we have server stats let's make sure the driver objects have it enabled\n if(this.recordQueryStats == true) {\n this.serverConfig.enableRecordQueryStats(true);\n }\n\n // Retry information\n this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 1000;\n this.numberOfRetries = this.options.numberOfRetries != null ? this.options.numberOfRetries : 60;\n\n // Set default read preference if any\n this.readPreference = this.options.readPreference;\n};\n\n/**\n * @ignore\n */\nfunction validateDatabaseName(databaseName) {\n if(typeof databaseName !== 'string') throw new Error(\"database name must be a string\");\n if(databaseName.length === 0) throw new Error(\"database name cannot be the empty string\");\n\n var invalidChars = [\" \", \".\", \"$\", \"/\", \"\\\\\"];\n for(var i = 0; i < invalidChars.length; i++) {\n if(databaseName.indexOf(invalidChars[i]) != -1) throw new Error(\"database names cannot contain the character '\" + invalidChars[i] + \"'\");\n }\n}\n\n/**\n * @ignore\n */\ninherits(Db, EventEmitter);\n\n/**\n * Initialize the database connection.\n *\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the index information or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.open = function(callback) {\n var self = this;\n\n // Check that the user has not called this twice\n if(this.openCalled) {\n // Close db\n this.close();\n // Throw error\n throw new Error(\"db object already connecting, open cannot be called multiple times\");\n }\n\n // If we have a specified read preference\n if(this.readPreference != null) this.serverConfig.setReadPreference(this.readPreference);\n\n // Set that db has been opened\n this.openCalled = true;\n\n // Set the status of the server\n self._state = 'connecting';\n // Set up connections\n if(self.serverConfig instanceof Server || self.serverConfig instanceof ReplSet || self.serverConfig instanceof Mongos) {\n self.serverConfig.connect(self, {firstCall: true}, function(err, result) {\n if(err != null) {\n // Set that db has been closed\n self.openCalled = false;\n // Return error from connection\n return callback(err, null);\n }\n // Set the status of the server\n self._state = 'connected';\n // If we have queued up commands execute a command to trigger replays\n if(self.commands.length > 0) _execute_queued_command(self);\n // Callback\n return callback(null, self);\n });\n } else {\n return callback(Error(\"Server parameter must be of type Server, ReplSet or Mongos\"), null);\n }\n};\n\n// Execute any baked up commands\nvar _execute_queued_command = function(self) {\n // Execute any backed up commands\n processor(function() {\n // Execute any backed up commands\n while(self.commands.length > 0) {\n // Fetch the command\n var command = self.commands.shift();\n // Execute based on type\n if(command['type'] == 'query') {\n __executeQueryCommand(self, command['db_command'], command['options'], command['callback']);\n } else if(command['type'] == 'insert') {\n __executeInsertCommand(self, command['db_command'], command['options'], command['callback']);\n }\n }\n }); \n}\n\n/**\n * Create a new Db instance sharing the current socket connections.\n *\n * @param {String} dbName the name of the database we want to use.\n * @return {Db} a db instance using the new database.\n * @api public\n */\nDb.prototype.db = function(dbName) {\n // Copy the options and add out internal override of the not shared flag\n var options = {};\n for(var key in this.options) {\n options[key] = this.options[key];\n }\n\n // Add override flag\n options['override_used_flag'] = true;\n // Create a new db instance\n var newDbInstance = new Db(dbName, this.serverConfig, options);\n //copy over any auths, we may need them for reconnecting\n if (this.serverConfig.db) {\n newDbInstance.auths = this.serverConfig.db.auths;\n }\n // Add the instance to the list of approved db instances\n var allServerInstances = this.serverConfig.allServerInstances();\n // Add ourselves to all server callback instances\n for(var i = 0; i < allServerInstances.length; i++) {\n var server = allServerInstances[i];\n server.dbInstances.push(newDbInstance);\n }\n // Return new db object\n return newDbInstance; \n}\n\n/**\n * Close the current db connection, including all the child db instances. Emits close event if no callback is provided.\n *\n * @param {Boolean} [forceClose] connection can never be reused.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.close = function(forceClose, callback) {\n var self = this;\n // Ensure we force close all connections\n this._applicationClosed = false;\n\n if(typeof forceClose == 'function') {\n callback = forceClose;\n } else if(typeof forceClose == 'boolean') {\n this._applicationClosed = forceClose;\n }\n\n // Remove all listeners and close the connection\n this.serverConfig.close(function(err, result) {\n // Emit the close event\n if(typeof callback !== 'function') self.emit(\"close\");\n\n // Emit close event across all db instances sharing the sockets\n var allServerInstances = self.serverConfig.allServerInstances();\n // Fetch the first server instance\n if(Array.isArray(allServerInstances) && allServerInstances.length > 0) {\n var server = allServerInstances[0];\n // For all db instances signal all db instances\n if(Array.isArray(server.dbInstances) && server.dbInstances.length > 1) {\n for(var i = 0; i < server.dbInstances.length; i++) {\n var dbInstance = server.dbInstances[i];\n // Check if it's our current db instance and skip if it is\n if(dbInstance.databaseName !== self.databaseName && dbInstance.tag !== self.tag) {\n server.dbInstances[i].emit(\"close\");\n }\n }\n }\n }\n\n // Remove all listeners\n self.removeAllEventListeners();\n // You can reuse the db as everything is shut down\n self.openCalled = false;\n // If we have a callback call it\n if(callback) callback(err, result);\n });\n};\n\n/**\n * Access the Admin database\n *\n * @param {Function} [callback] returns the results.\n * @return {Admin} the admin db object.\n * @api public\n */\nDb.prototype.admin = function(callback) {\n if(callback == null) return new Admin(this);\n callback(null, new Admin(this));\n};\n\n/**\n * Returns a cursor to all the collection information.\n *\n * @param {String} [collectionName] the collection name we wish to retrieve the information from.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the options or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.collectionsInfo = function(collectionName, callback) {\n if(callback == null && typeof collectionName == 'function') { callback = collectionName; collectionName = null; }\n // Create selector\n var selector = {};\n // If we are limiting the access to a specific collection name\n if(collectionName != null) selector.name = this.databaseName + \".\" + collectionName;\n\n // Return Cursor\n // callback for backward compatibility\n if(callback) {\n callback(null, new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector));\n } else {\n return new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector);\n }\n};\n\n/**\n * Get the list of all collection names for the specified db\n *\n * Options\n * - **namesOnly** {String, default:false}, Return only the full collection namespace.\n *\n * @param {String} [collectionName] the collection name we wish to filter by.\n * @param {Object} [options] additional options during update.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collection names or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.collectionNames = function(collectionName, options, callback) {\n var self = this;\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n collectionName = args.length ? args.shift() : null;\n options = args.length ? args.shift() : {};\n\n // Ensure no breaking behavior\n if(collectionName != null && typeof collectionName == 'object') {\n options = collectionName;\n collectionName = null;\n }\n\n // Let's make our own callback to reuse the existing collections info method\n self.collectionsInfo(collectionName, function(err, cursor) {\n if(err != null) return callback(err, null);\n\n cursor.toArray(function(err, documents) {\n if(err != null) return callback(err, null);\n\n // List of result documents that have been filtered\n var filtered_documents = documents.filter(function(document) {\n return !(document.name.indexOf(self.databaseName) == -1 || document.name.indexOf('$') != -1);\n });\n\n // If we are returning only the names\n if(options.namesOnly) {\n filtered_documents = filtered_documents.map(function(document) { return document.name });\n }\n\n // Return filtered items\n callback(null, filtered_documents);\n });\n });\n};\n\n/**\n * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can\n * can use it without a callback in the following way. var collection = db.collection('mycollection');\n *\n * Options\n* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write\n * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)\n * - **fsync**, (Boolean, default:false) write waits for fsync before returning\n * - **journal**, (Boolean, default:false) write waits for journal sync before returning\n * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.\n * - **raw** {Boolean, default:false}, perform all operations using raw bson objects.\n * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.\n * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * - **strict**, (Boolean, default:false) throws and error if the collection does not exist\n * \n * Deprecated Options \n * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.\n *\n * @param {String} collectionName the collection name we wish to access.\n * @param {Object} [options] returns option results.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collection or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.collection = function(collectionName, options, callback) {\n var self = this;\n if(typeof options === \"function\") { callback = options; options = {}; }\n // Execute safe\n\n if(options && (options.strict)) {\n self.collectionNames(collectionName, function(err, collections) {\n if(err != null) return callback(err, null);\n\n if(collections.length == 0) {\n return callback(new Error(\"Collection \" + collectionName + \" does not exist. Currently in safe mode.\"), null);\n } else {\n try {\n var collection = new Collection(self, collectionName, self.pkFactory, options);\n } catch(err) {\n return callback(err, null);\n }\n return callback(null, collection);\n }\n });\n } else {\n try {\n var collection = new Collection(self, collectionName, self.pkFactory, options);\n } catch(err) {\n if(callback == null) {\n throw err;\n } else {\n return callback(err, null);\n }\n }\n\n // If we have no callback return collection object\n return callback == null ? collection : callback(null, collection);\n }\n};\n\n/**\n * Fetch all collections for the current db.\n *\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collections or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.collections = function(callback) {\n var self = this;\n // Let's get the collection names\n self.collectionNames(function(err, documents) {\n if(err != null) return callback(err, null);\n var collections = [];\n documents.forEach(function(document) {\n collections.push(new Collection(self, document.name.replace(self.databaseName + \".\", ''), self.pkFactory));\n });\n // Return the collection objects\n callback(null, collections);\n });\n};\n\n/**\n * Evaluate javascript on the server\n *\n * Options\n * - **nolock** {Boolean, default:false}, Tell MongoDB not to block on the evaulation of the javascript.\n *\n * @param {Code} code javascript to execute on server.\n * @param {Object|Array} [parameters] the parameters for the call.\n * @param {Object} [options] the options\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from eval or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.eval = function(code, parameters, options, callback) {\n // Unpack calls\n var args = Array.prototype.slice.call(arguments, 1);\n callback = args.pop();\n parameters = args.length ? args.shift() : parameters;\n options = args.length ? args.shift() : {};\n\n var finalCode = code;\n var finalParameters = [];\n // If not a code object translate to one\n if(!(finalCode instanceof this.bsonLib.Code)) {\n finalCode = new this.bsonLib.Code(finalCode);\n }\n\n // Ensure the parameters are correct\n if(parameters != null && parameters.constructor != Array && typeof parameters !== 'function') {\n finalParameters = [parameters];\n } else if(parameters != null && parameters.constructor == Array && typeof parameters !== 'function') {\n finalParameters = parameters;\n }\n\n // Create execution selector\n var selector = {'$eval':finalCode, 'args':finalParameters};\n // Check if the nolock parameter is passed in\n if(options['nolock']) {\n selector['nolock'] = options['nolock'];\n }\n\n // Set primary read preference\n options.readPreference = ReadPreference.PRIMARY;\n\n // Execute the eval\n this.collection(DbCommand.SYSTEM_COMMAND_COLLECTION).findOne(selector, options, function(err, result) {\n if(err) return callback(err);\n\n if(result && result.ok == 1) {\n callback(null, result.retval);\n } else if(result) {\n callback(new Error(\"eval failed: \" + result.errmsg), null); return;\n } else {\n callback(err, result);\n }\n });\n};\n\n/**\n * Dereference a dbref, against a db\n *\n * @param {DBRef} dbRef db reference object we wish to resolve.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dereference or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.dereference = function(dbRef, callback) {\n var db = this;\n // If we have a db reference then let's get the db first\n if(dbRef.db != null) db = this.db(dbRef.db);\n // Fetch the collection and find the reference\n var collection = db.collection(dbRef.namespace);\n collection.findOne({'_id':dbRef.oid}, function(err, result) {\n callback(err, result);\n });\n};\n\n/**\n * Logout user from server, fire off on all connections and remove all auth info\n *\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.logout = function(options, callback) {\n var self = this;\n // Unpack calls\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n\n // Number of connections we need to logout from\n var numberOfConnections = this.serverConfig.allRawConnections().length;\n\n // Let's generate the logout command object\n var logoutCommand = DbCommand.logoutCommand(self, {logout:1}, options);\n self._executeQueryCommand(logoutCommand, {onAll:true}, function(err, result) {\n // Count down\n numberOfConnections = numberOfConnections - 1;\n // Work around the case where the number of connections are 0\n if(numberOfConnections <= 0 && typeof callback == 'function') {\n var internalCallback = callback;\n callback = null;\n // Reset auth\n self.auths = [];\n // Handle any errors\n if(err == null && result.documents[0].ok == 1) {\n internalCallback(null, true);\n } else {\n err != null ? internalCallback(err, false) : internalCallback(new Error(result.documents[0].errmsg), false);\n }\n }\n });\n}\n\n/**\n * Authenticate a user against the server.\n *\n * Options\n * - **authSource** {String}, The database that the credentials are for,\n * different from the name of the current DB, for example admin\n *\n * @param {String} username username.\n * @param {String} password password.\n * @param {Object} [options] the options\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authentication or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.authenticate = function(username, password, options, callback) {\n var self = this;\n\n if (typeof callback === 'undefined') {\n callback = options;\n options = {};\n }\n // the default db to authenticate against is 'this'\n // if authententicate is called from a retry context, it may be another one, like admin\n var authdb = options.authdb ? options.authdb : self.databaseName;\n authdb = options.authSource ? options.authSource : authdb;\n // Push the new auth if we have no previous record\n \n var numberOfConnections = 0;\n var errorObject = null;\n\n if(options['connection'] != null) {\n //if a connection was explicitly passed on options, then we have only one...\n numberOfConnections = 1;\n } else {\n // Get the amount of connections in the pool to ensure we have authenticated all comments\n numberOfConnections = this.serverConfig.allRawConnections().length;\n options['onAll'] = true;\n }\n\n // Execute all four\n this._executeQueryCommand(DbCommand.createGetNonceCommand(self), options, function(err, result, connection) {\n // Execute on all the connections\n if(err == null) {\n // Nonce used to make authentication request with md5 hash\n var nonce = result.documents[0].nonce;\n // Execute command\n self._executeQueryCommand(DbCommand.createAuthenticationCommand(self, username, password, nonce, authdb), {connection:connection}, function(err, result) {\n // Count down\n numberOfConnections = numberOfConnections - 1;\n // Ensure we save any error\n if(err) {\n errorObject = err;\n } else if(result.documents[0].err != null || result.documents[0].errmsg != null){\n errorObject = utils.toError(result.documents[0]);\n }\n\n // Work around the case where the number of connections are 0\n if(numberOfConnections <= 0 && typeof callback == 'function') {\n var internalCallback = callback;\n callback = null;\n\n if(errorObject == null && result.documents[0].ok == 1) {\n // We authenticated correctly save the credentials\n self.auths = [{'username':username, 'password':password, 'authdb': authdb}];\n // Return callback\n internalCallback(errorObject, true);\n } else {\n internalCallback(errorObject, false);\n }\n }\n });\n }\n });\n};\n\n/**\n * Add a user to the database.\n *\n * Options\n * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write\n * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)\n * - **fsync**, (Boolean, default:false) write waits for fsync before returning\n * - **journal**, (Boolean, default:false) write waits for journal sync before returning\n * \n * Deprecated Options \n * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.\n *\n * @param {String} username username.\n * @param {String} password password.\n * @param {Object} [options] additional options during update.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.addUser = function(username, password, options, callback) {\n var self = this;\n var args = Array.prototype.slice.call(arguments, 2);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n\n // Get the error options\n var errorOptions = _getWriteConcern(this, options, callback);\n errorOptions.w = errorOptions.w == null ? 1 : errorOptions.w;\n // Use node md5 generator\n var md5 = crypto.createHash('md5');\n // Generate keys used for authentication\n md5.update(username + \":mongo:\" + password);\n var userPassword = md5.digest('hex');\n // Fetch a user collection\n var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION);\n // Check if we are inserting the first user\n collection.count({}, function(err, count) {\n // We got an error (f.ex not authorized)\n if(err != null) return callback(err, null);\n // Check if the user exists and update i\n collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) {\n // We got an error (f.ex not authorized)\n if(err != null) return callback(err, null);\n // Add command keys\n var commandOptions = errorOptions;\n commandOptions.dbName = options['dbName'];\n commandOptions.upsert = true;\n\n // We have a user, let's update the password or upsert if not\n collection.update({user: username},{$set: {user: username, pwd: userPassword}}, commandOptions, function(err, results) {\n if(count == 0 && err) {\n callback(null, [{user:username, pwd:userPassword}]);\n } else if(err) {\n callback(err, null)\n } else {\n callback(null, [{user:username, pwd:userPassword}]);\n }\n });\n });\n });\n};\n\n/**\n * Remove a user from a database\n *\n * Options\n* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write\n * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)\n * - **fsync**, (Boolean, default:false) write waits for fsync before returning\n * - **journal**, (Boolean, default:false) write waits for journal sync before returning\n * \n * Deprecated Options \n * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.\n *\n * @param {String} username username.\n * @param {Object} [options] additional options during update.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.removeUser = function(username, options, callback) {\n var self = this;\n var args = Array.prototype.slice.call(arguments, 1);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n\n // Figure out the safe mode settings\n var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe;\n // Override with options passed in if applicable\n safe = options != null && options['safe'] != null ? options['safe'] : safe;\n // Ensure it's at least set to safe\n safe = safe == null ? {w: 1} : safe;\n\n // Fetch a user collection\n var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION);\n collection.findOne({user: username}, {dbName: options['dbName']}, function(err, user) {\n if(user != null) {\n // Add command keys\n var commandOptions = safe;\n commandOptions.dbName = options['dbName'];\n\n collection.remove({user: username}, commandOptions, function(err, result) {\n callback(err, true);\n });\n } else {\n callback(err, false);\n }\n });\n};\n\n/**\n * Creates a collection on a server pre-allocating space, need to create f.ex capped collections.\n *\n * Options\n* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write\n * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)\n * - **fsync**, (Boolean, default:false) write waits for fsync before returning\n * - **journal**, (Boolean, default:false) write waits for journal sync before returning\n * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.\n * - **raw** {Boolean, default:false}, perform all operations using raw bson objects.\n * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.\n * - **capped** {Boolean, default:false}, create a capped collection.\n * - **size** {Number}, the size of the capped collection in bytes.\n * - **max** {Number}, the maximum number of documents in the capped collection.\n * - **autoIndexId** {Boolean, default:true}, create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2.\n * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n * - **strict**, (Boolean, default:false) throws and error if collection already exists\n * \n * Deprecated Options \n * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.\n *\n * @param {String} collectionName the collection name we wish to access.\n * @param {Object} [options] returns option results.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from createCollection or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.createCollection = function(collectionName, options, callback) {\n var args = Array.prototype.slice.call(arguments, 1);\n callback = args.pop();\n options = args.length ? args.shift() : null;\n var self = this;\n\n // Figure out the safe mode settings\n var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe;\n // Override with options passed in if applicable\n safe = options != null && options['safe'] != null ? options['safe'] : safe;\n // Ensure it's at least set to safe\n safe = safe == null ? {w: 1} : safe;\n\n // Check if we have the name\n this.collectionNames(collectionName, function(err, collections) {\n if(err != null) return callback(err, null);\n\n var found = false;\n collections.forEach(function(collection) {\n if(collection.name == self.databaseName + \".\" + collectionName) found = true;\n });\n\n // If the collection exists either throw an exception (if db in safe mode) or return the existing collection\n if(found && options && options.strict) {\n return callback(new Error(\"Collection \" + collectionName + \" already exists. Currently in safe mode.\"), null);\n } else if(found){\n try {\n var collection = new Collection(self, collectionName, self.pkFactory, options);\n } catch(err) {\n return callback(err, null);\n }\n return callback(null, collection);\n }\n\n // Create a new collection and return it\n self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options), {read:false, safe:safe}, function(err, result) {\n var document = result.documents[0];\n // If we have no error let's return the collection\n if(err == null && document.ok == 1) {\n try {\n var collection = new Collection(self, collectionName, self.pkFactory, options);\n } catch(err) {\n return callback(err, null);\n }\n return callback(null, collection);\n } else {\n if (null == err) err = utils.toError(document);\n callback(err, null);\n }\n });\n });\n};\n\n/**\n * Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server.\n *\n * @param {Object} selector the command hash to send to the server, ex: {ping:1}.\n * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter.\n * @return {null}\n * @api public\n */\nDb.prototype.command = function(selector, options, callback) {\n var args = Array.prototype.slice.call(arguments, 1);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n\n // Set up the options\n var cursor = new Cursor(this\n , new Collection(this, DbCommand.SYSTEM_COMMAND_COLLECTION), selector, {}, {\n limit: -1, timeout: QueryCommand.OPTS_NO_CURSOR_TIMEOUT, dbName: options['dbName']\n });\n\n // Set read preference if we set one\n var readPreference = options['readPreference'] ? options['readPreference'] : false;\n\n // Ensure only commands who support read Prefrences are exeuted otherwise override and use Primary\n if(readPreference != false) {\n if(selector['group'] || selector['aggregate'] || selector['collStats'] || selector['dbStats']\n || selector['count'] || selector['distinct'] || selector['geoNear'] || selector['geoSearch'] || selector['geoWalk']\n || (selector['mapreduce'] && selector.out == 'inline')) {\n // Set the read preference\n cursor.setReadPreference(readPreference);\n } else {\n cursor.setReadPreference(ReadPreference.PRIMARY);\n }\n }\n\n // Return the next object\n cursor.nextObject(callback);\n};\n\n/**\n * Drop a collection from the database, removing it permanently. New accesses will create a new collection.\n *\n * @param {String} collectionName the name of the collection we wish to drop.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropCollection or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.dropCollection = function(collectionName, callback) {\n var self = this;\n callback || (callback = function(){});\n\n // Drop the collection\n this._executeQueryCommand(DbCommand.createDropCollectionCommand(this, collectionName), function(err, result) {\n if(err == null && result.documents[0].ok == 1) {\n return callback(null, true);\n }\n\n if(null == err) err = utils.toError(result.documents[0]);\n callback(err, null);\n });\n};\n\n/**\n * Rename a collection.\n * \n * Options\n * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists.\n *\n * @param {String} fromCollection the name of the current collection we wish to rename.\n * @param {String} toCollection the new name of the collection.\n * @param {Object} [options] returns option results.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from renameCollection or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {\n var self = this;\n\n if(typeof options == 'function') {\n callback = options;\n options = {}\n }\n\n callback || (callback = function(){});\n // Execute the command, return the new renamed collection if successful\n this._executeQueryCommand(DbCommand.createRenameCollectionCommand(this, fromCollection, toCollection, options), function(err, result) {\n if(err == null && result.documents[0].ok == 1) {\n return callback(null, new Collection(self, toCollection, self.pkFactory));\n }\n\n if(null == err) err = utils.toError(result.documents[0]);\n callback(err, null);\n });\n};\n\n/**\n * Return last error message for the given connection, note options can be combined.\n *\n * Options\n * - **fsync** {Boolean, default:false}, option forces the database to fsync all files before returning.\n * - **j** {Boolean, default:false}, awaits the journal commit before returning, > MongoDB 2.0.\n * - **w** {Number}, until a write operation has been replicated to N servers.\n * - **wtimeout** {Number}, number of miliseconds to wait before timing out.\n *\n * Connection Options\n * - **connection** {Connection}, fire the getLastError down a specific connection.\n *\n * @param {Object} [options] returns option results.\n * @param {Object} [connectionOptions] returns option results.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from lastError or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.lastError = function(options, connectionOptions, callback) {\n // Unpack calls\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n connectionOptions = args.length ? args.shift() : {};\n\n this._executeQueryCommand(DbCommand.createGetLastErrorCommand(options, this), connectionOptions, function(err, error) {\n callback(err, error && error.documents);\n });\n};\n\n/**\n * Legacy method calls.\n *\n * @ignore\n * @api private\n */\nDb.prototype.error = Db.prototype.lastError;\nDb.prototype.lastStatus = Db.prototype.lastError;\n\n/**\n * Return all errors up to the last time db reset_error_history was called.\n *\n * Options\n * - **connection** {Connection}, fire the getLastError down a specific connection.\n *\n * @param {Object} [options] returns option results.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from previousErrors or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.previousErrors = function(options, callback) {\n // Unpack calls\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n\n this._executeQueryCommand(DbCommand.createGetPreviousErrorsCommand(this), options, function(err, error) {\n callback(err, error.documents);\n });\n};\n\n/**\n * Runs a command on the database.\n * @ignore\n * @api private\n */\nDb.prototype.executeDbCommand = function(command_hash, options, callback) {\n if(callback == null) { callback = options; options = {}; }\n this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, command_hash, options), options, callback);\n};\n\n/**\n * Runs a command on the database as admin.\n * @ignore\n * @api private\n */\nDb.prototype.executeDbAdminCommand = function(command_hash, options, callback) {\n if(callback == null) { callback = options; options = {}; }\n this._executeQueryCommand(DbCommand.createAdminDbCommand(this, command_hash), options, callback);\n};\n\n/**\n * Resets the error history of the mongo instance.\n *\n * Options\n * - **connection** {Connection}, fire the getLastError down a specific connection.\n *\n * @param {Object} [options] returns option results.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from resetErrorHistory or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.resetErrorHistory = function(options, callback) {\n // Unpack calls\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n\n this._executeQueryCommand(DbCommand.createResetErrorHistoryCommand(this), options, function(err, error) {\n callback(err, error.documents);\n });\n};\n\n/**\n * Creates an index on the collection.\n *\n * Options\n* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write\n * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)\n * - **fsync**, (Boolean, default:false) write waits for fsync before returning\n * - **journal**, (Boolean, default:false) write waits for journal sync before returning\n * - **unique** {Boolean, default:false}, creates an unique index.\n * - **sparse** {Boolean, default:false}, creates a sparse index.\n * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible.\n * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value\n * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates.\n * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates.\n * - **v** {Number}, specify the format version of the indexes.\n * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)\n * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)\n * \n * Deprecated Options \n * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.\n *\n *\n * @param {String} collectionName name of the collection to create the index on.\n * @param {Object} fieldOrSpec fieldOrSpec that defines the index.\n * @param {Object} [options] additional options during update.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from createIndex or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.createIndex = function(collectionName, fieldOrSpec, options, callback) {\n var self = this;\n var args = Array.prototype.slice.call(arguments, 2);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n options = typeof callback === 'function' ? options : callback;\n options = options == null ? {} : options;\n\n // Get the error options\n var errorOptions = _getWriteConcern(this, options, callback);\n // Create command\n var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options);\n // Default command options\n var commandOptions = {};\n\n // If we have error conditions set handle them\n if(_hasWriteConcern(errorOptions) && typeof callback == 'function') {\n // Insert options\n commandOptions['read'] = false;\n // If we have safe set set async to false\n if(errorOptions == null) commandOptions['async'] = true;\n\n // Set safe option\n commandOptions['safe'] = errorOptions;\n // If we have an error option\n if(typeof errorOptions == 'object') {\n var keys = Object.keys(errorOptions);\n for(var i = 0; i < keys.length; i++) {\n commandOptions[keys[i]] = errorOptions[keys[i]];\n }\n }\n\n // Execute insert command\n this._executeInsertCommand(command, commandOptions, function(err, result) {\n if(err != null) return callback(err, null);\n\n result = result && result.documents;\n if (result[0].err) {\n callback(utils.toError(result[0]));\n } else {\n callback(null, command.documents[0].name);\n }\n });\n } else if(_hasWriteConcern(errorOptions) && callback == null) {\n throw new Error(\"Cannot use a writeConcern without a provided callback\");\n } else {\n // Execute insert command\n var result = this._executeInsertCommand(command, commandOptions);\n // If no callback just return\n if(!callback) return;\n // If error return error\n if(result instanceof Error) {\n return callback(result);\n }\n // Otherwise just return\n return callback(null, null);\n }\n};\n\n/**\n * Ensures that an index exists, if it does not it creates it\n *\n * Options\n* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write\n * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)\n * - **fsync**, (Boolean, default:false) write waits for fsync before returning\n * - **journal**, (Boolean, default:false) write waits for journal sync before returning\n * - **unique** {Boolean, default:false}, creates an unique index.\n * - **sparse** {Boolean, default:false}, creates a sparse index.\n * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible.\n * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value\n * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates.\n * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates.\n * - **v** {Number}, specify the format version of the indexes.\n * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)\n * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes)\n * \n * Deprecated Options \n * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.\n *\n * @param {String} collectionName name of the collection to create the index on.\n * @param {Object} fieldOrSpec fieldOrSpec that defines the index.\n * @param {Object} [options] additional options during update.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ensureIndex or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callback) {\n var self = this;\n\n if (typeof callback === 'undefined' && typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n if (options == null) {\n options = {};\n }\n\n // Get the error options\n var errorOptions = _getWriteConcern(this, options, callback);\n // Make sure we don't try to do a write concern without a callback\n if(_hasWriteConcern(errorOptions) && callback == null)\n throw new Error(\"Cannot use a writeConcern without a provided callback\");\n // Create command\n var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options);\n var index_name = command.documents[0].name;\n\n // Default command options\n var commandOptions = {};\n // Check if the index allready exists\n this.indexInformation(collectionName, function(err, collectionInfo) {\n if(err != null) return callback(err, null);\n\n if(!collectionInfo[index_name]) {\n // If we have error conditions set handle them\n if(_hasWriteConcern(errorOptions) && typeof callback == 'function') {\n // Insert options\n commandOptions['read'] = false;\n // If we have safe set set async to false\n if(errorOptions == null) commandOptions['async'] = true;\n\n // If we have an error option\n if(typeof errorOptions == 'object') {\n var keys = Object.keys(errorOptions);\n for(var i = 0; i < keys.length; i++) {\n commandOptions[keys[i]] = errorOptions[keys[i]];\n }\n }\n\n if(typeof callback === 'function' \n && commandOptions.w < 1 && !commandOptions.fsync && !commandOptions.journal) {\n commandOptions.w = 1;\n }\n\n self._executeInsertCommand(command, commandOptions, function(err, result) {\n // Only callback if we have one specified\n if(typeof callback === 'function') {\n if(err != null) return callback(err, null);\n\n result = result && result.documents;\n if (result[0].err) {\n callback(utils.toError(result[0]));\n } else {\n callback(null, command.documents[0].name);\n }\n }\n });\n } else {\n // Execute insert command\n var result = self._executeInsertCommand(command, commandOptions);\n // If no callback just return\n if(!callback) return;\n // If error return error\n if(result instanceof Error) {\n return callback(result);\n }\n // Otherwise just return\n return callback(null, index_name);\n }\n } else {\n if(typeof callback === 'function') return callback(null, index_name);\n }\n });\n};\n\n/**\n * Returns the information available on allocated cursors.\n *\n * Options\n * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).\n *\n * @param {Object} [options] additional options during update.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from cursorInfo or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.cursorInfo = function(options, callback) {\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n\n this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, {'cursorInfo':1}), options, function(err, result) {\n callback(err, result.documents[0]);\n });\n};\n\n/**\n * Drop an index on a collection.\n *\n * @param {String} collectionName the name of the collection where the command will drop an index.\n * @param {String} indexName name of the index to drop.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropIndex or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.dropIndex = function(collectionName, indexName, callback) { \n this._executeQueryCommand(DbCommand.createDropIndexCommand(this, collectionName, indexName), callback);\n};\n\n/**\n * Reindex all indexes on the collection\n * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.\n *\n * @param {String} collectionName the name of the collection.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from reIndex or null if an error occured.\n * @api public\n**/\nDb.prototype.reIndex = function(collectionName, callback) {\n this._executeQueryCommand(DbCommand.createReIndexCommand(this, collectionName), function(err, result) {\n if(err != null) {\n callback(err, false);\n } else if(result.documents[0].errmsg == null) {\n callback(null, true);\n } else {\n callback(new Error(result.documents[0].errmsg), false);\n }\n });\n};\n\n/**\n * Retrieves this collections index info.\n *\n * Options\n * - **full** {Boolean, default:false}, returns the full raw index information.\n * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST).\n *\n * @param {String} collectionName the name of the collection.\n * @param {Object} [options] additional options during update.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from indexInformation or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.indexInformation = function(collectionName, options, callback) {\n if(typeof callback === 'undefined') {\n if(typeof options === 'undefined') {\n callback = collectionName;\n collectionName = null;\n } else {\n callback = options;\n }\n options = {};\n }\n\n // If we specified full information\n var full = options['full'] == null ? false : options['full'];\n // Build selector for the indexes\n var selector = collectionName != null ? {ns: (this.databaseName + \".\" + collectionName)} : {};\n\n // Set read preference if we set one\n var readPreference = options['readPreference'] ? options['readPreference'] : ReadPreference.PRIMARY;\n\n // Iterate through all the fields of the index\n this.collection(DbCommand.SYSTEM_INDEX_COLLECTION, function(err, collection) {\n // Perform the find for the collection\n collection.find(selector).setReadPreference(readPreference).toArray(function(err, indexes) {\n if(err != null) return callback(err, null);\n // Contains all the information\n var info = {};\n\n // if full defined just return all the indexes directly\n if(full) return callback(null, indexes);\n\n // Process all the indexes\n for(var i = 0; i < indexes.length; i++) {\n var index = indexes[i];\n // Let's unpack the object\n info[index.name] = [];\n for(var name in index.key) {\n info[index.name].push([name, index.key[name]]);\n }\n }\n\n // Return all the indexes\n callback(null, info);\n });\n });\n};\n\n/**\n * Drop a database.\n *\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropDatabase or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.dropDatabase = function(callback) {\n var self = this;\n\n this._executeQueryCommand(DbCommand.createDropDatabaseCommand(this), function(err, result) {\n if(err == null && result.documents[0].ok == 1) {\n callback(null, true);\n } else {\n if(err) {\n callback(err, false);\n } else {\n callback(utils.toError(result.documents[0]), false);\n }\n }\n });\n};\n\n/**\n * Get all the db statistics.\n *\n * Options\n * - **scale** {Number}, divide the returned sizes by scale value.\n * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST).\n *\n * @param {Objects} [options] options for the stats command\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from stats or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.prototype.stats = function stats(options, callback) {\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n // Fetch all commands\n options = args.length ? args.shift() : {};\n\n // Build command object\n var commandObject = {\n dbStats:this.collectionName,\n }\n\n // Check if we have the scale value\n if(options['scale'] != null) commandObject['scale'] = options['scale'];\n\n // Execute the command\n this.command(commandObject, options, callback);\n}\n\n/**\n * @ignore\n */\nvar __executeQueryCommand = function(self, db_command, options, callback) {\n // Options unpacking\n var read = options['read'] != null ? options['read'] : false;\n var raw = options['raw'] != null ? options['raw'] : self.raw;\n var onAll = options['onAll'] != null ? options['onAll'] : false;\n var specifiedConnection = options['connection'] != null ? options['connection'] : null;\n\n // Correct read preference to default primary if set to false, null or primary\n if(!(typeof read == 'object') && read._type == 'ReadPreference') {\n read = (read == null || read == 'primary' || read == false) ? ReadPreference.PRIMARY : read;\n if(!ReadPreference.isValid(read)) return callback(new Error(\"Illegal readPreference mode specified, \" + read));\n } else if(typeof read == 'object' && read._type == 'ReadPreference') {\n if(!read.isValid()) return callback(new Error(\"Illegal readPreference mode specified, \" + read.mode));\n }\n\n // If we have a read preference set and we are a mongos pass the read preference on to the mongos instance,\n if(self.serverConfig.isMongos() && read != null && read != false) {\n db_command.setMongosReadPreference(read);\n }\n\n // If we got a callback object\n if(typeof callback === 'function' && !onAll) {\n // Override connection if we passed in a specific connection\n var connection = specifiedConnection != null ? specifiedConnection : null;\n\n if(connection instanceof Error) return callback(connection, null);\n\n // Fetch either a reader or writer dependent on the specified read option if no connection\n // was passed in\n if(connection == null) {\n connection = read == null || read == 'primary' || read == false ? self.serverConfig.checkoutWriter(true) : self.serverConfig.checkoutReader(read);\n }\n\n // Ensure we have a valid connection\n if(connection == null) {\n return callback(new Error(\"no open connections\"));\n } else if(connection instanceof Error || connection['message'] != null) {\n return callback(connection);\n }\n\n // Exhaust Option\n var exhaust = options.exhaust || false;\n // Register the handler in the data structure\n self.serverConfig._registerHandler(db_command, raw, connection, exhaust, callback);\n // Write the message out and handle any errors if there are any\n connection.write(db_command, function(err) {\n if(err != null) {\n // Call the handler with an error\n self.serverConfig._callHandler(db_command.getRequestId(), null, err);\n }\n });\n } else if(typeof callback === 'function' && onAll) {\n var connections = self.serverConfig.allRawConnections();\n var numberOfEntries = connections.length;\n // Go through all the connections\n for(var i = 0; i < connections.length; i++) {\n // Fetch a connection\n var connection = connections[i];\n\n // Ensure we have a valid connection\n if(connection == null) {\n return callback(new Error(\"no open connections\"));\n } else if(connection instanceof Error) {\n return callback(connection);\n }\n\n // Register the handler in the data structure\n self.serverConfig._registerHandler(db_command, raw, connection, callback);\n // Write the message out\n connection.write(db_command, function(err) {\n // Adjust the number of entries we need to process\n numberOfEntries = numberOfEntries - 1;\n // Remove listener\n if(err != null) {\n // Clean up listener and return error\n self.serverConfig._removeHandler(db_command.getRequestId());\n }\n\n // No more entries to process callback with the error\n if(numberOfEntries <= 0) {\n callback(err);\n }\n });\n\n // Update the db_command request id\n db_command.updateRequestId();\n }\n } else {\n // Fetch either a reader or writer dependent on the specified read option\n var connection = read == null || read == 'primary' || read == false ? self.serverConfig.checkoutWriter(true) : self.serverConfig.checkoutReader(read);\n // Override connection if needed\n connection = specifiedConnection != null ? specifiedConnection : connection;\n // Ensure we have a valid connection\n if(connection == null || connection instanceof Error || connection['message'] != null) return null;\n // Write the message out\n connection.write(db_command, function(err) {\n if(err != null) {\n // Emit the error\n self.emit(\"error\", err);\n }\n });\n }\n}\n\n/**\n * @ignore\n */\nvar __retryCommandOnFailure = function(self, retryInMilliseconds, numberOfTimes, command, db_command, options, callback) {\n if(this._state == 'connected' || this._state == 'disconnected') this._state = 'connecting';\n // Number of retries done\n var numberOfRetriesDone = numberOfTimes;\n // Retry function, execute once\n var retryFunction = function(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback) {\n _self.serverConfig.connect(_self, {}, function(err, result, _serverConfig) {\n if(_options) delete _options['connection'];\n\n // Adjust the number of retries left\n _numberOfRetriesDone = _numberOfRetriesDone - 1;\n // Definitively restart\n if(err != null && _numberOfRetriesDone > 0) {\n _self._state = 'connecting';\n // Close the server config\n _serverConfig.close(function(err) {\n // Retry the connect\n setTimeout(function() {\n retryFunction(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback);\n }, _retryInMilliseconds);\n });\n } else if(err != null && _numberOfRetriesDone <= 0) {\n _self._state = 'disconnected';\n // Force close the current connections\n _serverConfig.close(function(_err) {\n // Force close the current connections\n if(typeof _callback == 'function') _callback(err, null);\n });\n } else if(err == null && _self.serverConfig.isConnected() == true && Array.isArray(_self.auths) && _self.auths.length > 0) {\n _self._state = 'connected';\n // Get number of auths we need to execute\n var numberOfAuths = _self.auths.length;\n // Apply all auths\n for(var i = 0; i < _self.auths.length; i++) {\n _self.authenticate(_self.auths[i].username, _self.auths[i].password, {'authdb':_self.auths[i].authdb}, function(err, authenticated) {\n numberOfAuths = numberOfAuths - 1;\n\n // If we have no more authentications to replay\n if(numberOfAuths == 0) {\n if(err != null || !authenticated) {\n if(typeof _callback == 'function') _callback(err, null);\n return;\n } else {\n // Execute command\n command(_self, _db_command, _options, _callback);\n // Execute all the commands\n if(_self.commands.length > 0) _execute_queued_command(_self);\n }\n }\n });\n }\n } else if(err == null && _self.serverConfig.isConnected() == true) {\n _self._state = 'connected';\n\n // Execute command\n command(_self, _db_command, _options, _callback); \n \n processor(function() {\n // Execute any backed up commands\n while(_self.commands.length > 0) {\n // Fetch the command\n var command = _self.commands.shift();\n // Execute based on type\n if(command['type'] == 'query') {\n __executeQueryCommand(_self, command['db_command'], command['options'], command['callback']);\n } else if(command['type'] == 'insert') {\n __executeInsertCommand(_self, command['db_command'], command['options'], command['callback']);\n }\n }\n });\n } else {\n _self._state = 'connecting';\n // Force close the current connections\n _serverConfig.close(function(err) {\n // _self.serverConfig.close(function(err) {\n // Retry the connect\n setTimeout(function() {\n retryFunction(_self, _numberOfRetriesDone, _retryInMilliseconds, _numberOfTimes, _command, _db_command, _options, _callback);\n }, _retryInMilliseconds);\n });\n }\n });\n };\n\n // Execute function first time\n retryFunction(self, numberOfRetriesDone, retryInMilliseconds, numberOfTimes, command, db_command, options, callback);\n}\n\n/**\n * Execute db query command (not safe)\n * @ignore\n * @api private\n */\nDb.prototype._executeQueryCommand = function(db_command, options, callback) {\n var self = this;\n\n // Unpack the parameters\n if (typeof callback === 'undefined') {\n callback = options;\n options = {};\n }\n\n // fast fail option used for HA, no retry\n var failFast = options['failFast'] != null\n ? options['failFast']\n : false;\n\n // Check if the user force closed the command\n if(this._applicationClosed) {\n var err = new Error(\"db closed by application\");\n if('function' == typeof callback) {\n return callback(err, null);\n } else {\n throw err;\n }\n }\n\n var config = this.serverConfig;\n // If the pool is not connected, attemp to reconnect to send the message\n if(this._state == 'connecting' && config.autoReconnect && !failFast) {\n return processor(function() {\n self.commands.push({\n type: 'query',\n db_command: db_command,\n options: options,\n callback: callback\n });\n })\n }\n\n if(!failFast && !config.isConnected(options.read) && config.autoReconnect \n && (options.read == null \n || options.read == false\n || options.read == ReadPreference.PRIMARY \n || config.checkoutReader(options.read) == null)) {\n this._state = 'connecting';\n return __retryCommandOnFailure(this,\n this.retryMiliSeconds,\n this.numberOfRetries,\n __executeQueryCommand,\n db_command,\n options,\n callback);\n }\n\n if(!config.isConnected(options.read) && !config.autoReconnect && callback) {\n // Fire an error to the callback if we are not connected\n // and don't reconnect.\n return callback(new Error(\"no open connections\"), null);\n }\n\n __executeQueryCommand(self, db_command, options, function (err, result, conn) {\n if(callback) callback(err, result, conn);\n });\n\n};\n\n/**\n * @ignore\n */\nvar __executeInsertCommand = function(self, db_command, options, callback) {\n // Always checkout a writer for this kind of operations\n var connection = self.serverConfig.checkoutWriter();\n // Get safe mode\n var safe = options['safe'] != null ? options['safe'] : false;\n var raw = options['raw'] != null ? options['raw'] : self.raw;\n var specifiedConnection = options['connection'] != null ? options['connection'] : null;\n // Override connection if needed\n connection = specifiedConnection != null ? specifiedConnection : connection;\n\n // Ensure we have a valid connection\n if(typeof callback === 'function') {\n // Ensure we have a valid connection\n if(connection == null) {\n return callback(new Error(\"no open connections\"));\n } else if(connection instanceof Error) {\n return callback(connection);\n }\n\n var errorOptions = _getWriteConcern(self, options, callback);\n if(errorOptions.w > 0 || errorOptions.w == 'majority' || errorOptions.j || errorOptions.journal || errorOptions.fsync) { \n // db command is now an array of commands (original command + lastError)\n db_command = [db_command, DbCommand.createGetLastErrorCommand(safe, self)];\n // Register the handler in the data structure\n self.serverConfig._registerHandler(db_command[1], raw, connection, callback); \n }\n }\n\n // If we have no callback and there is no connection\n if(connection == null) return null;\n if(connection instanceof Error && typeof callback == 'function') return callback(connection, null);\n if(connection instanceof Error) return null;\n if(connection == null && typeof callback == 'function') return callback(new Error(\"no primary server found\"), null);\n\n // Write the message out\n connection.write(db_command, function(err) {\n // Return the callback if it's not a safe operation and the callback is defined\n if(typeof callback === 'function' && (safe == null || safe == false)) {\n // Perform the callback\n callback(err, null);\n } else if(typeof callback === 'function') {\n // Call the handler with an error\n self.serverConfig._callHandler(db_command[1].getRequestId(), null, err);\n } else if(typeof callback == 'function' && safe && safe.w == -1) {\n // Call the handler with no error\n self.serverConfig._callHandler(db_command[1].getRequestId(), null, null);\n } else if(!safe || safe.w == -1) {\n self.emit(\"error\", err);\n }\n });\n}\n\n/**\n * Execute an insert Command\n * @ignore\n * @api private\n */\nDb.prototype._executeInsertCommand = function(db_command, options, callback) {\n var self = this;\n\n // Unpack the parameters\n if(callback == null && typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n // Ensure options are not null\n options = options == null ? {} : options;\n\n // Check if the user force closed the command\n if(this._applicationClosed) {\n if(typeof callback == 'function') {\n return callback(new Error(\"db closed by application\"), null);\n } else {\n throw new Error(\"db closed by application\");\n }\n }\n\n // If the pool is not connected, attemp to reconnect to send the message\n if(self._state == 'connecting' && this.serverConfig.autoReconnect) {\n processor(function() {\n self.commands.push({type:'insert', 'db_command':db_command, 'options':options, 'callback':callback});\n })\n } else if(!this.serverConfig.isConnected() && this.serverConfig.autoReconnect) {\n this._state = 'connecting';\n // Retry command\n __retryCommandOnFailure(this, this.retryMiliSeconds, this.numberOfRetries, __executeInsertCommand, db_command, options, callback);\n } else if(!this.serverConfig.isConnected() && !this.serverConfig.autoReconnect && callback) {\n // Fire an error to the callback if we are not connected and don't do reconnect\n if(callback) callback(new Error(\"no open connections\"), null);\n } else {\n __executeInsertCommand(self, db_command, options, callback);\n }\n}\n\n/**\n * Update command is the same\n * @ignore\n * @api private\n */\nDb.prototype._executeUpdateCommand = Db.prototype._executeInsertCommand;\n/**\n * Remove command is the same\n * @ignore\n * @api private\n */\nDb.prototype._executeRemoveCommand = Db.prototype._executeInsertCommand;\n\n/**\n * Wrap a Mongo error document into an Error instance.\n * Deprecated. Use utils.toError instead.\n *\n * @ignore\n * @api private\n * @deprecated\n */\nDb.prototype.wrap = utils.toError;\n\n/**\n * Default URL\n *\n * @classconstant DEFAULT_URL\n **/\nDb.DEFAULT_URL = 'mongodb://localhost:27017/default';\n\n/**\n * Connect to MongoDB using a url as documented at\n *\n * docs.mongodb.org/manual/reference/connection-string/\n *\n * Options\n * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication\n * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor**\n * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor**\n * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor**\n * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor**\n *\n * @param {String} url connection url for MongoDB.\n * @param {Object} [options] optional options for insert command\n * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the db instance or null if an error occured.\n * @return {null}\n * @api public\n */\nDb.connect = function(url, options, callback) {\n var args = Array.prototype.slice.call(arguments, 1);\n callback = typeof args[args.length - 1] == 'function' ? args.pop() : null;\n options = args.length ? args.shift() : null;\n options = options || {};\n var serverOptions = options.server || {};\n var mongosOptions = options.mongos || {};\n var replSetServersOptions = options.replSet || options.replSetServers || {};\n var dbOptions = options.db || {};\n\n // If callback is null throw an exception\n if(callback == null) throw new Error(\"no callback function provided\");\n\n // Parse the string\n var object = parse(url);\n // Merge in any options for db in options object\n if(dbOptions) {\n for(var name in dbOptions) object.db_options[name] = dbOptions[name];\n }\n\n // Merge in any options for server in options object\n if(serverOptions) {\n for(var name in serverOptions) object.server_options[name] = serverOptions[name];\n }\n\n // Merge in any replicaset server options\n if(replSetServersOptions) {\n for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; \n }\n\n // Merge in any replicaset server options\n if(mongosOptions) {\n for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; \n }\n\n // We need to ensure that the list of servers are only either direct members or mongos\n // they cannot be a mix of monogs and mongod's\n var totalNumberOfServers = object.servers.length;\n var totalNumberOfMongosServers = 0;\n var totalNumberOfMongodServers = 0;\n var serverConfig = null;\n var errorServers = {};\n\n // Failure modes\n if(object.servers.length == 0) throw new Error(\"connection string must contain at least one seed host\");\n\n // If we have no db setting for the native parser try to set the c++ one first\n object.db_options.native_parser = _setNativeParser(object.db_options);\n // If no auto_reconnect is set, set it to true as default for single servers\n if(typeof object.server_options.auto_reconnect != 'boolean') {\n object.server_options.auto_reconnect = true;\n }\n\n // If we have more than a server, it could be replicaset or mongos list\n // need to verify that it's one or the other and fail if it's a mix\n // Connect to all servers and run ismaster\n for(var i = 0; i < object.servers.length; i++) {\n // Set up socket options\n var _server_options = {poolSize:1, socketOptions:{connectTimeoutMS:1000}, auto_reconnect:false};\n\n // Ensure we have ssl setup for the servers\n if(object.rs_options.ssl) {\n _server_options.ssl = object.rs_options.ssl;\n _server_options.sslValidate = object.rs_options.sslValidate;\n _server_options.sslCA = object.rs_options.sslCA;\n _server_options.sslCert = object.rs_options.sslCert;\n _server_options.sslKey = object.rs_options.sslKey;\n _server_options.sslPass = object.rs_options.sslPass;\n } else if(object.server_options.ssl) {\n _server_options.ssl = object.server_options.ssl;\n _server_options.sslValidate = object.server_options.sslValidate;\n _server_options.sslCA = object.server_options.sslCA;\n _server_options.sslCert = object.server_options.sslCert;\n _server_options.sslKey = object.server_options.sslKey;\n _server_options.sslPass = object.server_options.sslPass;\n }\n\n // Set up the Server object\n var _server = object.servers[i].domain_socket \n ? new Server(object.servers[i].domain_socket, _server_options)\n : new Server(object.servers[i].host, object.servers[i].port, _server_options);\n\n var connectFunction = function(__server) { \n // Attempt connect\n new Db(object.dbName, __server, {safe:false, native_parser:false}).open(function(err, db) {\n // Update number of servers\n totalNumberOfServers = totalNumberOfServers - 1; \n // If no error do the correct checks\n if(!err) {\n // Close the connection\n db.close(true);\n var isMasterDoc = db.serverConfig.isMasterDoc;\n // Check what type of server we have\n if(isMasterDoc.setName) totalNumberOfMongodServers++;\n if(isMasterDoc.msg && isMasterDoc.msg == \"isdbgrid\") totalNumberOfMongosServers++;\n } else {\n errorServers[__server.host + \":\" + __server.port] = __server;\n }\n\n if(totalNumberOfServers == 0) {\n // If we have a mix of mongod and mongos, throw an error\n if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0)\n return callback(new Error(\"cannot combine a list of replicaset seeds and mongos seeds\"));\n \n if(totalNumberOfMongodServers == 0 && object.servers.length == 1) {\n var obj = object.servers[0];\n serverConfig = obj.domain_socket ? \n new Server(obj.domain_socket, object.server_options)\n : new Server(obj.host, obj.port, object.server_options); \n } else if(totalNumberOfMongodServers > 0 || totalNumberOfMongosServers > 0) {\n var finalServers = object.servers\n .filter(function(serverObj) {\n return errorServers[serverObj.host + \":\" + serverObj.port] == null;\n })\n .map(function(serverObj) {\n return new Server(serverObj.host, serverObj.port, object.server_options);\n });\n // Clean out any error servers\n errorServers = {};\n // Set up the final configuration\n if(totalNumberOfMongodServers > 0) {\n serverConfig = new ReplSet(finalServers, object.rs_options); \n } else {\n serverConfig = new Mongos(finalServers, object.mongos_options); \n }\n }\n\n if(serverConfig == null) return callback(new Error(\"Could not locate any valid servers in initial seed list\"));\n // Set up all options etc and connect to the database\n _finishConnecting(serverConfig, object, options, callback)\n }\n }); \n }\n\n // Wrap the context of the call\n connectFunction(_server); \n } \n}\n\nvar _setNativeParser = function(db_options) {\n if(typeof db_options.native_parser == 'boolean') return db_options.native_parser;\n\n try {\n require('bson').BSONNative.BSON;\n return true;\n } catch(err) {\n return false;\n }\n}\n\nvar _finishConnecting = function(serverConfig, object, options, callback) {\n // Safe settings\n var safe = {};\n // Build the safe parameter if needed\n if(object.db_options.journal) safe.j = object.db_options.journal;\n if(object.db_options.w) safe.w = object.db_options.w;\n if(object.db_options.fsync) safe.fsync = object.db_options.fsync;\n if(object.db_options.wtimeoutMS) safe.wtimeout = object.db_options.wtimeoutMS;\n\n // If we have a read Preference set\n if(object.db_options.read_preference) {\n var readPreference = new ReadPreference(object.db_options.read_preference);\n // If we have the tags set up\n if(object.db_options.read_preference_tags)\n readPreference = new ReadPreference(object.db_options.read_preference, object.db_options.read_preference_tags);\n // Add the read preference\n object.db_options.readPreference = readPreference;\n }\n\n // No safe mode if no keys\n if(Object.keys(safe).length == 0) safe = false;\n\n // Add the safe object\n object.db_options.safe = safe;\n\n // Set up the db options\n var db = new Db(object.dbName, serverConfig, object.db_options);\n\n // Open the db\n db.open(function(err, db){\n if(err == null && object.auth){\n // What db to authenticate against\n var authentication_db = db;\n if(object.db_options && object.db_options.authSource) {\n authentication_db = db.db(object.db_options.authSource);\n }\n\n // Authenticate\n authentication_db.authenticate(object.auth.user, object.auth.password, function(err, success){\n if(success){\n callback(null, db);\n } else {\n if(db) db.close();\n callback(err ? err : new Error('Could not authenticate user ' + auth[0]), null);\n }\n });\n } else {\n callback(err, db);\n }\n });\n}\n\n/**\n * State of the db connection\n * @ignore\n */\nObject.defineProperty(Db.prototype, \"state\", { enumerable: true\n , get: function () {\n return this.serverConfig._serverState;\n }\n});\n\n/**\n * @ignore\n */\nvar _hasWriteConcern = function(errorOptions) {\n return errorOptions == true\n || errorOptions.w > 0\n || errorOptions.w == 'majority'\n || errorOptions.j == true\n || errorOptions.journal == true\n || errorOptions.fsync == true\n}\n\n/**\n * @ignore\n */\nvar _setWriteConcernHash = function(options) {\n var finalOptions = {};\n if(options.w != null) finalOptions.w = options.w; \n if(options.journal == true) finalOptions.j = options.journal;\n if(options.j == true) finalOptions.j = options.j;\n if(options.fsync == true) finalOptions.fsync = options.fsync;\n if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; \n return finalOptions;\n}\n\n/**\n * @ignore\n */\nvar _getWriteConcern = function(self, options, callback) {\n // Final options\n var finalOptions = {w:1};\n // Local options verification\n if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') {\n finalOptions = _setWriteConcernHash(options);\n } else if(options.safe != null && typeof options.safe == 'object') {\n finalOptions = _setWriteConcernHash(options.safe);\n } else if(typeof options.safe == \"boolean\") {\n finalOptions = {w: (options.safe ? 1 : 0)};\n } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') {\n finalOptions = _setWriteConcernHash(self.options);\n } else if(self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean') {\n finalOptions = _setWriteConcernHash(self.safe);\n } else if(typeof self.safe == \"boolean\") {\n finalOptions = {w: (self.safe ? 1 : 0)};\n }\n\n // Ensure we don't have an invalid combination of write concerns\n if(finalOptions.w < 1 \n && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error(\"No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true\");\n\n // Return the options\n return finalOptions;\n}\n\n/**\n * Legacy support\n *\n * @ignore\n * @api private\n */\nexports.connect = Db.connect;\nexports.Db = Db;\n\n/**\n * Remove all listeners to the db instance.\n * @ignore\n * @api private\n */\nDb.prototype.removeAllEventListeners = function() {\n this.removeAllListeners(\"close\");\n this.removeAllListeners(\"error\");\n this.removeAllListeners(\"timeout\");\n this.removeAllListeners(\"parseError\");\n this.removeAllListeners(\"poolReady\");\n this.removeAllListeners(\"message\");\n}\n\n});","sourceLength":90811,"scriptType":2,"compilationType":0,"context":{"ref":6},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/db.js (lines: 2149)"}],"refs":[{"handle":6,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":525,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[310]}}
{"seq":198,"request_seq":525,"type":"response","command":"scripts","success":true,"body":[{"handle":9,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js","id":310,"lineOffset":0,"columnOffset":0,"lineCount":227,"source":"(function (exports, require, module, __filename, __dirname) { var fs = require('fs'),\n ReadPreference = require('./read_preference').ReadPreference;\n\nexports.parse = function(url, options) {\n // Ensure we have a default options object if none set\n options = options || {};\n // Variables\n var connection_part = '';\n var auth_part = '';\n var query_string_part = '';\n var dbName = 'admin';\n\n // Must start with mongodb\n if(url.indexOf(\"mongodb://\") != 0)\n throw Error(\"URL must be in the format mongodb://user:pass@host:port/dbname\");\n // If we have a ? mark cut the query elements off\n if(url.indexOf(\"?\") != -1) {\n query_string_part = url.substr(url.indexOf(\"?\") + 1);\n connection_part = url.substring(\"mongodb://\".length, url.indexOf(\"?\"))\n } else {\n connection_part = url.substring(\"mongodb://\".length);\n }\n\n // Check if we have auth params\n if(connection_part.indexOf(\"@\") != -1) {\n auth_part = connection_part.split(\"@\")[0];\n connection_part = connection_part.split(\"@\")[1];\n }\n\n // Check if the connection string has a db\n if(connection_part.indexOf(\".sock\") != -1) {\n if(connection_part.indexOf(\".sock/\") != -1) {\n dbName = connection_part.split(\".sock/\")[1];\n connection_part = connection_part.split(\"/\", connection_part.indexOf(\".sock\") + \".sock\".length);\n } \n } else if(connection_part.indexOf(\"/\") != -1) {\n dbName = connection_part.split(\"/\")[1];\n connection_part = connection_part.split(\"/\")[0];\n }\n\n // Result object\n var object = {};\n\n // Pick apart the authentication part of the string\n var authPart = auth_part || '';\n var auth = authPart.split(':', 2);\n if(options['uri_decode_auth']){\n auth[0] = decodeURIComponent(auth[0]);\n if(auth[1]){\n auth[1] = decodeURIComponent(auth[1]);\n }\n }\n\n // Add auth to final object if we have 2 elements\n if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]};\n\n // Variables used for temporary storage\n var hostPart;\n var urlOptions;\n var servers;\n var serverOptions = {socketOptions: {}};\n var dbOptions = {read_preference_tags: []};\n var replSetServersOptions = {socketOptions: {}};\n // Add server options to final object\n object.server_options = serverOptions;\n object.db_options = dbOptions;\n object.rs_options = replSetServersOptions;\n object.mongos_options = {};\n\n // Let's check if we are using a domain socket\n if(url.match(/\\.sock/)) {\n // Split out the socket part\n var domainSocket = url.substring(\n url.indexOf(\"mongodb://\") + \"mongodb://\".length\n , url.lastIndexOf(\".sock\") + \".sock\".length);\n // Clean out any auth stuff if any\n if(domainSocket.indexOf(\"@\") != -1) domainSocket = domainSocket.split(\"@\")[1];\n servers = [{domain_socket: domainSocket}];\n } else {\n // Split up the db\n hostPart = connection_part;\n // Parse all server results\n servers = hostPart.split(',').map(function(h) {\n var hostPort = h.split(':', 2);\n var _host = hostPort[0] || 'localhost';\n var _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017;\n // Check for localhost?safe=true style case\n if(_host.indexOf(\"?\") != -1) _host = _host.split(/\\?/)[0];\n\n // Return the mapped object\n return {host: _host, port: _port};\n });\n }\n\n // Get the db name\n object.dbName = dbName || 'admin';\n // Split up all the options\n urlOptions = (query_string_part || '').split(/[&;]/); \n // Ugh, we have to figure out which options go to which constructor manually.\n urlOptions.forEach(function(opt) {\n if(!opt) return;\n var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1];\n // Options implementations\n switch(name) {\n case 'slaveOk':\n case 'slave_ok':\n serverOptions.slave_ok = (value == 'true');\n break;\n case 'maxPoolSize':\n case 'poolSize':\n serverOptions.poolSize = parseInt(value, 10);\n replSetServersOptions.poolSize = parseInt(value, 10);\n break;\n case 'autoReconnect':\n case 'auto_reconnect':\n serverOptions.auto_reconnect = (value == 'true');\n break;\n case 'minPoolSize':\n throw new Error(\"minPoolSize not supported\");\n case 'maxIdleTimeMS':\n throw new Error(\"maxIdleTimeMS not supported\");\n case 'waitQueueMultiple':\n throw new Error(\"waitQueueMultiple not supported\");\n case 'waitQueueTimeoutMS':\n throw new Error(\"waitQueueTimeoutMS not supported\");\n case 'uuidRepresentation':\n throw new Error(\"uuidRepresentation not supported\");\n case 'ssl':\n if(value == 'prefer') {\n serverOptions.ssl = value;\n replSetServersOptions.ssl = value;\n break;\n }\n serverOptions.ssl = (value == 'true');\n replSetServersOptions.ssl = (value == 'true');\n break;\n case 'replicaSet':\n case 'rs_name':\n replSetServersOptions.rs_name = value;\n break;\n case 'reconnectWait':\n replSetServersOptions.reconnectWait = parseInt(value, 10);\n break;\n case 'retries':\n replSetServersOptions.retries = parseInt(value, 10);\n break;\n case 'readSecondary':\n case 'read_secondary':\n replSetServersOptions.read_secondary = (value == 'true');\n break;\n case 'fsync':\n dbOptions.fsync = (value == 'true');\n break;\n case 'journal':\n dbOptions.journal = (value == 'true');\n break;\n case 'safe':\n dbOptions.safe = (value == 'true');\n break;\n case 'nativeParser':\n case 'native_parser':\n dbOptions.native_parser = (value == 'true');\n break;\n case 'connectTimeoutMS':\n serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);\n replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);\n break;\n case 'socketTimeoutMS':\n serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);\n replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);\n break;\n case 'w':\n dbOptions.w = parseInt(value, 10);\n break;\n case 'authSource':\n dbOptions.authSource = value;\n case 'wtimeoutMS':\n dbOptions.wtimeoutMS = parseInt(value, 10);\n break;\n case 'readPreference':\n if(!ReadPreference.isValid(value)) throw new Error(\"readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest\");\n dbOptions.read_preference = value;\n break;\n case 'readPreferenceTags':\n // Contains the tag object\n var tagObject = {};\n if(value == null || value == '') {\n dbOptions.read_preference_tags.push(tagObject);\n break;\n }\n\n // Split up the tags\n var tags = value.split(/\\,/);\n for(var i = 0; i < tags.length; i++) {\n var parts = tags[i].trim().split(/\\:/);\n tagObject[parts[0]] = parts[1];\n }\n\n // Set the preferences tags\n dbOptions.read_preference_tags.push(tagObject);\n break;\n default:\n break;\n }\n });\n\n // No tags: should be null (not [])\n if(dbOptions.read_preference_tags.length === 0) {\n dbOptions.read_preference_tags = null;\n }\n\n // Validate if there are an invalid write concern combinations\n if((dbOptions.w == -1 || dbOptions.w == 0) && (\n dbOptions.journal == true\n || dbOptions.fsync == true\n || dbOptions.safe == true)) throw new Error(\"w set to -1 or 0 cannot be combined with safe/w/journal/fsync\")\n\n // If no read preference set it to primary\n if(!dbOptions.read_preference) dbOptions.read_preference = 'primary';\n\n // Add servers to result\n object.servers = servers;\n // Returned parsed object\n return object;\n}\n\n});","sourceLength":7775,"scriptType":2,"compilationType":0,"context":{"ref":8},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/url_parser.js (lines: 227)"}],"refs":[{"handle":8,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":526,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[313]}}
{"seq":199,"request_seq":526,"type":"response","command":"scripts","success":true,"body":[{"handle":11,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js","id":313,"lineOffset":0,"columnOffset":0,"lineCount":105,"source":"(function (exports, require, module, __filename, __dirname) { var GridStore = require('./gridstore').GridStore,\n ObjectID = require('bson').ObjectID;\n\n/**\n * A class representation of a simple Grid interface.\n *\n * @class Represents the Grid.\n * @param {Db} db A database instance to interact with.\n * @param {String} [fsName] optional different root collection for GridFS.\n * @return {Grid}\n */\nfunction Grid(db, fsName) {\n\n if(!(this instanceof Grid)) return new Grid(db, fsName);\n\n this.db = db;\n this.fsName = fsName == null ? GridStore.DEFAULT_ROOT_COLLECTION : fsName;\n}\n\n/**\n * Puts binary data to the grid\n *\n * Options\n * - **_id** {Any}, unique id for this file\n * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.\n * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**.\n * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**.\n * - **metadata** {Object}, arbitrary data the user wants to store.\n *\n * @param {Buffer} data buffer with Binary Data.\n * @param {Object} [options] the options for the files.\n * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object.\n * @return {null}\n * @api public\n */\nGrid.prototype.put = function(data, options, callback) {\n var self = this;\n var args = Array.prototype.slice.call(arguments, 1);\n callback = args.pop();\n options = args.length ? args.shift() : {};\n // If root is not defined add our default one\n options['root'] = options['root'] == null ? this.fsName : options['root'];\n\n // Return if we don't have a buffer object as data\n if(!(Buffer.isBuffer(data))) return callback(new Error(\"Data object must be a buffer object\"), null);\n // Get filename if we are using it\n var filename = options['filename'] || null;\n // Get id if we are using it\n var id = options['_id'] || null;\n // Create gridstore\n var gridStore = new GridStore(this.db, id, filename, \"w\", options);\n gridStore.open(function(err, gridStore) {\n if(err) return callback(err, null);\n\n gridStore.write(data, function(err, result) {\n if(err) return callback(err, null);\n\n gridStore.close(function(err, result) {\n if(err) return callback(err, null);\n callback(null, result);\n })\n })\n })\n}\n\n/**\n * Get binary data to the grid\n *\n * @param {Any} id for file.\n * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object.\n * @return {null}\n * @api public\n */\nGrid.prototype.get = function(id, callback) {\n // Create gridstore\n var gridStore = new GridStore(this.db, id, null, \"r\", {root:this.fsName});\n gridStore.open(function(err, gridStore) {\n if(err) return callback(err, null);\n\n // Return the data\n gridStore.read(function(err, data) {\n return callback(err, data)\n });\n })\n}\n\n/**\n * Delete file from grid\n *\n * @param {Any} id for file.\n * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object.\n * @return {null}\n * @api public\n */\nGrid.prototype.delete = function(id, callback) {\n // Create gridstore\n GridStore.unlink(this.db, id, {root:this.fsName}, function(err, result) {\n if(err) return callback(err, false);\n return callback(null, true);\n });\n}\n\nexports.Grid = Grid;\n\n});","sourceLength":3736,"scriptType":2,"compilationType":0,"context":{"ref":10},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/grid.js (lines: 105)"}],"refs":[{"handle":10,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":527,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[316]}}
{"seq":200,"request_seq":527,"type":"response","command":"scripts","success":true,"body":[{"handle":13,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js","id":316,"lineOffset":0,"columnOffset":0,"lineCount":1478,"source":"(function (exports, require, module, __filename, __dirname) { /**\n * @fileOverview GridFS is a tool for MongoDB to store files to the database.\n * Because of the restrictions of the object size the database can hold, a\n * facility to split a file into several chunks is needed. The {@link GridStore}\n * class offers a simplified api to interact with files while managing the\n * chunks of split files behind the scenes. More information about GridFS can be\n * found <a href=\"http://www.mongodb.org/display/DOCS/GridFS\">here</a>.\n */\nvar Chunk = require('./chunk').Chunk,\n DbCommand = require('../commands/db_command').DbCommand,\n ObjectID = require('bson').ObjectID,\n Buffer = require('buffer').Buffer,\n fs = require('fs'),\n timers = require('timers'),\n util = require('util'),\n inherits = util.inherits,\n ReadStream = require('./readstream').ReadStream,\n Stream = require('stream');\n\n// Set processor, setImmediate if 0.10 otherwise nextTick\nvar processor = timers.setImmediate ? timers.setImmediate : process.nextTick;\nprocessor = process.nextTick\n\nvar REFERENCE_BY_FILENAME = 0,\n REFERENCE_BY_ID = 1;\n\n/**\n * A class representation of a file stored in GridFS.\n *\n * Modes\n * - **\"r\"** - read only. This is the default mode.\n * - **\"w\"** - write in truncate mode. Existing data will be overwriten.\n * - **w+\"** - write in edit mode.\n *\n * Options\n * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.\n * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**.\n * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**.\n * - **metadata** {Object}, arbitrary data the user wants to store.\n *\n * @class Represents the GridStore.\n * @param {Db} db A database instance to interact with.\n * @param {Any} [id] optional unique id for this file\n * @param {String} [filename] optional filename for this file, no unique constrain on the field\n * @param {String} mode set the mode for this file.\n * @param {Object} options optional properties to specify.\n * @return {GridStore}\n */\nvar GridStore = function GridStore(db, id, filename, mode, options) {\n if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options);\n\n var self = this;\n this.db = db;\n\n // Call stream constructor\n if(typeof Stream == 'function') {\n Stream.call(this);\n } else {\n // 0.4.X backward compatibility fix\n Stream.Stream.call(this);\n }\n\n // Handle options\n if(typeof options === 'undefined') options = {};\n // Handle mode\n if(typeof mode === 'undefined') {\n mode = filename;\n filename = undefined;\n } else if(typeof mode == 'object') {\n options = mode;\n mode = filename;\n filename = undefined;\n }\n\n if(id instanceof ObjectID) {\n this.referenceBy = REFERENCE_BY_ID;\n this.fileId = id;\n this.filename = filename;\n } else if(typeof filename == 'undefined') {\n this.referenceBy = REFERENCE_BY_FILENAME;\n this.filename = id;\n if (mode.indexOf('w') != null) {\n this.fileId = new ObjectID();\n }\n } else {\n this.referenceBy = REFERENCE_BY_ID;\n this.fileId = id;\n this.filename = filename;\n }\n\n // Set up the rest\n this.mode = mode == null ? \"r\" : mode;\n this.options = options == null ? {} : options;\n this.root = this.options['root'] == null ? exports.GridStore.DEFAULT_ROOT_COLLECTION : this.options['root'];\n this.position = 0;\n // Set default chunk size\n this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize'];\n}\n\n/**\n * Code for the streaming capabilities of the gridstore object\n * Most code from Aaron heckmanns project https://github.com/aheckmann/gridfs-stream\n * Modified to work on the gridstore object itself\n * @ignore\n */\nif(typeof Stream == 'function') {\n GridStore.prototype = { __proto__: Stream.prototype }\n} else {\n // Node 0.4.X compatibility code\n GridStore.prototype = { __proto__: Stream.Stream.prototype }\n}\n\n// Move pipe to _pipe\nGridStore.prototype._pipe = GridStore.prototype.pipe;\n\n/**\n * Opens the file from the database and initialize this object. Also creates a\n * new one if file does not exist.\n *\n * @param {Function} callback this will be called after executing this method. The first parameter will contain an **{Error}** object and the second parameter will be null if an error occured. Otherwise, the first parameter will be null and the second will contain the reference to this object.\n * @return {null}\n * @api public\n */\nGridStore.prototype.open = function(callback) {\n if( this.mode != \"w\" && this.mode != \"w+\" && this.mode != \"r\"){\n callback(new Error(\"Illegal mode \" + this.mode), null);\n return;\n }\n\n var self = this;\n\n if((self.mode == \"w\" || self.mode == \"w+\") && self.db.serverConfig.primary != null) {\n // Get files collection\n self.collection(function(err, collection) {\n if(err) return callback(err);\n\n // Put index on filename\n collection.ensureIndex([['filename', 1]], function(err, index) {\n if(err) return callback(err);\n\n // Get chunk collection\n self.chunkCollection(function(err, chunkCollection) {\n if(err) return callback(err);\n\n // Ensure index on chunk collection\n chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], function(err, index) {\n if(err) return callback(err);\n _open(self, callback);\n });\n });\n });\n });\n } else {\n // Open the gridstore\n _open(self, callback);\n }\n};\n\n/**\n * Hidding the _open function\n * @ignore\n * @api private\n */\nvar _open = function(self, callback) {\n self.collection(function(err, collection) {\n if(err!==null) {\n callback(new Error(\"at collection: \"+err), null);\n return;\n }\n\n // Create the query\n var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename};\n query = null == self.fileId && this.filename == null ? null : query;\n\n // Fetch the chunks\n if(query != null) {\n collection.find(query, function(err, cursor) {\n if(err) return error(err);\n\n // Fetch the file\n cursor.nextObject(function(err, doc) {\n if(err) return error(err);\n\n // Check if the collection for the files exists otherwise prepare the new one\n if(doc != null) {\n self.fileId = doc._id;\n self.filename = doc.filename;\n self.contentType = doc.contentType;\n self.internalChunkSize = doc.chunkSize;\n self.uploadDate = doc.uploadDate;\n self.aliases = doc.aliases;\n self.length = doc.length;\n self.metadata = doc.metadata;\n self.internalMd5 = doc.md5;\n } else if (self.mode != 'r') {\n self.fileId = self.fileId == null ? new ObjectID() : self.fileId;\n self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE;\n self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;\n self.length = 0;\n } else {\n self.length = 0;\n var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId;\n return error(new Error((self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename) + \" does not exist\", self));\n }\n\n // Process the mode of the object\n if(self.mode == \"r\") {\n nthChunk(self, 0, function(err, chunk) {\n if(err) return error(err);\n self.currentChunk = chunk;\n self.position = 0;\n callback(null, self);\n });\n } else if(self.mode == \"w\") {\n // Delete any existing chunks\n deleteChunks(self, function(err, result) {\n if(err) return error(err);\n self.currentChunk = new Chunk(self, {'n':0});\n self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];\n self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];\n self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.position = 0;\n callback(null, self);\n });\n } else if(self.mode == \"w+\") {\n nthChunk(self, lastChunkNumber(self), function(err, chunk) {\n if(err) return error(err);\n // Set the current chunk\n self.currentChunk = chunk == null ? new Chunk(self, {'n':0}) : chunk;\n self.currentChunk.position = self.currentChunk.data.length();\n self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.position = self.length;\n callback(null, self);\n });\n }\n });\n });\n } else {\n // Write only mode\n self.fileId = null == self.fileId ? new ObjectID() : self.fileId;\n self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE;\n self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;\n self.length = 0;\n\n self.chunkCollection(function(err, collection2) {\n if(err) return error(err);\n\n // No file exists set up write mode\n if(self.mode == \"w\") {\n // Delete any existing chunks\n deleteChunks(self, function(err, result) {\n if(err) return error(err);\n self.currentChunk = new Chunk(self, {'n':0});\n self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];\n self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];\n self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.position = 0;\n callback(null, self);\n });\n } else if(self.mode == \"w+\") {\n nthChunk(self, lastChunkNumber(self), function(err, chunk) {\n if(err) return error(err);\n // Set the current chunk\n self.currentChunk = chunk == null ? new Chunk(self, {'n':0}) : chunk;\n self.currentChunk.position = self.currentChunk.data.length();\n self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];\n self.position = self.length;\n callback(null, self);\n });\n }\n });\n }\n });\n\n // only pass error to callback once\n function error (err) {\n if(error.err) return;\n callback(error.err = err);\n }\n};\n\n/**\n * Stores a file from the file system to the GridFS database.\n *\n * @param {String|Buffer|FileHandle} file the file to store.\n * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the the second will contain the reference to this object.\n * @return {null}\n * @api public\n */\nGridStore.prototype.writeFile = function (file, callback) {\n var self = this;\n if (typeof file === 'string') {\n fs.open(file, 'r', 0666, function (err, fd) {\n if(err) return callback(err);\n self.writeFile(fd, callback);\n });\n return;\n }\n\n self.open(function (err, self) {\n if(err) return callback(err);\n\n fs.fstat(file, function (err, stats) {\n if(err) return callback(err);\n\n var offset = 0;\n var index = 0;\n var numberOfChunksLeft = Math.min(stats.size / self.chunkSize);\n\n // Write a chunk\n var writeChunk = function() {\n fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) {\n if(err) return callback(err);\n\n offset = offset + bytesRead;\n\n // Create a new chunk for the data\n var chunk = new Chunk(self, {n:index++});\n chunk.write(data, function(err, chunk) {\n if(err) return callback(err);\n\n chunk.save(function(err, result) {\n if(err) return callback(err);\n\n self.position = self.position + data.length;\n\n // Point to current chunk\n self.currentChunk = chunk;\n\n if(offset >= stats.size) {\n fs.close(file);\n self.close(callback);\n } else {\n return processor(writeChunk);\n }\n });\n });\n });\n }\n\n // Process the first write\n processor(writeChunk);\n });\n });\n};\n\n/**\n * Writes some data. This method will work properly only if initialized with mode\n * \"w\" or \"w+\".\n *\n * @param string {string} The data to write.\n * @param close {boolean=false} opt_argument Closes this file after writing if\n * true.\n * @param callback {function(*, GridStore)} This will be called after executing\n * this method. The first parameter will contain null and the second one\n * will contain a reference to this object.\n *\n * @ignore\n * @api private\n */\nvar writeBuffer = function(self, buffer, close, callback) {\n if(typeof close === \"function\") { callback = close; close = null; }\n var finalClose = (close == null) ? false : close;\n\n if(self.mode[0] != \"w\") {\n callback(new Error((self.referenceBy == REFERENCE_BY_ID ? self.toHexString() : self.filename) + \" not opened for writing\"), null);\n } else {\n if(self.currentChunk.position + buffer.length >= self.chunkSize) {\n // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left\n // to a new chunk (recursively)\n var previousChunkNumber = self.currentChunk.chunkNumber;\n var leftOverDataSize = self.chunkSize - self.currentChunk.position;\n var firstChunkData = buffer.slice(0, leftOverDataSize);\n var leftOverData = buffer.slice(leftOverDataSize);\n // A list of chunks to write out\n var chunksToWrite = [self.currentChunk.write(firstChunkData)];\n // If we have more data left than the chunk size let's keep writing new chunks\n while(leftOverData.length >= self.chunkSize) {\n // Create a new chunk and write to it\n var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)});\n var firstChunkData = leftOverData.slice(0, self.chunkSize);\n leftOverData = leftOverData.slice(self.chunkSize);\n // Update chunk number\n previousChunkNumber = previousChunkNumber + 1;\n // Write data\n newChunk.write(firstChunkData);\n // Push chunk to save list\n chunksToWrite.push(newChunk);\n }\n\n // Set current chunk with remaining data\n self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)});\n // If we have left over data write it\n if(leftOverData.length > 0) self.currentChunk.write(leftOverData);\n\n // Update the position for the gridstore\n self.position = self.position + buffer.length;\n // Total number of chunks to write\n var numberOfChunksToWrite = chunksToWrite.length;\n // Write out all the chunks and then return\n for(var i = 0; i < chunksToWrite.length; i++) {\n var chunk = chunksToWrite[i];\n chunk.save(function(err, result) {\n if(err) return callback(err);\n\n numberOfChunksToWrite = numberOfChunksToWrite - 1;\n\n if(numberOfChunksToWrite <= 0) {\n return callback(null, self);\n }\n })\n }\n } else {\n // Update the position for the gridstore\n self.position = self.position + buffer.length;\n // We have less data than the chunk size just write it and callback\n self.currentChunk.write(buffer);\n callback(null, self);\n }\n }\n};\n\n/**\n * Creates a mongoDB object representation of this object.\n *\n * @param callback {function(object)} This will be called after executing this\n * method. The object will be passed to the first parameter and will have\n * the structure:\n *\n * <pre><code>\n * {\n * '_id' : , // {number} id for this file\n * 'filename' : , // {string} name for this file\n * 'contentType' : , // {string} mime type for this file\n * 'length' : , // {number} size of this file?\n * 'chunksize' : , // {number} chunk size used by this file\n * 'uploadDate' : , // {Date}\n * 'aliases' : , // {array of string}\n * 'metadata' : , // {string}\n * }\n * </code></pre>\n *\n * @ignore\n * @api private\n */\nvar buildMongoObject = function(self, callback) {\n // // Keeps the final chunk number\n // var chunkNumber = 0;\n // var previousChunkSize = 0;\n // // Get the correct chunk Number, if we have an empty chunk return the previous chunk number\n // if(null != self.currentChunk && self.currentChunk.chunkNumber > 0 && self.currentChunk.position == 0) {\n // chunkNumber = self.currentChunk.chunkNumber - 1;\n // } else {\n // chunkNumber = self.currentChunk.chunkNumber;\n // previousChunkSize = self.currentChunk.position;\n // }\n\n // // Calcuate the length\n // var length = self.currentChunk != null ? (chunkNumber * self.chunkSize + previousChunkSize) : 0;\n var mongoObject = {\n '_id': self.fileId,\n 'filename': self.filename,\n 'contentType': self.contentType,\n 'length': self.position ? self.position : 0,\n 'chunkSize': self.chunkSize,\n 'uploadDate': self.uploadDate,\n 'aliases': self.aliases,\n 'metadata': self.metadata\n };\n\n var md5Command = {filemd5:self.fileId, root:self.root};\n self.db.command(md5Command, function(err, results) {\n mongoObject.md5 = results.md5;\n callback(mongoObject);\n });\n};\n\n/**\n * Saves this file to the database. This will overwrite the old entry if it\n * already exists. This will work properly only if mode was initialized to\n * \"w\" or \"w+\".\n *\n * @param {Function} callback this will be called after executing this method. Passes an **{Error}** object to the first parameter and null to the second if an error occured. Otherwise, passes null to the first and a reference to this object to the second.\n * @return {null}\n * @api public\n */\nGridStore.prototype.close = function(callback) {\n var self = this;\n\n if(self.mode[0] == \"w\") {\n if(self.currentChunk != null && self.currentChunk.position > 0) {\n self.currentChunk.save(function(err, chunk) {\n if(err) return callback(err);\n\n self.collection(function(err, files) {\n if(err) return callback(err);\n\n // Build the mongo object\n if(self.uploadDate != null) {\n files.remove({'_id':self.fileId}, {safe:true}, function(err, collection) {\n if(err) return callback(err);\n\n buildMongoObject(self, function(mongoObject) {\n files.save(mongoObject, {safe:true}, function(err) {\n callback(err, mongoObject);\n });\n });\n });\n } else {\n self.uploadDate = new Date();\n buildMongoObject(self, function(mongoObject) {\n files.save(mongoObject, {safe:true}, function(err) {\n callback(err, mongoObject);\n });\n });\n }\n });\n });\n } else {\n self.collection(function(err, files) {\n if(err) return callback(err);\n\n self.uploadDate = new Date();\n buildMongoObject(self, function(mongoObject) {\n files.save(mongoObject, {safe:true}, function(err) {\n callback(err, mongoObject);\n });\n });\n });\n }\n } else if(self.mode[0] == \"r\") {\n callback(null, null);\n } else {\n callback(new Error(\"Illegal mode \" + self.mode), null);\n }\n};\n\n/**\n * Gets the nth chunk of this file.\n *\n * @param chunkNumber {number} The nth chunk to retrieve.\n * @param callback {function(*, Chunk|object)} This will be called after\n * executing this method. null will be passed to the first parameter while\n * a new {@link Chunk} instance will be passed to the second parameter if\n * the chunk was found or an empty object {} if not.\n *\n * @ignore\n * @api private\n */\nvar nthChunk = function(self, chunkNumber, callback) {\n self.chunkCollection(function(err, collection) {\n if(err) return callback(err);\n\n collection.find({'files_id':self.fileId, 'n':chunkNumber}, function(err, cursor) {\n if(err) return callback(err);\n\n cursor.nextObject(function(err, chunk) {\n if(err) return callback(err);\n\n var finalChunk = chunk == null ? {} : chunk;\n callback(null, new Chunk(self, finalChunk));\n });\n });\n });\n};\n\n/**\n *\n * @ignore\n * @api private\n */\nGridStore.prototype._nthChunk = function(chunkNumber, callback) {\n nthChunk(this, chunkNumber, callback);\n}\n\n/**\n * @return {Number} The last chunk number of this file.\n *\n * @ignore\n * @api private\n */\nvar lastChunkNumber = function(self) {\n return Math.floor(self.length/self.chunkSize);\n};\n\n/**\n * Retrieve this file's chunks collection.\n *\n * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured.\n * @return {null}\n * @api public\n */\nGridStore.prototype.chunkCollection = function(callback) {\n this.db.collection((this.root + \".chunks\"), callback);\n};\n\n/**\n * Deletes all the chunks of this file in the database.\n *\n * @param callback {function(*, boolean)} This will be called after this method\n * executes. Passes null to the first and true to the second argument.\n *\n * @ignore\n * @api private\n */\nvar deleteChunks = function(self, callback) {\n if(self.fileId != null) {\n self.chunkCollection(function(err, collection) {\n if(err) return callback(err, false);\n collection.remove({'files_id':self.fileId}, {safe:true}, function(err, result) {\n if(err) return callback(err, false);\n callback(null, true);\n });\n });\n } else {\n callback(null, true);\n }\n};\n\n/**\n * Deletes all the chunks of this file in the database.\n *\n * @param {Function} callback this will be called after this method executes. Passes null to the first and true to the second argument.\n * @return {null}\n * @api public\n */\nGridStore.prototype.unlink = function(callback) {\n var self = this;\n deleteChunks(this, function(err) {\n if(err!==null) {\n err.message = \"at deleteChunks: \" + err.message;\n return callback(err);\n }\n\n self.collection(function(err, collection) {\n if(err!==null) {\n err.message = \"at collection: \" + err.message;\n return callback(err);\n }\n\n collection.remove({'_id':self.fileId}, {safe:true}, function(err) {\n callback(err, self);\n });\n });\n });\n};\n\n/**\n * Retrieves the file collection associated with this object.\n *\n * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured.\n * @return {null}\n * @api public\n */\nGridStore.prototype.collection = function(callback) {\n this.db.collection(this.root + \".files\", callback);\n};\n\n/**\n * Reads the data of this file.\n *\n * @param {String} [separator] the character to be recognized as the newline separator.\n * @param {Function} callback This will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character.\n * @return {null}\n * @api public\n */\nGridStore.prototype.readlines = function(separator, callback) {\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n separator = args.length ? args.shift() : \"\\n\";\n\n this.read(function(err, data) {\n if(err) return callback(err);\n\n var items = data.toString().split(separator);\n items = items.length > 0 ? items.splice(0, items.length - 1) : [];\n for(var i = 0; i < items.length; i++) {\n items[i] = items[i] + separator;\n }\n\n callback(null, items);\n });\n};\n\n/**\n * Deletes all the chunks of this file in the database if mode was set to \"w\" or\n * \"w+\" and resets the read/write head to the initial position.\n *\n * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {null}\n * @api public\n */\nGridStore.prototype.rewind = function(callback) {\n var self = this;\n\n if(this.currentChunk.chunkNumber != 0) {\n if(this.mode[0] == \"w\") {\n deleteChunks(self, function(err, gridStore) {\n if(err) return callback(err);\n self.currentChunk = new Chunk(self, {'n': 0});\n self.position = 0;\n callback(null, self);\n });\n } else {\n self.currentChunk(0, function(err, chunk) {\n if(err) return callback(err);\n self.currentChunk = chunk;\n self.currentChunk.rewind();\n self.position = 0;\n callback(null, self);\n });\n }\n } else {\n self.currentChunk.rewind();\n self.position = 0;\n callback(null, self);\n }\n};\n\n/**\n * Retrieves the contents of this file and advances the read/write head. Works with Buffers only.\n *\n * There are 3 signatures for this method:\n *\n * (callback)\n * (length, callback)\n * (length, buffer, callback)\n *\n * @param {Number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.\n * @param {String|Buffer} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method.\n * @param {Function} callback this will be called after this method is executed. null will be passed to the first parameter and a string containing the contents of the buffer concatenated with the contents read from this file will be passed to the second.\n * @return {null}\n * @api public\n */\nGridStore.prototype.read = function(length, buffer, callback) {\n var self = this;\n\n var args = Array.prototype.slice.call(arguments, 0);\n callback = args.pop();\n length = args.length ? args.shift() : null;\n buffer = args.length ? args.shift() : null;\n\n // The data is a c-terminated string and thus the length - 1\n var finalLength = length == null ? self.length - self.position : length;\n var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer;\n // Add a index to buffer to keep track of writing position or apply current index\n finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0;\n\n if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) {\n var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index);\n // Copy content to final buffer\n slice.copy(finalBuffer, finalBuffer._index);\n // Update internal position\n self.position = self.position + finalBuffer.length;\n // Check if we don't have a file at all\n if(finalLength == 0 && finalBuffer.length == 0) return callback(new Error(\"File does not exist\"), null);\n // Else return data\n callback(null, finalBuffer);\n } else {\n var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position);\n // Copy content to final buffer\n slice.copy(finalBuffer, finalBuffer._index);\n // Update index position\n finalBuffer._index += slice.length;\n\n // Load next chunk and read more\n nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {\n if(err) return callback(err);\n\n if(chunk.length() > 0) {\n self.currentChunk = chunk;\n self.read(length, finalBuffer, callback);\n } else {\n if (finalBuffer._index > 0) {\n callback(null, finalBuffer)\n } else {\n callback(new Error(\"no chunks found for file, possibly corrupt\"), null);\n }\n }\n });\n }\n}\n\n/**\n * Retrieves the position of the read/write head of this file.\n *\n * @param {Function} callback This gets called after this method terminates. null is passed to the first parameter and the position is passed to the second.\n * @return {null}\n * @api public\n */\nGridStore.prototype.tell = function(callback) {\n callback(null, this.position);\n};\n\n/**\n * Moves the read/write head to a new location.\n *\n * There are 3 signatures for this method\n *\n * Seek Location Modes\n * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file.\n * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file.\n * - **GridStore.IO_SEEK_END**, set the position from the end of the file.\n *\n * @param {Number} [position] the position to seek to\n * @param {Number} [seekLocation] seek mode. Use one of the Seek Location modes.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {null}\n * @api public\n */\nGridStore.prototype.seek = function(position, seekLocation, callback) {\n var self = this;\n\n var args = Array.prototype.slice.call(arguments, 1);\n callback = args.pop();\n seekLocation = args.length ? args.shift() : null;\n\n var seekLocationFinal = seekLocation == null ? exports.GridStore.IO_SEEK_SET : seekLocation;\n var finalPosition = position;\n var targetPosition = 0;\n\n // console.dir(targetPosition)\n\n // Calculate the position\n if(seekLocationFinal == exports.GridStore.IO_SEEK_CUR) {\n targetPosition = self.position + finalPosition;\n } else if(seekLocationFinal == exports.GridStore.IO_SEEK_END) {\n targetPosition = self.length + finalPosition;\n } else {\n targetPosition = finalPosition;\n }\n\n // Get the chunk\n var newChunkNumber = Math.floor(targetPosition/self.chunkSize);\n if(newChunkNumber != self.currentChunk.chunkNumber) {\n var seekChunk = function() {\n nthChunk(self, newChunkNumber, function(err, chunk) {\n self.currentChunk = chunk;\n self.position = targetPosition;\n self.currentChunk.position = (self.position % self.chunkSize);\n callback(err, self);\n });\n };\n\n if(self.mode[0] == 'w') {\n self.currentChunk.save(function(err) {\n if(err) return callback(err);\n seekChunk();\n });\n } else {\n seekChunk();\n }\n } else {\n self.position = targetPosition;\n self.currentChunk.position = (self.position % self.chunkSize);\n callback(null, self);\n }\n};\n\n/**\n * Verify if the file is at EOF.\n *\n * @return {Boolean} true if the read/write head is at the end of this file.\n * @api public\n */\nGridStore.prototype.eof = function() {\n return this.position == this.length ? true : false;\n};\n\n/**\n * Retrieves a single character from this file.\n *\n * @param {Function} callback this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file.\n * @return {null}\n * @api public\n */\nGridStore.prototype.getc = function(callback) {\n var self = this;\n\n if(self.eof()) {\n callback(null, null);\n } else if(self.currentChunk.eof()) {\n nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {\n self.currentChunk = chunk;\n self.position = self.position + 1;\n callback(err, self.currentChunk.getc());\n });\n } else {\n self.position = self.position + 1;\n callback(null, self.currentChunk.getc());\n }\n};\n\n/**\n * Writes a string to the file with a newline character appended at the end if\n * the given string does not have one.\n *\n * @param {String} string the string to write.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {null}\n * @api public\n */\nGridStore.prototype.puts = function(string, callback) {\n var finalString = string.match(/\\n$/) == null ? string + \"\\n\" : string;\n this.write(finalString, callback);\n};\n\n/**\n * Returns read stream based on this GridStore file\n *\n * Events\n * - **data** {function(item) {}} the data event triggers when a document is ready.\n * - **end** {function() {}} the end event triggers when there is no more documents available.\n * - **close** {function() {}} the close event triggers when the stream is closed.\n * - **error** {function(err) {}} the error event triggers if an error happens.\n *\n * @param {Boolean} autoclose if true current GridStore will be closed when EOF and 'close' event will be fired\n * @return {null}\n * @api public\n */\nGridStore.prototype.stream = function(autoclose) {\n return new ReadStream(autoclose, this);\n};\n\n/**\n* The collection to be used for holding the files and chunks collection.\n*\n* @classconstant DEFAULT_ROOT_COLLECTION\n**/\nGridStore.DEFAULT_ROOT_COLLECTION = 'fs';\n\n/**\n* Default file mime type\n*\n* @classconstant DEFAULT_CONTENT_TYPE\n**/\nGridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream';\n\n/**\n* Seek mode where the given length is absolute.\n*\n* @classconstant IO_SEEK_SET\n**/\nGridStore.IO_SEEK_SET = 0;\n\n/**\n* Seek mode where the given length is an offset to the current read/write head.\n*\n* @classconstant IO_SEEK_CUR\n**/\nGridStore.IO_SEEK_CUR = 1;\n\n/**\n* Seek mode where the given length is an offset to the end of the file.\n*\n* @classconstant IO_SEEK_END\n**/\nGridStore.IO_SEEK_END = 2;\n\n/**\n * Checks if a file exists in the database.\n *\n * @param {Db} db the database to query.\n * @param {String} name the name of the file to look for.\n * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.\n * @param {Function} callback this will be called after this method executes. Passes null to the first and passes true to the second if the file exists and false otherwise.\n * @return {null}\n * @api public\n */\nGridStore.exist = function(db, fileIdObject, rootCollection, callback) {\n var args = Array.prototype.slice.call(arguments, 2);\n callback = args.pop();\n rootCollection = args.length ? args.shift() : null;\n\n // Fetch collection\n var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;\n db.collection(rootCollectionFinal + \".files\", function(err, collection) {\n if(err) return callback(err);\n\n // Build query\n var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' )\n ? {'filename':fileIdObject}\n : {'_id':fileIdObject}; // Attempt to locate file\n\n collection.find(query, function(err, cursor) {\n if(err) return callback(err);\n\n cursor.nextObject(function(err, item) {\n if(err) return callback(err);\n callback(null, item == null ? false : true);\n });\n });\n });\n};\n\n/**\n * Gets the list of files stored in the GridFS.\n *\n * @param {Db} db the database to query.\n * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.\n * @param {Function} callback this will be called after this method executes. Passes null to the first and passes an array of strings containing the names of the files.\n * @return {null}\n * @api public\n */\nGridStore.list = function(db, rootCollection, options, callback) {\n var args = Array.prototype.slice.call(arguments, 1);\n callback = args.pop();\n rootCollection = args.length ? args.shift() : null;\n options = args.length ? args.shift() : {};\n\n // Ensure we have correct values\n if(rootCollection != null && typeof rootCollection == 'object') {\n options = rootCollection;\n rootCollection = null;\n }\n\n // Check if we are returning by id not filename\n var byId = options['id'] != null ? options['id'] : false;\n // Fetch item\n var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;\n var items = [];\n db.collection((rootCollectionFinal + \".files\"), function(err, collection) {\n if(err) return callback(err);\n\n collection.find(function(err, cursor) {\n if(err) return callback(err);\n\n cursor.each(function(err, item) {\n if(item != null) {\n items.push(byId ? item._id : item.filename);\n } else {\n callback(err, items);\n }\n });\n });\n });\n};\n\n/**\n * Reads the contents of a file.\n *\n * This method has the following signatures\n *\n * (db, name, callback)\n * (db, name, length, callback)\n * (db, name, length, offset, callback)\n * (db, name, length, offset, options, callback)\n *\n * @param {Db} db the database to query.\n * @param {String} name the name of the file.\n * @param {Number} [length] the size of data to read.\n * @param {Number} [offset] the offset from the head of the file of which to start reading from.\n * @param {Object} [options] the options for the file.\n * @param {Function} callback this will be called after this method executes. A string with an error message will be passed to the first parameter when the length and offset combination exceeds the length of the file while an Error object will be passed if other forms of error occured, otherwise, a string is passed. The second parameter will contain the data read if successful or null if an error occured.\n * @return {null}\n * @api public\n */\nGridStore.read = function(db, name, length, offset, options, callback) {\n var args = Array.prototype.slice.call(arguments, 2);\n callback = args.pop();\n length = args.length ? args.shift() : null;\n offset = args.length ? args.shift() : null;\n options = args.length ? args.shift() : null;\n\n new GridStore(db, name, \"r\", options).open(function(err, gridStore) {\n if(err) return callback(err);\n // Make sure we are not reading out of bounds\n if(offset && offset >= gridStore.length) return callback(\"offset larger than size of file\", null);\n if(length && length > gridStore.length) return callback(\"length is larger than the size of the file\", null);\n if(offset && length && (offset + length) > gridStore.length) return callback(\"offset and length is larger than the size of the file\", null);\n\n if(offset != null) {\n gridStore.seek(offset, function(err, gridStore) {\n if(err) return callback(err);\n gridStore.read(length, callback);\n });\n } else {\n gridStore.read(length, callback);\n }\n });\n};\n\n/**\n * Reads the data of this file.\n *\n * @param {Db} db the database to query.\n * @param {String} name the name of the file.\n * @param {String} [separator] the character to be recognized as the newline separator.\n * @param {Object} [options] file options.\n * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character.\n * @return {null}\n * @api public\n */\nGridStore.readlines = function(db, name, separator, options, callback) {\n var args = Array.prototype.slice.call(arguments, 2);\n callback = args.pop();\n separator = args.length ? args.shift() : null;\n options = args.length ? args.shift() : null;\n\n var finalSeperator = separator == null ? \"\\n\" : separator;\n new GridStore(db, name, \"r\", options).open(function(err, gridStore) {\n if(err) return callback(err);\n gridStore.readlines(finalSeperator, callback);\n });\n};\n\n/**\n * Deletes the chunks and metadata information of a file from GridFS.\n *\n * @param {Db} db the database to interact with.\n * @param {String|Array} names the name/names of the files to delete.\n * @param {Object} [options] the options for the files.\n * @callback {Function} this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object.\n * @return {null}\n * @api public\n */\nGridStore.unlink = function(db, names, options, callback) {\n var self = this;\n var args = Array.prototype.slice.call(arguments, 2);\n callback = args.pop();\n options = args.length ? args.shift() : null;\n\n if(names.constructor == Array) {\n var tc = 0;\n for(var i = 0; i < names.length; i++) {\n ++tc;\n self.unlink(db, names[i], function(result) {\n if(--tc == 0) {\n callback(null, self);\n }\n });\n }\n } else {\n new GridStore(db, names, \"w\", options).open(function(err, gridStore) {\n if(err) return callback(err);\n deleteChunks(gridStore, function(err, result) {\n if(err) return callback(err);\n gridStore.collection(function(err, collection) {\n if(err) return callback(err);\n collection.remove({'_id':gridStore.fileId}, {safe:true}, function(err, collection) {\n callback(err, self);\n });\n });\n });\n });\n }\n};\n\n/**\n * Returns the current chunksize of the file.\n *\n * @field chunkSize\n * @type {Number}\n * @getter\n * @setter\n * @property return number of bytes in the current chunkSize.\n */\nObject.defineProperty(GridStore.prototype, \"chunkSize\", { enumerable: true\n , get: function () {\n return this.internalChunkSize;\n }\n , set: function(value) {\n if(!(this.mode[0] == \"w\" && this.position == 0 && this.uploadDate == null)) {\n this.internalChunkSize = this.internalChunkSize;\n } else {\n this.internalChunkSize = value;\n }\n }\n});\n\n/**\n * The md5 checksum for this file.\n *\n * @field md5\n * @type {Number}\n * @getter\n * @setter\n * @property return this files md5 checksum.\n */\nObject.defineProperty(GridStore.prototype, \"md5\", { enumerable: true\n , get: function () {\n return this.internalMd5;\n }\n});\n\n/**\n * GridStore Streaming methods\n * Handles the correct return of the writeable stream status\n * @ignore\n */\nObject.defineProperty(GridStore.prototype, \"writable\", { enumerable: true\n , get: function () {\n if(this._writeable == null) {\n this._writeable = this.mode != null && this.mode.indexOf(\"w\") != -1;\n }\n // Return the _writeable\n return this._writeable;\n }\n , set: function(value) {\n this._writeable = value;\n }\n});\n\n/**\n * Handles the correct return of the readable stream status\n * @ignore\n */\nObject.defineProperty(GridStore.prototype, \"readable\", { enumerable: true\n , get: function () {\n if(this._readable == null) {\n this._readable = this.mode != null && this.mode.indexOf(\"r\") != -1;\n }\n return this._readable;\n }\n , set: function(value) {\n this._readable = value;\n }\n});\n\nGridStore.prototype.paused;\n\n/**\n * Handles the correct setting of encoding for the stream\n * @ignore\n */\nGridStore.prototype.setEncoding = fs.ReadStream.prototype.setEncoding;\n\n/**\n * Handles the end events\n * @ignore\n */\nGridStore.prototype.end = function end(data) {\n var self = this;\n // allow queued data to write before closing\n if(!this.writable) return;\n this.writable = false;\n\n if(data) {\n this._q.push(data);\n }\n\n this.on('drain', function () {\n self.close(function (err) {\n if (err) return _error(self, err);\n self.emit('close');\n });\n });\n\n _flush(self);\n}\n\n/**\n * Handles the normal writes to gridstore\n * @ignore\n */\nvar _writeNormal = function(self, data, close, callback) {\n // If we have a buffer write it using the writeBuffer method\n if(Buffer.isBuffer(data)) {\n return writeBuffer(self, data, close, callback);\n } else {\n // Wrap the string in a buffer and write\n return writeBuffer(self, new Buffer(data, 'binary'), close, callback);\n }\n}\n\n/**\n * Writes some data. This method will work properly only if initialized with mode \"w\" or \"w+\".\n *\n * @param {String|Buffer} data the data to write.\n * @param {Boolean} [close] closes this file after writing if set to true.\n * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.\n * @return {null}\n * @api public\n */\nGridStore.prototype.write = function write(data, close, callback) {\n // If it's a normal write delegate the call\n if(typeof close == 'function' || typeof callback == 'function') {\n return _writeNormal(this, data, close, callback);\n }\n\n // Otherwise it's a stream write\n var self = this;\n if (!this.writable) {\n throw new Error('GridWriteStream is not writable');\n }\n\n // queue data until we open.\n if (!this._opened) {\n // Set up a queue to save data until gridstore object is ready\n this._q = [];\n _openStream(self);\n this._q.push(data);\n return false;\n }\n\n // Push data to queue\n this._q.push(data);\n _flush(this);\n // Return write successful\n return true;\n}\n\n/**\n * Handles the destroy part of a stream\n * @ignore\n */\nGridStore.prototype.destroy = function destroy() {\n // close and do not emit any more events. queued data is not sent.\n if(!this.writable) return;\n this.readable = false;\n if(this.writable) {\n this.writable = false;\n this._q.length = 0;\n this.emit('close');\n }\n}\n\n/**\n * Handles the destroySoon part of a stream\n * @ignore\n */\nGridStore.prototype.destroySoon = function destroySoon() {\n // as soon as write queue is drained, destroy.\n // may call destroy immediately if no data is queued.\n if(!this._q.length) {\n return this.destroy();\n }\n this._destroying = true;\n}\n\n/**\n * Handles the pipe part of the stream\n * @ignore\n */\nGridStore.prototype.pipe = function(destination, options) {\n var self = this;\n // Open the gridstore\n this.open(function(err, result) {\n if(err) _errorRead(self, err);\n if(!self.readable) return;\n // Set up the pipe\n self._pipe(destination, options);\n // Emit the stream is open\n self.emit('open');\n // Read from the stream\n _read(self);\n })\n}\n\n/**\n * Internal module methods\n * @ignore\n */\nvar _read = function _read(self) {\n if (!self.readable || self.paused || self.reading) {\n return;\n }\n\n self.reading = true;\n var stream = self._stream = self.stream();\n stream.paused = self.paused;\n\n stream.on('data', function (data) {\n if (self._decoder) {\n var str = self._decoder.write(data);\n if (str.length) self.emit('data', str);\n } else {\n self.emit('data', data);\n }\n });\n\n stream.on('end', function (data) {\n self.emit('end', data);\n });\n\n stream.on('error', function (data) {\n _errorRead(self, data);\n });\n\n stream.on('close', function (data) {\n self.emit('close', data);\n });\n\n self.pause = function () {\n // native doesn't always pause.\n // bypass its pause() method to hack it\n self.paused = stream.paused = true;\n }\n\n self.resume = function () {\n if(!self.paused) return;\n\n self.paused = false;\n stream.resume();\n self.readable = stream.readable;\n }\n\n self.destroy = function () {\n self.readable = false;\n stream.destroy();\n }\n}\n\n/**\n * pause\n * @ignore\n */\nGridStore.prototype.pause = function pause () {\n // Overridden when the GridStore opens.\n this.paused = true;\n}\n\n/**\n * resume\n * @ignore\n */\nGridStore.prototype.resume = function resume () {\n // Overridden when the GridStore opens.\n this.paused = false;\n}\n\n/**\n * Internal module methods\n * @ignore\n */\nvar _flush = function _flush(self, _force) {\n if (!self._opened) return;\n if (!_force && self._flushing) return;\n self._flushing = true;\n\n // write the entire q to gridfs\n if (!self._q.length) {\n self._flushing = false;\n self.emit('drain');\n\n if(self._destroying) {\n self.destroy();\n }\n return;\n }\n\n self.write(self._q.shift(), function (err, store) {\n if (err) return _error(self, err);\n self.emit('progress', store.position);\n _flush(self, true);\n });\n}\n\nvar _openStream = function _openStream (self) {\n if(self._opening == true) return;\n self._opening = true;\n\n // Open the store\n self.open(function (err, gridstore) {\n if (err) return _error(self, err);\n self._opened = true;\n self.emit('open');\n _flush(self);\n });\n}\n\nvar _error = function _error(self, err) {\n self.destroy();\n self.emit('error', err);\n}\n\nvar _errorRead = function _errorRead (self, err) {\n self.readable = false;\n self.emit('error', err);\n}\n\n/**\n * @ignore\n * @api private\n */\nexports.GridStore = GridStore;\n\n});","sourceLength":48386,"scriptType":2,"compilationType":0,"context":{"ref":12},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js (lines: 1478)"}],"refs":[{"handle":12,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":528,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[319]}}
{"seq":201,"request_seq":528,"type":"response","command":"scripts","success":true,"body":[{"handle":15,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js","id":319,"lineOffset":0,"columnOffset":0,"lineCount":215,"source":"(function (exports, require, module, __filename, __dirname) { var Binary = require('bson').Binary,\n ObjectID = require('bson').ObjectID;\n\n/**\n * Class for representing a single chunk in GridFS.\n *\n * @class\n *\n * @param file {GridStore} The {@link GridStore} object holding this chunk.\n * @param mongoObject {object} The mongo object representation of this chunk.\n *\n * @throws Error when the type of data field for {@link mongoObject} is not\n * supported. Currently supported types for data field are instances of\n * {@link String}, {@link Array}, {@link Binary} and {@link Binary}\n * from the bson module\n *\n * @see Chunk#buildMongoObject\n */\nvar Chunk = exports.Chunk = function(file, mongoObject) {\n if(!(this instanceof Chunk)) return new Chunk(file, mongoObject);\n\n this.file = file;\n var self = this;\n var mongoObjectFinal = mongoObject == null ? {} : mongoObject;\n\n this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id;\n this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n;\n this.data = new Binary();\n\n if(mongoObjectFinal.data == null) {\n } else if(typeof mongoObjectFinal.data == \"string\") {\n var buffer = new Buffer(mongoObjectFinal.data.length);\n buffer.write(mongoObjectFinal.data, 'binary', 0);\n this.data = new Binary(buffer);\n } else if(Array.isArray(mongoObjectFinal.data)) {\n var buffer = new Buffer(mongoObjectFinal.data.length);\n buffer.write(mongoObjectFinal.data.join(''), 'binary', 0);\n this.data = new Binary(buffer);\n } else if(mongoObjectFinal.data instanceof Binary || Object.prototype.toString.call(mongoObjectFinal.data) == \"[object Binary]\") {\n this.data = mongoObjectFinal.data;\n } else if(Buffer.isBuffer(mongoObjectFinal.data)) {\n } else {\n throw Error(\"Illegal chunk format\");\n }\n // Update position\n this.internalPosition = 0;\n};\n\n/**\n * Writes a data to this object and advance the read/write head.\n *\n * @param data {string} the data to write \n * @param callback {function(*, GridStore)} This will be called after executing\n * this method. The first parameter will contain null and the second one\n * will contain a reference to this object.\n */\nChunk.prototype.write = function(data, callback) {\n this.data.write(data, this.internalPosition);\n this.internalPosition = this.data.length();\n if(callback != null) return callback(null, this);\n return this;\n};\n\n/**\n * Reads data and advances the read/write head.\n *\n * @param length {number} The length of data to read.\n *\n * @return {string} The data read if the given length will not exceed the end of\n * the chunk. Returns an empty String otherwise.\n */\nChunk.prototype.read = function(length) {\n // Default to full read if no index defined\n length = length == null || length == 0 ? this.length() : length;\n\n if(this.length() - this.internalPosition + 1 >= length) {\n var data = this.data.read(this.internalPosition, length);\n this.internalPosition = this.internalPosition + length;\n return data;\n } else {\n return '';\n }\n};\n\nChunk.prototype.readSlice = function(length) {\n if ((this.length() - this.internalPosition) >= length) {\n var data = null;\n if (this.data.buffer != null) { //Pure BSON\n data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length);\n } else { //Native BSON\n data = new Buffer(length);\n length = this.data.readInto(data, this.internalPosition);\n }\n this.internalPosition = this.internalPosition + length;\n return data;\n } else {\n return null;\n }\n};\n\n/**\n * Checks if the read/write head is at the end.\n *\n * @return {boolean} Whether the read/write head has reached the end of this\n * chunk.\n */\nChunk.prototype.eof = function() {\n return this.internalPosition == this.length() ? true : false;\n};\n\n/**\n * Reads one character from the data of this chunk and advances the read/write\n * head.\n *\n * @return {string} a single character data read if the the read/write head is\n * not at the end of the chunk. Returns an empty String otherwise.\n */\nChunk.prototype.getc = function() {\n return this.read(1);\n};\n\n/**\n * Clears the contents of the data in this chunk and resets the read/write head\n * to the initial position.\n */\nChunk.prototype.rewind = function() {\n this.internalPosition = 0;\n this.data = new Binary();\n};\n\n/**\n * Saves this chunk to the database. Also overwrites existing entries having the\n * same id as this chunk.\n *\n * @param callback {function(*, GridStore)} This will be called after executing\n * this method. The first parameter will contain null and the second one\n * will contain a reference to this object.\n */\nChunk.prototype.save = function(callback) {\n var self = this;\n\n self.file.chunkCollection(function(err, collection) {\n if(err) return callback(err);\n\n collection.remove({'_id':self.objectId}, {safe:true}, function(err, result) {\n if(err) return callback(err);\n\n if(self.data.length() > 0) {\n self.buildMongoObject(function(mongoObject) {\n collection.insert(mongoObject, {safe:true}, function(err, collection) {\n callback(err, self);\n });\n });\n } else {\n callback(null, self);\n }\n });\n });\n};\n\n/**\n * Creates a mongoDB object representation of this chunk.\n *\n * @param callback {function(Object)} This will be called after executing this \n * method. The object will be passed to the first parameter and will have\n * the structure:\n * \n * <pre><code>\n * {\n * '_id' : , // {number} id for this chunk\n * 'files_id' : , // {number} foreign key to the file collection\n * 'n' : , // {number} chunk number\n * 'data' : , // {bson#Binary} the chunk data itself\n * }\n * </code></pre>\n *\n * @see <a href=\"http://www.mongodb.org/display/DOCS/GridFS+Specification#GridFSSpecification-{{chunks}}\">MongoDB GridFS Chunk Object Structure</a>\n */\nChunk.prototype.buildMongoObject = function(callback) {\n var mongoObject = {'_id': this.objectId,\n 'files_id': this.file.fileId,\n 'n': this.chunkNumber,\n 'data': this.data};\n callback(mongoObject);\n};\n\n/**\n * @return {number} the length of the data\n */\nChunk.prototype.length = function() {\n return this.data.length();\n};\n\n/**\n * The position of the read/write head\n * @name position\n * @lends Chunk#\n * @field\n */\nObject.defineProperty(Chunk.prototype, \"position\", { enumerable: true\n , get: function () {\n return this.internalPosition;\n }\n , set: function(value) {\n this.internalPosition = value;\n }\n});\n\n/**\n * The default chunk size\n * @constant\n */\nChunk.DEFAULT_CHUNK_SIZE = 1024 * 256;\n\n});","sourceLength":6678,"scriptType":2,"compilationType":0,"context":{"ref":14},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/chunk.js (lines: 215)"}],"refs":[{"handle":14,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":529,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[322]}}
{"seq":202,"request_seq":529,"type":"response","command":"scripts","success":true,"body":[{"handle":17,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js","id":322,"lineOffset":0,"columnOffset":0,"lineCount":195,"source":"(function (exports, require, module, __filename, __dirname) { var Stream = require('stream').Stream,\n timers = require('timers'),\n util = require('util');\n\n// Set processor, setImmediate if 0.10 otherwise nextTick\nvar processor = timers.setImmediate ? timers.setImmediate : process.nextTick;\nprocessor = process.nextTick\n\n/**\n * ReadStream\n *\n * Returns a stream interface for the **file**.\n *\n * Events\n * - **data** {function(item) {}} the data event triggers when a document is ready.\n * - **end** {function() {}} the end event triggers when there is no more documents available.\n * - **close** {function() {}} the close event triggers when the stream is closed.\n * - **error** {function(err) {}} the error event triggers if an error happens.\n *\n * @class Represents a GridFS File Stream.\n * @param {Boolean} autoclose automatically close file when the stream reaches the end.\n * @param {GridStore} cursor a cursor object that the stream wraps.\n * @return {ReadStream}\n */\nfunction ReadStream(autoclose, gstore) {\n if (!(this instanceof ReadStream)) return new ReadStream(autoclose, gstore);\n Stream.call(this);\n\n this.autoclose = !!autoclose;\n this.gstore = gstore;\n\n this.finalLength = gstore.length - gstore.position;\n this.completedLength = 0;\n this.currentChunkNumber = gstore.currentChunk.chunkNumber;\n\n this.paused = false;\n this.readable = true;\n this.pendingChunk = null;\n this.executing = false; \n \n // Calculate the number of chunks\n this.numberOfChunks = Math.ceil(gstore.length/gstore.chunkSize);\n\n // This seek start position inside the current chunk\n this.seekStartPosition = gstore.position - (this.currentChunkNumber * gstore.chunkSize);\n \n var self = this;\n processor(function() {\n self._execute();\n });\n};\n\n/**\n * Inherit from Stream\n * @ignore\n * @api private\n */\nReadStream.prototype.__proto__ = Stream.prototype;\n\n/**\n * Flag stating whether or not this stream is readable.\n */\nReadStream.prototype.readable;\n\n/**\n * Flag stating whether or not this stream is paused.\n */\nReadStream.prototype.paused;\n\n/**\n * @ignore\n * @api private\n */\nReadStream.prototype._execute = function() {\n if(this.paused === true || this.readable === false) {\n return;\n }\n\n var gstore = this.gstore;\n var self = this;\n // Set that we are executing\n this.executing = true;\n\n var last = false;\n var toRead = 0;\n\n if(gstore.currentChunk.chunkNumber >= (this.numberOfChunks - 1)) {\n self.executing = false; \n last = true; \n }\n\n // Data setup\n var data = null;\n\n // Read a slice (with seek set if none)\n if(this.seekStartPosition > 0 && (gstore.currentChunk.length() - this.seekStartPosition) > 0) {\n data = gstore.currentChunk.readSlice(gstore.currentChunk.length() - this.seekStartPosition);\n this.seekStartPosition = 0;\n } else {\n data = gstore.currentChunk.readSlice(gstore.currentChunk.length());\n }\n\n // Return the data\n if(data != null && gstore.currentChunk.chunkNumber == self.currentChunkNumber) {\n self.currentChunkNumber = self.currentChunkNumber + 1;\n self.completedLength += data.length;\n self.pendingChunk = null;\n self.emit(\"data\", data);\n }\n\n if(last === true) {\n self.readable = false;\n self.emit(\"end\");\n \n if(self.autoclose === true) {\n if(gstore.mode[0] == \"w\") {\n gstore.close(function(err, doc) {\n if (err) {\n self.emit(\"error\", err);\n return;\n }\n self.readable = false; \n self.emit(\"close\", doc);\n });\n } else {\n self.readable = false;\n self.emit(\"close\");\n }\n }\n } else {\n gstore._nthChunk(gstore.currentChunk.chunkNumber + 1, function(err, chunk) {\n if(err) {\n self.readable = false;\n self.emit(\"error\", err);\n self.executing = false;\n return;\n }\n\n self.pendingChunk = chunk;\n if(self.paused === true) {\n self.executing = false;\n return;\n }\n\n gstore.currentChunk = self.pendingChunk;\n self._execute(); \n });\n }\n};\n\n/**\n * Pauses this stream, then no farther events will be fired.\n *\n * @ignore\n * @api public\n */\nReadStream.prototype.pause = function() {\n if(!this.executing) {\n this.paused = true; \n }\n};\n\n/**\n * Destroys the stream, then no farther events will be fired.\n *\n * @ignore\n * @api public\n */\nReadStream.prototype.destroy = function() {\n this.readable = false;\n // Emit close event\n this.emit(\"close\");\n};\n\n/**\n * Resumes this stream.\n *\n * @ignore\n * @api public\n */\nReadStream.prototype.resume = function() {\n if(this.paused === false || !this.readable) {\n return;\n }\n \n this.paused = false;\n var self = this;\n processor(function() {\n self._execute();\n });\n};\n\nexports.ReadStream = ReadStream;\n\n});","sourceLength":4765,"scriptType":2,"compilationType":0,"context":{"ref":16},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mongodb/lib/mongodb/gridfs/readstream.js (lines: 195)"}],"refs":[{"handle":16,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":530,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[325]}}
{"seq":203,"request_seq":530,"type":"response","command":"scripts","success":true,"body":[{"handle":19,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/objectid.js","id":325,"lineOffset":0,"columnOffset":0,"lineCount":45,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/**\n * ObjectId type constructor\n *\n * ####Example\n *\n * var id = new mongoose.Types.ObjectId;\n *\n * @constructor ObjectId\n */\n\nvar ObjectId = require(driver + '/objectid');\nmodule.exports = ObjectId;\n\n/**\n * Creates an ObjectId from `str`\n *\n * @param {ObjectId|HexString} str\n * @static fromString\n * @receiver ObjectId\n * @return {ObjectId}\n * @api private\n */\n\nObjectId.fromString;\n\n/**\n * Converts `oid` to a string.\n *\n * @param {ObjectId} oid ObjectId instance\n * @static toString\n * @receiver ObjectId\n * @return {String}\n * @api private\n */\n\nObjectId.toString;\n\n});","sourceLength":747,"scriptType":2,"compilationType":0,"context":{"ref":18},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/objectid.js (lines: 45)"}],"refs":[{"handle":18,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":531,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[328]}}
{"seq":204,"request_seq":531,"type":"response","command":"scripts","success":true,"body":[{"handle":21,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js","id":328,"lineOffset":0,"columnOffset":0,"lineCount":31,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId\n * @constructor NodeMongoDbObjectId\n * @see ObjectId\n */\n\nvar ObjectId = require('mongodb').BSONPure.ObjectID;\n\n/*!\n * ignore\n */\n\nvar ObjectIdToString = ObjectId.toString.bind(ObjectId);\nmodule.exports = exports = ObjectId;\n\nObjectId.fromString = function(str){\n // patch native driver bug in V0.9.6.4\n if (!('string' === typeof str && 24 === str.length)) {\n throw new Error(\"Invalid ObjectId\");\n }\n\n return ObjectId.createFromHexString(str);\n};\n\nObjectId.toString = function(oid){\n if (!arguments.length) return ObjectIdToString();\n return oid.toHexString();\n};\n\n});","sourceLength":726,"scriptType":2,"compilationType":0,"context":{"ref":20},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js (lines: 31)"}],"refs":[{"handle":20,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":532,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[331]}}
{"seq":207,"request_seq":532,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/ms/ms.js","id":331,"lineOffset":0,"columnOffset":0,"lineCount":37,"source":"(function (exports, require, module, __filename, __dirname) { /**\n\n# ms.js\n\nNo more painful `setTimeout(fn, 60 * 4 * 3 * 2 * 1 * Infinity * NaN * '')`.\n\n ms('2d') // 172800000\n ms('1.5h') // 5400000\n ms('1h') // 3600000\n ms('1m') // 60000\n ms('5s') // 5000\n ms('500ms') // 500\n ms('100') // '100'\n ms(100) // 100\n\n**/\n\n(function (g) {\n var r = /(\\d*.?\\d+)([mshd]+)/\n , _ = {}\n\n _.ms = 1;\n _.s = 1000;\n _.m = _.s * 60;\n _.h = _.m * 60;\n _.d = _.h * 24;\n\n function ms (s) {\n if (s == Number(s)) return Number(s);\n r.exec(s.toLowerCase());\n return RegExp.$1 * _[RegExp.$2];\n }\n\n g.top ? g.ms = ms : module.exports = ms;\n})(this);\n\n});","sourceLength":713,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/ms/ms.js (lines: 37)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":533,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[334]}}
{"seq":210,"request_seq":533,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/sliced/index.js","id":334,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function (exports, require, module, __filename, __dirname) { module.exports = exports = require('./lib/sliced');\n\n});","sourceLength":118,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/sliced/index.js (lines: 3)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":534,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[337]}}
{"seq":211,"request_seq":534,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/sliced/lib/sliced.js","id":337,"lineOffset":0,"columnOffset":0,"lineCount":35,"source":"(function (exports, require, module, __filename, __dirname) { \n/**\n * An Array.prototype.slice.call(arguments) alternative\n *\n * @param {Object} args something with a length\n * @param {Number} slice\n * @param {Number} sliceEnd\n * @api public\n */\n\nmodule.exports = function (args, slice, sliceEnd) {\n var ret = [];\n var len = args.length;\n\n if (0 === len) return ret;\n\n var start = slice < 0\n ? Math.max(0, slice + len)\n : slice || 0;\n\n var end = 3 === arguments.length\n ? sliceEnd < 0\n ? sliceEnd + len\n : sliceEnd\n : len;\n\n for (var i = start; i < end; ++i) {\n ret[i - start] = args[i];\n }\n\n return ret;\n}\n\n\n});","sourceLength":645,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/sliced/lib/sliced.js (lines: 35)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":535,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[340]}}
{"seq":214,"request_seq":535,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpath/index.js","id":340,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function (exports, require, module, __filename, __dirname) { module.exports = exports = require('./lib');\n\n});","sourceLength":111,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpath/index.js (lines: 3)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":536,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[343]}}
{"seq":215,"request_seq":536,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpath/lib/index.js","id":343,"lineOffset":0,"columnOffset":0,"lineCount":185,"source":"(function (exports, require, module, __filename, __dirname) { \n/**\n * Returns the value of object `o` at the given `path`.\n *\n * ####Example:\n *\n * var obj = {\n * comments: [\n * { title: 'exciting!', _doc: { title: 'great!' }}\n * , { title: 'number dos' }\n * ]\n * }\n *\n * mpath.get('comments.0.title', o) // 'exciting!'\n * mpath.get('comments.0.title', o, '_doc') // 'great!'\n * mpath.get('comments.title', o) // ['exciting!', 'number dos']\n *\n * // summary\n * mpath.get(path, o)\n * mpath.get(path, o, special)\n * mpath.get(path, o, map)\n * mpath.get(path, o, special, map)\n *\n * @param {String} path\n * @param {Object} o\n * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property.\n * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place.\n */\n\nexports.get = function (path, o, special, map) {\n if ('function' == typeof special) {\n map = special;\n special = undefined;\n }\n\n map || (map = K);\n\n var parts = 'string' == typeof path\n ? path.split('.')\n : path\n\n if (!Array.isArray(parts)) {\n throw new TypeError('Invalid `path`. Must be either string or array');\n }\n\n var obj = o\n , part;\n\n for (var i = 0; i < parts.length; ++i) {\n part = parts[i];\n\n if (Array.isArray(obj) && !/^\\d+$/.test(part)) {\n // reading a property from the array items\n var paths = parts.slice(i);\n\n return obj.map(function (item) {\n return item\n ? exports.get(paths, item, special, map)\n : map(undefined);\n });\n }\n\n obj = special && obj[special]\n ? obj[special][part]\n : obj[part];\n\n if (!obj) return map(obj);\n }\n\n return map(obj);\n}\n\n/**\n * Sets the `val` at the given `path` of object `o`.\n *\n * @param {String} path\n * @param {Anything} val\n * @param {Object} o\n * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property.\n * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place.\n\n */\n\nexports.set = function (path, val, o, special, map, _copying) {\n if ('function' == typeof special) {\n map = special;\n special = undefined;\n }\n\n map || (map = K);\n\n var parts = 'string' == typeof path\n ? path.split('.')\n : path\n\n if (!Array.isArray(parts)) {\n throw new TypeError('Invalid `path`. Must be either string or array');\n }\n\n if (null == o) return;\n\n // the existance of $ in a path tells us if the user desires\n // the copying of an array instead of setting each value of\n // the array to the one by one to matching positions of the\n // current array.\n var copy = _copying || /\\$/.test(path)\n , obj = o\n , part\n\n for (var i = 0, len = parts.length - 1; i < len; ++i) {\n part = parts[i];\n\n if ('$' == part) {\n if (i == len - 1) {\n break;\n } else {\n continue;\n }\n }\n\n if (Array.isArray(obj) && !/^\\d+$/.test(part)) {\n var paths = parts.slice(i);\n if (!copy && Array.isArray(val)) {\n for (var j = 0; j < obj.length && j < val.length; ++j) {\n // assignment of single values of array\n exports.set(paths, val[j], obj[j], special, map, copy);\n }\n } else {\n for (var j = 0; j < obj.length; ++j) {\n // assignment of entire value\n exports.set(paths, val, obj[j], special, map, copy);\n }\n }\n return;\n }\n\n obj = special && obj[special]\n ? obj[special][part]\n : obj[part];\n\n if (!obj) return;\n }\n\n // process the last property of the path\n\n part = parts[len];\n\n // use the special property if exists\n if (special && obj[special]) {\n obj = obj[special];\n }\n\n // set the value on the last branch\n if (Array.isArray(obj) && !/^\\d+$/.test(part)) {\n if (!copy && Array.isArray(val)) {\n for (var item, j = 0; j < obj.length && j < val.length; ++j) {\n item = obj[j];\n if (item) {\n if (item[special]) item = item[special];\n item[part] = map(val[j]);\n }\n }\n } else {\n for (var j = 0; j < obj.length; ++j) {\n item = obj[j];\n if (item) {\n if (item[special]) item = item[special];\n item[part] = map(val);\n }\n }\n }\n } else {\n obj[part] = map(val);\n }\n}\n\n/*!\n * Returns the value passed to it.\n */\n\nfunction K (v) {\n return v;\n}\n\n});","sourceLength":4660,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpath/lib/index.js (lines: 185)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":537,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[346]}}
{"seq":216,"request_seq":537,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/index.js","id":346,"lineOffset":0,"columnOffset":0,"lineCount":30,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module exports.\n */\n\nexports.String = require('./string');\n\nexports.Number = require('./number');\n\nexports.Boolean = require('./boolean');\n\nexports.DocumentArray = require('./documentarray');\n\nexports.Array = require('./array');\n\nexports.Buffer = require('./buffer');\n\nexports.Date = require('./date');\n\nexports.ObjectId = require('./objectid');\n\nexports.Mixed = require('./mixed');\n\n// alias\n\nexports.Oid = exports.ObjectId;\nexports.Object = exports.Mixed;\nexports.Bool = exports.Boolean;\n\n});","sourceLength":564,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/index.js (lines: 30)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":538,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[349]}}
{"seq":219,"request_seq":538,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/string.js","id":349,"lineOffset":0,"columnOffset":0,"lineCount":297,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar SchemaType = require('../schematype')\n , CastError = SchemaType.CastError\n , utils = require('../utils')\n , Document\n\n/**\n * String SchemaType constructor.\n *\n * @param {String} key\n * @param {Object} options\n * @inherits SchemaType\n * @api private\n */\n\nfunction SchemaString (key, options) {\n this.enumValues = [];\n this.regExp = null;\n SchemaType.call(this, key, options, 'String');\n};\n\n/*!\n * Inherits from SchemaType.\n */\n\nSchemaString.prototype.__proto__ = SchemaType.prototype;\n\n/**\n * Adds enumeration values and a coinciding validator.\n *\n * ####Example:\n *\n * var states = 'opening open closing closed'.split(' ')\n * var s = new Schema({ state: { type: String, enum: states })\n * var M = db.model('M', s)\n * var m = new M({ state: 'invalid' })\n * m.save(function (err) {\n * console.error(err) // validator error\n * m.state = 'open'\n * m.save() // success\n * })\n *\n * @param {String} [args...] enumeration values\n * @api public\n */\n\nSchemaString.prototype.enum = function () {\n var len = arguments.length;\n if (!len || undefined === arguments[0] || false === arguments[0]) {\n if (this.enumValidator){\n this.enumValidator = false;\n this.validators = this.validators.filter(function(v){\n return v[1] != 'enum';\n });\n }\n return;\n }\n\n for (var i = 0; i < len; i++) {\n if (undefined !== arguments[i]) {\n this.enumValues.push(this.cast(arguments[i]));\n }\n }\n\n if (!this.enumValidator) {\n var values = this.enumValues;\n this.enumValidator = function(v){\n return undefined === v || ~values.indexOf(v);\n };\n this.validators.push([this.enumValidator, 'enum']);\n }\n};\n\n/**\n * Adds a lowercase setter.\n *\n * ####Example:\n *\n * var s = new Schema({ email: { type: String, lowercase: true }})\n * var M = db.model('M', s);\n * var m = new M({ email: '[email protected]' });\n * console.log(m.email) // [email protected]\n *\n * @api public\n */\n\nSchemaString.prototype.lowercase = function () {\n return this.set(function (v, self) {\n if ('string' != typeof v) v = self.cast(v)\n if (v) return v.toLowerCase();\n return v;\n });\n};\n\n/**\n * Adds an uppercase setter.\n *\n * ####Example:\n *\n * var s = new Schema({ caps: { type: String, uppercase: true }})\n * var M = db.model('M', s);\n * var m = new M({ caps: 'an example' });\n * console.log(m.caps) // AN EXAMPLE\n *\n * @api public\n */\n\nSchemaString.prototype.uppercase = function () {\n return this.set(function (v, self) {\n if ('string' != typeof v) v = self.cast(v)\n if (v) return v.toUpperCase();\n return v;\n });\n};\n\n/**\n * Adds a trim setter.\n *\n * The string value will be trimmed when set.\n *\n * ####Example:\n *\n * var s = new Schema({ name: { type: String, trim: true }})\n * var M = db.model('M', s)\n * var string = ' some name '\n * console.log(string.length) // 11\n * var m = new M({ name: string })\n * console.log(m.name.length) // 9\n *\n * @api public\n */\n\nSchemaString.prototype.trim = function () {\n return this.set(function (v, self) {\n if ('string' != typeof v) v = self.cast(v)\n if (v) return v.trim();\n return v;\n });\n};\n\n/**\n * Sets a regexp validator.\n *\n * Any value that does not pass `regExp`.test(val) will fail validation.\n *\n * ####Example:\n *\n * var s = new Schema({ name: { type: String, match: /^a/ }})\n * var M = db.model('M', s)\n * var m = new M({ name: 'invalid' })\n * m.validate(function (err) {\n * console.error(err) // validation error\n * m.name = 'apples'\n * m.validate(function (err) {\n * assert.ok(err) // success\n * })\n * })\n *\n * @param {RegExp} regExp regular expression to test against\n * @api public\n */\n\nSchemaString.prototype.match = function match (regExp) {\n this.validators.push([function(v){\n return null != v && '' !== v\n ? regExp.test(v)\n : true\n }, 'regexp']);\n};\n\n/**\n * Check required\n *\n * @param {String|null|undefined} value\n * @api private\n */\n\nSchemaString.prototype.checkRequired = function checkRequired (value, doc) {\n if (SchemaType._isRef(this, value, doc, true)) {\n return null != value;\n } else {\n return (value instanceof String || typeof value == 'string') && value.length;\n }\n};\n\n/**\n * Casts to String\n *\n * @api private\n */\n\nSchemaString.prototype.cast = function (value, doc, init) {\n if (SchemaType._isRef(this, value, doc, init)) {\n // wait! we may need to cast this to a document\n\n // lazy load\n Document || (Document = require('./../document'));\n\n if (value instanceof Document || null == value) {\n return value;\n }\n\n // setting a populated path\n if ('string' == typeof value) {\n return value;\n } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {\n throw new CastError('string', value, this.path);\n }\n\n // Handle the case where user directly sets a populated\n // path to a plain object; cast to the Model used in\n // the population query.\n var path = doc.$__fullPath(this.path);\n var owner = doc.ownerDocument ? doc.ownerDocument() : doc;\n var pop = owner.populated(path, true);\n return new pop.options.model(value);\n }\n\n if (value === null) {\n return value;\n }\n\n if ('undefined' !== typeof value) {\n // handle documents being passed\n if (value._id && 'string' == typeof value._id) {\n return value._id;\n }\n if (value.toString) {\n return value.toString();\n }\n }\n\n\n throw new CastError('string', value, this.path);\n};\n\n/*!\n * ignore\n */\n\nfunction handleSingle (val) {\n return this.castForQuery(val);\n}\n\nfunction handleArray (val) {\n var self = this;\n return val.map(function (m) {\n return self.castForQuery(m);\n });\n}\n\nSchemaString.prototype.$conditionalHandlers = {\n '$ne' : handleSingle\n , '$in' : handleArray\n , '$nin': handleArray\n , '$gt' : handleSingle\n , '$lt' : handleSingle\n , '$gte': handleSingle\n , '$lte': handleSingle\n , '$all': handleArray\n , '$regex': handleSingle\n , '$options': handleSingle\n};\n\n/**\n * Casts contents for queries.\n *\n * @param {String} $conditional\n * @param {any} [val]\n * @api private\n */\n\nSchemaString.prototype.castForQuery = function ($conditional, val) {\n var handler;\n if (arguments.length === 2) {\n handler = this.$conditionalHandlers[$conditional];\n if (!handler)\n throw new Error(\"Can't use \" + $conditional + \" with String.\");\n return handler.call(this, val);\n } else {\n val = $conditional;\n if (val instanceof RegExp) return val;\n return this.cast(val);\n }\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = SchemaString;\n\n});","sourceLength":6713,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/string.js (lines: 297)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":539,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[352]}}
{"seq":220,"request_seq":539,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schematype.js","id":352,"lineOffset":0,"columnOffset":0,"lineCount":645,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar utils = require('./utils');\nvar CastError = require('./error').CastError;\nvar ValidatorError = require('./error').ValidatorError;\n\n/**\n * SchemaType constructor\n *\n * @param {String} path\n * @param {Object} [options]\n * @param {String} [instance]\n * @api public\n */\n\nfunction SchemaType (path, options, instance) {\n this.path = path;\n this.instance = instance;\n this.validators = [];\n this.setters = [];\n this.getters = [];\n this.options = options;\n this._index = null;\n this.selected;\n\n for (var i in options) if (this[i] && 'function' == typeof this[i]) {\n // { unique: true, index: true }\n if ('index' == i && this._index) continue;\n\n var opts = Array.isArray(options[i])\n ? options[i]\n : [options[i]];\n\n this[i].apply(this, opts);\n }\n};\n\n/**\n * Sets a default value for this SchemaType.\n *\n * ####Example:\n *\n * var schema = new Schema({ n: { type: Number, default: 10 })\n * var M = db.model('M', schema)\n * var m = new M;\n * console.log(m.n) // 10\n *\n * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.\n *\n * ####Example:\n *\n * // values are cast:\n * var schema = new Schema({ aNumber: Number, default: \"4.815162342\" })\n * var M = db.model('M', schema)\n * var m = new M;\n * console.log(m.aNumber) // 4.815162342\n *\n * // default unique objects for Mixed types:\n * var schema = new Schema({ mixed: Schema.Types.Mixed });\n * schema.path('mixed').default(function () {\n * return {};\n * });\n *\n * // if we don't use a function to return object literals for Mixed defaults,\n * // each document will receive a reference to the same object literal creating\n * // a \"shared\" object instance:\n * var schema = new Schema({ mixed: Schema.Types.Mixed });\n * schema.path('mixed').default({});\n * var M = db.model('M', schema);\n * var m1 = new M;\n * m1.mixed.added = 1;\n * console.log(m1.mixed); // { added: 1 }\n * var m2 = new M;\n * console.log(m2.mixed); // { added: 1 }\n *\n * @param {Function|any} val the default value\n * @return {defaultValue}\n * @api public\n */\n\nSchemaType.prototype.default = function (val) {\n if (1 === arguments.length) {\n this.defaultValue = typeof val === 'function'\n ? val\n : this.cast(val);\n return this;\n } else if (arguments.length > 1) {\n this.defaultValue = utils.args(arguments);\n }\n return this.defaultValue;\n};\n\n/**\n * Declares the index options for this schematype.\n *\n * ####Example:\n *\n * var s = new Schema({ name: { type: String, index: true })\n * var s = new Schema({ loc: { type: [Number], index: 'hashed' })\n * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })\n * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})\n * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})\n * Schema.path('my.path').index(true);\n * Schema.path('my.date').index({ expires: 60 });\n * Schema.path('my.path').index({ unique: true, sparse: true });\n *\n * ####NOTE:\n *\n * _Indexes are created in the background by default. Specify `background: false` to override._\n *\n * [Direction doesn't matter for single key indexes](http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes)\n *\n * @param {Object|Boolean|String} options\n * @return {SchemaType} this\n * @api public\n */\n\nSchemaType.prototype.index = function (options) {\n this._index = options;\n utils.expires(this._index);\n return this;\n};\n\n/**\n * Declares an unique index.\n *\n * ####Example:\n *\n * var s = new Schema({ name: { type: String, unique: true })\n * Schema.path('name').index({ unique: true });\n *\n * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._\n *\n * @param {Boolean} bool\n * @return {SchemaType} this\n * @api public\n */\n\nSchemaType.prototype.unique = function (bool) {\n if (null == this._index || 'boolean' == typeof this._index) {\n this._index = {};\n } else if ('string' == typeof this._index) {\n this._index = { type: this._index };\n }\n\n this._index.unique = bool;\n return this;\n};\n\n/**\n * Declares a sparse index.\n *\n * ####Example:\n *\n * var s = new Schema({ name: { type: String, sparse: true })\n * Schema.path('name').index({ sparse: true });\n *\n * @param {Boolean} bool\n * @return {SchemaType} this\n * @api public\n */\n\nSchemaType.prototype.sparse = function (bool) {\n if (null == this._index || 'boolean' == typeof this._index) {\n this._index = {};\n } else if ('string' == typeof this._index) {\n this._index = { type: this._index };\n }\n\n this._index.sparse = bool;\n return this;\n};\n\n/**\n * Adds a setter to this schematype.\n *\n * ####Example:\n *\n * function capitalize (val) {\n * if ('string' != typeof val) val = '';\n * return val.charAt(0).toUpperCase() + val.substring(1);\n * }\n *\n * // defining within the schema\n * var s = new Schema({ name: { type: String, set: capitalize }})\n *\n * // or by retreiving its SchemaType\n * var s = new Schema({ name: String })\n * s.path('name').set(capitalize)\n *\n * Setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key.\n *\n * Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, [email protected] can be registered for 2 accounts via [email protected] and [email protected].\n *\n * You can set up email lower case normalization easily via a Mongoose setter.\n *\n * function toLower (v) {\n * return v.toLowerCase();\n * }\n *\n * var UserSchema = new Schema({\n * email: { type: String, set: toLower }\n * })\n *\n * var User = db.model('User', UserSchema)\n *\n * var user = new User({email: '[email protected]'})\n * console.log(user.email); // '[email protected]'\n *\n * // or\n * var user = new User\n * user.email = '[email protected]'\n * console.log(user.email) // '[email protected]'\n *\n * As you can see above, setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key.\n *\n * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._\n *\n * new Schema({ email: { type: String, lowercase: true }})\n *\n * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.\n *\n * function inspector (val, schematype) {\n * if (schematype.options.required) {\n * return schematype.path + ' is required';\n * } else {\n * return val;\n * }\n * }\n *\n * var VirusSchema = new Schema({\n * name: { type: String, required: true, set: inspector },\n * taxonomy: { type: String, set: inspector }\n * })\n *\n * var Virus = db.model('Virus', VirusSchema);\n * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });\n *\n * console.log(v.name); // name is required\n * console.log(v.taxonomy); // Parvovirinae\n *\n * @param {Function} fn\n * @return {SchemaType} this\n * @api public\n */\n\nSchemaType.prototype.set = function (fn) {\n if ('function' != typeof fn)\n throw new TypeError('A setter must be a function.');\n this.setters.push(fn);\n return this;\n};\n\n/**\n * Adds a getter to this schematype.\n *\n * ####Example:\n *\n * function dob (val) {\n * if (!val) return val;\n * return (val.getMonth() + 1) + \"/\" + val.getDate() + \"/\" + val.getFullYear();\n * }\n *\n * // defining within the schema\n * var s = new Schema({ born: { type: Date, get: dob })\n *\n * // or by retreiving its SchemaType\n * var s = new Schema({ born: Date })\n * s.path('born').get(dob)\n *\n * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.\n *\n * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:\n *\n * function obfuscate (cc) {\n * return '****-****-****-' + cc.slice(cc.length-4, cc.length);\n * }\n *\n * var AccountSchema = new Schema({\n * creditCardNumber: { type: String, get: obfuscate }\n * });\n *\n * var Account = db.model('Account', AccountSchema);\n *\n * Account.findById(id, function (err, found) {\n * console.log(found.creditCardNumber); // '****-****-****-1234'\n * });\n *\n * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.\n *\n * function inspector (val, schematype) {\n * if (schematype.options.required) {\n * return schematype.path + ' is required';\n * } else {\n * return schematype.path + ' is not';\n * }\n * }\n *\n * var VirusSchema = new Schema({\n * name: { type: String, required: true, get: inspector },\n * taxonomy: { type: String, get: inspector }\n * })\n *\n * var Virus = db.model('Virus', VirusSchema);\n *\n * Virus.findById(id, function (err, virus) {\n * console.log(virus.name); // name is required\n * console.log(virus.taxonomy); // taxonomy is not\n * })\n *\n * @param {Function} fn\n * @return {SchemaType} this\n * @api public\n */\n\nSchemaType.prototype.get = function (fn) {\n if ('function' != typeof fn)\n throw new TypeError('A getter must be a function.');\n this.getters.push(fn);\n return this;\n};\n\n/**\n * Adds validator(s) for this document path.\n *\n * Validators always receive the value to validate as their first argument and must return `Boolean`. Returning false is interpreted as validation failure.\n *\n * ####Examples:\n *\n * function validator (val) {\n * return val == 'something';\n * }\n *\n * new Schema({ name: { type: String, validate: validator }});\n *\n * // with a custom error message\n *\n * var custom = [validator, 'validation failed']\n * new Schema({ name: { type: String, validate: custom }});\n *\n * var many = [\n * { validator: validator, msg: 'uh oh' }\n * , { validator: fn, msg: 'failed' }\n * ]\n * new Schema({ name: { type: String, validate: many }});\n *\n * // or utilizing SchemaType methods directly:\n *\n * var schema = new Schema({ name: 'string' });\n * schema.path('name').validate(validator, 'validation failed');\n *\n * ####Asynchronous validation:\n *\n * Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The second argument is an callback function that must be passed either `true` or `false` when validation is complete.\n *\n * schema.path('name').validate(function (value, respond) {\n * doStuff(value, function () {\n * ...\n * respond(false); // validation failed\n * })\n* }, 'my error type');\n*\n * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.\n *\n * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate).\n *\n * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along.\n *\n * var conn = mongoose.createConnection(..);\n * conn.on('error', handleError);\n *\n * var Product = conn.model('Product', yourSchema);\n * var dvd = new Product(..);\n * dvd.save(); // emits error on the `conn` above\n *\n * If you desire handling these errors at the Model level, attach an `error` listener to your Model and the event will instead be emitted there.\n *\n * // registering an error listener on the Model lets us handle errors more locally\n * Product.on('error', handleError);\n *\n * @param {RegExp|Function|Object} obj validator\n * @param {String} [error] optional error message\n * @api public\n */\n\nSchemaType.prototype.validate = function (obj, error) {\n if ('function' == typeof obj || obj && 'RegExp' === obj.constructor.name) {\n this.validators.push([obj, error]);\n return this;\n }\n\n var i = arguments.length\n , arg\n\n while (i--) {\n arg = arguments[i];\n if (!(arg && 'Object' == arg.constructor.name)) {\n var msg = 'Invalid validator. Received (' + typeof arg + ') '\n + arg\n + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate';\n\n throw new Error(msg);\n }\n this.validate(arg.validator, arg.msg);\n }\n\n return this;\n};\n\n/**\n * Adds a required validator to this schematype.\n *\n * ####Example:\n *\n * var s = new Schema({ born: { type: Date, required: true })\n * // or\n * Schema.path('name').required(true);\n *\n *\n * @param {Boolean} required enable/disable the validator\n * @return {SchemaType} this\n * @api public\n */\n\nSchemaType.prototype.required = function (required) {\n var self = this;\n\n function __checkRequired (v) {\n // in here, `this` refers to the validating document.\n // no validation when this path wasn't selected in the query.\n if ('isSelected' in this &&\n !this.isSelected(self.path) &&\n !this.isModified(self.path)) return true;\n return self.checkRequired(v, this);\n }\n\n if (false === required) {\n this.isRequired = false;\n this.validators = this.validators.filter(function (v) {\n return v[0].name !== '__checkRequired';\n });\n } else {\n this.isRequired = true;\n this.validators.push([__checkRequired, 'required']);\n }\n\n return this;\n};\n\n/**\n * Gets the default value\n *\n * @param {Object} scope the scope which callback are executed\n * @param {Boolean} init\n * @api private\n */\n\nSchemaType.prototype.getDefault = function (scope, init) {\n var ret = 'function' === typeof this.defaultValue\n ? this.defaultValue.call(scope)\n : this.defaultValue;\n\n if (null !== ret && undefined !== ret) {\n return this.cast(ret, scope, init);\n } else {\n return ret;\n }\n};\n\n/**\n * Applies setters\n *\n * @param {Object} value\n * @param {Object} scope\n * @param {Boolean} init\n * @api private\n */\n\nSchemaType.prototype.applySetters = function (value, scope, init, priorVal) {\n if (SchemaType._isRef(this, value, scope, init)) {\n return init\n ? value\n : this.cast(value, scope, init, priorVal);\n }\n\n var v = value\n , setters = this.setters\n , len = setters.length\n\n if (!len) {\n if (null === v || undefined === v) return v;\n return this.cast(v, scope, init, priorVal)\n }\n\n while (len--) {\n v = setters[len].call(scope, v, this);\n }\n\n if (null === v || undefined === v) return v;\n\n // do not cast until all setters are applied #665\n v = this.cast(v, scope, init, priorVal);\n\n return v;\n};\n\n/**\n * Applies getters to a value\n *\n * @param {Object} value\n * @param {Object} scope\n * @api private\n */\n\nSchemaType.prototype.applyGetters = function (value, scope) {\n if (SchemaType._isRef(this, value, scope, true)) return value;\n\n var v = value\n , getters = this.getters\n , len = getters.length;\n\n if (!len) {\n return v;\n }\n\n while (len--) {\n v = getters[len].call(scope, v, this);\n }\n\n return v;\n};\n\n/**\n * Sets default `select()` behavior for this path.\n *\n * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level.\n *\n * ####Example:\n *\n * T = db.model('T', new Schema({ x: { type: String, select: true }}));\n * T.find(..); // field x will always be selected ..\n * // .. unless overridden;\n * T.find().select('-x').exec(callback);\n *\n * @param {Boolean} val\n * @api public\n */\n\nSchemaType.prototype.select = function select (val) {\n this.selected = !! val;\n}\n\n/**\n * Performs a validation of `value` using the validators declared for this SchemaType.\n *\n * @param {any} value\n * @param {Function} callback\n * @param {Object} scope\n * @api private\n */\n\nSchemaType.prototype.doValidate = function (value, fn, scope) {\n var err = false\n , path = this.path\n , count = this.validators.length;\n\n if (!count) return fn(null);\n\n function validate (ok, msg, val) {\n if (err) return;\n if (ok === undefined || ok) {\n --count || fn(null);\n } else {\n fn(err = new ValidatorError(path, msg, val));\n }\n }\n\n this.validators.forEach(function (v) {\n var validator = v[0]\n , message = v[1];\n\n if (validator instanceof RegExp) {\n validate(validator.test(value), message, value);\n } else if ('function' === typeof validator) {\n if (2 === validator.length) {\n validator.call(scope, value, function (ok) {\n validate(ok, message, value);\n });\n } else {\n validate(validator.call(scope, value), message, value);\n }\n }\n });\n};\n\n/**\n * Determines if value is a valid Reference.\n *\n * @param {SchemaType} self\n * @param {Object} value\n * @param {Document} doc\n * @param {Boolean} init\n * @return {Boolean}\n * @api private\n */\n\nSchemaType._isRef = function (self, value, doc, init) {\n // fast path\n var ref = init && self.options && self.options.ref;\n\n if (!ref && doc && doc.$__fullPath) {\n // checks for\n // - this populated with adhoc model and no ref was set in schema OR\n // - setting / pushing values after population\n var path = doc.$__fullPath(self.path);\n var owner = doc.ownerDocument ? doc.ownerDocument() : doc;\n ref = owner.populated(path);\n }\n\n if (ref) {\n if (null == value) return true;\n if (!Buffer.isBuffer(value) && // buffers are objects too\n 'Binary' != value._bsontype // raw binary value from the db\n && utils.isObject(value) // might have deselected _id in population query\n ) {\n return true;\n }\n }\n\n return false;\n}\n\n/*!\n * Module exports.\n */\n\nmodule.exports = exports = SchemaType;\n\nexports.CastError = CastError;\n\nexports.ValidatorError = ValidatorError;\n\n});","sourceLength":18536,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schematype.js (lines: 645)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":540,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[355]}}
{"seq":228,"request_seq":540,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/error.js","id":355,"lineOffset":0,"columnOffset":0,"lineCount":41,"source":"(function (exports, require, module, __filename, __dirname) { \n/**\n * MongooseError constructor\n *\n * @param {String} msg Error message\n * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error\n */\n\nfunction MongooseError (msg) {\n Error.call(this);\n Error.captureStackTrace(this, arguments.callee);\n this.message = msg;\n this.name = 'MongooseError';\n};\n\n/*!\n * Inherits from Error.\n */\n\nMongooseError.prototype.__proto__ = Error.prototype;\n\n/*!\n * Module exports.\n */\n\nmodule.exports = exports = MongooseError;\n\n/*!\n * Expose subclasses\n */\n\nMongooseError.CastError = require('./errors/cast');\nMongooseError.DocumentError = require('./errors/document');\nMongooseError.ValidationError = require('./errors/validation')\nMongooseError.ValidatorError = require('./errors/validator')\nMongooseError.VersionError =require('./errors/version')\nMongooseError.OverwriteModelError = require('./errors/overwriteModel')\nMongooseError.MissingSchemaError = require('./errors/missingSchema')\nMongooseError.DivergentArrayError = require('./errors/divergentArray')\n\n});","sourceLength":1089,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/error.js (lines: 41)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":541,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[358]}}
{"seq":229,"request_seq":541,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/cast.js","id":358,"lineOffset":0,"columnOffset":0,"lineCount":37,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar MongooseError = require('../error');\n\n/**\n * Casting Error constructor.\n *\n * @param {String} type\n * @param {String} value\n * @inherits MongooseError\n * @api private\n */\n\nfunction CastError (type, value, path) {\n MongooseError.call(this, 'Cast to ' + type + ' failed for value \"' + value + '\" at path \"' + path + '\"');\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'CastError';\n this.type = type;\n this.value = value;\n this.path = path;\n};\n\n/*!\n * Inherits from MongooseError.\n */\n\nCastError.prototype.__proto__ = MongooseError.prototype;\n\n/*!\n * exports\n */\n\nmodule.exports = CastError;\n\n});","sourceLength":715,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/cast.js (lines: 37)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":542,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[361]}}
{"seq":230,"request_seq":542,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/document.js","id":361,"lineOffset":0,"columnOffset":0,"lineCount":34,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module requirements\n */\n\nvar MongooseError = require('../error')\n\n/**\n * Document Error\n *\n * @param {String} msg\n * @inherits MongooseError\n * @api private\n */\n\nfunction DocumentError (msg) {\n MongooseError.call(this, msg);\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'DocumentError';\n};\n\n/*!\n * Inherits from MongooseError.\n */\n\nDocumentError.prototype.__proto__ = MongooseError.prototype;\n\n/*!\n * Module exports.\n */\n\nmodule.exports = exports = DocumentError;\n\n});","sourceLength":559,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/document.js (lines: 34)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":543,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[364]}}
{"seq":231,"request_seq":543,"type":"response","command":"scripts","success":true,"body":[{"handle":7,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/validation.js","id":364,"lineOffset":0,"columnOffset":0,"lineCount":51,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module requirements\n */\n\nvar MongooseError = require('../error')\n\n/**\n * Document Validation Error\n *\n * @api private\n * @param {Document} instance\n * @inherits MongooseError\n */\n\nfunction ValidationError (instance) {\n MongooseError.call(this, \"Validation failed\");\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'ValidationError';\n this.errors = instance.errors = {};\n};\n\n/**\n * Console.log helper\n */\n\nValidationError.prototype.toString = function () {\n var ret = this.name + ': ';\n var msgs = [];\n\n Object.keys(this.errors).forEach(function (key) {\n if (this == this.errors[key]) return;\n msgs.push(String(this.errors[key]));\n }, this)\n\n return ret + msgs.join(', ');\n};\n\n/*!\n * Inherits from MongooseError.\n */\n\nValidationError.prototype.__proto__ = MongooseError.prototype;\n\n/*!\n * Module exports\n */\n\nmodule.exports = exports = ValidationError;\n\n});","sourceLength":956,"scriptType":2,"compilationType":0,"context":{"ref":6},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/validation.js (lines: 51)"}],"refs":[{"handle":6,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":544,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[367]}}
{"seq":232,"request_seq":544,"type":"response","command":"scripts","success":true,"body":[{"handle":9,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/validator.js","id":367,"lineOffset":0,"columnOffset":0,"lineCount":53,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar MongooseError = require('../error');\n\n/**\n * Schema validator error\n *\n * @param {String} path\n * @param {String} msg\n * @param {String|Number|any} val\n * @inherits MongooseError\n * @api private\n */\n\nfunction ValidatorError (path, type, val) {\n var msg = type\n ? '\"' + type + '\" '\n : '';\n\n var message = 'Validator ' + msg + 'failed for path ' + path\n if (2 < arguments.length) message += ' with value `' + String(val) + '`';\n\n MongooseError.call(this, message);\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'ValidatorError';\n this.path = path;\n this.type = type;\n this.value = val;\n};\n\n/*!\n * toString helper\n */\n\nValidatorError.prototype.toString = function () {\n return this.message;\n}\n\n/*!\n * Inherits from MongooseError\n */\n\nValidatorError.prototype.__proto__ = MongooseError.prototype;\n\n/*!\n * exports\n */\n\nmodule.exports = ValidatorError;\n\n});","sourceLength":983,"scriptType":2,"compilationType":0,"context":{"ref":8},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/validator.js (lines: 53)"}],"refs":[{"handle":8,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":545,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[370]}}
{"seq":233,"request_seq":545,"type":"response","command":"scripts","success":true,"body":[{"handle":11,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/version.js","id":370,"lineOffset":0,"columnOffset":0,"lineCount":33,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar MongooseError = require('../error');\n\n/**\n * Version Error constructor.\n *\n * @inherits MongooseError\n * @api private\n */\n\nfunction VersionError () {\n MongooseError.call(this, 'No matching document found.');\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'VersionError';\n};\n\n/*!\n * Inherits from MongooseError.\n */\n\nVersionError.prototype.__proto__ = MongooseError.prototype;\n\n/*!\n * exports\n */\n\nmodule.exports = VersionError;\n\n});","sourceLength":551,"scriptType":2,"compilationType":0,"context":{"ref":10},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/version.js (lines: 33)"}],"refs":[{"handle":10,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":546,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[373]}}
{"seq":234,"request_seq":546,"type":"response","command":"scripts","success":true,"body":[{"handle":13,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/overwriteModel.js","id":373,"lineOffset":0,"columnOffset":0,"lineCount":32,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar MongooseError = require('../error');\n\n/*!\n * OverwriteModel Error constructor.\n *\n * @inherits MongooseError\n */\n\nfunction OverwriteModelError (name) {\n MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.');\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'OverwriteModelError';\n};\n\n/*!\n * Inherits from MongooseError.\n */\n\nOverwriteModelError.prototype.__proto__ = MongooseError.prototype;\n\n/*!\n * exports\n */\n\nmodule.exports = OverwriteModelError;\n\n});","sourceLength":599,"scriptType":2,"compilationType":0,"context":{"ref":12},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/overwriteModel.js (lines: 32)"}],"refs":[{"handle":12,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":547,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[376]}}
{"seq":237,"request_seq":547,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/missingSchema.js","id":376,"lineOffset":0,"columnOffset":0,"lineCount":34,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar MongooseError = require('../error');\n\n/*!\n * MissingSchema Error constructor.\n *\n * @inherits MongooseError\n */\n\nfunction MissingSchemaError (name) {\n var msg = 'Schema hasn\\'t been registered for model \"' + name + '\".\\n'\n + 'Use mongoose.model(name, schema)';\n MongooseError.call(this, msg);\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'MissingSchemaError';\n};\n\n/*!\n * Inherits from MongooseError.\n */\n\nMissingSchemaError.prototype.__proto__ = MongooseError.prototype;\n\n/*!\n * exports\n */\n\nmodule.exports = MissingSchemaError;\n\n});","sourceLength":664,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/missingSchema.js (lines: 34)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":548,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[379]}}
{"seq":238,"request_seq":548,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/divergentArray.js","id":379,"lineOffset":0,"columnOffset":0,"lineCount":42,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar MongooseError = require('../error');\n\n/*!\n * DivergentArrayError constructor.\n *\n * @inherits MongooseError\n */\n\nfunction DivergentArrayError (paths) {\n var msg = 'For your own good, using `document.save()` to update an array '\n + 'which was selected using an $elemMatch projection OR '\n + 'populated using skip, limit, query conditions, or exclusion of '\n + 'the _id field when the operation results in a $pop or $set of '\n + 'the entire array is not supported. The following '\n + 'path(s) would have been modified unsafely:\\n'\n + ' ' + paths.join('\\n ') + '\\n'\n + 'Use Model.update() to update these arrays instead.'\n // TODO write up a docs page (FAQ) and link to it\n\n MongooseError.call(this, msg);\n Error.captureStackTrace(this, arguments.callee);\n this.name = 'DivergentArrayError';\n};\n\n/*!\n * Inherits from MongooseError.\n */\n\nDivergentArrayError.prototype.__proto__ = MongooseError.prototype;\n\n/*!\n * exports\n */\n\nmodule.exports = DivergentArrayError;\n\n});","sourceLength":1142,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/errors/divergentArray.js (lines: 42)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":549,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[382]}}
{"seq":243,"request_seq":549,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/number.js","id":382,"lineOffset":0,"columnOffset":0,"lineCount":214,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module requirements.\n */\n\nvar SchemaType = require('../schematype')\n , CastError = SchemaType.CastError\n , utils = require('../utils')\n , Document\n\n/**\n * Number SchemaType constructor.\n *\n * @param {String} key\n * @param {Object} options\n * @inherits SchemaType\n * @api private\n */\n\nfunction SchemaNumber (key, options) {\n SchemaType.call(this, key, options, 'Number');\n};\n\n/*!\n * Inherits from SchemaType.\n */\n\nSchemaNumber.prototype.__proto__ = SchemaType.prototype;\n\n/**\n * Required validator for number\n *\n * @api private\n */\n\nSchemaNumber.prototype.checkRequired = function checkRequired (value, doc) {\n if (SchemaType._isRef(this, value, doc, true)) {\n return null != value;\n } else {\n return typeof value == 'number' || value instanceof Number;\n }\n};\n\n/**\n * Sets a minimum number validator.\n *\n * ####Example:\n *\n * var s = new Schema({ n: { type: Number, min: 10 })\n * var M = db.model('M', s)\n * var m = new M({ n: 9 })\n * m.save(function (err) {\n * console.error(err) // validator error\n * m.n = 10;\n * m.save() // success\n * })\n *\n * @param {Number} value minimum number\n * @param {String} message\n * @api public\n */\n\nSchemaNumber.prototype.min = function (value, message) {\n if (this.minValidator)\n this.validators = this.validators.filter(function(v){\n return v[1] != 'min';\n });\n if (value != null)\n this.validators.push([function(v){\n return v === null || v >= value;\n }, 'min']);\n return this;\n};\n\n/**\n * Sets a maximum number validator.\n *\n * ####Example:\n *\n * var s = new Schema({ n: { type: Number, max: 10 })\n * var M = db.model('M', s)\n * var m = new M({ n: 11 })\n * m.save(function (err) {\n * console.error(err) // validator error\n * m.n = 10;\n * m.save() // success\n * })\n *\n * @param {Number} maximum number\n * @param {String} message\n * @api public\n */\n\nSchemaNumber.prototype.max = function (value, message) {\n if (this.maxValidator)\n this.validators = this.validators.filter(function(v){\n return v[1] != 'max';\n });\n if (value != null)\n this.validators.push([this.maxValidator = function(v){\n return v === null || v <= value;\n }, 'max']);\n return this;\n};\n\n/**\n * Casts to number\n *\n * @param {Object} value value to cast\n * @param {Document} doc document that triggers the casting\n * @param {Boolean} init\n * @api private\n */\n\nSchemaNumber.prototype.cast = function (value, doc, init) {\n if (SchemaType._isRef(this, value, doc, init)) {\n // wait! we may need to cast this to a document\n\n // lazy load\n Document || (Document = require('./../document'));\n\n if (value instanceof Document || null == value) {\n return value;\n }\n\n // setting a populated path\n if ('number' == typeof value) {\n return value;\n } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {\n throw new CastError('number', value, this.path);\n }\n\n // Handle the case where user directly sets a populated\n // path to a plain object; cast to the Model used in\n // the population query.\n var path = doc.$__fullPath(this.path);\n var owner = doc.ownerDocument ? doc.ownerDocument() : doc;\n var pop = owner.populated(path, true);\n return new pop.options.model(value);\n }\n\n var val = value && value._id\n ? value._id // documents\n : value;\n\n if (!isNaN(val)){\n if (null === val) return val;\n if ('' === val) return null;\n if ('string' == typeof val) val = Number(val);\n if (val instanceof Number) return val\n if ('number' == typeof val) return val;\n if (val.toString && !Array.isArray(val) &&\n val.toString() == Number(val)) {\n return new Number(val)\n }\n }\n\n throw new CastError('number', value, this.path);\n};\n\n/*!\n * ignore\n */\n\nfunction handleSingle (val) {\n return this.cast(val)\n}\n\nfunction handleArray (val) {\n var self = this;\n return val.map(function (m) {\n return self.cast(m)\n });\n}\n\nSchemaNumber.prototype.$conditionalHandlers = {\n '$lt' : handleSingle\n , '$lte': handleSingle\n , '$gt' : handleSingle\n , '$gte': handleSingle\n , '$ne' : handleSingle\n , '$in' : handleArray\n , '$nin': handleArray\n , '$mod': handleArray\n , '$all': handleArray\n};\n\n/**\n * Casts contents for queries.\n *\n * @param {String} $conditional\n * @param {any} [value]\n * @api private\n */\n\nSchemaNumber.prototype.castForQuery = function ($conditional, val) {\n var handler;\n if (arguments.length === 2) {\n handler = this.$conditionalHandlers[$conditional];\n if (!handler)\n throw new Error(\"Can't use \" + $conditional + \" with Number.\");\n return handler.call(this, val);\n } else {\n val = this.cast($conditional);\n return val == null ? val : val\n }\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = SchemaNumber;\n\n});","sourceLength":4847,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/number.js (lines: 214)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":550,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[385]}}
{"seq":244,"request_seq":550,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/boolean.js","id":385,"lineOffset":0,"columnOffset":0,"lineCount":94,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar SchemaType = require('../schematype');\n\n/**\n * Boolean SchemaType constructor.\n *\n * @param {String} path\n * @param {Object} options\n * @inherits SchemaType\n * @api private\n */\n\nfunction SchemaBoolean (path, options) {\n SchemaType.call(this, path, options);\n};\n\n/*!\n * Inherits from SchemaType.\n */\nSchemaBoolean.prototype.__proto__ = SchemaType.prototype;\n\n/**\n * Required validator\n *\n * @api private\n */\n\nSchemaBoolean.prototype.checkRequired = function (value) {\n return value === true || value === false;\n};\n\n/**\n * Casts to boolean\n *\n * @param {Object} value\n * @api private\n */\n\nSchemaBoolean.prototype.cast = function (value) {\n if (null === value) return value;\n if ('0' === value) return false;\n if ('true' === value) return true;\n if ('false' === value) return false;\n return !! value;\n}\n\n/*!\n * ignore\n */\n\nfunction handleArray (val) {\n var self = this;\n return val.map(function (m) {\n return self.cast(m);\n });\n}\n\nSchemaBoolean.$conditionalHandlers = {\n '$in': handleArray\n}\n\n/**\n * Casts contents for queries.\n *\n * @param {String} $conditional\n * @param {any} val\n * @api private\n */\n\nSchemaBoolean.prototype.castForQuery = function ($conditional, val) {\n var handler;\n if (2 === arguments.length) {\n handler = SchemaBoolean.$conditionalHandlers[$conditional];\n\n if (handler) {\n return handler.call(this, val);\n }\n\n return this.cast(val);\n }\n\n return this.cast($conditional);\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = SchemaBoolean;\n\n});","sourceLength":1596,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/boolean.js (lines: 94)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":551,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[388]}}
{"seq":245,"request_seq":551,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/documentarray.js","id":388,"lineOffset":0,"columnOffset":0,"lineCount":191,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar SchemaType = require('../schematype')\n , ArrayType = require('./array')\n , MongooseDocumentArray = require('../types/documentarray')\n , Subdocument = require('../types/embedded')\n , Document = require('../document');\n\n/**\n * SubdocsArray SchemaType constructor\n *\n * @param {String} key\n * @param {Schema} schema\n * @param {Object} options\n * @inherits SchemaArray\n * @api private\n */\n\nfunction DocumentArray (key, schema, options) {\n\n // compile an embedded document for this schema\n function EmbeddedDocument () {\n Subdocument.apply(this, arguments);\n }\n\n EmbeddedDocument.prototype.__proto__ = Subdocument.prototype;\n EmbeddedDocument.prototype.$__setSchema(schema);\n EmbeddedDocument.schema = schema;\n\n // apply methods\n for (var i in schema.methods) {\n EmbeddedDocument.prototype[i] = schema.methods[i];\n }\n\n // apply statics\n for (var i in schema.statics)\n EmbeddedDocument[i] = schema.statics[i];\n\n EmbeddedDocument.options = options;\n this.schema = schema;\n\n ArrayType.call(this, key, EmbeddedDocument, options);\n\n this.schema = schema;\n var path = this.path;\n var fn = this.defaultValue;\n\n this.default(function(){\n var arr = fn.call(this);\n if (!Array.isArray(arr)) arr = [arr];\n return new MongooseDocumentArray(arr, path, this);\n });\n};\n\n/*!\n * Inherits from ArrayType.\n */\n\nDocumentArray.prototype.__proto__ = ArrayType.prototype;\n\n/**\n * Performs local validations first, then validations on each embedded doc\n *\n * @api private\n */\n\nDocumentArray.prototype.doValidate = function (array, fn, scope) {\n var self = this;\n\n SchemaType.prototype.doValidate.call(this, array, function (err) {\n if (err) return fn(err);\n\n var count = array && array.length\n , error;\n\n if (!count) return fn();\n\n // handle sparse arrays, do not use array.forEach which does not\n // iterate over sparse elements yet reports array.length including\n // them :(\n\n for (var i = 0, len = count; i < len; ++i) {\n // sidestep sparse entries\n var doc = array[i];\n if (!doc) {\n --count || fn();\n continue;\n }\n\n ;(function (i) {\n doc.validate(function (err) {\n if (err && !error) {\n // rewrite the key\n err.key = self.key + '.' + i + '.' + err.key;\n return fn(error = err);\n }\n --count || fn();\n });\n })(i);\n }\n }, scope);\n};\n\n/**\n * Casts contents\n *\n * @param {Object} value\n * @param {Document} document that triggers the casting\n * @api private\n */\n\nDocumentArray.prototype.cast = function (value, doc, init, prev) {\n var selected\n , subdoc\n , i\n\n if (!Array.isArray(value)) {\n return this.cast([value], doc, init, prev);\n }\n\n if (!(value instanceof MongooseDocumentArray)) {\n value = new MongooseDocumentArray(value, this.path, doc);\n }\n\n i = value.length;\n\n while (i--) {\n if (!(value[i] instanceof Subdocument) && value[i]) {\n if (init) {\n selected || (selected = scopePaths(this, doc.$__.selected, init));\n subdoc = new this.casterConstructor(null, value, true, selected);\n value[i] = subdoc.init(value[i]);\n } else {\n if (prev && (subdoc = prev.id(value[i]._id))) {\n // handle resetting doc with existing id but differing data\n // doc.array = [{ doc: 'val' }]\n subdoc.set(value[i]);\n } else {\n subdoc = new this.casterConstructor(value[i], value);\n }\n\n // if set() is hooked it will have no return value\n // see gh-746\n value[i] = subdoc;\n }\n }\n }\n\n return value;\n}\n\n/*!\n * Scopes paths selected in a query to this array.\n * Necessary for proper default application of subdocument values.\n *\n * @param {DocumentArray} array - the array to scope `fields` paths\n * @param {Object|undefined} fields - the root fields selected in the query\n * @param {Boolean|undefined} init - if we are being created part of a query result\n */\n\nfunction scopePaths (array, fields, init) {\n if (!(init && fields)) return undefined;\n\n var path = array.path + '.'\n , keys = Object.keys(fields)\n , i = keys.length\n , selected = {}\n , hasKeys\n , key\n\n while (i--) {\n key = keys[i];\n if (0 === key.indexOf(path)) {\n hasKeys || (hasKeys = true);\n selected[key.substring(path.length)] = fields[key];\n }\n }\n\n return hasKeys && selected || undefined;\n}\n\n/*!\n * Module exports.\n */\n\nmodule.exports = DocumentArray;\n\n});","sourceLength":4547,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/documentarray.js (lines: 191)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":552,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[391]}}
{"seq":246,"request_seq":552,"type":"response","command":"scripts","success":true,"body":[{"handle":7,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/array.js","id":391,"lineOffset":0,"columnOffset":0,"lineCount":315,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar SchemaType = require('../schematype')\n , CastError = SchemaType.CastError\n , NumberSchema = require('./number')\n , Types = {\n Boolean: require('./boolean')\n , Date: require('./date')\n , Number: require('./number')\n , String: require('./string')\n , ObjectId: require('./objectid')\n , Buffer: require('./buffer')\n }\n , MongooseArray = require('../types').Array\n , EmbeddedDoc = require('../types').Embedded\n , Mixed = require('./mixed')\n , Query = require('../query')\n , utils = require('../utils')\n , isMongooseObject = utils.isMongooseObject\n\n/**\n * Array SchemaType constructor\n *\n * @param {String} key\n * @param {SchemaType} cast\n * @param {Object} options\n * @inherits SchemaType\n * @api private\n */\n\nfunction SchemaArray (key, cast, options) {\n if (cast) {\n var castOptions = {};\n\n if ('Object' === cast.constructor.name) {\n if (cast.type) {\n // support { type: Woot }\n castOptions = utils.clone(cast); // do not alter user arguments\n delete castOptions.type;\n cast = cast.type;\n } else {\n cast = Mixed;\n }\n }\n\n // support { type: 'String' }\n var name = 'string' == typeof cast\n ? cast\n : cast.name;\n\n var caster = name in Types\n ? Types[name]\n : cast;\n\n this.casterConstructor = caster;\n this.caster = new caster(null, castOptions);\n if (!(this.caster instanceof EmbeddedDoc)) {\n this.caster.path = key;\n }\n }\n\n SchemaType.call(this, key, options);\n\n var self = this\n , defaultArr\n , fn;\n\n if (this.defaultValue) {\n defaultArr = this.defaultValue;\n fn = 'function' == typeof defaultArr;\n }\n\n this.default(function(){\n var arr = fn ? defaultArr() : defaultArr || [];\n return new MongooseArray(arr, self.path, this);\n });\n};\n\n/*!\n * Inherits from SchemaType.\n */\n\nSchemaArray.prototype.__proto__ = SchemaType.prototype;\n\n/**\n * Check required\n *\n * @param {Array} value\n * @api private\n */\n\nSchemaArray.prototype.checkRequired = function (value) {\n return !!(value && value.length);\n};\n\n/**\n * Overrides the getters application for the population special-case\n *\n * @param {Object} value\n * @param {Object} scope\n * @api private\n */\n\nSchemaArray.prototype.applyGetters = function (value, scope) {\n if (this.caster.options && this.caster.options.ref) {\n // means the object id was populated\n return value;\n }\n\n return SchemaType.prototype.applyGetters.call(this, value, scope);\n};\n\n/**\n * Casts contents\n *\n * @param {Object} value\n * @param {Document} doc document that triggers the casting\n * @param {Boolean} init whether this is an initialization cast\n * @api private\n */\n\nSchemaArray.prototype.cast = function (value, doc, init) {\n if (Array.isArray(value)) {\n if (!(value instanceof MongooseArray)) {\n value = new MongooseArray(value, this.path, doc);\n }\n\n if (this.caster) {\n try {\n for (var i = 0, l = value.length; i < l; i++) {\n value[i] = this.caster.cast(value[i], doc, init);\n }\n } catch (e) {\n // rethrow\n throw new CastError(e.type, value, this.path);\n }\n }\n\n return value;\n } else {\n return this.cast([value], doc, init);\n }\n};\n\n/**\n * Casts contents for queries.\n *\n * @param {String} $conditional\n * @param {any} [value]\n * @api private\n */\n\nSchemaArray.prototype.castForQuery = function ($conditional, value) {\n var handler\n , val;\n if (arguments.length === 2) {\n handler = this.$conditionalHandlers[$conditional];\n if (!handler)\n throw new Error(\"Can't use \" + $conditional + \" with Array.\");\n val = handler.call(this, value);\n } else {\n val = $conditional;\n var proto = this.casterConstructor.prototype;\n var method = proto.castForQuery || proto.cast;\n\n var caster = this.caster;\n if (Array.isArray(val)) {\n val = val.map(function (v) {\n if (method) v = method.call(caster, v);\n\n return isMongooseObject(v)\n ? v.toObject()\n : v;\n });\n } else if (method) {\n val = method.call(caster, val);\n }\n }\n return val && isMongooseObject(val)\n ? val.toObject()\n : val;\n};\n\n/*!\n * @ignore\n */\n\nfunction castToNumber (val) {\n return Types.Number.prototype.cast.call(this, val);\n}\n\nfunction castArray (arr, self) {\n self || (self = this);\n\n arr.forEach(function (v, i) {\n if (Array.isArray(v)) {\n castArray(v, self);\n } else {\n arr[i] = castToNumber.call(self, v);\n }\n });\n}\n\nSchemaArray.prototype.$conditionalHandlers = {\n '$all': function handle$all (val) {\n if (!Array.isArray(val)) {\n val = [val];\n }\n\n val = val.map(function (v) {\n if (v && 'Object' === v.constructor.name) {\n var o = {};\n o[this.path] = v;\n var query = new Query(o);\n query.cast(this.casterConstructor);\n return query._conditions[this.path];\n }\n return v;\n }, this);\n\n return this.castForQuery(val);\n }\n , '$elemMatch': function (val) {\n if (val.$in) {\n val.$in = this.castForQuery('$in', val.$in);\n return val;\n }\n\n var query = new Query(val);\n query.cast(this.casterConstructor);\n return query._conditions;\n }\n , '$size': castToNumber\n , '$ne': SchemaArray.prototype.castForQuery\n , '$in': SchemaArray.prototype.castForQuery\n , '$nin': SchemaArray.prototype.castForQuery\n , '$regex': SchemaArray.prototype.castForQuery\n , '$near': SchemaArray.prototype.castForQuery\n , '$nearSphere': SchemaArray.prototype.castForQuery\n , '$gt': SchemaArray.prototype.castForQuery\n , '$gte': SchemaArray.prototype.castForQuery\n , '$lt': SchemaArray.prototype.castForQuery\n , '$lte': SchemaArray.prototype.castForQuery\n , '$within': function (val) {\n var self = this;\n\n if (val.$maxDistance) {\n val.$maxDistance = castToNumber.call(this, val.$maxDistance);\n }\n\n if (val.$box || val.$polygon) {\n var type = val.$box ? '$box' : '$polygon';\n val[type].forEach(function (arr) {\n if (!Array.isArray(arr)) {\n var msg = 'Invalid $within $box argument. '\n + 'Expected an array, received ' + arr;\n throw new TypeError(msg);\n }\n arr.forEach(function (v, i) {\n arr[i] = castToNumber.call(this, v);\n });\n })\n } else if (val.$center || val.$centerSphere) {\n var type = val.$center ? '$center' : '$centerSphere';\n val[type].forEach(function (item, i) {\n if (Array.isArray(item)) {\n item.forEach(function (v, j) {\n item[j] = castToNumber.call(this, v);\n });\n } else {\n val[type][i] = castToNumber.call(this, item);\n }\n })\n } else if (val.$geometry) {\n switch (val.$geometry.type) {\n case 'Polygon':\n case 'LineString':\n case 'Point':\n val.$geometry.coordinates.forEach(castArray);\n break;\n default:\n // ignore unknowns\n break;\n }\n }\n\n return val;\n }\n , '$geoIntersects': function (val) {\n var geo = val.$geometry;\n if (!geo) return;\n\n switch (val.$geometry.type) {\n case 'Polygon':\n case 'LineString':\n case 'Point':\n val.$geometry.coordinates.forEach(castArray);\n break;\n default:\n // ignore unknowns\n break;\n }\n }\n , '$maxDistance': castToNumber\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = SchemaArray;\n\n});","sourceLength":7642,"scriptType":2,"compilationType":0,"context":{"ref":6},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/array.js (lines: 315)"}],"refs":[{"handle":6,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":553,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[394]}}
{"seq":249,"request_seq":553,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/date.js","id":394,"lineOffset":0,"columnOffset":0,"lineCount":169,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module requirements.\n */\n\nvar SchemaType = require('../schematype');\nvar CastError = SchemaType.CastError;\nvar utils = require('../utils');\n\n/**\n * Date SchemaType constructor.\n *\n * @param {String} key\n * @param {Object} options\n * @inherits SchemaType\n * @api private\n */\n\nfunction SchemaDate (key, options) {\n SchemaType.call(this, key, options);\n};\n\n/*!\n * Inherits from SchemaType.\n */\n\nSchemaDate.prototype.__proto__ = SchemaType.prototype;\n\n/**\n * Declares a TTL index (rounded to the nearest second) for _Date_ types only.\n *\n * This sets the `expiresAfterSeconds` index option available in MongoDB >= 2.1.2.\n * This index type is only compatible with Date types.\n *\n * ####Example:\n *\n * // expire in 24 hours\n * new Schema({ createdAt: { type: Date, expires: 60*60*24 }});\n *\n * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax:\n *\n * ####Example:\n *\n * // expire in 24 hours\n * new Schema({ createdAt: { type: Date, expires: '24h' }});\n *\n * // expire in 1.5 hours\n * new Schema({ createdAt: { type: Date, expires: '1.5h' }});\n *\n * // expire in 7 days\n * var schema = new Schema({ createdAt: Date });\n * schema.path('createdAt').expires('7d');\n *\n * @param {Number|String} when\n * @added 3.0.0\n * @return {SchemaType} this\n * @api public\n */\n\nSchemaDate.prototype.expires = function (when) {\n if (!this._index || 'Object' !== this._index.constructor.name) {\n this._index = {};\n }\n\n this._index.expires = when;\n utils.expires(this._index);\n return this;\n};\n\n/**\n * Required validator for date\n *\n * @api private\n */\n\nSchemaDate.prototype.checkRequired = function (value) {\n return value instanceof Date;\n};\n\n/**\n * Casts to date\n *\n * @param {Object} value to cast\n * @api private\n */\n\nSchemaDate.prototype.cast = function (value) {\n if (value === null || value === '')\n return null;\n\n if (value instanceof Date)\n return value;\n\n var date;\n\n // support for timestamps\n if (value instanceof Number || 'number' == typeof value \n || String(value) == Number(value))\n date = new Date(Number(value));\n\n // support for date strings\n else if (value.toString)\n date = new Date(value.toString());\n\n if (date.toString() != 'Invalid Date')\n return date;\n\n throw new CastError('date', value, this.path);\n};\n\n/*!\n * Date Query casting.\n *\n * @api private\n */\n\nfunction handleSingle (val) {\n return this.cast(val);\n}\n\nfunction handleArray (val) {\n var self = this;\n return val.map( function (m) {\n return self.cast(m);\n });\n}\n\nSchemaDate.prototype.$conditionalHandlers = {\n '$lt': handleSingle\n , '$lte': handleSingle\n , '$gt': handleSingle\n , '$gte': handleSingle\n , '$ne': handleSingle\n , '$in': handleArray\n , '$nin': handleArray\n , '$all': handleArray\n};\n\n\n/**\n * Casts contents for queries.\n *\n * @param {String} $conditional\n * @param {any} [value]\n * @api private\n */\n\nSchemaDate.prototype.castForQuery = function ($conditional, val) {\n var handler;\n\n if (2 !== arguments.length) {\n return this.cast($conditional);\n }\n\n handler = this.$conditionalHandlers[$conditional];\n\n if (!handler) {\n throw new Error(\"Can't use \" + $conditional + \" with Date.\");\n }\n\n return handler.call(this, val);\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = SchemaDate;\n\n});","sourceLength":3398,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/date.js (lines: 169)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":554,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[397]}}
{"seq":250,"request_seq":554,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/objectid.js","id":397,"lineOffset":0,"columnOffset":0,"lineCount":178,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar SchemaType = require('../schematype')\n , CastError = SchemaType.CastError\n , driver = global.MONGOOSE_DRIVER_PATH || './../drivers/node-mongodb-native'\n , oid = require('../types/objectid')\n , utils = require('../utils')\n , Document\n\n/**\n * ObjectId SchemaType constructor.\n *\n * @param {String} key\n * @param {Object} options\n * @inherits SchemaType\n * @api private\n */\n\nfunction ObjectId (key, options) {\n SchemaType.call(this, key, options, 'ObjectID');\n};\n\n/*!\n * Inherits from SchemaType.\n */\n\nObjectId.prototype.__proto__ = SchemaType.prototype;\n\n/**\n * Check required\n *\n * @api private\n */\n\nObjectId.prototype.checkRequired = function checkRequired (value, doc) {\n if (SchemaType._isRef(this, value, doc, true)) {\n return null != value;\n } else {\n return value instanceof oid;\n }\n};\n\n/**\n * Casts to ObjectId\n *\n * @param {Object} value\n * @param {Object} doc\n * @param {Boolean} init whether this is an initialization cast\n * @api private\n */\n\nObjectId.prototype.cast = function (value, doc, init) {\n if (SchemaType._isRef(this, value, doc, init)) {\n // wait! we may need to cast this to a document\n\n // lazy load\n Document || (Document = require('./../document'));\n\n if (value instanceof Document || null == value) {\n return value;\n }\n\n // setting a populated path\n if (value instanceof oid) {\n return value;\n } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {\n throw new CastError('ObjectId', value, this.path);\n }\n\n // Handle the case where user directly sets a populated\n // path to a plain object; cast to the Model used in\n // the population query.\n var path = doc.$__fullPath(this.path);\n var owner = doc.ownerDocument ? doc.ownerDocument() : doc;\n var pop = owner.populated(path, true);\n return new pop.options.model(value);\n }\n\n if (value === null) return value;\n\n if (value instanceof oid)\n return value;\n\n if (value._id && value._id instanceof oid)\n return value._id;\n\n if (value.toString) {\n try {\n return oid.fromString(value.toString());\n } catch (err) {\n throw new CastError('ObjectId', value, this.path);\n }\n }\n\n throw new CastError('ObjectId', value, this.path);\n};\n\n/*!\n * ignore\n */\n\nfunction handleSingle (val) {\n return this.cast(val);\n}\n\nfunction handleArray (val) {\n var self = this;\n return val.map(function (m) {\n return self.cast(m);\n });\n}\n\nObjectId.prototype.$conditionalHandlers = {\n '$ne': handleSingle\n , '$in': handleArray\n , '$nin': handleArray\n , '$gt': handleSingle\n , '$lt': handleSingle\n , '$gte': handleSingle\n , '$lte': handleSingle\n , '$all': handleArray\n};\n\n/**\n * Casts contents for queries.\n *\n * @param {String} $conditional\n * @param {any} [val]\n * @api private\n */\n\nObjectId.prototype.castForQuery = function ($conditional, val) {\n var handler;\n if (arguments.length === 2) {\n handler = this.$conditionalHandlers[$conditional];\n if (!handler)\n throw new Error(\"Can't use \" + $conditional + \" with ObjectId.\");\n return handler.call(this, val);\n } else {\n return this.cast($conditional);\n }\n};\n\n/**\n * Adds an auto-generated ObjectId default if turnOn is true.\n * @param {Boolean} turnOn auto generated ObjectId defaults\n * @api public\n */\n\nObjectId.prototype.auto = function (turnOn) {\n if (turnOn) {\n this.default(defaultId);\n this.set(resetId)\n }\n};\n\n/*!\n * ignore\n */\n\nfunction defaultId () {\n return new oid();\n};\n\nfunction resetId (v) {\n this.$__._id = null;\n return v;\n}\n\n/*!\n * Module exports.\n */\n\nmodule.exports = ObjectId;\n\n});","sourceLength":3662,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/objectid.js (lines: 178)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":555,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[400]}}
{"seq":257,"request_seq":555,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/buffer.js","id":400,"lineOffset":0,"columnOffset":0,"lineCount":159,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar SchemaType = require('../schematype')\n , CastError = SchemaType.CastError\n , MongooseBuffer = require('../types').Buffer\n , Binary = MongooseBuffer.Binary\n , Query = require('../query')\n , utils = require('../utils')\n , Document\n\n/**\n * Buffer SchemaType constructor\n *\n * @param {String} key\n * @param {SchemaType} cast\n * @inherits SchemaType\n * @api private\n */\n\nfunction SchemaBuffer (key, options) {\n SchemaType.call(this, key, options, 'Buffer');\n};\n\n/*!\n * Inherits from SchemaType.\n */\n\nSchemaBuffer.prototype.__proto__ = SchemaType.prototype;\n\n/**\n * Check required\n *\n * @api private\n */\n\nSchemaBuffer.prototype.checkRequired = function (value, doc) {\n if (SchemaType._isRef(this, value, doc, true)) {\n return null != value;\n } else {\n return !!(value && value.length);\n }\n};\n\n/**\n * Casts contents\n *\n * @param {Object} value\n * @param {Document} doc document that triggers the casting\n * @param {Boolean} init\n * @api private\n */\n\nSchemaBuffer.prototype.cast = function (value, doc, init) {\n if (SchemaType._isRef(this, value, doc, init)) {\n // wait! we may need to cast this to a document\n\n // lazy load\n Document || (Document = require('./../document'));\n\n if (value instanceof Document || null == value) {\n return value;\n }\n\n // setting a populated path\n if (Buffer.isBuffer(value)) {\n return value;\n } else if (!utils.isObject(value)) {\n throw new CastError('buffer', value, this.path);\n }\n\n // Handle the case where user directly sets a populated\n // path to a plain object; cast to the Model used in\n // the population query.\n var path = doc.$__fullPath(this.path);\n var owner = doc.ownerDocument ? doc.ownerDocument() : doc;\n var pop = owner.populated(path, true);\n var ret = new pop.options.model(value);\n return ret;\n }\n\n // documents\n if (value && value._id) {\n value = value._id;\n }\n\n if (Buffer.isBuffer(value)) {\n if (!(value instanceof MongooseBuffer)) {\n value = new MongooseBuffer(value, [this.path, doc]);\n }\n\n return value;\n } else if (value instanceof Binary) {\n return new MongooseBuffer(value.value(true), [this.path, doc]);\n }\n\n if (null === value) return value;\n\n var type = typeof value;\n if ('string' == type || 'number' == type || Array.isArray(value)) {\n return new MongooseBuffer(value, [this.path, doc]);\n }\n\n throw new CastError('buffer', value, this.path);\n};\n\n/*!\n * ignore\n */\nfunction handleSingle (val) {\n return this.castForQuery(val);\n}\n\nfunction handleArray (val) {\n var self = this;\n return val.map( function (m) {\n return self.castForQuery(m);\n });\n}\n\nSchemaBuffer.prototype.$conditionalHandlers = {\n '$ne' : handleSingle\n , '$in' : handleArray\n , '$nin': handleArray\n , '$gt' : handleSingle\n , '$lt' : handleSingle\n , '$gte': handleSingle\n , '$lte': handleSingle\n};\n\n/**\n * Casts contents for queries.\n *\n * @param {String} $conditional\n * @param {any} [value]\n * @api private\n */\n\nSchemaBuffer.prototype.castForQuery = function ($conditional, val) {\n var handler;\n if (arguments.length === 2) {\n handler = this.$conditionalHandlers[$conditional];\n if (!handler)\n throw new Error(\"Can't use \" + $conditional + \" with Buffer.\");\n return handler.call(this, val);\n } else {\n val = $conditional;\n return this.cast(val).toObject();\n }\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = SchemaBuffer;\n\n});","sourceLength":3507,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/buffer.js (lines: 159)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":556,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[403]}}
{"seq":258,"request_seq":556,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/index.js","id":403,"lineOffset":0,"columnOffset":0,"lineCount":15,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module exports.\n */\n\nexports.Array = require('./array');\nexports.Buffer = require('./buffer');\n\nexports.Document = // @deprecate\nexports.Embedded = require('./embedded');\n\nexports.DocumentArray = require('./documentarray');\nexports.ObjectId = require('./objectid');\n\n});","sourceLength":340,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/index.js (lines: 15)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":557,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[406]}}
{"seq":259,"request_seq":557,"type":"response","command":"scripts","success":true,"body":[{"handle":7,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/array.js","id":406,"lineOffset":0,"columnOffset":0,"lineCount":682,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar EmbeddedDocument = require('./embedded');\nvar Document = require('../document');\nvar ObjectId = require('./objectid');\nvar utils = require('../utils');\nvar isMongooseObject = utils.isMongooseObject;\n\n/**\n * Mongoose Array constructor.\n *\n * ####NOTE:\n *\n * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._\n *\n * @param {Array} values\n * @param {String} path\n * @param {Document} doc parent document\n * @api private\n * @inherits Array\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseArray (values, path, doc) {\n var arr = [];\n arr.push.apply(arr, values);\n arr.__proto__ = MongooseArray.prototype;\n\n arr._atomics = {};\n arr.validators = [];\n arr._path = path;\n\n if (doc) {\n arr._parent = doc;\n arr._schema = doc.schema.path(path);\n }\n\n return arr;\n};\n\n/*!\n * Inherit from Array\n */\n\nMongooseArray.prototype = new Array;\n\n/**\n * Stores a queue of atomic operations to perform\n *\n * @property _atomics\n * @api private\n */\n\nMongooseArray.prototype._atomics;\n\n/**\n * Parent owner document\n *\n * @property _parent\n * @api private\n */\n\nMongooseArray.prototype._parent;\n\n/**\n * Casts a member based on this arrays schema.\n *\n * @param {any} value\n * @return value the casted value\n * @api private\n */\n\nMongooseArray.prototype._cast = function (value) {\n var owner = this._owner;\n var populated = false;\n var Model;\n\n if (this._parent) {\n // if a populated array, we must cast to the same model\n // instance as specified in the original query.\n if (!owner) {\n owner = this._owner = this._parent.ownerDocument\n ? this._parent.ownerDocument()\n : this._parent;\n }\n\n populated = owner.populated(this._path, true);\n }\n\n if (populated && null != value) {\n // cast to the populated Models schema\n var Model = populated.options.model;\n\n // only objects are permitted so we can safely assume that\n // non-objects are to be interpreted as _id\n if (Buffer.isBuffer(value) ||\n value instanceof ObjectId || !utils.isObject(value)) {\n value = { _id: value };\n }\n\n value = new Model(value);\n return this._schema.caster.cast(value, this._parent, true)\n }\n\n return this._schema.caster.cast(value, this._parent, false)\n}\n\n/**\n * Marks this array as modified.\n *\n * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)\n *\n * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array\n * @param {String} embeddedPath the path which changed in the embeddedDoc\n * @api private\n */\n\nMongooseArray.prototype._markModified = function (elem, embeddedPath) {\n var parent = this._parent\n , dirtyPath;\n\n if (parent) {\n dirtyPath = this._path;\n\n if (arguments.length) {\n if (null != embeddedPath) {\n // an embedded doc bubbled up the change\n dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath;\n } else {\n // directly set an index\n dirtyPath = dirtyPath + '.' + elem;\n }\n }\n parent.markModified(dirtyPath);\n }\n\n return this;\n};\n\n/**\n * Register an atomic operation with the parent.\n *\n * @param {Array} op operation\n * @param {any} val\n * @api private\n */\n\nMongooseArray.prototype._registerAtomic = function (op, val) {\n if ('$set' == op) {\n // $set takes precedence over all other ops.\n // mark entire array modified.\n this._atomics = { $set: val };\n return this;\n }\n\n var atomics = this._atomics;\n\n // reset pop/shift after save\n if ('$pop' == op && !('$pop' in atomics)) {\n var self = this;\n this._parent.once('save', function () {\n self._popped = self._shifted = null;\n });\n }\n\n // check for impossible $atomic combos (Mongo denies more than one\n // $atomic op on a single path\n if (this._atomics.$set ||\n Object.keys(atomics).length && !(op in atomics)) {\n // a different op was previously registered.\n // save the entire thing.\n this._atomics = { $set: this };\n return this;\n }\n\n if (op === '$pullAll' || op === '$pushAll' || op === '$addToSet') {\n atomics[op] || (atomics[op] = []);\n atomics[op] = atomics[op].concat(val);\n } else if (op === '$pullDocs') {\n var pullOp = atomics['$pull'] || (atomics['$pull'] = {})\n , selector = pullOp['_id'] || (pullOp['_id'] = {'$in' : [] });\n selector['$in'] = selector['$in'].concat(val);\n } else {\n atomics[op] = val;\n }\n\n return this;\n};\n\n/**\n * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB.\n *\n * If no atomics exist, we return all array values after conversion.\n *\n * @return {Array}\n * @method $__getAtomics\n * @memberOf MongooseArray\n * @api private\n */\n\nMongooseArray.prototype.$__getAtomics = function () {\n var ret = [];\n var keys = Object.keys(this._atomics);\n var i = keys.length;\n\n if (0 === i) {\n ret[0] = ['$set', this.toObject({ depopulate: 1 })];\n return ret;\n }\n\n while (i--) {\n var op = keys[i];\n var val = this._atomics[op];\n\n // the atomic values which are arrays are not MongooseArrays. we\n // need to convert their elements as if they were MongooseArrays\n // to handle populated arrays versus DocumentArrays properly.\n if (isMongooseObject(val)) {\n val = val.toObject({ depopulate: 1 });\n } else if (Array.isArray(val)) {\n val = this.toObject.call(val, { depopulate: 1 });\n } else if (val.valueOf) {\n val = val.valueOf();\n }\n\n if ('$addToSet' == op) {\n val = { $each: val }\n }\n\n ret.push([op, val]);\n }\n\n return ret;\n}\n\n/**\n * Returns the number of pending atomic operations to send to the db for this array.\n *\n * @api private\n * @return {Number}\n */\n\nMongooseArray.prototype.hasAtomics = function hasAtomics () {\n if (!(this._atomics && 'Object' === this._atomics.constructor.name)) {\n return 0;\n }\n\n return Object.keys(this._atomics).length;\n}\n\n/**\n * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.\n *\n * @param {Object} [args...]\n * @api public\n */\n\nMongooseArray.prototype.push = function () {\n var values = [].map.call(arguments, this._cast, this)\n , ret = [].push.apply(this, values);\n\n // $pushAll might be fibbed (could be $push). But it makes it easier to\n // handle what could have been $push, $pushAll combos\n this._registerAtomic('$pushAll', values);\n this._markModified();\n return ret;\n};\n\n/**\n * Pushes items to the array non-atomically.\n *\n * ####NOTE:\n *\n * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._\n *\n * @param {any} [args...]\n * @api public\n */\n\nMongooseArray.prototype.nonAtomicPush = function () {\n var values = [].map.call(arguments, this._cast, this)\n , ret = [].push.apply(this, values);\n this._registerAtomic('$set', this);\n this._markModified();\n return ret;\n};\n\n/**\n * Pops the array atomically at most one time per document `save()`.\n *\n * #### NOTE:\n *\n * _Calling this mulitple times on an array before saving sends the same command as calling it once._\n * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._\n *\n * doc.array = [1,2,3];\n *\n * var popped = doc.array.$pop();\n * console.log(popped); // 3\n * console.log(doc.array); // [1,2]\n *\n * // no affect\n * popped = doc.array.$pop();\n * console.log(doc.array); // [1,2]\n *\n * doc.save(function (err) {\n * if (err) return handleError(err);\n *\n * // we saved, now $pop works again\n * popped = doc.array.$pop();\n * console.log(popped); // 2\n * console.log(doc.array); // [1]\n * })\n *\n * @api public\n * @method $pop\n * @memberOf MongooseArray\n * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop\n */\n\nMongooseArray.prototype.$pop = function () {\n this._registerAtomic('$pop', 1);\n this._markModified();\n\n // only allow popping once\n if (this._popped) return;\n this._popped = true;\n\n return [].pop.call(this);\n};\n\n/**\n * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.\n *\n * ####Note:\n *\n * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._\n *\n * @see MongooseArray#$pop #types_array_MongooseArray-%24pop\n * @api public\n */\n\nMongooseArray.prototype.pop = function () {\n var ret = [].pop.call(this);\n this._registerAtomic('$set', this);\n this._markModified();\n return ret;\n};\n\n/**\n * Atomically shifts the array at most one time per document `save()`.\n *\n * ####NOTE:\n *\n * _Calling this mulitple times on an array before saving sends the same command as calling it once._\n * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._\n *\n * doc.array = [1,2,3];\n *\n * var shifted = doc.array.$shift();\n * console.log(shifted); // 1\n * console.log(doc.array); // [2,3]\n *\n * // no affect\n * shifted = doc.array.$shift();\n * console.log(doc.array); // [2,3]\n *\n * doc.save(function (err) {\n * if (err) return handleError(err);\n *\n * // we saved, now $shift works again\n * shifted = doc.array.$shift();\n * console.log(shifted ); // 2\n * console.log(doc.array); // [3]\n * })\n *\n * @api public\n * @memberOf MongooseArray\n * @method $shift\n * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop\n */\n\nMongooseArray.prototype.$shift = function $shift () {\n this._registerAtomic('$pop', -1);\n this._markModified();\n\n // only allow shifting once\n if (this._shifted) return;\n this._shifted = true;\n\n return [].shift.call(this);\n};\n\n/**\n * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.\n *\n * ####Example:\n *\n * doc.array = [2,3];\n * var res = doc.array.shift();\n * console.log(res) // 2\n * console.log(doc.array) // [3]\n *\n * ####Note:\n *\n * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._\n *\n * @api public\n */\n\nMongooseArray.prototype.shift = function () {\n var ret = [].shift.call(this);\n this._registerAtomic('$set', this);\n this._markModified();\n return ret;\n};\n\n/**\n * Pulls items from the array atomically.\n *\n * ####Examples:\n *\n * doc.array.pull(ObjectId)\n * doc.array.pull({ _id: 'someId' })\n * doc.array.pull(36)\n * doc.array.pull('tag 1', 'tag 2')\n *\n * To remove a document from a subdocument array we may pass an object with a matching `_id`.\n *\n * doc.subdocs.push({ _id: 4815162342 })\n * doc.subdocs.pull({ _id: 4815162342 }) // removed\n *\n * Or we may passing the _id directly and let mongoose take care of it.\n *\n * doc.subdocs.push({ _id: 4815162342 })\n * doc.subdocs.pull(4815162342); // works\n *\n * @param {any} [args...]\n * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull\n * @api public\n */\n\nMongooseArray.prototype.pull = function () {\n var values = [].map.call(arguments, this._cast, this)\n , cur = this._parent.get(this._path)\n , i = cur.length\n , mem;\n\n while (i--) {\n mem = cur[i];\n if (mem instanceof EmbeddedDocument) {\n if (values.some(function (v) { return v.equals(mem); } )) {\n [].splice.call(cur, i, 1);\n }\n } else if (~cur.indexOf.call(values, mem)) {\n [].splice.call(cur, i, 1);\n }\n }\n\n if (values[0] instanceof EmbeddedDocument) {\n this._registerAtomic('$pullDocs', values.map( function (v) { return v._id; } ));\n } else {\n this._registerAtomic('$pullAll', values);\n }\n\n this._markModified();\n return this;\n};\n\n/**\n * Alias of [pull](#types_array_MongooseArray-pull)\n *\n * @see MongooseArray#pull #types_array_MongooseArray-pull\n * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull\n * @api public\n * @memberOf MongooseArray\n * @method remove\n */\n\nMongooseArray.prototype.remove = MongooseArray.prototype.pull;\n\n/**\n * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.\n *\n * ####Note:\n *\n * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._\n *\n * @api public\n */\n\nMongooseArray.prototype.splice = function splice () {\n var ret, vals, i;\n\n if (arguments.length) {\n vals = [];\n for (i = 0; i < arguments.length; ++i) {\n vals[i] = i < 2\n ? arguments[i]\n : this._cast(arguments[i]);\n }\n ret = [].splice.apply(this, vals);\n this._registerAtomic('$set', this);\n this._markModified();\n }\n\n return ret;\n}\n\n/**\n * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.\n *\n * ####Note:\n *\n * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._\n *\n * @api public\n */\n\nMongooseArray.prototype.unshift = function () {\n var values = [].map.call(arguments, this._cast, this);\n [].unshift.apply(this, values);\n this._registerAtomic('$set', this);\n this._markModified();\n return this.length;\n};\n\n/**\n * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.\n *\n * ####NOTE:\n *\n * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._\n *\n * @api public\n */\n\nMongooseArray.prototype.sort = function () {\n var ret = [].sort.apply(this, arguments);\n this._registerAtomic('$set', this);\n this._markModified();\n return ret;\n}\n\n/**\n * Adds values to the array if not already present.\n *\n * ####Example:\n *\n * console.log(doc.array) // [2,3,4]\n * var added = doc.array.addToSet(4,5);\n * console.log(doc.array) // [2,3,4,5]\n * console.log(added) // [5]\n *\n * @param {any} [args...]\n * @return {Array} the values that were added\n * @api public\n */\n\nMongooseArray.prototype.addToSet = function addToSet () {\n var values = [].map.call(arguments, this._cast, this)\n , added = []\n , type = values[0] instanceof EmbeddedDocument ? 'doc' :\n values[0] instanceof Date ? 'date' :\n '';\n\n values.forEach(function (v) {\n var found;\n switch (type) {\n case 'doc':\n found = this.some(function(doc){ return doc.equals(v) });\n break;\n case 'date':\n var val = +v;\n found = this.some(function(d){ return +d === val });\n break;\n default:\n found = ~this.indexOf(v);\n }\n\n if (!found) {\n [].push.call(this, v);\n this._registerAtomic('$addToSet', v);\n this._markModified();\n [].push.call(added, v);\n }\n }, this);\n\n return added;\n};\n\n/**\n * Sets the casted `val` at index `i` and marks the array modified.\n *\n * ####Example:\n *\n * // given documents based on the following\n * var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));\n *\n * var doc = new Doc({ array: [2,3,4] })\n *\n * console.log(doc.array) // [2,3,4]\n *\n * doc.array.set(1,\"5\");\n * console.log(doc.array); // [2,5,4] // properly cast to number\n * doc.save() // the change is saved\n *\n * // VS not using array#set\n * doc.array[1] = \"5\";\n * console.log(doc.array); // [2,\"5\",4] // no casting\n * doc.save() // change is not saved\n *\n * @return {Array} this\n * @api public\n */\n\nMongooseArray.prototype.set = function set (i, val) {\n this[i] = this._cast(val);\n this._markModified(i);\n return this;\n}\n\n/**\n * Returns a native js Array.\n *\n * @param {Object} options\n * @return {Array}\n * @api public\n */\n\nMongooseArray.prototype.toObject = function (options) {\n if (options && options.depopulate) {\n return this.map(function (doc) {\n // this is called on populated arrays too\n return doc instanceof Document\n ? doc._id\n : doc\n });\n }\n\n return this.slice()\n}\n\n/**\n * Helper for console.log\n *\n * @api public\n */\n\nMongooseArray.prototype.inspect = function () {\n return '[' + this.map(function (doc) {\n return ' ' + doc;\n }) + ' ]';\n};\n\n/**\n * Return the index of `obj` or `-1` if not found.\n *\n * @param {Object} obj the item to look for\n * @return {Number}\n * @api public\n */\n\nMongooseArray.prototype.indexOf = function indexOf (obj) {\n if (obj instanceof ObjectId) obj = obj.toString();\n for (var i = 0, len = this.length; i < len; ++i) {\n if (obj == this[i])\n return i;\n }\n return -1;\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = exports = MongooseArray;\n\n});","sourceLength":17469,"scriptType":2,"compilationType":0,"context":{"ref":6},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/array.js (lines: 682)"}],"refs":[{"handle":6,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":558,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[409]}}
{"seq":260,"request_seq":558,"type":"response","command":"scripts","success":true,"body":[{"handle":9,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/embedded.js","id":409,"lineOffset":0,"columnOffset":0,"lineCount":246,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar Document = require('../document')\n , inspect = require('util').inspect;\n\n/**\n * EmbeddedDocument constructor.\n *\n * @param {Object} obj js object returned from the db\n * @param {MongooseDocumentArray} parentArr the parent array of this document\n * @param {Boolean} skipId\n * @inherits Document\n * @api private\n */\n\nfunction EmbeddedDocument (obj, parentArr, skipId, fields) {\n if (parentArr) {\n this.__parentArray = parentArr;\n this.__parent = parentArr._parent;\n } else {\n this.__parentArray = undefined;\n this.__parent = undefined;\n }\n\n Document.call(this, obj, fields, skipId);\n\n var self = this;\n this.on('isNew', function (val) {\n self.isNew = val;\n });\n};\n\n/*!\n * Inherit from Document\n */\n\nEmbeddedDocument.prototype.__proto__ = Document.prototype;\n\n/**\n * Marks the embedded doc modified.\n *\n * ####Example:\n *\n * var doc = blogpost.comments.id(hexstring);\n * doc.mixed.type = 'changed';\n * doc.markModified('mixed.type');\n *\n * @param {String} path the path which changed\n * @api public\n */\n\nEmbeddedDocument.prototype.markModified = function (path) {\n if (!this.__parentArray) return;\n\n this.$__.activePaths.modify(path);\n\n if (this.isNew) {\n // Mark the WHOLE parent array as modified\n // if this is a new document (i.e., we are initializing\n // a document),\n this.__parentArray._markModified();\n } else\n this.__parentArray._markModified(this, path);\n};\n\n/**\n * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3)\n *\n * ####NOTE:\n *\n * _This is a no-op. Does not actually save the doc to the db._\n *\n * @param {Function} [fn]\n * @return {EmbeddedDocument} this\n * @api private\n */\n\nEmbeddedDocument.prototype.save = function(fn) {\n if (fn)\n fn(null);\n return this;\n};\n\n/**\n * Removes the subdocument from its parent array.\n *\n * @param {Function} [fn]\n * @api public\n */\n\nEmbeddedDocument.prototype.remove = function (fn) {\n if (!this.__parentArray) return this;\n\n var _id;\n if (!this.willRemove) {\n _id = this._doc._id;\n if (!_id) {\n throw new Error('For your own good, Mongoose does not know ' +\n 'how to remove an EmbeddedDocument that has no _id');\n }\n this.__parentArray.pull({ _id: _id });\n this.willRemove = true;\n }\n\n if (fn)\n fn(null);\n\n return this;\n};\n\n/**\n * Override #update method of parent documents.\n * @api private\n */\n\nEmbeddedDocument.prototype.update = function () {\n throw new Error('The #update method is not available on EmbeddedDocuments');\n}\n\n/**\n * Helper for console.log\n *\n * @api public\n */\n\nEmbeddedDocument.prototype.inspect = function () {\n return inspect(this.toObject());\n};\n\n/**\n * Marks a path as invalid, causing validation to fail.\n *\n * @param {String} path the field to invalidate\n * @param {String|Error} err error which states the reason `path` was invalid\n * @return {Boolean}\n * @api public\n */\n\nEmbeddedDocument.prototype.invalidate = function (path, err, val, first) {\n if (!this.__parent) {\n var msg = 'Unable to invalidate a subdocument that has not been added to an array.'\n throw new Error(msg);\n }\n\n var index = this.__parentArray.indexOf(this);\n var parentPath = this.__parentArray._path;\n var fullPath = [parentPath, index, path].join('.');\n\n // sniffing arguments:\n // need to check if user passed a value to keep\n // our error message clean.\n if (2 < arguments.length) {\n this.__parent.invalidate(fullPath, err, val);\n } else {\n this.__parent.invalidate(fullPath, err);\n }\n\n if (first)\n this.$__.validationError = this.ownerDocument().$__.validationError;\n return true;\n}\n\n/**\n * Returns the top level document of this sub-document.\n *\n * @return {Document}\n */\n\nEmbeddedDocument.prototype.ownerDocument = function () {\n if (this.$__.ownerDocument) {\n return this.$__.ownerDocument;\n }\n\n var parent = this.__parent;\n if (!parent) return this;\n\n while (parent.__parent) {\n parent = parent.__parent;\n }\n\n return this.$__.ownerDocument = parent;\n}\n\n/**\n * Returns the full path to this document. If optional `path` is passed, it is appended to the full path.\n *\n * @param {String} [path]\n * @return {String}\n * @api private\n * @method $__fullPath\n * @memberOf EmbeddedDocument\n */\n\nEmbeddedDocument.prototype.$__fullPath = function (path) {\n if (!this.$__.fullPath) {\n var parent = this;\n if (!parent.__parent) return path;\n\n var paths = [];\n while (parent.__parent) {\n paths.unshift(parent.__parentArray._path);\n parent = parent.__parent;\n }\n\n this.$__.fullPath = paths.join('.');\n\n if (!this.$__.ownerDocument) {\n // optimization\n this.$__.ownerDocument = parent;\n }\n }\n\n return path\n ? this.$__.fullPath + '.' + path\n : this.$__.fullPath;\n}\n\n/**\n * Returns this sub-documents parent document.\n *\n * @api public\n */\n\nEmbeddedDocument.prototype.parent = function () {\n return this.__parent;\n}\n\n/**\n * Returns this sub-documents parent array.\n *\n * @api public\n */\n\nEmbeddedDocument.prototype.parentArray = function () {\n return this.__parentArray;\n}\n\n/*!\n * Module exports.\n */\n\nmodule.exports = EmbeddedDocument;\n\n});","sourceLength":5250,"scriptType":2,"compilationType":0,"context":{"ref":8},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/embedded.js (lines: 246)"}],"refs":[{"handle":8,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":559,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[412]}}
{"seq":261,"request_seq":559,"type":"response","command":"scripts","success":true,"body":[{"handle":11,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/document.js","id":412,"lineOffset":0,"columnOffset":0,"lineCount":1692,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar EventEmitter = require('events').EventEmitter\n , setMaxListeners = EventEmitter.prototype.setMaxListeners\n , MongooseError = require('./error')\n , MixedSchema = require('./schema/mixed')\n , Schema = require('./schema')\n , ValidatorError = require('./schematype').ValidatorError\n , utils = require('./utils')\n , clone = utils.clone\n , isMongooseObject = utils.isMongooseObject\n , inspect = require('util').inspect\n , ElemMatchError = MongooseError.ElemMatchError\n , ValidationError = MongooseError.ValidationError\n , DocumentError = MongooseError.DocumentError\n , InternalCache = require('./internal')\n , deepEqual = utils.deepEqual\n , hooks = require('hooks')\n , DocumentArray\n , MongooseArray\n , Embedded\n\n/**\n * Document constructor.\n *\n * @param {Object} obj the values to set\n * @param {Object} [opts] optional object containing the fields which were selected in the query returning this document and any populated paths data\n * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id\n * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter\n * @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.\n * @event `save`: Emitted when the document is successfully saved\n * @api private\n */\n\nfunction Document (obj, fields, skipId) {\n this.$__ = new InternalCache;\n this.isNew = true;\n this.errors = undefined;\n\n var schema = this.schema;\n\n if ('boolean' === typeof fields) {\n this.$__.strictMode = fields;\n fields = undefined;\n } else {\n this.$__.strictMode = schema.options && schema.options.strict;\n this.$__.selected = fields;\n }\n\n var required = schema.requiredPaths();\n for (var i = 0; i < required.length; ++i) {\n this.$__.activePaths.require(required[i]);\n }\n\n setMaxListeners.call(this, 0);\n this._doc = this.$__buildDoc(obj, fields, skipId);\n\n if (obj) {\n this.set(obj, undefined, true);\n }\n\n this.$__registerHooks();\n}\n\n/*!\n * Inherit from EventEmitter.\n */\n\nDocument.prototype.__proto__ = EventEmitter.prototype;\n\n/**\n * The documents schema.\n *\n * @api public\n * @property schema\n */\n\nDocument.prototype.schema;\n\n/**\n * Boolean flag specifying if the document is new.\n *\n * @api public\n * @property isNew\n */\n\nDocument.prototype.isNew;\n\n/**\n * The string version of this documents _id.\n *\n * ####Note:\n *\n * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time.\n *\n * new Schema({ name: String }, { id: false });\n *\n * @api public\n * @see Schema options /docs/guide.html#options\n * @property id\n */\n\nDocument.prototype.id;\n\n/**\n * Hash containing current validation errors.\n *\n * @api public\n * @property errors\n */\n\nDocument.prototype.errors;\n\n/**\n * Builds the default doc structure\n *\n * @param {Object} obj\n * @param {Object} [fields]\n * @param {Boolean} [skipId]\n * @return {Object}\n * @api private\n * @method $__buildDoc\n * @memberOf Document\n */\n\nDocument.prototype.$__buildDoc = function (obj, fields, skipId) {\n var doc = {}\n , self = this\n , exclude\n , keys\n , key\n , ki\n\n // determine if this doc is a result of a query with\n // excluded fields\n if (fields && 'Object' === fields.constructor.name) {\n keys = Object.keys(fields);\n ki = keys.length;\n\n while (ki--) {\n if ('_id' !== keys[ki]) {\n exclude = 0 === fields[keys[ki]];\n break;\n }\n }\n }\n\n var paths = Object.keys(this.schema.paths)\n , plen = paths.length\n , ii = 0\n\n for (; ii < plen; ++ii) {\n var p = paths[ii];\n\n if ('_id' == p) {\n if (skipId) continue;\n if (obj && '_id' in obj) continue;\n }\n\n var type = this.schema.paths[p]\n , path = p.split('.')\n , len = path.length\n , last = len-1\n , doc_ = doc\n , i = 0\n\n for (; i < len; ++i) {\n var piece = path[i]\n , def\n\n if (i === last) {\n if (fields) {\n if (exclude) {\n // apply defaults to all non-excluded fields\n if (p in fields) continue;\n\n def = type.getDefault(self, true);\n if ('undefined' !== typeof def) {\n doc_[piece] = def;\n self.$__.activePaths.default(p);\n }\n\n } else if (p in fields) {\n // selected field\n def = type.getDefault(self, true);\n if ('undefined' !== typeof def) {\n doc_[piece] = def;\n self.$__.activePaths.default(p);\n }\n }\n } else {\n def = type.getDefault(self, true);\n if ('undefined' !== typeof def) {\n doc_[piece] = def;\n self.$__.activePaths.default(p);\n }\n }\n } else {\n doc_ = doc_[piece] || (doc_[piece] = {});\n }\n }\n };\n\n return doc;\n};\n\n/**\n * Initializes the document without setters or marking anything modified.\n *\n * Called internally after a document is returned from mongodb.\n *\n * @param {Object} doc document returned by mongo\n * @param {Function} fn callback\n * @api private\n */\n\nDocument.prototype.init = function (doc, opts, fn) {\n // do not prefix this method with $__ since its\n // used by public hooks\n\n if ('function' == typeof opts) {\n fn = opts;\n opts = null;\n }\n\n this.isNew = false;\n\n // handle docs with populated paths\n if (doc._id && opts && opts.populated && opts.populated.length) {\n var id = String(doc._id);\n for (var i = 0; i < opts.populated.length; ++i) {\n var item = opts.populated[i];\n this.populated(item.path, item._docs[id], item);\n }\n }\n\n init(this, doc, this._doc);\n this.$__storeShard();\n\n this.emit('init', this);\n if (fn) fn(null);\n return this;\n};\n\n/*!\n * Init helper.\n *\n * @param {Object} self document instance\n * @param {Object} obj raw mongodb doc\n * @param {Object} doc object we are initializing\n * @api private\n */\n\nfunction init (self, obj, doc, prefix) {\n prefix = prefix || '';\n\n var keys = Object.keys(obj)\n , len = keys.length\n , schema\n , path\n , i;\n\n while (len--) {\n i = keys[len];\n path = prefix + i;\n schema = self.schema.path(path);\n\n if (!schema && obj[i] && 'Object' === obj[i].constructor.name) {\n // assume nested object\n if (!doc[i]) doc[i] = {};\n init(self, obj[i], doc[i], path + '.');\n } else {\n if (obj[i] === null) {\n doc[i] = null;\n } else if (obj[i] !== undefined) {\n if (schema) {\n self.$__try(function(){\n doc[i] = schema.cast(obj[i], self, true);\n });\n } else {\n doc[i] = obj[i];\n }\n }\n // mark as hydrated\n self.$__.activePaths.init(path);\n }\n }\n};\n\n/**\n * Stores the current values of the shard keys.\n *\n * ####Note:\n *\n * _Shard key values do not / are not allowed to change._\n *\n * @api private\n * @method $__storeShard\n * @memberOf Document\n */\n\nDocument.prototype.$__storeShard = function () {\n // backwards compat\n var key = this.schema.options.shardKey || this.schema.options.shardkey;\n if (!(key && 'Object' == key.constructor.name)) return;\n\n var orig = this.$__.shardval = {}\n , paths = Object.keys(key)\n , len = paths.length\n , val\n\n for (var i = 0; i < len; ++i) {\n val = this.getValue(paths[i]);\n if (isMongooseObject(val)) {\n orig[paths[i]] = val.toObject({ depopulate: true })\n } else if (null != val && val.valueOf) {\n orig[paths[i]] = val.valueOf();\n } else {\n orig[paths[i]] = val;\n }\n }\n}\n\n/*!\n * Set up middleware support\n */\n\nfor (var k in hooks) {\n Document.prototype[k] = Document[k] = hooks[k];\n}\n\n/**\n * Sends an update command with this document `_id` as the query selector.\n *\n * ####Example:\n *\n * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);\n *\n * ####Valid options:\n *\n * - same as in [Model.update](#model_Model.update)\n *\n * @see Model.update #model_Model.update\n * @param {Object} doc\n * @param {Object} options\n * @param {Function} callback\n * @return {Query}\n * @api public\n */\n\nDocument.prototype.update = function update () {\n var args = utils.args(arguments);\n args.unshift({_id: this._id});\n return this.constructor.update.apply(this.constructor, args);\n}\n\n/**\n * Sets the value of a path, or many paths.\n *\n * ####Example:\n *\n * // path, value\n * doc.set(path, value)\n *\n * // object\n * doc.set({\n * path : value\n * , path2 : {\n * path : value\n * }\n * })\n *\n * // only-the-fly cast to number\n * doc.set(path, value, Number)\n *\n * // only-the-fly cast to string\n * doc.set(path, value, String)\n *\n * // changing strict mode behavior\n * doc.set(path, value, { strict: false });\n *\n * @param {String|Object} path path or object of key/vals to set\n * @param {Any} val the value to set\n * @param {Schema|String|Number|Buffer|etc..} [type] optionally specify a type for \"on-the-fly\" attributes\n * @param {Object} [options] optionally specify options that modify the behavior of the set\n * @api public\n */\n\nDocument.prototype.set = function (path, val, type, options) {\n if (type && 'Object' == type.constructor.name) {\n options = type;\n type = undefined;\n }\n\n var merge = options && options.merge\n , adhoc = type && true !== type\n , constructing = true === type\n , adhocs\n\n var strict = options && 'strict' in options\n ? options.strict\n : this.$__.strictMode;\n\n if (adhoc) {\n adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});\n adhocs[path] = Schema.interpretAsType(path, type);\n }\n\n if ('string' !== typeof path) {\n // new Document({ key: val })\n\n if (null === path || undefined === path) {\n var _ = path;\n path = val;\n val = _;\n\n } else {\n var prefix = val\n ? val + '.'\n : '';\n\n if (path instanceof Document) path = path._doc;\n\n var keys = Object.keys(path)\n , i = keys.length\n , pathtype\n , key\n\n while (i--) {\n key = keys[i];\n pathtype = this.schema.pathType(prefix + key);\n if (null != path[key]\n && 'Object' == path[key].constructor.name\n && 'virtual' != pathtype\n && !(this.$__path(prefix + key) instanceof MixedSchema)) {\n this.set(path[key], prefix + key, constructing);\n } else if (strict) {\n if ('real' === pathtype || 'virtual' === pathtype) {\n this.set(prefix + key, path[key], constructing);\n } else if ('throw' == strict) {\n throw new Error(\"Field `\" + key + \"` is not in schema.\");\n }\n } else if (undefined !== path[key]) {\n this.set(prefix + key, path[key], constructing);\n }\n }\n\n return this;\n }\n }\n\n // ensure _strict is honored for obj props\n // docschema = new Schema({ path: { nest: 'string' }})\n // doc.set('path', obj);\n var pathType = this.schema.pathType(path);\n if ('nested' == pathType && val && 'Object' == val.constructor.name) {\n if (!merge) this.setValue(path, null);\n this.set(val, path, constructing);\n return this;\n }\n\n var schema;\n if ('adhocOrUndefined' == pathType && strict) {\n return this;\n } else if ('virtual' == pathType) {\n schema = this.schema.virtualpath(path);\n schema.applySetters(val, this);\n return this;\n } else {\n schema = this.$__path(path);\n }\n\n var parts = path.split('.')\n , pathToMark\n\n // When using the $set operator the path to the field must already exist.\n // Else mongodb throws: \"LEFT_SUBFIELD only supports Object\"\n\n if (parts.length <= 1) {\n pathToMark = path;\n } else {\n for (var i = 0; i < parts.length; ++i) {\n var part = parts[i];\n var subpath = parts.slice(0, i).concat(part).join('.');\n if (this.isDirectModified(subpath) // earlier prefixes that are already\n // marked as dirty have precedence\n || this.get(subpath) === null) {\n pathToMark = subpath;\n break;\n }\n }\n\n if (!pathToMark) pathToMark = path;\n }\n\n if (!schema || null === val || undefined === val) {\n this.$__set(pathToMark, path, constructing, parts, schema, val);\n return this;\n }\n\n var self = this;\n\n // if this doc is being constructed we should not\n // trigger getters.\n var priorVal = constructing\n ? undefined\n : this.get(path);\n\n var shouldSet = this.$__try(function(){\n val = schema.applySetters(val, self, false, priorVal);\n });\n\n if (shouldSet) {\n this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);\n }\n\n return this;\n}\n\n/**\n * Determine if we should mark this change as modified.\n *\n * @return {Boolean}\n * @api private\n * @method $__shouldModify\n * @memberOf Document\n */\n\nDocument.prototype.$__shouldModify = function (\n pathToMark, path, constructing, parts, schema, val, priorVal) {\n\n if (this.isNew) return true;\n if (this.isDirectModified(pathToMark)) return false;\n\n if (undefined === val && !this.isSelected(path)) {\n // when a path is not selected in a query, its initial\n // value will be undefined.\n return true;\n }\n\n if (undefined === val && path in this.$__.activePaths.states.default) {\n // we're just unsetting the default value which was never saved\n return false;\n }\n\n if (!deepEqual(val, priorVal || this.get(path))) {\n return true;\n }\n\n if (!constructing &&\n null != val &&\n path in this.$__.activePaths.states.default &&\n deepEqual(val, schema.getDefault(this, constructing))) {\n // a path with a default was $unset on the server\n // and the user is setting it to the same value again\n return true;\n }\n\n return false;\n}\n\n/**\n * Handles the actual setting of the value and marking the path modified if appropriate.\n *\n * @api private\n * @method $__set\n * @memberOf Document\n */\n\nDocument.prototype.$__set = function (\n pathToMark, path, constructing, parts, schema, val, priorVal) {\n\n var shouldModify = this.$__shouldModify.apply(this, arguments);\n\n if (shouldModify) {\n this.markModified(pathToMark, val);\n\n // handle directly setting arrays (gh-1126)\n MongooseArray || (MongooseArray = require('./types/array'));\n if (val instanceof MongooseArray) {\n val._registerAtomic('$set', val);\n }\n }\n\n var obj = this._doc\n , i = 0\n , l = parts.length\n\n for (; i < l; i++) {\n var next = i + 1\n , last = next === l;\n\n if (last) {\n obj[parts[i]] = val;\n } else {\n if (obj[parts[i]] && 'Object' === obj[parts[i]].constructor.name) {\n obj = obj[parts[i]];\n } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {\n obj = obj[parts[i]];\n } else {\n obj = obj[parts[i]] = {};\n }\n }\n }\n}\n\n/**\n * Gets a raw value from a path (no getters)\n *\n * @param {String} path\n * @api private\n */\n\nDocument.prototype.getValue = function (path) {\n return utils.getValue(path, this._doc);\n}\n\n/**\n * Sets a raw value for a path (no casting, setters, transformations)\n *\n * @param {String} path\n * @param {Object} value\n * @api private\n */\n\nDocument.prototype.setValue = function (path, val) {\n utils.setValue(path, val, this._doc);\n return this;\n}\n\n/**\n * Returns the value of a path.\n *\n * ####Example\n *\n * // path\n * doc.get('age') // 47\n *\n * // dynamic casting to a string\n * doc.get('age', String) // \"47\"\n *\n * @param {String} path\n * @param {Schema|String|Number|Buffer|etc..} [type] optionally specify a type for on-the-fly attributes\n * @api public\n */\n\nDocument.prototype.get = function (path, type) {\n var adhocs;\n if (type) {\n adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});\n adhocs[path] = Schema.interpretAsType(path, type);\n }\n\n var schema = this.$__path(path) || this.schema.virtualpath(path)\n , pieces = path.split('.')\n , obj = this._doc;\n\n for (var i = 0, l = pieces.length; i < l; i++) {\n obj = null == obj ? null : obj[pieces[i]];\n }\n\n if (schema) {\n obj = schema.applyGetters(obj, this);\n }\n\n return obj;\n};\n\n/**\n * Returns the schematype for the given `path`.\n *\n * @param {String} path\n * @api private\n * @method $__path\n * @memberOf Document\n */\n\nDocument.prototype.$__path = function (path) {\n var adhocs = this.$__.adhocPaths\n , adhocType = adhocs && adhocs[path];\n\n if (adhocType) {\n return adhocType;\n } else {\n return this.schema.path(path);\n }\n};\n\n/**\n * Marks the path as having pending changes to write to the db.\n *\n * _Very helpful when using [Mixed](./schematypes.html#mixed) types._\n *\n * ####Example:\n *\n * doc.mixed.type = 'changed';\n * doc.markModified('mixed.type');\n * doc.save() // changes to mixed.type are now persisted\n *\n * @param {String} path the path to mark modified\n * @api public\n */\n\nDocument.prototype.markModified = function (path) {\n this.$__.activePaths.modify(path);\n}\n\n/**\n * Catches errors that occur during execution of `fn` and stores them to later be passed when `save()` is executed.\n *\n * @param {Function} fn function to execute\n * @param {Object} scope the scope with which to call fn\n * @api private\n * @method $__try\n * @memberOf Document\n */\n\nDocument.prototype.$__try = function (fn, scope) {\n var res;\n try {\n fn.call(scope);\n res = true;\n } catch (e) {\n this.$__error(e);\n res = false;\n }\n return res;\n};\n\n/**\n * Returns the list of paths that have been modified.\n *\n * @return {Array}\n * @api public\n */\n\nDocument.prototype.modifiedPaths = function () {\n var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);\n\n return directModifiedPaths.reduce(function (list, path) {\n var parts = path.split('.');\n return list.concat(parts.reduce(function (chains, part, i) {\n return chains.concat(parts.slice(0, i).concat(part).join('.'));\n }, []));\n }, []);\n};\n\n/**\n * Returns true if this document was modified, else false.\n *\n * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified.\n *\n * ####Example\n *\n * doc.set('documents.0.title', 'changed');\n * doc.isModified() // true\n * doc.isModified('documents') // true\n * doc.isModified('documents.0.title') // true\n * doc.isDirectModified('documents') // false\n *\n * @param {String} [path] optional\n * @return {Boolean}\n * @api public\n */\n\nDocument.prototype.isModified = function (path) {\n return path\n ? !!~this.modifiedPaths().indexOf(path)\n : this.$__.activePaths.some('modify');\n};\n\n/**\n * Returns true if `path` was directly set and modified, else false.\n *\n * ####Example\n *\n * doc.set('documents.0.title', 'changed');\n * doc.isDirectModified('documents.0.title') // true\n * doc.isDirectModified('documents') // false\n *\n * @param {String} path\n * @return {Boolean}\n * @api public\n */\n\nDocument.prototype.isDirectModified = function (path) {\n return (path in this.$__.activePaths.states.modify);\n};\n\n/**\n * Checks if `path` was initialized.\n *\n * @param {String} path\n * @return {Boolean}\n * @api public\n */\n\nDocument.prototype.isInit = function (path) {\n return (path in this.$__.activePaths.states.init);\n};\n\n/**\n * Checks if `path` was selected in the source query which initialized this document.\n *\n * ####Example\n *\n * Thing.findOne().select('name').exec(function (err, doc) {\n * doc.isSelected('name') // true\n * doc.isSelected('age') // false\n * })\n *\n * @param {String} path\n * @return {Boolean}\n * @api public\n */\n\nDocument.prototype.isSelected = function isSelected (path) {\n if (this.$__.selected) {\n\n if ('_id' === path) {\n return 0 !== this.$__.selected._id;\n }\n\n var paths = Object.keys(this.$__.selected)\n , i = paths.length\n , inclusive = false\n , cur\n\n if (1 === i && '_id' === paths[0]) {\n // only _id was selected.\n return 0 === this.$__.selected._id;\n }\n\n while (i--) {\n cur = paths[i];\n if ('_id' == cur) continue;\n inclusive = !! this.$__.selected[cur];\n break;\n }\n\n if (path in this.$__.selected) {\n return inclusive;\n }\n\n i = paths.length;\n var pathDot = path + '.';\n\n while (i--) {\n cur = paths[i];\n if ('_id' == cur) continue;\n\n if (0 === cur.indexOf(pathDot)) {\n return inclusive;\n }\n\n if (0 === pathDot.indexOf(cur)) {\n return inclusive;\n }\n }\n\n return ! inclusive;\n }\n\n return true;\n}\n\n/**\n * Executes registered validation rules for this document.\n *\n * ####Note:\n *\n * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`.\n *\n * ####Example:\n *\n * doc.validate(function (err) {\n * if (err) handleError(err);\n * else // validation passed\n * });\n *\n * @param {Function} cb called after validation completes, passing an error if one occurred\n * @api public\n */\n\nDocument.prototype.validate = function (cb) {\n var self = this\n\n // only validate required fields when necessary\n var paths = Object.keys(this.$__.activePaths.states.require).filter(function (path) {\n if (!self.isSelected(path) && !self.isModified(path)) return false;\n return true;\n });\n\n paths = paths.concat(Object.keys(this.$__.activePaths.states.init));\n paths = paths.concat(Object.keys(this.$__.activePaths.states.modify));\n paths = paths.concat(Object.keys(this.$__.activePaths.states.default));\n\n if (0 === paths.length) {\n complete();\n return this;\n }\n\n var validating = {}\n , total = 0;\n\n paths.forEach(validatePath);\n return this;\n\n function validatePath (path) {\n if (validating[path]) return;\n\n validating[path] = true;\n total++;\n\n process.nextTick(function(){\n var p = self.schema.path(path);\n if (!p) return --total || complete();\n\n var val = self.getValue(path);\n p.doValidate(val, function (err) {\n if (err) {\n self.invalidate(\n path\n , err\n , undefined\n , true // embedded docs\n );\n }\n --total || complete();\n }, self);\n });\n }\n\n function complete () {\n var err = self.$__.validationError;\n self.$__.validationError = undefined;\n self.emit('validate', self);\n cb(err);\n }\n};\n\n/**\n * Marks a path as invalid, causing validation to fail.\n *\n * @param {String} path the field to invalidate\n * @param {String|Error} err the error which states the reason `path` was invalid\n * @param {Object|String|Number|any} value optional invalid value\n * @api public\n */\n\nDocument.prototype.invalidate = function (path, err, val) {\n if (!this.$__.validationError) {\n this.$__.validationError = new ValidationError(this);\n }\n\n if (!err || 'string' === typeof err) {\n // sniffing arguments:\n // need to handle case where user does not pass value\n // so our error message is cleaner\n err = 2 < arguments.length\n ? new ValidatorError(path, err, val)\n : new ValidatorError(path, err)\n }\n\n this.$__.validationError.errors[path] = err;\n}\n\n/**\n * Resets the internal modified state of this document.\n *\n * @api private\n * @return {Document}\n * @method $__reset\n * @memberOf Document\n */\n\nDocument.prototype.$__reset = function reset () {\n var self = this;\n DocumentArray || (DocumentArray = require('./types/documentarray'));\n\n this.$__.activePaths\n .map('init', 'modify', function (i) {\n return self.getValue(i);\n })\n .filter(function (val) {\n return val && val instanceof DocumentArray && val.length;\n })\n .forEach(function (array) {\n var i = array.length;\n while (i--) {\n var doc = array[i];\n if (!doc) continue;\n doc.$__reset();\n }\n });\n\n // clear atomics\n this.$__dirty().forEach(function (dirt) {\n var type = dirt.value;\n if (type && type._atomics) {\n type._atomics = {};\n }\n });\n\n // Clear 'modify'('dirty') cache\n this.$__.activePaths.clear('modify');\n this.$__.validationError = undefined;\n this.errors = undefined;\n var self = this;\n this.schema.requiredPaths().forEach(function (path) {\n self.$__.activePaths.require(path);\n });\n\n return this;\n}\n\n/**\n * Returns this documents dirty paths / vals.\n *\n * @api private\n * @method $__dirty\n * @memberOf Document\n */\n\nDocument.prototype.$__dirty = function () {\n var self = this;\n\n var all = this.$__.activePaths.map('modify', function (path) {\n return { path: path\n , value: self.getValue(path)\n , schema: self.$__path(path) };\n });\n\n // Sort dirty paths in a flat hierarchy.\n all.sort(function (a, b) {\n return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0));\n });\n\n // Ignore \"foo.a\" if \"foo\" is dirty already.\n var minimal = []\n , lastPath\n , top;\n\n all.forEach(function (item, i) {\n if (item.path.indexOf(lastPath) !== 0) {\n lastPath = item.path + '.';\n minimal.push(item);\n top = item;\n } else {\n // special case for top level MongooseArrays\n if (top.value && top.value._atomics && top.value.hasAtomics()) {\n // the `top` array itself and a sub path of `top` are being modified.\n // the only way to honor all of both modifications is through a $set\n // of entire array.\n top.value._atomics = {};\n top.value._atomics.$set = top.value;\n }\n }\n });\n\n top = lastPath = null;\n return minimal;\n}\n\n/*!\n * Compiles schemas.\n */\n\nfunction compile (tree, proto, prefix) {\n var keys = Object.keys(tree)\n , i = keys.length\n , limb\n , key;\n\n while (i--) {\n key = keys[i];\n limb = tree[key];\n\n define(key\n , (('Object' === limb.constructor.name\n && Object.keys(limb).length)\n && (!limb.type || limb.type.type)\n ? limb\n : null)\n , proto\n , prefix\n , keys);\n }\n};\n\n/*!\n * Defines the accessor named prop on the incoming prototype.\n */\n\nfunction define (prop, subprops, prototype, prefix, keys) {\n var prefix = prefix || ''\n , path = (prefix ? prefix + '.' : '') + prop;\n\n if (subprops) {\n\n Object.defineProperty(prototype, prop, {\n enumerable: true\n , get: function () {\n if (!this.$__.getters)\n this.$__.getters = {};\n\n if (!this.$__.getters[path]) {\n var nested = Object.create(this);\n\n // save scope for nested getters/setters\n if (!prefix) nested.$__.scope = this;\n\n // shadow inherited getters from sub-objects so\n // thing.nested.nested.nested... doesn't occur (gh-366)\n var i = 0\n , len = keys.length;\n\n for (; i < len; ++i) {\n // over-write the parents getter without triggering it\n Object.defineProperty(nested, keys[i], {\n enumerable: false // It doesn't show up.\n , writable: true // We can set it later.\n , configurable: true // We can Object.defineProperty again.\n , value: undefined // It shadows its parent.\n });\n }\n\n nested.toObject = function () {\n return this.get(path);\n };\n\n compile(subprops, nested, path);\n this.$__.getters[path] = nested;\n }\n\n return this.$__.getters[path];\n }\n , set: function (v) {\n if (v instanceof Document) v = v.toObject();\n return (this.$__.scope || this).set(path, v);\n }\n });\n\n } else {\n\n Object.defineProperty(prototype, prop, {\n enumerable: true\n , get: function ( ) { return this.get.call(this.$__.scope || this, path); }\n , set: function (v) { return this.set.call(this.$__.scope || this, path, v); }\n });\n }\n};\n\n/**\n * Assigns/compiles `schema` into this documents prototype.\n *\n * @param {Schema} schema\n * @api private\n * @method $__setSchema\n * @memberOf Document\n */\n\nDocument.prototype.$__setSchema = function (schema) {\n compile(schema.tree, this);\n this.schema = schema;\n}\n\n/**\n * Register default hooks\n *\n * @api private\n * @method $__registerHooks\n * @memberOf Document\n */\n\nDocument.prototype.$__registerHooks = function () {\n if (!this.save) return;\n\n DocumentArray || (DocumentArray = require('./types/documentarray'));\n\n this.pre('save', function (next) {\n // validate all document arrays.\n // we keep the error semaphore to make sure we don't\n // call `save` unnecessarily (we only need 1 error)\n var subdocs = 0\n , error = false\n , self = this;\n\n // check for DocumentArrays\n var arrays = this.$__.activePaths\n .map('init', 'modify', function (i) {\n return self.getValue(i);\n })\n .filter(function (val) {\n return val && val instanceof DocumentArray && val.length;\n });\n\n if (!arrays.length)\n return next();\n\n arrays.forEach(function (array) {\n if (error) return;\n\n // handle sparse arrays by using for loop vs array.forEach\n // which skips the sparse elements\n\n var len = array.length\n subdocs += len;\n\n for (var i = 0; i < len; ++i) {\n if (error) break;\n\n var doc = array[i];\n if (!doc) {\n --subdocs || next();\n continue;\n }\n\n doc.save(handleSave);\n }\n });\n\n function handleSave (err) {\n if (error) return;\n\n if (err) {\n self.$__.validationError = undefined;\n return next(error = err);\n }\n\n --subdocs || next();\n }\n\n }, function (err) {\n // emit on the Model if listening\n if (this.constructor.listeners('error').length) {\n this.constructor.emit('error', err);\n } else {\n // emit on the connection\n if (!this.db.listeners('error').length) {\n err.stack = 'No listeners detected, throwing. '\n + 'Consider adding an error listener to your connection.\\n'\n + err.stack\n }\n this.db.emit('error', err);\n }\n }).pre('save', function checkForExistingErrors (next) {\n // if any doc.set() calls failed\n var err = this.$__.saveError;\n if (err) {\n this.$__.saveError = null;\n next(err);\n } else {\n next();\n }\n }).pre('save', function validation (next) {\n return this.validate(next);\n });\n\n // add user defined queues\n this.$__doQueue();\n};\n\n/**\n * Registers an error\n *\n * @param {Error} err\n * @api private\n * @method $__error\n * @memberOf Document\n */\n\nDocument.prototype.$__error = function (err) {\n this.$__.saveError = err;\n return this;\n};\n\n/**\n * Executes methods queued from the Schema definition\n *\n * @api private\n * @method $__doQueue\n * @memberOf Document\n */\n\nDocument.prototype.$__doQueue = function () {\n var q = this.schema && this.schema.callQueue;\n if (q) {\n for (var i = 0, l = q.length; i < l; i++) {\n this[q[i][0]].apply(this, q[i][1]);\n }\n }\n return this;\n};\n\n/**\n * Converts this document into a plain javascript object, ready for storage in MongoDB.\n *\n * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage.\n *\n * ####Options:\n *\n * - `getters` apply all getters (path and virtual getters)\n * - `virtuals` apply virtual getters (can override `getters` option)\n * - `minimize` remove empty objects (defaults to true)\n * - `transform` a transform function to apply to the resulting document before returning\n *\n * ####Getters/Virtuals\n *\n * Example of only applying path getters\n *\n * doc.toObject({ getters: true, virtuals: false })\n *\n * Example of only applying virtual getters\n *\n * doc.toObject({ virtuals: true })\n *\n * Example of applying both path and virtual getters\n *\n * doc.toObject({ getters: true })\n *\n * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument.\n *\n * schema.set('toObject', { virtuals: true })\n *\n * ####Transform\n *\n * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function.\n *\n * Transform functions receive three arguments\n *\n * function (doc, ret, options) {}\n *\n * - `doc` The mongoose document which is being converted\n * - `ret` The plain object representation which has been converted\n * - `options` The options in use (either schema options or the options passed inline)\n *\n * ####Example\n *\n * // specify the transform schema option\n * schema.options.toObject.transform = function (doc, ret, options) {\n * // remove the _id of every document before returning the result\n * delete ret._id;\n * }\n *\n * // without the transformation in the schema\n * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }\n *\n * // with the transformation\n * doc.toObject(); // { name: 'Wreck-it Ralph' }\n *\n * With transformations we can do a lot more than remove properties. We can even return completely new customized objects:\n *\n * schema.options.toObject.transform = function (doc, ret, options) {\n * return { movie: ret.name }\n * }\n *\n * // without the transformation in the schema\n * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }\n *\n * // with the transformation\n * doc.toObject(); // { movie: 'Wreck-it Ralph' }\n *\n * _Note: if a transform function returns `undefined`, the return value will be ignored._\n *\n * Transformations may also be applied inline, overridding any transform set in the options:\n *\n * function xform (doc, ret, options) {\n * return { inline: ret.name, custom: true }\n * }\n *\n * // pass the transform as an inline option\n * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }\n *\n * _Note: if you call `toObject` and pass any options, the transform declared in your schema options will __not__ be applied. To force its application pass `transform: true`_\n *\n * schema.options.toObject.hide = '_id';\n * schema.options.toObject.transform = function (doc, ret, options) {\n * if (options.hide) {\n * options.hide.split(' ').forEach(function (prop) {\n * delete ret[prop];\n * });\n * }\n * }\n *\n * var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });\n * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }\n * doc.toObject({ hide: 'secret _id' }); // { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }\n * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }\n *\n * Transforms are applied to the document _and each of its sub-documents_. To determine whether or not you are currently operating on a sub-document you might use the following guard:\n *\n * if ('function' == typeof doc.ownerDocument) {\n * // working with a sub doc\n * }\n *\n * Transforms, like all of these options, are also available for `toJSON`.\n *\n * See [schema options](/docs/guide.html#toObject) for some more details.\n *\n * @param {Object} [options]\n * @return {Object} js object\n * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html\n * @api public\n */\n\nDocument.prototype.toObject = function (options) {\n if (options && options.convertToId) {\n // populated paths that we set to a document?\n Embedded || (Embedded = require('./types/embedded'));\n if (!(this instanceof Embedded)) {\n return clone(this._id, options);\n }\n }\n\n // When internally saving this document we always pass options,\n // bypassing the custom schema options.\n if (!(options && 'Object' == options.constructor.name)) {\n options = this.schema.options.toObject\n ? clone(this.schema.options.toObject)\n : {};\n }\n\n ;('minimize' in options) || (options.minimize = this.schema.options.minimize);\n\n var ret = clone(this._doc, options);\n\n if (options.virtuals || options.getters && false !== options.virtuals) {\n applyGetters(this, ret, 'virtuals', options);\n }\n\n if (options.getters) {\n applyGetters(this, ret, 'paths', options);\n }\n\n if (true === options.transform) {\n var opts = options.json\n ? this.schema.options.toJSON\n : this.schema.options.toObject;\n if (opts) {\n options.transform = opts.transform;\n }\n }\n\n if ('function' == typeof options.transform) {\n var xformed = options.transform(this, ret, options);\n if ('undefined' != typeof xformed) ret = xformed;\n }\n\n return ret;\n};\n\n/*!\n * Applies virtuals properties to `json`.\n *\n * @param {Document} self\n * @param {Object} json\n * @param {String} type either `virtuals` or `paths`\n * @return {Object} `json`\n */\n\nfunction applyGetters (self, json, type, options) {\n var schema = self.schema\n , paths = Object.keys(schema[type])\n , i = paths.length\n , path\n\n while (i--) {\n path = paths[i];\n\n var parts = path.split('.')\n , plen = parts.length\n , last = plen - 1\n , branch = json\n , part\n\n for (var ii = 0; ii < plen; ++ii) {\n part = parts[ii];\n if (ii === last) {\n branch[part] = clone(self.get(path), options);\n } else {\n branch = branch[part] || (branch[part] = {});\n }\n }\n }\n\n return json;\n}\n\n/**\n * The return value of this method is used in calls to JSON.stringify(doc).\n *\n * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument.\n *\n * schema.set('toJSON', { virtuals: true })\n *\n * See [schema options](/docs/guide.html#toJSON) for details.\n *\n * @param {Object} options same options as [Document#toObject](#document_Document-toObject)\n * @return {Object}\n * @see Document#toObject #document_Document-toObject\n\n * @api public\n */\n\nDocument.prototype.toJSON = function (options) {\n // check for object type since an array of documents\n // being stringified passes array indexes instead\n // of options objects. JSON.stringify([doc, doc])\n if (!(options && 'Object' == options.constructor.name)) {\n options = this.schema.options.toJSON\n ? clone(this.schema.options.toJSON)\n : {};\n }\n options.json = true;\n return this.toObject(options);\n};\n\n/**\n * Helper for console.log\n *\n * @api public\n */\n\nDocument.prototype.inspect = function (options) {\n var opts = options && 'Object' == options.constructor.name ? options :\n this.schema.options.toObject ? clone(this.schema.options.toObject) :\n {};\n opts.minimize = false;\n return inspect(this.toObject(opts));\n};\n\n/**\n * Helper for console.log\n *\n * @api public\n * @method toString\n */\n\nDocument.prototype.toString = Document.prototype.inspect;\n\n/**\n * Returns true if the Document stores the same data as doc.\n *\n * Documents are considered equal when they have matching `_id`s.\n *\n * @param {Document} doc a document to compare\n * @return {Boolean}\n * @api public\n */\n\nDocument.prototype.equals = function (doc) {\n var tid = this.get('_id');\n var docid = doc.get('_id');\n return tid.equals\n ? tid.equals(docid)\n : tid === docid;\n}\n\n/**\n * Populates document references, executing the `callback` when complete.\n *\n * ####Example:\n *\n * doc\n * .populate('company')\n * .populate({\n * path: 'notes',\n * match: /airline/,\n * select: 'text',\n * match: 'modelName'\n * options: opts\n * }, function (err, user) {\n * assert(doc._id == user._id) // the document itself is passed\n * })\n *\n * // summary\n * doc.populate(path) // not executed\n * doc.populate(options); // not executed\n * doc.populate(path, callback) // executed\n * doc.populate(options, callback); // executed\n * doc.populate(callback); // executed\n *\n *\n * ####NOTE:\n *\n * Population does not occur unless a `callback` is passed.\n * Passing the same path a second time will overwrite the previous path options.\n * See [Model.populate()](#model_Model.populate) for explaination of options.\n *\n * @see Model.populate #model_Model.populate\n * @param {String|Object} [path] The path to populate or an options object\n * @param {Function} [callback] When passed, population is invoked\n * @api public\n * @return {Document} this\n */\n\nDocument.prototype.populate = function populate () {\n if (0 === arguments.length) return this;\n\n var pop = this.$__.populate || (this.$__.populate = {});\n var args = utils.args(arguments);\n var fn;\n\n if ('function' == typeof args[args.length-1]) {\n fn = args.pop();\n }\n\n // allow `doc.populate(callback)`\n if (args.length) {\n // use hash to remove duplicate paths\n var res = utils.populate.apply(null, args);\n for (var i = 0; i < res.length; ++i) {\n pop[res[i].path] = res[i];\n }\n }\n\n if (fn) {\n var paths = utils.object.vals(pop);\n this.$__.populate = undefined;\n this.constructor.populate(this, paths, fn);\n }\n\n return this;\n}\n\n\n/**\n * Gets _id(s) used during population of the given `path`.\n *\n * ####Example:\n *\n * Model.findOne().populate('author').exec(function (err, doc) {\n * console.log(doc.author.name) // Dr.Seuss\n * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'\n * })\n *\n * If the path was not populated, undefined is returned.\n *\n * @param {String} path\n * @return {Array|ObjectId|Number|Buffer|String|undefined}\n * @api public\n */\n\nDocument.prototype.populated = function (path, val, options) {\n // val and options are internal\n\n if (null == val) {\n if (!this.$__.populated) return undefined;\n var v = this.$__.populated[path];\n if (v) return v.value;\n return undefined;\n }\n\n // internal\n\n if (true === val) {\n if (!this.$__.populated) return undefined;\n return this.$__.populated[path];\n }\n\n this.$__.populated || (this.$__.populated = {});\n this.$__.populated[path] = { value: val, options: options };\n return val;\n}\n\n/**\n * Returns the full path to this document.\n *\n * @param {String} [path]\n * @return {String}\n * @api private\n * @method $__fullPath\n * @memberOf Document\n */\n\nDocument.prototype.$__fullPath = function (path) {\n // overridden in SubDocuments\n return path || '';\n}\n\n/*!\n * Module exports.\n */\n\nDocument.ValidationError = ValidationError;\nmodule.exports = exports = Document;\nexports.Error = DocumentError;\n\n});","sourceLength":42512,"scriptType":2,"compilationType":0,"context":{"ref":10},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/document.js (lines: 1692)"}],"refs":[{"handle":10,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":560,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[415]}}
{"seq":262,"request_seq":560,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/mixed.js","id":415,"lineOffset":0,"columnOffset":0,"lineCount":85,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar SchemaType = require('../schematype');\nvar utils = require('../utils');\n\n/**\n * Mixed SchemaType constructor.\n *\n * @param {String} path\n * @param {Object} options\n * @inherits SchemaType\n * @api private\n */\n\nfunction Mixed (path, options) {\n if (options && options.default) {\n var def = options.default;\n if (Array.isArray(def) && 0 === def.length) {\n // make sure empty array defaults are handled\n options.default = Array;\n } else if (!options.shared &&\n utils.isObject(def) &&\n 0 === Object.keys(def).length) {\n // prevent odd \"shared\" objects between documents\n options.default = function () {\n return {}\n }\n }\n }\n\n SchemaType.call(this, path, options);\n};\n\n/*!\n * Inherits from SchemaType.\n */\n\nMixed.prototype.__proto__ = SchemaType.prototype;\n\n/**\n * Required validator\n *\n * @api private\n */\n\nMixed.prototype.checkRequired = function (val) {\n return true;\n};\n\n/**\n * Casts `val` for Mixed.\n *\n * _this is a no-op_\n *\n * @param {Object} value to cast\n * @api private\n */\n\nMixed.prototype.cast = function (val) {\n return val;\n};\n\n/**\n * Casts contents for queries.\n *\n * @param {String} $cond\n * @param {any} [val]\n * @api private\n */\n\nMixed.prototype.castForQuery = function ($cond, val) {\n if (arguments.length === 2) return val;\n return $cond;\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = Mixed;\n\n});","sourceLength":1492,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schema/mixed.js (lines: 85)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":561,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[418]}}
{"seq":272,"request_seq":561,"type":"response","command":"scripts","success":true,"body":[{"handle":6,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/internal.js","id":418,"lineOffset":0,"columnOffset":0,"lineCount":32,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Dependencies\n */\n\nvar StateMachine = require('./statemachine')\nvar ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default')\n\nmodule.exports = exports = InternalCache;\n\nfunction InternalCache () {\n this.strictMode = undefined;\n this.selected = undefined;\n this.shardval = undefined;\n this.saveError = undefined;\n this.validationError = undefined;\n this.adhocPaths = undefined;\n this.removing = undefined;\n this.inserting = undefined;\n this.version = undefined;\n this.getters = {};\n this._id = undefined;\n this.populate = undefined;\n this.populated = undefined;\n this.scope = undefined;\n this.activePaths = new ActiveRoster;\n\n // embedded docs\n this.ownerDocument = undefined;\n this.fullPath = undefined;\n}\n\n});","sourceLength":812,"scriptType":2,"compilationType":0,"context":{"ref":5},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/internal.js (lines: 32)"}],"refs":[{"handle":5,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":562,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[421]}}
{"seq":273,"request_seq":562,"type":"response","command":"scripts","success":true,"body":[{"handle":8,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/statemachine.js","id":421,"lineOffset":0,"columnOffset":0,"lineCount":181,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar utils = require('./utils');\n\n/*!\n * StateMachine represents a minimal `interface` for the\n * constructors it builds via StateMachine.ctor(...).\n *\n * @api private\n */\n\nvar StateMachine = module.exports = exports = function StateMachine () {\n this.paths = {};\n this.states = {};\n}\n\n/*!\n * StateMachine.ctor('state1', 'state2', ...)\n * A factory method for subclassing StateMachine.\n * The arguments are a list of states. For each state,\n * the constructor's prototype gets state transition\n * methods named after each state. These transition methods\n * place their path argument into the given state.\n *\n * @param {String} state\n * @param {String} [state]\n * @return {Function} subclass constructor\n * @private\n */\n\nStateMachine.ctor = function () {\n var states = utils.args(arguments);\n\n var ctor = function () {\n StateMachine.apply(this, arguments);\n this.stateNames = states;\n\n var i = states.length\n , state;\n\n while (i--) {\n state = states[i];\n this.states[state] = {};\n }\n };\n\n ctor.prototype.__proto__ = StateMachine.prototype;\n\n states.forEach(function (state) {\n // Changes the `path`'s state to `state`.\n ctor.prototype[state] = function (path) {\n this._changeState(path, state);\n }\n });\n\n return ctor;\n};\n\n/*!\n * This function is wrapped by the state change functions:\n *\n * - `require(path)`\n * - `modify(path)`\n * - `init(path)`\n *\n * @api private\n */\n\nStateMachine.prototype._changeState = function _changeState (path, nextState) {\n var prevBucket = this.states[this.paths[path]];\n if (prevBucket) delete prevBucket[path];\n\n this.paths[path] = nextState;\n this.states[nextState][path] = true;\n}\n\n/*!\n * ignore\n */\n\nStateMachine.prototype.clear = function clear (state) {\n var keys = Object.keys(this.states[state])\n , i = keys.length\n , path\n\n while (i--) {\n path = keys[i];\n delete this.states[state][path];\n delete this.paths[path];\n }\n}\n\n/*!\n * Checks to see if at least one path is in the states passed in via `arguments`\n * e.g., this.some('required', 'inited')\n *\n * @param {String} state that we want to check for.\n * @private\n */\n\nStateMachine.prototype.some = function some () {\n var self = this;\n var what = arguments.length ? arguments : this.stateNames;\n return Array.prototype.some.call(what, function (state) {\n return Object.keys(self.states[state]).length;\n });\n}\n\n/*!\n * This function builds the functions that get assigned to `forEach` and `map`,\n * since both of those methods share a lot of the same logic.\n *\n * @param {String} iterMethod is either 'forEach' or 'map'\n * @return {Function}\n * @api private\n */\n\nStateMachine.prototype._iter = function _iter (iterMethod) {\n return function () {\n var numArgs = arguments.length\n , states = utils.args(arguments, 0, numArgs-1)\n , callback = arguments[numArgs-1];\n\n if (!states.length) states = this.stateNames;\n\n var self = this;\n\n var paths = states.reduce(function (paths, state) {\n return paths.concat(Object.keys(self.states[state]));\n }, []);\n\n return paths[iterMethod](function (path, i, paths) {\n return callback(path, i, paths);\n });\n };\n}\n\n/*!\n * Iterates over the paths that belong to one of the parameter states.\n *\n * The function profile can look like:\n * this.forEach(state1, fn); // iterates over all paths in state1\n * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2\n * this.forEach(fn); // iterates over all paths in all states\n *\n * @param {String} [state]\n * @param {String} [state]\n * @param {Function} callback\n * @private\n */\n\nStateMachine.prototype.forEach = function forEach () {\n this.forEach = this._iter('forEach');\n return this.forEach.apply(this, arguments);\n}\n\n/*!\n * Maps over the paths that belong to one of the parameter states.\n *\n * The function profile can look like:\n * this.forEach(state1, fn); // iterates over all paths in state1\n * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2\n * this.forEach(fn); // iterates over all paths in all states\n *\n * @param {String} [state]\n * @param {String} [state]\n * @param {Function} callback\n * @return {Array}\n * @private\n */\n\nStateMachine.prototype.map = function map () {\n this.map = this._iter('map');\n return this.map.apply(this, arguments);\n}\n\n\n});","sourceLength":4456,"scriptType":2,"compilationType":0,"context":{"ref":7},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/statemachine.js (lines: 181)"}],"refs":[{"handle":7,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":563,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[424]}}
{"seq":274,"request_seq":563,"type":"response","command":"scripts","success":true,"body":[{"handle":10,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/hooks/hooks.js","id":424,"lineOffset":0,"columnOffset":0,"lineCount":163,"source":"(function (exports, require, module, __filename, __dirname) { // TODO Add in pre and post skipping options\nmodule.exports = {\n /**\n * Declares a new hook to which you can add pres and posts\n * @param {String} name of the function\n * @param {Function} the method\n * @param {Function} the error handler callback\n */\n hook: function (name, fn, errorCb) {\n if (arguments.length === 1 && typeof name === 'object') {\n for (var k in name) { // `name` is a hash of hookName->hookFn\n this.hook(k, name[k]);\n }\n return;\n }\n\n var proto = this.prototype || this\n , pres = proto._pres = proto._pres || {}\n , posts = proto._posts = proto._posts || {};\n pres[name] = pres[name] || [];\n posts[name] = posts[name] || [];\n\n proto[name] = function () {\n var self = this\n , hookArgs // arguments eventually passed to the hook - are mutable\n , lastArg = arguments[arguments.length-1]\n , pres = this._pres[name]\n , posts = this._posts[name]\n , _total = pres.length\n , _current = -1\n , _asyncsLeft = proto[name].numAsyncPres\n , _next = function () {\n if (arguments[0] instanceof Error) {\n return handleError(arguments[0]);\n }\n var _args = Array.prototype.slice.call(arguments)\n , currPre\n , preArgs;\n if (_args.length && !(arguments[0] == null && typeof lastArg === 'function'))\n hookArgs = _args;\n if (++_current < _total) {\n currPre = pres[_current]\n if (currPre.isAsync && currPre.length < 2)\n throw new Error(\"Your pre must have next and done arguments -- e.g., function (next, done, ...)\");\n if (currPre.length < 1)\n throw new Error(\"Your pre must have a next argument -- e.g., function (next, ...)\");\n preArgs = (currPre.isAsync\n ? [once(_next), once(_asyncsDone)]\n : [once(_next)]).concat(hookArgs);\n return currPre.apply(self, preArgs);\n } else if (!proto[name].numAsyncPres) {\n return _done.apply(self, hookArgs);\n }\n }\n , _done = function () {\n var args_ = Array.prototype.slice.call(arguments)\n , ret, total_, current_, next_, done_, postArgs;\n if (_current === _total) {\n ret = fn.apply(self, args_);\n total_ = posts.length;\n current_ = -1;\n next_ = function () {\n if (arguments[0] instanceof Error) {\n return handleError(arguments[0]);\n }\n var args_ = Array.prototype.slice.call(arguments, 1)\n , currPost\n , postArgs;\n if (args_.length) hookArgs = args_;\n if (++current_ < total_) {\n currPost = posts[current_]\n if (currPost.length < 1)\n throw new Error(\"Your post must have a next argument -- e.g., function (next, ...)\");\n postArgs = [once(next_)].concat(hookArgs);\n return currPost.apply(self, postArgs);\n }\n };\n if (total_) return next_();\n return ret;\n }\n };\n if (_asyncsLeft) {\n function _asyncsDone (err) {\n if (err && err instanceof Error) {\n return handleError(err);\n }\n --_asyncsLeft || _done.apply(self, hookArgs);\n }\n }\n function handleError (err) {\n if ('function' == typeof lastArg)\n return lastArg(err);\n if (errorCb) return errorCb.call(self, err);\n throw err;\n }\n return _next.apply(this, arguments);\n };\n \n proto[name].numAsyncPres = 0;\n\n return this;\n },\n\n pre: function (name, isAsync, fn, errorCb) {\n if ('boolean' !== typeof arguments[1]) {\n errorCb = fn;\n fn = isAsync;\n isAsync = false;\n }\n var proto = this.prototype || this\n , pres = proto._pres = proto._pres || {};\n\n this._lazySetupHooks(proto, name, errorCb);\n\n if (fn.isAsync = isAsync) {\n proto[name].numAsyncPres++;\n }\n\n (pres[name] = pres[name] || []).push(fn);\n return this;\n },\n post: function (name, isAsync, fn) {\n if (arguments.length === 2) {\n fn = isAsync;\n isAsync = false;\n }\n var proto = this.prototype || this\n , posts = proto._posts = proto._posts || {};\n \n this._lazySetupHooks(proto, name);\n (posts[name] = posts[name] || []).push(fn);\n return this;\n },\n removePre: function (name, fnToRemove) {\n var proto = this.prototype || this\n , pres = proto._pres || (proto._pres || {});\n if (!pres[name]) return this;\n if (arguments.length === 1) {\n // Remove all pre callbacks for hook `name`\n pres[name].length = 0;\n } else {\n pres[name] = pres[name].filter( function (currFn) {\n return currFn !== fnToRemove;\n });\n }\n return this;\n },\n _lazySetupHooks: function (proto, methodName, errorCb) {\n if ('undefined' === typeof proto[methodName].numAsyncPres) {\n this.hook(methodName, proto[methodName], errorCb);\n }\n }\n};\n\nfunction once (fn, scope) {\n return function fnWrapper () {\n if (fnWrapper.hookCalled) return;\n fnWrapper.hookCalled = true;\n fn.apply(scope, arguments);\n };\n}\n\n});","sourceLength":5451,"scriptType":2,"compilationType":0,"context":{"ref":9},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/hooks/hooks.js (lines: 163)"}],"refs":[{"handle":9,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":564,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[427]}}
{"seq":275,"request_seq":564,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":565,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[430]}}
{"seq":276,"request_seq":565,"type":"response","command":"scripts","success":true,"body":[{"handle":12,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js","id":430,"lineOffset":0,"columnOffset":0,"lineCount":10,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar Binary = require('mongodb').BSONPure.Binary;\n\nmodule.exports = exports = Binary;\n\n});","sourceLength":185,"scriptType":2,"compilationType":0,"context":{"ref":11},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js (lines: 10)"}],"refs":[{"handle":11,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":566,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[433]}}
{"seq":277,"request_seq":566,"type":"response","command":"scripts","success":true,"body":[{"handle":14,"type":"script","id":433,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeUInt8.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":110,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":13},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":13,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":567,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[434]}}
{"seq":278,"request_seq":567,"type":"response","command":"scripts","success":true,"body":[{"handle":16,"type":"script","id":434,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeInt8.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":109,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":15},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":15,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":568,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[435]}}
{"seq":279,"request_seq":568,"type":"response","command":"scripts","success":true,"body":[{"handle":18,"type":"script","id":435,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.fill.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":104,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":17},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":17,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":569,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[436]}}
{"seq":280,"request_seq":569,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","id":436,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.utf8Write.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":109,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":0},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":570,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[437]}}
{"seq":284,"request_seq":570,"type":"response","command":"scripts","success":true,"body":[{"handle":6,"type":"script","id":437,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.binaryWrite.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":111,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":5},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":5,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":571,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[438]}}
{"seq":285,"request_seq":571,"type":"response","command":"scripts","success":true,"body":[{"handle":8,"type":"script","id":438,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.asciiWrite.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":110,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":7},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":7,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":572,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[439]}}
{"seq":286,"request_seq":572,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","id":439,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.set.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":103,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":0},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":573,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[440]}}
{"seq":297,"request_seq":573,"type":"response","command":"scripts","success":true,"body":[{"handle":6,"type":"script","id":440,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeUInt16LE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":113,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":5},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":5,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":574,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[441]}}
{"seq":298,"request_seq":574,"type":"response","command":"scripts","success":true,"body":[{"handle":8,"type":"script","id":441,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeUInt16BE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":113,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":7},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":7,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":575,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[442]}}
{"seq":299,"request_seq":575,"type":"response","command":"scripts","success":true,"body":[{"handle":10,"type":"script","id":442,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeUInt32LE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":113,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":9},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":9,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":576,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[443]}}
{"seq":300,"request_seq":576,"type":"response","command":"scripts","success":true,"body":[{"handle":12,"type":"script","id":443,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeUInt32BE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":113,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":11},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":11,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":577,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[444]}}
{"seq":301,"request_seq":577,"type":"response","command":"scripts","success":true,"body":[{"handle":14,"type":"script","id":444,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeInt16LE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":112,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":13},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":13,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":578,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[445]}}
{"seq":302,"request_seq":578,"type":"response","command":"scripts","success":true,"body":[{"handle":16,"type":"script","id":445,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeInt16BE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":112,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":15},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":15,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":579,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[446]}}
{"seq":303,"request_seq":579,"type":"response","command":"scripts","success":true,"body":[{"handle":18,"type":"script","id":446,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeInt32LE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":112,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":17},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":17,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":580,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[447]}}
{"seq":304,"request_seq":580,"type":"response","command":"scripts","success":true,"body":[{"handle":20,"type":"script","id":447,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeInt32BE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":112,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":19},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":19,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":581,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[448]}}
{"seq":305,"request_seq":581,"type":"response","command":"scripts","success":true,"body":[{"handle":22,"type":"script","id":448,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeFloatLE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":112,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":21},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":21,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":582,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[449]}}
{"seq":306,"request_seq":582,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","id":449,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeFloatBE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":112,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":0},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":583,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[450]}}
{"seq":310,"request_seq":583,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","id":450,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeDoubleLE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":113,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":0},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":584,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[451]}}
{"seq":311,"request_seq":584,"type":"response","command":"scripts","success":true,"body":[{"handle":6,"type":"script","id":451,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function() {\nvar ret = Buffer.prototype.writeDoubleBE.apply(this, arguments);this._markModified();return ret;\n})","sourceLength":113,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":3},"evalFromLocation":{"line":148,"column":37},"evalFromFunctionName":{"type_":"string","value_":"","handle_":4},"context":{"ref":5},"text":"undefined (lines: 3)"}],"refs":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js","id":427,"lineOffset":0,"columnOffset":0,"lineCount":212,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Access driver.\n */\n\nvar driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native';\n\n/*!\n * Module dependencies.\n */\n\nvar Binary = require(driver + '/binary');\n\n/**\n * Mongoose Buffer constructor.\n *\n * Values always have to be passed to the constructor to initialize.\n *\n * @param {Buffer} value\n * @param {String} encode\n * @param {Number} offset\n * @api private\n * @inherits Buffer\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseBuffer (value, encode, offset) {\n var length = arguments.length;\n var val;\n\n if (0 === length || null === arguments[0] || undefined === arguments[0]) {\n val = 0;\n } else {\n val = value;\n }\n\n var encoding;\n var path;\n var doc;\n\n if (Array.isArray(encode)) {\n // internal casting\n path = encode[0];\n doc = encode[1];\n } else {\n encoding = encode;\n }\n\n var buf = new Buffer(val, encoding, offset);\n buf.__proto__ = MongooseBuffer.prototype;\n\n // make sure these internal props don't show up in Object.keys()\n Object.defineProperties(buf, {\n validators: { value: [] }\n , _path: { value: path }\n , _parent: { value: doc }\n });\n\n if (doc && \"string\" === typeof path) {\n Object.defineProperty(buf, '_schema', {\n value: doc.schema.path(path)\n });\n }\n\n return buf;\n};\n\n/*!\n * Inherit from Buffer.\n */\n\nMongooseBuffer.prototype = new Buffer(0);\n\n/**\n * Parent owner document\n *\n * @api private\n * @property _parent\n */\n\nMongooseBuffer.prototype._parent;\n\n/**\n * Marks this buffer as modified.\n *\n * @api private\n */\n\nMongooseBuffer.prototype._markModified = function () {\n var parent = this._parent;\n\n if (parent) {\n parent.markModified(this._path);\n }\n return this;\n};\n\n/**\n* Writes the buffer.\n*/\n\nMongooseBuffer.prototype.write = function () {\n var written = Buffer.prototype.write.apply(this, arguments);\n\n if (written > 0) {\n this._markModified();\n }\n\n return written;\n};\n\n/**\n * Copies the buffer.\n *\n * ####Note:\n *\n * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.\n *\n * @return {MongooseBuffer}\n * @param {Buffer} target\n */\n\nMongooseBuffer.prototype.copy = function (target) {\n var ret = Buffer.prototype.copy.apply(this, arguments);\n\n if (target instanceof MongooseBuffer) {\n target._markModified();\n }\n\n return ret;\n};\n\n/*!\n * Compile other Buffer methods marking this buffer as modified.\n */\n\n;(\n// node < 0.5\n'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' +\n'writeFloat writeDouble fill ' +\n'utf8Write binaryWrite asciiWrite set ' +\n\n// node >= 0.5\n'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' +\n'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' +\n'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE'\n).split(' ').forEach(function (method) {\n if (!Buffer.prototype[method]) return;\n MongooseBuffer.prototype[method] = new Function(\n 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' +\n 'this._markModified();' +\n 'return ret;'\n )\n});\n\n/**\n * Converts this buffer to its Binary type representation.\n *\n * ####SubTypes:\n *\n * - 0x00: Binary/Generic\n * - 0x01: Function\n * - 0x02: Binary (Deprecated, 0x00 is new default)\n * - 0x03: UUID\n * - 0x04: MD5\n * - 0x80: User Defined\n *\n * @see http://bsonspec.org/#/specification\n * @param {Hex} [subtype]\n * @return {Binary}\n * @api public\n */\n\nMongooseBuffer.prototype.toObject = function (options) {\n var subtype = 'number' == typeof options\n ? options\n : 0x00;\n return new Binary(this, subtype);\n};\n\n/**\n * Determines if this buffer is equals to `other` buffer\n *\n * @param {Buffer} other\n * @return {Boolean}\n */\n\nMongooseBuffer.prototype.equals = function (other) {\n if (!Buffer.isBuffer(other)) {\n return false;\n }\n\n if (this.length !== other.length) {\n return false;\n }\n\n for (var i = 0; i < this.length; ++i) {\n if (this[i] !== other[i]) return false;\n }\n\n return true;\n}\n\n/*!\n * Module exports.\n */\n\nMongooseBuffer.Binary = Binary;\n\nmodule.exports = MongooseBuffer;\n\n});","sourceLength":4171,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/buffer.js (lines: 212)"},{"handle":5,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":585,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[452]}}
{"seq":312,"request_seq":585,"type":"response","command":"scripts","success":true,"body":[{"handle":8,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/documentarray.js","id":452,"lineOffset":0,"columnOffset":0,"lineCount":189,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar MongooseArray = require('./array')\n , driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native'\n , ObjectId = require(driver + '/objectid')\n , ObjectIdSchema = require('../schema/objectid')\n , utils = require('../utils')\n , util = require('util')\n\n/**\n * DocumentArray constructor\n *\n * @param {Array} values\n * @param {String} path the path to this array\n * @param {Document} doc parent document\n * @api private\n * @return {MongooseDocumentArray}\n * @inherits MongooseArray\n * @see http://bit.ly/f6CnZU\n */\n\nfunction MongooseDocumentArray (values, path, doc) {\n var arr = [];\n\n // Values always have to be passed to the constructor to initialize, since\n // otherwise MongooseArray#push will mark the array as modified to the parent.\n arr.push.apply(arr, values);\n arr.__proto__ = MongooseDocumentArray.prototype;\n\n arr._atomics = {};\n arr.validators = [];\n arr._path = path;\n\n if (doc) {\n arr._parent = doc;\n arr._schema = doc.schema.path(path);\n doc.on('save', arr.notify('save'));\n doc.on('isNew', arr.notify('isNew'));\n }\n\n return arr;\n};\n\n/*!\n * Inherits from MongooseArray\n */\n\nMongooseDocumentArray.prototype.__proto__ = MongooseArray.prototype;\n\n/**\n * Overrides MongooseArray#cast\n *\n * @api private\n */\n\nMongooseDocumentArray.prototype._cast = function (value) {\n if (value instanceof this._schema.casterConstructor) {\n if (!(value.__parent && value.__parentArray)) {\n // value may have been created using array.create()\n value.__parent = this._parent;\n value.__parentArray = this;\n }\n return value;\n }\n\n // handle cast('string') or cast(ObjectId) etc.\n // only objects are permitted so we can safely assume that\n // non-objects are to be interpreted as _id\n if (Buffer.isBuffer(value) ||\n value instanceof ObjectId || !utils.isObject(value)) {\n value = { _id: value };\n }\n\n return new this._schema.casterConstructor(value, this);\n};\n\n/**\n * Searches array items for the first document with a matching _id.\n *\n * ####Example:\n *\n * var embeddedDoc = m.array.id(some_id);\n *\n * @return {EmbeddedDocument|null} the subdocuent or null if not found.\n * @param {ObjectId|String|Number|Buffer} id\n * @api public\n */\n\nMongooseDocumentArray.prototype.id = function (id) {\n var casted\n , _id;\n\n try {\n casted = ObjectId.toString(ObjectIdSchema.prototype.cast.call({}, id));\n } catch (e) {\n casted = null;\n }\n\n for (var i = 0, l = this.length; i < l; i++) {\n _id = this[i].get('_id');\n if (!(_id instanceof ObjectId)) {\n if (String(id) == _id)\n return this[i];\n } else {\n if (casted == _id)\n return this[i];\n }\n }\n\n return null;\n};\n\n/**\n * Returns a native js Array of plain js objects\n *\n * ####NOTE:\n *\n * _Each sub-document is converted to a plain object by calling its `#toObject` method._\n *\n * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion\n * @return {Array}\n * @api public\n */\n\nMongooseDocumentArray.prototype.toObject = function (options) {\n return this.map(function (doc) {\n return doc && doc.toObject(options) || null;\n });\n};\n\n/**\n * Helper for console.log\n *\n * @api public\n */\n\nMongooseDocumentArray.prototype.inspect = function () {\n return '[' + this.map(function (doc) {\n if (doc) {\n return doc.inspect\n ? doc.inspect()\n : util.inspect(doc)\n }\n return 'null'\n }).join('\\n') + ']';\n};\n\n/**\n * Creates a subdocument casted to this schema.\n *\n * This is the same subdocument constructor used for casting.\n *\n * @param {Object} obj the value to cast to this arrays SubDocument schema\n * @api public\n */\n\nMongooseDocumentArray.prototype.create = function (obj) {\n return new this._schema.casterConstructor(obj);\n}\n\n/**\n * Creates a fn that notifies all child docs of `event`.\n *\n * @param {String} event\n * @return {Function}\n * @api private\n */\n\nMongooseDocumentArray.prototype.notify = function notify (event) {\n var self = this;\n return function notify (val) {\n var i = self.length;\n while (i--) {\n if (!self[i]) continue;\n self[i].emit(event, val);\n }\n }\n}\n\n/*!\n * Module exports.\n */\n\nmodule.exports = MongooseDocumentArray;\n\n});","sourceLength":4306,"scriptType":2,"compilationType":0,"context":{"ref":7},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/types/documentarray.js (lines: 189)"}],"refs":[{"handle":7,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":586,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[455]}}
{"seq":315,"request_seq":586,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/query.js","id":455,"lineOffset":0,"columnOffset":0,"lineCount":2592,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar utils = require('./utils')\n , merge = utils.merge\n , Promise = require('./promise')\n , Document = require('./document')\n , Types = require('./schema/index')\n , inGroupsOf = utils.inGroupsOf\n , tick = utils.tick\n , QueryStream = require('./querystream')\n , helpers = require('./queryhelpers')\n , ReadPref = require('mongodb').ReadPreference\n\n/**\n * Query constructor used for building queries.\n *\n * ####Example:\n *\n * var query = Model.find();\n * query.where('age').gte(21).exec(callback);\n *\n * @param {Object} criteria\n * @param {Object} options\n * @api public\n */\n\nfunction Query (criteria, options) {\n this.setOptions(options, true);\n this._conditions = {};\n this._updateArg = {};\n this._fields = undefined;\n this._geoComparison = undefined;\n if (criteria) this.find(criteria);\n}\n\n/**\n * Sets query options.\n *\n * ####Options:\n *\n * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) *\n * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\\)%7D%7D) *\n * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) *\n * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) *\n * - [maxscan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) *\n * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) *\n * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) *\n * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) *\n * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) *\n * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) *\n * - [lean](./api.html#query_Query-lean) *\n * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command)\n *\n * _* denotes a query helper method is also available_\n *\n * @param {Object} options\n * @api public\n */\n\nQuery.prototype.setOptions = function (options, overwrite) {\n // overwrite is internal use only\n if (overwrite) {\n options = this.options = options || {};\n this.safe = options.safe;\n if ('populate' in options) {\n this.populate(this.options.populate);\n }\n return this;\n }\n\n if (!(options && 'Object' == options.constructor.name))\n return this;\n\n if ('safe' in options)\n this.safe = options.safe;\n\n // set arbitrary options\n var methods = Object.keys(options)\n , i = methods.length\n , method\n\n while (i--) {\n method = methods[i];\n\n // use methods if exist (safer option manipulation)\n if ('function' == typeof this[method]) {\n var args = Array.isArray(options[method])\n ? options[method]\n : [options[method]];\n this[method].apply(this, args)\n } else {\n this.options[method] = options[method];\n }\n }\n\n return this;\n}\n\n/**\n * Binds this query to a model.\n *\n * @param {Model} model the model to which the query is bound\n * @param {String} op the operation to execute\n * @param {Object} updateArg used in update methods\n * @return {Query}\n * @api private\n */\n\nQuery.prototype.bind = function bind (model, op, updateArg) {\n this.model = model;\n this.op = op;\n\n if (model._mapreduce) this.options.lean = true;\n\n if (op == 'update' || op == 'findOneAndUpdate') {\n merge(this._updateArg, updateArg || {});\n }\n\n return this;\n};\n\n/**\n * Executes the query\n *\n * ####Examples\n *\n * query.exec();\n * query.exec(callback);\n * query.exec('update');\n * query.exec('find', callback);\n *\n * @param {String|Function} [operation]\n * @param {Function} [callback]\n * @return {Promise}\n * @api public\n */\n\nQuery.prototype.exec = function exec (op, callback) {\n var promise = new Promise();\n\n switch (typeof op) {\n case 'function':\n callback = op;\n op = null;\n break;\n case 'string':\n this.op = op;\n break;\n }\n\n if (callback) promise.addBack(callback);\n\n if (!this.op) {\n promise.complete();\n return promise;\n }\n\n if ('update' == this.op) {\n this[this.op](this._updateArg, promise.resolve.bind(promise));\n return promise;\n }\n\n if ('distinct' == this.op) {\n this.distinct(this._distinctArg, promise.resolve.bind(promise));\n return promise;\n }\n\n this[this.op](promise.resolve.bind(promise));\n return promise;\n};\n\n/**\n * Finds documents.\n *\n * When no `callback` is passed, the query is not executed.\n *\n * ####Example\n *\n * query.find({ name: 'Los Pollos Hermanos' }).find(callback)\n *\n * @param {Object} [criteria] mongodb selector\n * @param {Function} [callback]\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.find = function (criteria, callback) {\n this.op = 'find';\n if ('function' === typeof criteria) {\n callback = criteria;\n criteria = {};\n } else if (criteria instanceof Query) {\n // TODO Merge options, too\n merge(this._conditions, criteria._conditions);\n } else if (criteria instanceof Document) {\n merge(this._conditions, criteria.toObject());\n } else if (criteria && 'Object' === criteria.constructor.name) {\n merge(this._conditions, criteria);\n }\n if (!callback) return this;\n return this.execFind(callback);\n};\n\n/**\n * Casts this query to the schema of `model`\n *\n * ####Note\n *\n * If `obj` is present, it is cast instead of this query.\n *\n * @param {Model} model\n * @param {Object} [obj]\n * @return {Object}\n * @api public\n */\n\nQuery.prototype.cast = function (model, obj) {\n obj || (obj= this._conditions);\n\n var schema = model.schema\n , paths = Object.keys(obj)\n , i = paths.length\n , any$conditionals\n , schematype\n , nested\n , path\n , type\n , val;\n\n while (i--) {\n path = paths[i];\n val = obj[path];\n\n if ('$or' === path || '$nor' === path || '$and' === path) {\n var k = val.length\n , orComponentQuery;\n\n while (k--) {\n orComponentQuery = new Query(val[k]);\n orComponentQuery.cast(model);\n val[k] = orComponentQuery._conditions;\n }\n\n } else if (path === '$where') {\n type = typeof val;\n\n if ('string' !== type && 'function' !== type) {\n throw new Error(\"Must have a string or function for $where\");\n }\n\n if ('function' === type) {\n obj[path] = val.toString();\n }\n\n continue;\n\n } else {\n\n if (!schema) {\n // no casting for Mixed types\n continue;\n }\n\n schematype = schema.path(path);\n\n if (!schematype) {\n // Handle potential embedded array queries\n var split = path.split('.')\n , j = split.length\n , pathFirstHalf\n , pathLastHalf\n , remainingConds\n , castingQuery;\n\n // Find the part of the var path that is a path of the Schema\n while (j--) {\n pathFirstHalf = split.slice(0, j).join('.');\n schematype = schema.path(pathFirstHalf);\n if (schematype) break;\n }\n\n // If a substring of the input path resolves to an actual real path...\n if (schematype) {\n // Apply the casting; similar code for $elemMatch in schema/array.js\n if (schematype.caster && schematype.caster.schema) {\n remainingConds = {};\n pathLastHalf = split.slice(j).join('.');\n remainingConds[pathLastHalf] = val;\n castingQuery = new Query(remainingConds);\n castingQuery.cast(schematype.caster);\n obj[path] = castingQuery._conditions[pathLastHalf];\n } else {\n obj[path] = val;\n }\n continue;\n }\n\n if (utils.isObject(val)) {\n // handle geo schemas that use object notation\n // { loc: { long: Number, lat: Number }\n\n var geo = val.$near ? '$near' :\n val.$nearSphere ? '$nearSphere' :\n val.$within ? '$within' :\n val.$geoIntersects ? '$geoIntersects' : '';\n\n if (!geo) {\n continue;\n }\n\n var numbertype = new Types.Number('__QueryCasting__')\n var value = val[geo];\n\n if (val.$maxDistance) {\n val.$maxDistance = numbertype.castForQuery(val.$maxDistance);\n }\n\n if ('$within' == geo) {\n var withinType = value.$center\n || value.$centerSphere\n || value.$box\n || value.$polygon;\n\n if (!withinType) {\n throw new Error('Bad $within paramater: ' + JSON.stringify(val));\n }\n\n value = withinType;\n\n } else if ('$near' == geo &&\n 'string' == typeof value.type && Array.isArray(value.coordinates)) {\n // geojson; cast the coordinates\n value = value.coordinates;\n\n } else if (('$near' == geo || '$geoIntersects' == geo) &&\n value.$geometry && 'string' == typeof value.$geometry.type &&\n Array.isArray(value.$geometry.coordinates)) {\n // geojson; cast the coordinates\n value = value.$geometry.coordinates;\n }\n\n ;(function _cast (val) {\n if (Array.isArray(val)) {\n val.forEach(function (item, i) {\n if (Array.isArray(item) || utils.isObject(item)) {\n return _cast(item);\n }\n val[i] = numbertype.castForQuery(item);\n });\n } else {\n var nearKeys= Object.keys(val);\n var nearLen = nearKeys.length;\n while (nearLen--) {\n var nkey = nearKeys[nearLen];\n var item = val[nkey];\n if (Array.isArray(item) || utils.isObject(item)) {\n _cast(item);\n val[nkey] = item;\n } else {\n val[nkey] = numbertype.castForQuery(item);\n }\n }\n }\n })(value);\n }\n\n } else if (val === null || val === undefined) {\n continue;\n } else if ('Object' === val.constructor.name) {\n\n any$conditionals = Object.keys(val).some(function (k) {\n return k.charAt(0) === '$' && k !== '$id' && k !== '$ref';\n });\n\n if (!any$conditionals) {\n obj[path] = schematype.castForQuery(val);\n } else {\n\n var ks = Object.keys(val)\n , k = ks.length\n , $cond;\n\n while (k--) {\n $cond = ks[k];\n nested = val[$cond];\n\n if ('$exists' === $cond) {\n if ('boolean' !== typeof nested) {\n throw new Error(\"$exists parameter must be Boolean\");\n }\n continue;\n }\n\n if ('$type' === $cond) {\n if ('number' !== typeof nested) {\n throw new Error(\"$type parameter must be Number\");\n }\n continue;\n }\n\n if ('$not' === $cond) {\n this.cast(model, nested);\n } else {\n val[$cond] = schematype.castForQuery($cond, nested);\n }\n }\n }\n } else {\n obj[path] = schematype.castForQuery(val);\n }\n }\n }\n\n return obj;\n};\n\n/**\n * Returns default options.\n * @param {Model} model\n * @api private\n */\n\nQuery.prototype._optionsForExec = function (model) {\n var options = utils.clone(this.options, { retainKeyOrder: true });\n delete options.populate;\n\n if (!('safe' in options))\n options.safe = model.schema.options.safe;\n\n if (!('readPreference' in options) && model.schema.options.read)\n options.readPreference = model.schema.options.read;\n\n return options;\n};\n\n/**\n * Applies schematype selected options to this query.\n * @api private\n */\n\nQuery.prototype._applyPaths = function applyPaths () {\n // determine if query is selecting or excluding fields\n\n var fields = this._fields\n , exclude\n , keys\n , ki\n\n if (fields) {\n keys = Object.keys(fields);\n ki = keys.length;\n\n while (ki--) {\n if ('+' == keys[ki][0]) continue;\n exclude = 0 === fields[keys[ki]];\n break;\n }\n }\n\n // if selecting, apply default schematype select:true fields\n // if excluding, apply schematype select:false fields\n\n var selected = []\n , excluded = []\n , seen = [];\n\n analyzeSchema(this.model.schema);\n\n switch (exclude) {\n case true:\n excluded.length && this.select('-' + excluded.join(' -'));\n break;\n case false:\n selected.length && this.select(selected.join(' '));\n break;\n case undefined:\n // user didn't specify fields, implies returning all fields.\n // only need to apply excluded fields\n excluded.length && this.select('-' + excluded.join(' -'));\n break;\n }\n\n return seen = excluded = selected = keys = fields = null;\n\n function analyzeSchema (schema, prefix) {\n prefix || (prefix = '');\n\n // avoid recursion\n if (~seen.indexOf(schema)) return;\n seen.push(schema);\n\n schema.eachPath(function (path, type) {\n if (prefix) path = prefix + '.' + path;\n\n analyzePath(path, type);\n\n // array of subdocs?\n if (type.schema) {\n analyzeSchema(type.schema, path);\n }\n\n });\n }\n\n function analyzePath (path, type) {\n if ('boolean' != typeof type.selected) return;\n\n var plusPath = '+' + path;\n if (fields && plusPath in fields) {\n // forced inclusion\n delete fields[plusPath];\n\n // if there are other fields being included, add this one\n // if no other included fields, leave this out (implied inclusion)\n if (false === exclude && keys.length > 1 && !~keys.indexOf(path)) {\n fields[path] = 1;\n }\n\n return\n };\n\n // check for parent exclusions\n var root = path.split('.')[0];\n if (~excluded.indexOf(root)) return;\n\n ;(type.selected ? selected : excluded).push(path);\n }\n}\n\n/**\n * Specifies a javascript function or expression to pass to MongoDBs query system.\n *\n * ####Example\n *\n * query.$where('this.comments.length > 10 || this.name.length > 5')\n *\n * // or\n *\n * query.$where(function () {\n * return this.comments.length > 10 || this.name.length > 5;\n * })\n *\n * ####NOTE:\n *\n * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`.\n * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.**\n *\n * @see $where http://docs.mongodb.org/manual/reference/operator/where/\n * @param {String|Function} js javascript string or function\n * @return {Query} this\n * @memberOf Query\n * @method $where\n * @api public\n */\n\nQuery.prototype.$where = function (js) {\n this._conditions['$where'] = js;\n return this;\n};\n\n/**\n * Specifies a `path` for use with chaining.\n *\n * ####Example\n *\n * // instead of writing:\n * User.find({age: {$gte: 21, $lte: 65}}, callback);\n *\n * // we can instead write:\n * User.where('age').gte(21).lte(65);\n *\n * // Moreover, you can also chain a bunch of these together:\n *\n * User\n * .where('age').gte(21).lte(65)\n * .where('name', /^b/i)\n * .where('friends').slice(10)\n * .exec(callback)\n *\n * @param {String} [path]\n * @param {Object} [val]\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.where = function (path, val) {\n if (!arguments.length) return this;\n\n if ('string' != typeof path) {\n throw new TypeError('path must be a string');\n }\n\n this._currPath = path;\n\n if (2 === arguments.length) {\n this._conditions[path] = val;\n }\n\n return this;\n};\n\n/**\n * Specifies the complementary comparison value for paths specified with `where()`\n *\n * ####Example\n *\n * User.where('age').equals(49);\n *\n * // is the same as\n *\n * User.where('age', 49);\n *\n * @param {Object} val\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.equals = function equals (val) {\n var path = this._currPath;\n if (!path) throw new Error('equals() must be used after where()');\n this._conditions[path] = val;\n return this;\n}\n\n/**\n * Specifies arguments for an `$or` condition.\n *\n * ####Example\n *\n * query.or([{ color: 'red' }, { status: 'emergency' }])\n *\n * @see $or http://docs.mongodb.org/manual/reference/operator/or/\n * @param {Array} array array of conditions\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.or = function or (array) {\n var or = this._conditions.$or || (this._conditions.$or = []);\n if (!Array.isArray(array)) array = [array];\n or.push.apply(or, array);\n return this;\n}\n\n/**\n * Specifies arguments for a `$nor` condition.\n *\n * ####Example\n *\n * query.nor([{ color: 'green' }, { status: 'ok' }])\n *\n * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/\n * @param {Array} array array of conditions\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.nor = function nor (array) {\n var nor = this._conditions.$nor || (this._conditions.$nor = []);\n if (!Array.isArray(array)) array = [array];\n nor.push.apply(nor, array);\n return this;\n}\n\n/**\n * Specifies arguments for a `$and` condition.\n *\n * ####Example\n *\n * query.and([{ color: 'green' }, { status: 'ok' }])\n *\n * @see $and http://docs.mongodb.org/manual/reference/operator/and/\n * @param {Array} array array of conditions\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.and = function and (array) {\n var and = this._conditions.$and || (this._conditions.$and = []);\n if (!Array.isArray(array)) array = [array];\n and.push.apply(and, array);\n return this;\n}\n\n/**\n * Specifies a $gt query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * ####Example\n *\n * Thing.find().where('age').gt(21)\n *\n * // or\n * Thing.find().gt('age', 21)\n *\n * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/\n * @method gt\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies a $gte query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/\n * @method gte\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies a $lt query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/\n * @method lt\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies a $lte query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/\n * @method lte\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies a $ne query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/\n * @method ne\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies an $in query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $in http://docs.mongodb.org/manual/reference/operator/in/\n * @method in\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies an $nin query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/\n * @method nin\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies an $all query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $all http://docs.mongodb.org/manual/reference/operator/all/\n * @method all\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies an $size query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $size http://docs.mongodb.org/manual/reference/operator/size/\n * @method size\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies a $regex query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/\n * @method regex\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/**\n * Specifies a $maxDistance query condition.\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/\n * @method maxDistance\n * @memberOf Query\n * @param {String} path\n * @param {Number} val\n * @api public\n */\n\n/*!\n * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance\n *\n * Thing.where('type').nin(array)\n */\n\n'gt gte lt lte ne in nin all regex size maxDistance'.split(' ').forEach(function ($conditional) {\n Query.prototype[$conditional] = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds['$' + $conditional] = val;\n return this;\n };\n});\n\n/**\n * Specifies a `$near` condition\n *\n * @param {String} path\n * @param {Number} val\n * @return {Query} this\n * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing\n * @see $near http://docs.mongodb.org/manual/reference/operator/near/\n * @api public\n */\n\nQuery.prototype.near = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath\n } else if (arguments.length === 2 && !Array.isArray(val)) {\n val = utils.args(arguments);\n path = this._currPath;\n } else if (arguments.length === 3) {\n val = utils.args(arguments, 1);\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$near = val;\n return this;\n}\n\n/**\n * Specifies a `$nearSphere` condition.\n *\n * @param {String} path\n * @param {Object} val\n * @return {Query} this\n * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing\n * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/\n * @api public\n */\n\nQuery.prototype.nearSphere = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath\n } else if (arguments.length === 2 && !Array.isArray(val)) {\n val = utils.args(arguments);\n path = this._currPath;\n } else if (arguments.length === 3) {\n val = utils.args(arguments, 1);\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$nearSphere = val;\n return this;\n}\n\n/**\n * Specifies a `$mod` condition\n *\n * @param {String} path\n * @param {Number} val\n * @return {Query} this\n * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/\n * @api public\n */\n\nQuery.prototype.mod = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath\n } else if (arguments.length === 2 && !Array.isArray(val)) {\n val = utils.args(arguments);\n path = this._currPath;\n } else if (arguments.length === 3) {\n val = utils.args(arguments, 1);\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds.$mod = val;\n return this;\n}\n\n/**\n * Specifies an `$exists` condition\n *\n * @param {String} path\n * @param {Number} val\n * @return {Query} this\n * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/\n * @api public\n */\n\nQuery.prototype.exists = function (path, val) {\n if (arguments.length === 0) {\n path = this._currPath\n val = true;\n } else if (arguments.length === 1) {\n if ('boolean' === typeof path) {\n val = path;\n path = this._currPath;\n } else {\n val = true;\n }\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds['$exists'] = val;\n return this;\n};\n\n/**\n * Specifies an `$elemMatch` condition\n *\n * ####Example\n *\n * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})\n *\n * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})\n *\n * query.elemMatch('comment', function (elem) {\n * elem.where('author').equals('autobot');\n * elem.where('votes').gte(5);\n * })\n *\n * query.where('comment').elemMatch(function (elem) {\n * elem.where('author').equals('autobot');\n * elem.where('votes').gte(5);\n * })\n *\n * @param {String|Object|Function} path\n * @param {Object|Function} criteria\n * @return {Query} this\n * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/\n * @api public\n */\n\nQuery.prototype.elemMatch = function (path, criteria) {\n var block;\n if ('Object' === path.constructor.name) {\n criteria = path;\n path = this._currPath;\n } else if ('function' === typeof path) {\n block = path;\n path = this._currPath;\n } else if ('Object' === criteria.constructor.name) {\n } else if ('function' === typeof criteria) {\n block = criteria;\n } else {\n throw new Error(\"Argument error\");\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n if (block) {\n criteria = new Query();\n block(criteria);\n conds['$elemMatch'] = criteria._conditions;\n } else {\n conds['$elemMatch'] = criteria;\n }\n return this;\n};\n\n// Spatial queries\n\n/**\n * Defines a $within query for `box()`, `center()`, etc\n *\n * ####Example\n *\n * query.within.box()\n * query.within.center()\n * query.within.geometry()\n *\n * @property within\n * @memberOf Query\n * @see Query#box #query_Query-box\n * @see Query#center #query_Query-center\n * @see Query#centerSphere #query_Query-centerSphere\n * @see Query#polygon #query_Query-polygon\n * @see Query#geometry #query_Query-geometry\n * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/within/\n * @return {Query} this\n * @api public\n */\n\nObject.defineProperty(Query.prototype, 'within', {\n get: function () {\n this._geoComparison = '$within';\n return this\n }\n});\n\n/**\n * Declares an intersects query for `geometry()`.\n *\n * ####Example\n *\n * query.intersects.geometry({\n * type: 'LineString'\n * , coordinates: [[180.0, 11.0], [180, 9.0]]\n * })\n *\n * @property intersects\n * @see Query#geometry #query_Query-geometry\n * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/\n * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/\n * @memberOf Query\n * @return {Query} this\n * @api public\n */\n\nObject.defineProperty(Query.prototype, 'intersects', {\n get: function () {\n this._geoComparison = '$geoIntersects';\n return this\n }\n});\n\n/**\n * Specifies a $box condition\n *\n * ####Example\n *\n * var lowerLeft = [40.73083, -73.99756]\n * var upperRight= [40.741404, -73.988135]\n * query.where('loc').within.box({ ll: lowerLeft , ur: upperRight })\n *\n * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing\n * @see Query#within #query_Query-within\n * @see $box http://docs.mongodb.org/manual/reference/operator/box/\n * @param {String} path\n * @param {Object} val\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.box = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath;\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds['$within'] = { '$box': [val.ll, val.ur] };\n return this;\n};\n\n/**\n * Specifies a $center condition\n *\n * ####Example\n *\n * var area = { center: [50, 50], radius: 10 }\n * query.where('loc').within.center(area)\n *\n * @param {String} path\n * @param {Object} val\n * @param {Object} [opts] options e.g. { $uniqueDocs: true }\n * @return {Query} this\n * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing\n * @see $center http://docs.mongodb.org/manual/reference/operator/center/\n * @api public\n */\n\nQuery.prototype.center = function (path, val, opts) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath;\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds['$within'] = { '$center': [val.center, val.radius] };\n\n // copy any options\n if (opts && 'Object' == opts.constructor.name) {\n utils.options(opts, conds.$within);\n }\n\n return this;\n};\n\n/**\n * Specifies a $centerSphere condition\n *\n * ####Example\n *\n * var area = { center: [50, 50], radius: 10 }\n * query.where('loc').within.centerSphere(area)\n *\n * @param {String} [path]\n * @param {Object} val\n * @return {Query} this\n * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing\n * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/\n * @api public\n */\n\nQuery.prototype.centerSphere = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath;\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds['$within'] = { '$centerSphere': [val.center, val.radius] };\n return this;\n};\n\n/**\n * Specifies a $polygon condition\n *\n * ####Example\n *\n * var polyA = [ [ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ] ]\n * query.where('loc').within.polygon(polyA)\n *\n * // or\n * var polyB = { a : { x : 10, y : 20 }, b : { x : 15, y : 25 }, c : { x : 20, y : 20 } }\n * query.where('loc').within.polygon(polyB)\n *\n * @param {String} [path]\n * @param {Array|Object} val\n * @return {Query} this\n * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing\n * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/\n * @api public\n */\n\nQuery.prototype.polygon = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath;\n }\n var conds = this._conditions[path] || (this._conditions[path] = {});\n conds['$within'] = { '$polygon': val };\n return this;\n};\n\n/**\n * Specifies a $geometry condition\n *\n * ####Example\n *\n * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]\n * query.where('loc').within.geometry({ type: 'Polygon', coordinates: polyA })\n *\n * // or\n * var polyB = [[ 0, 0 ], [ 1, 1 ]]\n * query.where('loc').within.geometry({ type: 'LineString', coordinates: polyB })\n *\n * // or\n * var polyC = [ 0, 0 ]\n * query.where('loc').within.geometry({ type: 'Point', coordinates: polyC })\n *\n * // or\n * var polyC = [ 0, 0 ]\n * query.where('loc').intersects.geometry({ type: 'Point', coordinates: polyC })\n *\n * ####NOTE:\n *\n * `geometry()` **must** come after either `intersects` or `within`.\n *\n * The `object` argument must contain `type` and `coordinates` properties.\n * - type {String}\n * - coordinates {Array}\n *\n * When called with one argument, the most recent path passed to `where()` is used.\n *\n * @param {String} [path] Optional name of a path to match against\n * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the example.\n * @return {Query} this\n * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry\n * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing\n * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/\n * @api public\n */\n\nQuery.prototype.geometry = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath;\n }\n\n var conds = this._conditions[path] || (this._conditions[path] = {});\n\n if (!this._geoComparison) {\n throw new Error('query.geometry() must come after either `within` or `intersects`');\n }\n\n conds[this._geoComparison] = { $geometry: val };\n return this;\n};\n\n/**\n * Specifies which document fields to include or exclude\n *\n * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select).\n *\n * ####Example\n *\n * // include a and b, exclude c\n * query.select('a b -c');\n *\n * // or you may use object notation, useful when\n * // you have keys already prefixed with a \"-\"\n * query.select({a: 1, b: 1, c: 0});\n *\n * // force inclusion of field excluded at schema level\n * query.select('+path')\n *\n * ####NOTE:\n *\n * _v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3._\n *\n * @param {Object|String} arg\n * @return {Query} this\n * @see SchemaType\n * @api public\n */\n\nQuery.prototype.select = function select (arg) {\n if (!arg) return this;\n\n var fields = this._fields || (this._fields = {});\n\n if ('Object' === arg.constructor.name) {\n Object.keys(arg).forEach(function (field) {\n fields[field] = arg[field];\n });\n } else if (1 === arguments.length && 'string' == typeof arg) {\n arg.split(/\\s+/).forEach(function (field) {\n if (!field) return;\n var include = '-' == field[0] ? 0 : 1;\n if (include === 0) field = field.substring(1);\n fields[field] = include;\n });\n } else {\n throw new TypeError('Invalid select() argument. Must be a string or object.');\n }\n\n return this;\n};\n\n/**\n * Specifies a $slice projection for an array.\n *\n * ####Example\n *\n * query.slice('comments', 5)\n * query.slice('comments', -5)\n * query.slice('comments', [10, 5])\n * query.where('comments').slice(5)\n * query.where('comments').slice([-10, 5])\n *\n * @param {String} path\n * @param {Number} val number of elements to slice\n * @return {Query} this\n * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements\n * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice\n * @api public\n */\n\nQuery.prototype.slice = function (path, val) {\n if (arguments.length === 1) {\n val = path;\n path = this._currPath\n } else if (arguments.length === 2) {\n if ('number' === typeof path) {\n val = [path, val];\n path = this._currPath;\n }\n } else if (arguments.length === 3) {\n val = utils.args(arguments, 1);\n }\n var myFields = this._fields || (this._fields = {});\n myFields[path] = { '$slice': val };\n return this;\n};\n\n/**\n * Sets the sort order\n *\n * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.\n *\n * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.\n *\n * ####Example\n *\n * // sort by \"field\" ascending and \"test\" descending\n * query.sort({ field: 'asc', test: -1 });\n *\n * // equivalent\n * query.sort('field -test');\n *\n * @param {Object|String} arg\n * @return {Query} this\n * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/\n * @api public\n */\n\nQuery.prototype.sort = function (arg) {\n if (!arg) return this;\n\n var sort = this.options.sort || (this.options.sort = []);\n\n if ('Object' === arg.constructor.name) {\n Object.keys(arg).forEach(function (field) {\n push(sort, field, arg[field]);\n });\n } else if (1 === arguments.length && 'string' == typeof arg) {\n arg.split(/\\s+/).forEach(function (field) {\n if (!field) return;\n var ascend = '-' == field[0] ? -1 : 1;\n if (ascend === -1) field = field.substring(1);\n push(sort, field, ascend);\n });\n } else {\n throw new TypeError('Invalid sort() argument. Must be a string or object.');\n }\n\n return this;\n};\n\n/*!\n * @ignore\n */\n\nfunction push (arr, field, value) {\n var val = String(value || 1).toLowerCase();\n if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) {\n if (Array.isArray(value)) value = '['+value+']';\n throw new TypeError('Invalid sort value: {' + field + ': ' + value + ' }');\n }\n arr.push([field, value]);\n}\n\n/**\n * Specifies the maximum number of documents the query will return.\n *\n * ####Example\n *\n * Kitten.find().limit(20).exec(callback)\n *\n * @method limit\n * @memberOf Query\n * @param {Number} val\n * @api public\n */\n/**\n * Specifies the number of documents to skip.\n *\n * ####Example\n *\n * Kitten.find().skip(100).limit(20)\n *\n * @method skip\n * @memberOf Query\n * @param {Number} val\n * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/\n * @api public\n */\n/**\n * Specifies the maxscan option.\n *\n * ####Example\n *\n * Kitten.find().maxscan(100)\n *\n * @method maxscan\n * @memberOf Query\n * @param {Number} val\n * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/\n * @api public\n */\n/**\n * Specifies the batchSize option.\n *\n * ####Example\n *\n * Kitten.find().batchSize(100)\n *\n * @method batchSize\n * @memberOf Query\n * @param {Number} val\n * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/\n * @api public\n */\n/**\n * Specifies the `comment` option.\n *\n * ####Example\n *\n * Kitten.findOne(condition).comment('login query')\n *\n * @method comment\n * @memberOf Query\n * @param {Number} val\n * @see comment http://docs.mongodb.org/manual/reference/operator/comment/\n * @api public\n */\n\n/*!\n * limit, skip, maxscan, batchSize, comment\n *\n * Sets these associated options.\n *\n * query.comment('feed query');\n */\n\n;['limit', 'skip', 'maxscan', 'batchSize', 'comment'].forEach(function (method) {\n Query.prototype[method] = function (v) {\n this.options[method] = v;\n return this;\n };\n});\n\n/**\n * Specifies this query as a `snapshot` query.\n *\n * ####Example\n *\n * Kitten.find().snapshot()\n *\n * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.snapshot = function () {\n this.options.snapshot = true;\n return this;\n};\n\n/**\n * Sets query hints.\n *\n * ####Example\n *\n * Model.find().hint({ indexA: 1, indexB: -1})\n *\n * @param {Object} val a hint object\n * @return {Query} this\n * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/\n * @api public\n */\n\nQuery.prototype.hint = function (val) {\n if (!val) return this;\n\n var hint = this.options.hint || (this.options.hint = {});\n\n if ('Object' === val.constructor.name) {\n // must keep object keys in order so don't use Object.keys()\n for (var k in val) {\n hint[k] = val[k];\n }\n } else {\n throw new TypeError('Invalid hint. ' + val);\n }\n\n return this;\n};\n\n/**\n * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of [read preferences](#query_Query-read).\n *\n * ####Example:\n *\n * new Query().slaveOk() // true\n * new Query().slaveOk(true)\n * new Query().slaveOk(false)\n *\n * @param {Boolean} v defaults to true\n * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference\n * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.slaveOk = function (v) {\n this.options.slaveOk = arguments.length ? !!v : true;\n return this;\n}\n\n/**\n * Determines the MongoDB nodes from which to read.\n *\n * ####Preferences:\n *\n * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.\n * secondary Read from secondary if available, otherwise error.\n * primaryPreferred Read from primary if available, otherwise a secondary.\n * secondaryPreferred Read from a secondary if available, otherwise read from the primary.\n * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the selection.\n *\n * Aliases\n *\n * p primary\n * pp primaryPreferred\n * s secondary\n * sp secondaryPreferred\n * n nearest\n *\n * ####Example:\n *\n * new Query().read('primary')\n * new Query().read('p') // same as primary\n *\n * new Query().read('primaryPreferred')\n * new Query().read('pp') // same as primaryPreferred\n *\n * new Query().read('secondary')\n * new Query().read('s') // same as secondary\n *\n * new Query().read('secondaryPreferred')\n * new Query().read('sp') // same as secondaryPreferred\n *\n * new Query().read('nearest')\n * new Query().read('n') // same as nearest\n *\n * // read from secondaries with matching tags\n * new Query().read('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])\n *\n * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).\n *\n * @param {String} pref one of the listed preference options or aliases\n * @param {Array} [tags] optional tags for this query\n * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference\n * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.read = function (pref, tags) {\n this.options.readPreference = utils.readPref(pref, tags);\n return this;\n}\n\n/**\n * Sets the lean option.\n *\n * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied.\n *\n * ####Example:\n *\n * new Query().lean() // true\n * new Query().lean(true)\n * new Query().lean(false)\n *\n * Model.find().lean().exec(function (err, docs) {\n * docs[0] instanceof mongoose.Document // false\n * });\n *\n * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream).\n *\n * @param {Boolean} bool defaults to true\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.lean = function (v) {\n this.options.lean = arguments.length ? !!v : true;\n return this;\n}\n\n/**\n * Sets the tailable option (for use with capped collections).\n *\n * ####Example\n *\n * Kitten.find().tailable() // true\n * Kitten.find().tailable(true)\n * Kitten.find().tailable(false)\n *\n * @param {Boolean} bool defaults to true\n * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/\n * @api public\n */\n\nQuery.prototype.tailable = function (v) {\n this.options.tailable = arguments.length ? !!v : true;\n return this;\n};\n\n/**\n * Executes the query as a find() operation.\n *\n * @param {Function} callback\n * @return {Query} this\n * @api private\n */\n\nQuery.prototype.execFind = function (callback) {\n var model = this.model\n , promise = new Promise(callback);\n\n try {\n this.cast(model);\n } catch (err) {\n promise.error(err);\n return this;\n }\n\n // apply default schematype path selections\n this._applyPaths();\n\n var self = this\n , castQuery = this._conditions\n , options = this._optionsForExec(model)\n , fields = utils.clone(this._fields)\n\n options.fields = this._castFields(fields);\n if (options.fields instanceof Error) {\n promise.error(options.fields);\n return this;\n }\n\n model.collection.find(castQuery, options, function (err, cursor) {\n if (err) return promise.error(err);\n cursor.toArray(tick(cb));\n });\n\n function cb (err, docs) {\n if (err) return promise.error(err);\n\n if (0 === docs.length) {\n return promise.complete(docs);\n }\n\n if (!self.options.populate) {\n return true === options.lean\n ? promise.complete(docs)\n : completeMany(model, docs, fields, self, null, promise);\n }\n\n var pop = helpers.preparePopulationOptions(self, options);\n model.populate(docs, pop, function (err, docs) {\n if (err) return promise.error(err);\n return true === options.lean\n ? promise.complete(docs)\n : completeMany(model, docs, fields, self, pop, promise);\n });\n }\n\n return this;\n}\n\n/*!\n * hydrates many documents\n *\n * @param {Model} model\n * @param {Array} docs\n * @param {Object} fields\n * @param {Query} self\n * @param {Array} [pop] array of paths used in population\n * @param {Promise} promise\n */\n\nfunction completeMany (model, docs, fields, self, pop, promise) {\n var arr = [];\n var count = docs.length;\n var len = count;\n var i = 0;\n var opts = pop ?\n { populated: pop }\n : undefined;\n\n for (; i < len; ++i) {\n arr[i] = new model(undefined, fields, true);\n arr[i].init(docs[i], opts, function (err) {\n if (err) return promise.error(err);\n --count || promise.complete(arr);\n });\n }\n}\n\n/**\n * Executes the query as a findOne() operation, passing the first found document to the callback.\n *\n * ####Example\n *\n * var query = Kitten.find({ color: 'white'});\n *\n * query.findOne(function (err, kitten) {\n * if (err) return handleError(err);\n *\n * // kitten may be null if no document matched\n * if (kitten) {\n * ...\n * }\n * })\n *\n * @param {Function} callback\n * @return {Query} this\n * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/\n * @api public\n */\n\nQuery.prototype.findOne = function (callback) {\n this.op = 'findOne';\n\n if (!callback) return this;\n\n var model = this.model;\n var promise = new Promise(callback);\n\n try {\n this.cast(model);\n } catch (err) {\n promise.error(err);\n return this;\n }\n\n // apply default schematype path selections\n this._applyPaths();\n\n var self = this\n , castQuery = this._conditions\n , options = this._optionsForExec(model)\n , fields = utils.clone(this._fields)\n\n options.fields = this._castFields(fields);\n if (options.fields instanceof Error) {\n promise.error(options.fields);\n return this;\n }\n\n model.collection.findOne(castQuery, options, tick(function (err, doc) {\n if (err) return promise.error(err);\n if (!doc) return promise.complete(null);\n\n if (!self.options.populate) {\n return true === options.lean\n ? promise.complete(doc)\n : completeOne(model, doc, fields, self, null, promise);\n }\n\n var pop = helpers.preparePopulationOptions(self, options);\n model.populate(doc, pop, function (err, doc) {\n if (err) return promise.error(err);\n return true === options.lean\n ? promise.complete(doc)\n : completeOne(model, doc, fields, self, pop, promise);\n })\n }));\n\n return this;\n}\n\n/*!\n * hydrates a document\n *\n * @param {Model} model\n * @param {Document} doc\n * @param {Object} fields\n * @param {Query} self\n * @param {Array} [pop] array of paths used in population\n * @param {Promise} promise\n */\n\nfunction completeOne (model, doc, fields, self, pop, promise) {\n var opts = pop ?\n { populated: pop }\n : undefined;\n\n var casted = new model(undefined, fields, true);\n casted.init(doc, opts, function (err) {\n if (err) return promise.error(err);\n promise.complete(casted);\n });\n}\n\n/**\n * Exectues the query as a count() operation.\n *\n * ####Example\n *\n * Kitten.where('color', 'black').count(function (err, count) {\n * if (err) return handleError(err);\n * console.log('there are %d black kittens', count);\n * })\n *\n * @param {Function} callback\n * @return {Query} this\n * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/\n * @api public\n */\n\nQuery.prototype.count = function (callback) {\n this.op = 'count';\n var model = this.model;\n\n try {\n this.cast(model);\n } catch (err) {\n return callback(err);\n }\n\n var castQuery = this._conditions;\n model.collection.count(castQuery, tick(callback));\n\n return this;\n};\n\n/**\n * Executes this query as a distict() operation.\n *\n * @param {String} field\n * @param {Function} callback\n * @return {Query} this\n * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/\n * @api public\n */\n\nQuery.prototype.distinct = function (field, callback) {\n this.op = 'distinct';\n var model = this.model;\n\n try {\n this.cast(model);\n } catch (err) {\n return callback(err);\n }\n\n var castQuery = this._conditions;\n model.collection.distinct(field, castQuery, tick(callback));\n\n return this;\n};\n\n/*!\n * These operators require casting docs\n * to real Documents for Update operations.\n */\n\nvar castOps = {\n $push: 1\n , $pushAll: 1\n , $addToSet: 1\n , $set: 1\n};\n\n/*!\n * These operators should be cast to numbers instead\n * of their path schema type.\n */\n\nvar numberOps = {\n $pop: 1\n , $unset: 1\n , $inc: 1\n}\n\n/**\n * Executes this query as an update() operation.\n *\n * _All paths passed that are not $atomic operations will become $set ops so we retain backwards compatibility._\n *\n * ####Example\n *\n * Model.update({..}, { title: 'remove words' }, ...)\n *\n * // becomes\n *\n * Model.update({..}, { $set: { title: 'remove words' }}, ...)\n *\n * ####Note\n *\n * Passing an empty object `{}` as the doc will result in a no-op. The update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting the collection.\n *\n * @param {Object} doc the update conditions\n * @param {Function} callback\n * @return {Query} this\n * @api public\n * @see Model.update http://localhost:8088/docs/api.html#model_Model.update\n * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/\n */\n\nQuery.prototype.update = function update (doc, callback) {\n this.op = 'update';\n this._updateArg = doc;\n\n var model = this.model\n , options = this._optionsForExec(model)\n , fn = 'function' == typeof callback\n , castedQuery\n , castedDoc\n\n castedQuery = castQuery(this);\n if (castedQuery instanceof Error) {\n if (fn) {\n process.nextTick(callback.bind(null, castedQuery));\n return this;\n }\n throw castedQuery;\n }\n\n castedDoc = castDoc(this);\n if (!castedDoc) {\n fn && process.nextTick(callback.bind(null, null, 0));\n return this;\n }\n\n if (castedDoc instanceof Error) {\n if (fn) {\n process.nextTick(callback.bind(null, castedDoc));\n return this;\n }\n throw castedDoc;\n }\n\n if (!fn) {\n options.safe = { w: 0 };\n }\n\n model.collection.update(castedQuery, castedDoc, options, tick(callback));\n return this;\n};\n\n/**\n * Casts obj for an update command.\n *\n * @param {Object} obj\n * @return {Object} obj after casting its values\n * @api private\n */\n\nQuery.prototype._castUpdate = function _castUpdate (obj) {\n var ops = Object.keys(obj)\n , i = ops.length\n , ret = {}\n , hasKeys\n , val\n\n while (i--) {\n var op = ops[i];\n if ('$' !== op[0]) {\n // fix up $set sugar\n if (!ret.$set) {\n if (obj.$set) {\n ret.$set = obj.$set;\n } else {\n ret.$set = {};\n }\n }\n ret.$set[op] = obj[op];\n ops.splice(i, 1);\n if (!~ops.indexOf('$set')) ops.push('$set');\n } else if ('$set' === op) {\n if (!ret.$set) {\n ret[op] = obj[op];\n }\n } else {\n ret[op] = obj[op];\n }\n }\n\n // cast each value\n i = ops.length;\n\n while (i--) {\n op = ops[i];\n val = ret[op];\n if ('Object' === val.constructor.name) {\n hasKeys |= this._walkUpdatePath(val, op);\n } else {\n var msg = 'Invalid atomic update value for ' + op + '. '\n + 'Expected an object, received ' + typeof val;\n throw new Error(msg);\n }\n }\n\n return hasKeys && ret;\n}\n\n/**\n * Walk each path of obj and cast its values\n * according to its schema.\n *\n * @param {Object} obj - part of a query\n * @param {String} op - the atomic operator ($pull, $set, etc)\n * @param {String} pref - path prefix (internal only)\n * @return {Bool} true if this path has keys to update\n * @api private\n */\n\nQuery.prototype._walkUpdatePath = function _walkUpdatePath (obj, op, pref) {\n var prefix = pref ? pref + '.' : ''\n , keys = Object.keys(obj)\n , i = keys.length\n , hasKeys = false\n , schema\n , key\n , val\n\n var strict = 'strict' in this.options\n ? this.options.strict\n : this.model.schema.options.strict;\n\n while (i--) {\n key = keys[i];\n val = obj[key];\n\n if (val && 'Object' === val.constructor.name) {\n // watch for embedded doc schemas\n schema = this._getSchema(prefix + key);\n if (schema && schema.caster && op in castOps) {\n // embedded doc schema\n\n if (strict && !schema) {\n // path is not in our strict schema\n if ('throw' == strict) {\n throw new Error('Field `' + key + '` is not in schema.');\n } else {\n // ignore paths not specified in schema\n delete obj[key];\n }\n } else {\n hasKeys = true;\n\n if ('$each' in val) {\n obj[key] = {\n $each: this._castUpdateVal(schema, val.$each, op)\n }\n\n if (val.$slice) {\n obj[key].$slice = val.$slice | 0;\n }\n\n if (val.$sort) {\n obj[key].$sort = val.$sort;\n }\n\n } else {\n obj[key] = this._castUpdateVal(schema, val, op);\n }\n }\n } else {\n hasKeys |= this._walkUpdatePath(val, op, prefix + key);\n }\n } else {\n schema = '$each' === key\n ? this._getSchema(pref)\n : this._getSchema(prefix + key);\n\n var skip = strict &&\n !schema &&\n !/real|nested/.test(this.model.schema.pathType(prefix + key));\n\n if (skip) {\n if ('throw' == strict) {\n throw new Error('Field `' + prefix + key + '` is not in schema.');\n } else {\n delete obj[key];\n }\n } else {\n hasKeys = true;\n obj[key] = this._castUpdateVal(schema, val, op, key);\n }\n }\n }\n return hasKeys;\n}\n\n/**\n * Casts `val` according to `schema` and atomic `op`.\n *\n * @param {Schema} schema\n * @param {Object} val\n * @param {String} op - the atomic operator ($pull, $set, etc)\n * @param {String} [$conditional]\n * @api private\n */\n\nQuery.prototype._castUpdateVal = function _castUpdateVal (schema, val, op, $conditional) {\n if (!schema) {\n // non-existing schema path\n return op in numberOps\n ? Number(val)\n : val\n }\n\n if (schema.caster && op in castOps &&\n ('Object' === val.constructor.name || Array.isArray(val))) {\n // Cast values for ops that add data to MongoDB.\n // Ensures embedded documents get ObjectIds etc.\n var tmp = schema.cast(val);\n\n if (Array.isArray(val)) {\n val = tmp;\n } else {\n val = tmp[0];\n }\n }\n\n if (op in numberOps) return Number(val);\n if (/^\\$/.test($conditional)) return schema.castForQuery($conditional, val);\n return schema.castForQuery(val)\n}\n\n/**\n * Finds the schema for `path`. This is different than\n * calling `schema.path` as it also resolves paths with\n * positional selectors (something.$.another.$.path).\n *\n * @param {String} path\n * @api private\n */\n\nQuery.prototype._getSchema = function _getSchema (path) {\n return this.model._getSchema(path);\n}\n\n/**\n * Casts selected field arguments for field selection with mongo 2.2\n *\n * query.select({ ids: { $elemMatch: { $in: [hexString] }})\n *\n * @param {Object} fields\n * @see https://github.com/LearnBoost/mongoose/issues/1091\n * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/\n * @api private\n */\n\nQuery.prototype._castFields = function _castFields (fields) {\n var selected\n , elemMatchKeys\n , keys\n , key\n , out\n , i\n\n if (fields) {\n keys = Object.keys(fields);\n elemMatchKeys = [];\n i = keys.length;\n\n // collect $elemMatch args\n while (i--) {\n key = keys[i];\n if (fields[key].$elemMatch) {\n selected || (selected = {});\n selected[key] = fields[key];\n elemMatchKeys.push(key);\n }\n }\n }\n\n if (selected) {\n // they passed $elemMatch, cast em\n try {\n out = this.cast(this.model, selected);\n } catch (err) {\n return err;\n }\n\n // apply the casted field args\n i = elemMatchKeys.length;\n while (i--) {\n key = elemMatchKeys[i];\n fields[key] = out[key];\n }\n }\n\n return fields;\n}\n\n/**\n * Executes this query as a remove() operation.\n *\n * ####Example\n *\n * Cassette.where('artist').equals('Anne Murray').remove(callback)\n *\n * @param {Function} callback\n * @api public\n * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/\n */\n\nQuery.prototype.remove = function (callback) {\n this.op = 'remove';\n\n var model = this.model\n , options = this._optionsForExec(model)\n , cb = 'function' == typeof callback\n\n try {\n this.cast(model);\n } catch (err) {\n if (cb) return callback(err);\n throw err;\n }\n\n if (!cb) {\n options.safe = { w: 0 };\n }\n\n var castQuery = this._conditions;\n model.collection.remove(castQuery, options, tick(callback));\n return this;\n};\n\n/**\n * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command.\n *\n * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned.\n *\n * ####Available options\n *\n * - `new`: bool - true to return the modified document rather than the original. defaults to true\n * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.\n * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update\n *\n * ####Examples\n *\n * query.findOneAndUpdate(conditions, update, options, callback) // executes\n * query.findOneAndUpdate(conditions, update, options) // returns Query\n * query.findOneAndUpdate(conditions, update, callback) // executes\n * query.findOneAndUpdate(conditions, update) // returns Query\n * query.findOneAndUpdate(callback) // executes\n * query.findOneAndUpdate() // returns Query\n *\n * @param {Object} [query]\n * @param {Object} [doc]\n * @param {Object} [options]\n * @param {Function} [callback]\n * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.findOneAndUpdate = function (query, doc, options, callback) {\n this.op = 'findOneAndUpdate';\n\n switch (arguments.length) {\n case 3:\n if ('function' == typeof options)\n callback = options, options = {};\n break;\n case 2:\n if ('function' == typeof doc) {\n callback = doc;\n doc = query;\n query = undefined;\n }\n options = undefined;\n break;\n case 1:\n if ('function' == typeof query) {\n callback = query;\n query = options = doc = undefined;\n } else {\n doc = query;\n query = options = undefined;\n }\n }\n\n // apply query\n if (query) {\n if ('Object' === query.constructor.name) {\n merge(this._conditions, query);\n } else if (query instanceof Query) {\n merge(this._conditions, query._conditions);\n } else if (query instanceof Document) {\n merge(this._conditions, query.toObject());\n }\n }\n\n // apply doc\n if (doc) {\n merge(this._updateArg, doc);\n }\n\n // apply options\n options && this.setOptions(options);\n\n if (!callback) return this;\n\n return this._findAndModify('update', callback);\n}\n\n/**\n * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command.\n *\n * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed else a Query object is returned.\n *\n * ####Available options\n *\n * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update\n *\n * ####Examples\n *\n * A.where().findOneAndRemove(conditions, options, callback) // executes\n * A.where().findOneAndRemove(conditions, options) // return Query\n * A.where().findOneAndRemove(conditions, callback) // executes\n * A.where().findOneAndRemove(conditions) // returns Query\n * A.where().findOneAndRemove(callback) // executes\n * A.where().findOneAndRemove() // returns Query\n *\n * @param {Object} [conditions]\n * @param {Object} [options]\n * @param {Function} [callback]\n * @return {Query} this\n * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command\n * @api public\n */\n\nQuery.prototype.findOneAndRemove = function (conditions, options, callback) {\n this.op = 'findOneAndRemove';\n\n if ('function' == typeof options) {\n callback = options;\n options = undefined;\n } else if ('function' == typeof conditions) {\n callback = conditions;\n conditions = undefined;\n }\n\n // apply conditions\n if (conditions) {\n if ('Object' === conditions.constructor.name) {\n merge(this._conditions, conditions);\n } else if (conditions instanceof Query) {\n merge(this._conditions, conditions._conditions);\n } else if (conditions instanceof Document) {\n merge(this._conditions, conditions.toObject());\n }\n }\n\n // apply options\n options && this.setOptions(options);\n\n if (!callback) return this;\n\n return this._findAndModify('remove', callback);\n}\n\n/**\n * _findAndModify\n *\n * @param {String} type - either \"remove\" or \"update\"\n * @param {Function} callback\n * @api private\n */\n\nQuery.prototype._findAndModify = function (type, callback) {\n var model = this.model\n , promise = new Promise(callback)\n , self = this\n , castedQuery\n , castedDoc\n , fields\n , sort\n , opts\n\n castedQuery = castQuery(this);\n if (castedQuery instanceof Error) {\n process.nextTick(promise.error.bind(promise, castedQuery));\n return promise;\n }\n\n opts = this._optionsForExec(model);\n\n if ('remove' == type) {\n opts.remove = true;\n } else {\n if (!('new' in opts)) opts.new = true;\n if (!('upsert' in opts)) opts.upsert = false;\n\n castedDoc = castDoc(this);\n if (!castedDoc) {\n if (opts.upsert) {\n // still need to do the upsert to empty doc\n castedDoc = { $set: {} };\n } else {\n return this.findOne(callback);\n }\n } else if (castedDoc instanceof Error) {\n process.nextTick(promise.error.bind(promise, castedDoc));\n return promise;\n }\n }\n\n this._applyPaths();\n\n if (this._fields) {\n fields = utils.clone(this._fields)\n opts.fields = this._castFields(fields);\n if (opts.fields instanceof Error) {\n process.nextTick(promise.error.bind(promise, opts.fields));\n return promise;\n }\n }\n\n // the driver needs a default\n sort = opts.sort || [];\n\n model\n .collection\n .findAndModify(castedQuery, sort, castedDoc, opts, tick(function (err, doc) {\n if (err) return promise.error(err);\n if (!doc) return promise.complete(null);\n\n if (!self.options.populate) {\n return true === opts.lean\n ? promise.complete(doc)\n : completeOne(model, doc, fields, self, null, promise);\n }\n\n var pop = helpers.preparePopulationOptions(self, opts);\n model.populate(doc, pop, function (err, doc) {\n if (err) return promise.error(err);\n return true === opts.lean\n ? promise.complete(doc)\n : completeOne(model, doc, fields, self, pop, promise);\n })\n }));\n\n return promise;\n}\n\n/**\n * Specifies paths which should be populated with other documents.\n *\n * ####Example:\n *\n * Kitten.findOne().populate('owner').exec(function (err, kitten) {\n * console.log(kitten.owner.name) // Max\n * })\n *\n * Kitten.find().populate({\n * path: 'owner'\n * , select: 'name'\n * , match: { color: 'black' }\n * , options: { sort: { name: -1 }}\n * }).exec(function (err, kittens) {\n * console.log(kittens[0].owner.name) // Zoopa\n * })\n *\n * // alternatively\n * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {\n * console.log(kittens[0].owner.name) // Zoopa\n * })\n *\n * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.\n *\n * @param {Object|String} path either the path to populate or an object specifying all parameters\n * @param {Object|String} [select] Field selection for the population query\n * @param {Model} [model] The name of the model you wish to use for population. If not specified, the name is looked up from the Schema ref.\n * @param {Object} [match] Conditions for the population query\n * @param {Object} [options] Options for the population query (sort, etc)\n * @see population ./populate.html\n * @see Query#select #query_Query-select\n * @see Model.populate #model_Model.populate\n * @return {Query} this\n * @api public\n */\n\nQuery.prototype.populate = function populate () {\n var res = utils.populate.apply(null, arguments);\n var opts = this.options;\n\n if (!utils.isObject(opts.populate)) {\n opts.populate = {};\n }\n\n for (var i = 0; i < res.length; ++i) {\n opts.populate[res[i].path] = res[i];\n }\n\n return this;\n}\n\n/**\n * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface.\n *\n * ####Example\n *\n * // follows the nodejs 0.8 stream api\n * Thing.find({ name: /^hello/ }).stream().pipe(res)\n *\n * // manual streaming\n * var stream = Thing.find({ name: /^hello/ }).stream();\n *\n * stream.on('data', function (doc) {\n * // do something with the mongoose document\n * }).on('error', function (err) {\n * // handle the error\n * }).on('close', function () {\n * // the stream is closed\n * });\n *\n * ####Valid options\n *\n * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`.\n *\n * ####Example\n *\n * // JSON.stringify all documents before emitting\n * var stream = Thing.find().stream({ transform: JSON.stringify });\n * stream.pipe(writeStream);\n *\n * @return {QueryStream}\n * @param {Object} [options]\n * @see QueryStream\n * @api public\n */\n\nQuery.prototype.stream = function stream (opts) {\n return new QueryStream(this, opts);\n}\n\n// helpers\n\n/*!\n * castDoc\n * @api private\n */\n\nfunction castDoc (query) {\n try {\n return query._castUpdate(query._updateArg);\n } catch (err) {\n return err;\n }\n}\n\n/*!\n * castQuery\n * @api private\n */\n\nfunction castQuery (query) {\n try {\n return query.cast(query.model);\n } catch (err) {\n return err;\n }\n}\n\n/*!\n * Exports.\n */\n\nmodule.exports = Query;\nmodule.exports.QueryStream = QueryStream;\n\n});","sourceLength":67221,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/query.js (lines: 2592)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":587,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[458]}}
{"seq":316,"request_seq":587,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/promise.js","id":458,"lineOffset":0,"columnOffset":0,"lineCount":233,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies\n */\n\nvar MPromise = require('mpromise');\n\n/**\n * Promise constructor.\n *\n * Promises are returned from executed queries. Example:\n *\n * var query = Candy.find({ bar: true });\n * var promise = query.exec();\n *\n * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature\n * @inherits mpromise https://github.com/aheckmann/mpromise\n * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter\n * @event `err`: Emits when the promise is rejected\n * @event `complete`: Emits when the promise is fulfilled\n * @api public\n */\n\nfunction Promise (fn) {\n MPromise.call(this, fn);\n}\n\n/*!\n * Inherit from mpromise\n */\n\nPromise.prototype = Object.create(MPromise.prototype, {\n constructor: {\n value: Promise\n , enumerable: false\n , writable: true\n , configurable: true\n }\n});\n\n/*!\n * Override event names for backward compatibility.\n */\n\nPromise.SUCCESS = 'complete';\nPromise.FAILURE = 'err';\n\n/**\n * Adds `listener` to the `event`.\n *\n * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event.\n *\n * @see mpromise#on https://github.com/aheckmann/mpromise#on\n * @method on\n * @memberOf Promise\n * @param {String} event\n * @param {Function} listener\n * @return {Promise} this\n * @api public\n */\n\n/**\n * Rejects this promise with `reason`.\n *\n * If the promise has already been fulfilled or rejected, not action is taken.\n *\n * @see mpromise#reject https://github.com/aheckmann/mpromise#reject\n * @method reject\n * @memberOf Promise\n * @param {Object|String|Error} reason\n * @return {Promise} this\n * @api public\n */\n\n/**\n * Rejects this promise with `err`.\n *\n * If the promise has already been fulfilled or rejected, not action is taken.\n *\n * Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`.\n *\n * @api public\n * @param {Error|String} err\n * @return {Promise} this\n */\n\nPromise.prototype.error = function (err) {\n if (!(err instanceof Error)) err = new Error(err);\n return this.reject(err);\n}\n\n/**\n * Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed.\n *\n * If the promise has already been fulfilled or rejected, not action is taken.\n *\n * `err` will be cast to an Error if not already instanceof Error.\n *\n * _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._\n *\n * @param {Error} [err] error or null\n * @param {Object} [val] value to fulfill the promise with\n * @api public\n */\n\nPromise.prototype.resolve = function (err, val) {\n if (err) return this.error(err);\n return this.fulfill(val);\n}\n\n/**\n * Adds a single function as a listener to both err and complete.\n *\n * It will be executed with traditional node.js argument position when the promise is resolved. \n *\n * promise.addBack(function (err, args...) {\n * if (err) return handleError(err);\n * console.log('success');\n * })\n *\n * Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve).\n *\n * @method addBack\n * @param {Function} listener\n * @return {Promise} this\n */\n\nPromise.prototype.addBack = Promise.prototype.onResolve;\n\n/**\n * Fulfills this promise with passed arguments.\n *\n * Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill).\n *\n * @method complete\n * @param {any} args\n * @api public\n */\n\nPromise.prototype.complete = MPromise.prototype.fulfill;\n\n/**\n * Adds a listener to the `complete` (success) event.\n *\n * Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill).\n *\n * @method addCallback\n * @param {Function} listener\n * @return {Promise} this\n * @api public\n */\n\nPromise.prototype.addCallback = Promise.prototype.onFulfill;\n\n/**\n * Adds a listener to the `err` (rejected) event.\n *\n * Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject).\n *\n * @method addErrback\n * @param {Function} listener\n * @return {Promise} this\n * @api public\n */\n\nPromise.prototype.addErrback = Promise.prototype.onReject;\n\n/**\n * Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.\n *\n * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification.\n *\n * ####Example:\n *\n * var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();\n * promise.then(function (meetups) {\n * var ids = meetups.map(function (m) {\n * return m._id;\n * });\n * return People.find({ meetups: { $in: ids }).exec();\n * }).then(function (people) {\n * if (people.length < 10000) {\n * throw new Error('Too few people!!!');\n * } else {\n * throw new Error('Still need more people!!!');\n * }\n * }).then(null, function (err) {\n * assert.ok(err instanceof Error);\n * });\n *\n * @see promises-A+ https://github.com/promises-aplus/promises-spec\n * @see mpromise#then https://github.com/aheckmann/mpromise#then\n * @method then\n * @memberOf Promise\n * @param {Function} onFulFill\n * @param {Function} onReject\n * @return {Promise} newPromise\n */\n\n/**\n * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught.\n *\n * ####Example:\n *\n * var p = new Promise;\n * p.then(function(){ throw new Error('shucks') });\n * setTimeout(function () {\n * p.fulfill();\n * // error was caught and swallowed by the promise returned from\n * // p.then(). we either have to always register handlers on\n * // the returned promises or we can do the following...\n * }, 10);\n *\n * // this time we use .end() which prevents catching thrown errors\n * var p = new Promise;\n * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--\n * setTimeout(function () {\n * p.fulfill(); // throws \"shucks\"\n * }, 10);\n *\n * @api public\n * @see mpromise#end https://github.com/aheckmann/mpromise#end\n * @method end\n * @memberOf Promise\n */\n\n/*!\n * expose\n */\n\nmodule.exports = Promise;\n\n});","sourceLength":6445,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/promise.js (lines: 233)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":588,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[461]}}
{"seq":319,"request_seq":588,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpromise/index.js","id":461,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function (exports, require, module, __filename, __dirname) { module.exports = exports = require('./lib/promise');\n\n});","sourceLength":119,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpromise/index.js (lines: 3)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":589,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[464]}}
{"seq":331,"request_seq":589,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpromise/lib/promise.js","id":464,"lineOffset":0,"columnOffset":0,"lineCount":270,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar slice = require('sliced');\nvar EventEmitter = require('events').EventEmitter;\n\n/**\n * Promise constructor.\n *\n * _NOTE: The success and failure event names can be overridden by setting `Promise.SUCCESS` and `Promise.FAILURE` respectively._\n *\n * @param {Function} back a function that accepts `fn(err, ...){}` as signature\n * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter\n * @event `reject`: Emits when the promise is rejected (event name may be overridden)\n * @event `fulfill`: Emits when the promise is fulfilled (event name may be overridden)\n * @api public\n */\n\nfunction Promise (back) {\n this.emitted = {};\n this.ended = false;\n if ('function' == typeof back)\n this.onResolve(back);\n}\n\n/*!\n * event names\n */\n\nPromise.SUCCESS = 'fulfill';\nPromise.FAILURE = 'reject';\n\n/*!\n * Inherits from EventEmitter.\n */\n\nPromise.prototype.__proto__ = EventEmitter.prototype;\n\n/**\n * Adds `listener` to the `event`.\n *\n * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event.\n *\n * @param {String} event\n * @param {Function} callback\n * @return {Promise} this\n * @api public\n */\n\nPromise.prototype.on = function (event, callback) {\n if (this.emitted[event])\n callback.apply(this, this.emitted[event]);\n else\n EventEmitter.prototype.on.call(this, event, callback);\n\n return this;\n}\n\n/**\n * Keeps track of emitted events to run them on `on`.\n *\n * @api private\n */\n\nPromise.prototype.emit = function (event) {\n // ensures a promise can't be fulfill() or reject() more than once\n var success = this.constructor.SUCCESS;\n var failure = this.constructor.FAILURE;\n\n if (event == success || event == failure) {\n if (this.emitted[success] || this.emitted[failure]) {\n return this;\n }\n this.emitted[event] = slice(arguments, 1);\n }\n\n return EventEmitter.prototype.emit.apply(this, arguments);\n}\n\n/**\n * Fulfills this promise with passed arguments.\n *\n * If this promise has already been fulfilled or rejected, no action is taken.\n *\n * @api public\n */\n\nPromise.prototype.fulfill = function () {\n var args = slice(arguments);\n return this.emit.apply(this, [this.constructor.SUCCESS].concat(args));\n}\n\n/**\n * Rejects this promise with `reason`.\n *\n * If this promise has already been fulfilled or rejected, no action is taken.\n *\n * @api public\n * @param {Object|String} reason\n * @return {Promise} this\n */\n\nPromise.prototype.reject = function (reason) {\n return this.emit(this.constructor.FAILURE, reason);\n}\n\n/**\n * Resolves this promise to a rejected state if `err` is passed or\n * fulfilled state if no `err` is passed.\n *\n * @param {Error} [err] error or null\n * @param {Object} [val] value to fulfill the promise with\n * @api public\n */\n\nPromise.prototype.resolve = function (err, val) {\n if (err) return this.reject(err);\n return this.fulfill(val);\n}\n\n/**\n * Adds a listener to the SUCCESS event.\n *\n * @return {Promise} this\n * @api public\n */\n\nPromise.prototype.onFulfill = function (fn) {\n return this.on(this.constructor.SUCCESS, fn);\n}\n\n/**\n * Adds a listener to the FAILURE event.\n *\n * @return {Promise} this\n * @api public\n */\n\nPromise.prototype.onReject = function (fn) {\n return this.on(this.constructor.FAILURE, fn);\n}\n\n/**\n * Adds a single function as a listener to both SUCCESS and FAILURE.\n *\n * It will be executed with traditional node.js argument position:\n * function (err, args...) {}\n *\n * @param {Function} fn\n * @return {Promise} this\n */\n\nPromise.prototype.onResolve = function (fn) {\n this.on(this.constructor.FAILURE, function(err){\n fn.call(this, err);\n });\n\n this.on(this.constructor.SUCCESS, function(){\n var args = slice(arguments);\n fn.apply(this, [null].concat(args));\n });\n\n return this;\n}\n\n/**\n * Creates a new promise and returns it. If `onFulfill` or\n * `onReject` are passed, they are added as SUCCESS/ERROR callbacks\n * to this promise after the nextTick.\n *\n * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification. Read for more detail how to use this method.\n *\n * ####Example:\n *\n * var p = new Promise;\n * p.then(function (arg) {\n * return arg + 1;\n * }).then(function (arg) {\n * throw new Error(arg + ' is an error!');\n * }).then(null, function (err) {\n * assert.ok(err instanceof Error);\n * assert.equal('2 is an error', err.message);\n * });\n * p.complete(1);\n *\n * @see promises-A+ https://github.com/promises-aplus/promises-spec\n * @param {Function} onFulFill\n * @param {Function} onReject\n * @return {Promise} newPromise\n */\n\nPromise.prototype.then = function (onFulfill, onReject) {\n var self = this\n , retPromise = new Promise;\n\n function handler (fn) {\n return function handle (arg) {\n var val;\n\n try {\n val = fn(arg);\n } catch (err) {\n if (retPromise.ended) throw err;\n return retPromise.reject(err);\n }\n\n if (val && 'function' == typeof val.then) {\n val.then(\n retPromise.fulfill.bind(retPromise)\n , retPromise.reject.bind(retPromise))\n } else {\n retPromise.fulfill(val);\n }\n }\n }\n\n process.nextTick(function () {\n if ('function' == typeof onReject) {\n self.onReject(handler(onReject));\n } else {\n self.onReject(retPromise.reject.bind(retPromise));\n }\n\n if ('function' == typeof onFulfill) {\n self.onFulfill(handler(onFulfill));\n } else {\n self.onFulfill(retPromise.fulfill.bind(retPromise));\n }\n })\n\n return retPromise;\n}\n\n/**\n * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught.\n *\n * ####Example:\n *\n * var p = new Promise;\n * p.then(function(){ throw new Error('shucks') });\n * setTimeout(function () {\n * p.fulfill();\n * // error was caught and swallowed by the promise returned from\n * // p.then(). we either have to always register handlers on\n * // the returned promises or we can do the following...\n * }, 10);\n *\n * // this time we use .end() which prevents catching thrown errors\n * var p = new Promise;\n * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <--\n * setTimeout(function () {\n * p.fulfill(); // throws \"shucks\"\n * }, 10);\n *\n * @api public\n */\n\nPromise.prototype.end = function () {\n this.ended = true;\n}\n\n/*!\n * Module exports.\n */\n\nmodule.exports = Promise;\n\n});","sourceLength":6697,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpromise/lib/promise.js (lines: 270)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":590,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[467]}}
{"seq":332,"request_seq":590,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpromise/node_modules/sliced/index.js","id":467,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function (exports, require, module, __filename, __dirname) { module.exports = exports = require('./lib/sliced');\n\n});","sourceLength":118,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpromise/node_modules/sliced/index.js (lines: 3)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":591,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[470]}}
{"seq":333,"request_seq":591,"type":"response","command":"scripts","success":true,"body":[{"handle":7,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpromise/node_modules/sliced/lib/sliced.js","id":470,"lineOffset":0,"columnOffset":0,"lineCount":39,"source":"(function (exports, require, module, __filename, __dirname) { \n/**\n * An Array.prototype.slice.call(arguments) alternative\n *\n * @param {Object} args something with a length\n * @param {Number} slice\n * @param {Number} sliceEnd\n * @api public\n */\n\nmodule.exports = function () {\n var args = arguments[0];\n var slice = arguments[1];\n var sliceEnd = arguments[2];\n\n var ret = [];\n var len = args.length;\n\n if (0 === len) return ret;\n\n var start = slice < 0\n ? Math.max(0, slice + len)\n : slice || 0;\n\n var end = 3 === arguments.length\n ? sliceEnd < 0\n ? sliceEnd + len\n : sliceEnd\n : len;\n\n while (end-- > start) {\n ret[end - start] = args[end];\n }\n\n return ret;\n}\n\n\n});","sourceLength":703,"scriptType":2,"compilationType":0,"context":{"ref":6},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/mpromise/node_modules/sliced/lib/sliced.js (lines: 39)"}],"refs":[{"handle":6,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":592,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[473]}}
{"seq":334,"request_seq":592,"type":"response","command":"scripts","success":true,"body":[{"handle":9,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/querystream.js","id":473,"lineOffset":0,"columnOffset":0,"lineCount":338,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar Stream = require('stream').Stream\nvar utils = require('./utils')\nvar helpers = require('./queryhelpers')\nvar K = function(k){ return k }\n\n/**\n * Provides a Node.js 0.8 style [ReadStream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface for Queries.\n *\n * var stream = Model.find().stream();\n *\n * stream.on('data', function (doc) {\n * // do something with the mongoose document\n * }).on('error', function (err) {\n * // handle the error\n * }).on('close', function () {\n * // the stream is closed\n * });\n *\n *\n * The stream interface allows us to simply \"plug-in\" to other _Node.js 0.8_ style write streams.\n *\n * Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream);\n *\n * ####Valid options\n *\n * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`.\n *\n * ####Example\n *\n * // JSON.stringify all documents before emitting\n * var stream = Thing.find().stream({ transform: JSON.stringify });\n * stream.pipe(writeStream);\n *\n * _NOTE: plugging into an HTTP response will *not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary._\n *\n * _NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work._\n *\n * @param {Query} query\n * @param {Object} [options]\n * @inherits NodeJS Stream http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream\n * @event `data`: emits a single Mongoose document\n * @event `error`: emits when an error occurs during streaming. This will emit _before_ the `close` event.\n * @event `close`: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually `destroy`ed. After this event, no more events are emitted.\n * @api public\n */\n\nfunction QueryStream (query, options) {\n Stream.call(this);\n\n this.query = query;\n this.readable = true;\n this.paused = false;\n this._cursor = null;\n this._destroyed = null;\n this._fields = null;\n this._buffer = null;\n this._inline = T_INIT;\n this._running = false;\n this._transform = options && 'function' == typeof options.transform\n ? options.transform\n : K;\n\n // give time to hook up events\n var self = this;\n process.nextTick(function () {\n self._init();\n });\n}\n\n/*!\n * Inherit from Stream\n */\n\nQueryStream.prototype.__proto__ = Stream.prototype;\n\n/**\n * Flag stating whether or not this stream is readable.\n *\n * @property readable\n * @api public\n */\n\nQueryStream.prototype.readable;\n\n/**\n * Flag stating whether or not this stream is paused.\n *\n * @property paused\n * @api public\n */\n\nQueryStream.prototype.paused;\n\n// trampoline flags\nvar T_INIT = 0;\nvar T_IDLE = 1;\nvar T_CONT = 2;\n\n/**\n * Initializes the query.\n *\n * @api private\n */\n\nQueryStream.prototype._init = function () {\n if (this._destroyed) return;\n\n var query = this.query\n , model = query.model\n , options = query._optionsForExec(model)\n , self = this\n\n try {\n query.cast(model);\n } catch (err) {\n return self.destroy(err);\n }\n\n self._fields = utils.clone(query._fields);\n options.fields = query._castFields(self._fields);\n\n model.collection.find(query._conditions, options, function (err, cursor) {\n if (err) return self.destroy(err);\n self._cursor = cursor;\n self._next();\n });\n}\n\n/**\n * Trampoline for pulling the next doc from cursor.\n *\n * @see QueryStream#__next #querystream_QueryStream-__next\n * @api private\n */\n\nQueryStream.prototype._next = function _next () {\n if (this.paused || this._destroyed) {\n return this._running = false;\n }\n\n this._running = true;\n\n if (this._buffer && this._buffer.length) {\n var arg;\n while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) {\n this._onNextObject.apply(this, arg);\n }\n }\n\n // avoid stack overflows with large result sets.\n // trampoline instead of recursion.\n while (this.__next()) {}\n}\n\n/**\n * Pulls the next doc from the cursor.\n *\n * @see QueryStream#_next #querystream_QueryStream-_next\n * @api private\n */\n\nQueryStream.prototype.__next = function () {\n if (this.paused || this._destroyed)\n return this._running = false;\n\n var self = this;\n self._inline = T_INIT;\n\n self._cursor.nextObject(function cursorcb (err, doc) {\n self._onNextObject(err, doc);\n });\n\n // if onNextObject() was already called in this tick\n // return ourselves to the trampoline.\n if (T_CONT === this._inline) {\n return true;\n } else {\n // onNextObject() hasn't fired yet. tell onNextObject\n // that its ok to call _next b/c we are not within\n // the trampoline anymore.\n this._inline = T_IDLE;\n }\n}\n\n/**\n * Transforms raw `doc`s returned from the cursor into a model instance.\n *\n * @param {Error|null} err\n * @param {Object} doc\n * @api private\n */\n\nQueryStream.prototype._onNextObject = function _onNextObject (err, doc) {\n if (this._destroyed) return;\n\n if (this.paused) {\n this._buffer || (this._buffer = []);\n this._buffer.push([err, doc]);\n return this._running = false;\n }\n\n if (err) return this.destroy(err);\n\n // when doc is null we hit the end of the cursor\n if (!doc) {\n this.emit('end');\n return this.destroy();\n }\n\n var opts = this.query.options;\n\n if (!opts.populate) {\n return true === opts.lean\n ? emit(this, doc)\n : createAndEmit(this, doc);\n }\n\n var self = this;\n var pop = helpers.preparePopulationOptions(self.query, self.query.options);\n\n self.query.model.populate(doc, pop, function (err, doc) {\n if (err) return self.destroy(err);\n return true === opts.lean\n ? emit(self, doc)\n : createAndEmit(self, doc);\n })\n}\n\nfunction createAndEmit (self, doc) {\n var instance = new self.query.model(undefined, self._fields, true);\n instance.init(doc, function (err) {\n if (err) return self.destroy(err);\n emit(self, instance);\n });\n}\n\n/*!\n * Emit a data event and manage the trampoline state\n */\n\nfunction emit (self, doc) {\n self.emit('data', self._transform(doc));\n\n // trampoline management\n if (T_IDLE === self._inline) {\n // no longer in trampoline. restart it.\n self._next();\n } else {\n // in a trampoline. tell __next that its\n // ok to continue jumping.\n self._inline = T_CONT;\n }\n}\n\n/**\n * Pauses this stream.\n *\n * @api public\n */\n\nQueryStream.prototype.pause = function () {\n this.paused = true;\n}\n\n/**\n * Resumes this stream.\n *\n * @api public\n */\n\nQueryStream.prototype.resume = function () {\n this.paused = false;\n\n if (!this._cursor) {\n // cannot start if not initialized\n return;\n }\n\n // are we within the trampoline?\n if (T_INIT === this._inline) {\n return;\n }\n\n if (!this._running) {\n // outside QueryStream control, need manual restart\n return this._next();\n }\n}\n\n/**\n * Destroys the stream, closing the underlying cursor. No more events will be emitted.\n *\n * @param {Error} [err]\n * @api public\n */\n\nQueryStream.prototype.destroy = function (err) {\n if (this._destroyed) return;\n this._destroyed = true;\n this._running = false;\n this.readable = false;\n\n if (this._cursor) {\n this._cursor.close();\n }\n\n if (err) {\n this.emit('error', err);\n }\n\n this.emit('close');\n}\n\n/**\n * Pipes this query stream into another stream. This method is inherited from NodeJS Streams.\n *\n * ####Example:\n *\n * query.stream().pipe(writeStream [, options])\n *\n * @method pipe\n * @memberOf QueryStream\n * @see NodeJS http://nodejs.org/api/stream.html\n * @api public\n */\n\n/*!\n * Module exports\n */\n\nmodule.exports = exports = QueryStream;\n\n});","sourceLength":7801,"scriptType":2,"compilationType":0,"context":{"ref":8},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/querystream.js (lines: 338)"}],"refs":[{"handle":8,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":593,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[476]}}
{"seq":335,"request_seq":593,"type":"response","command":"scripts","success":true,"body":[{"handle":11,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/queryhelpers.js","id":476,"lineOffset":0,"columnOffset":0,"lineCount":37,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies\n */\n\nvar utils = require('./utils')\n\n/*!\n * Prepare a set of path options for query population.\n *\n * @param {Query} query\n * @param {Object} options\n * @return {Array}\n */\n\nexports.preparePopulationOptions = function preparePopulationOptions (query, options) {\n var pop = utils.object.vals(query.options.populate);\n\n // lean options should trickle through all queries\n if (options.lean) pop.forEach(makeLean);\n\n return pop;\n}\n\n/*!\n * Set each path query option to lean\n *\n * @param {Object} option\n */\n\nfunction makeLean (option) {\n option.options || (option.options = {});\n option.options.lean = true;\n}\n\n\n});","sourceLength":707,"scriptType":2,"compilationType":0,"context":{"ref":10},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/queryhelpers.js (lines: 37)"}],"refs":[{"handle":10,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":594,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[479]}}
{"seq":336,"request_seq":594,"type":"response","command":"scripts","success":true,"body":[{"handle":13,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/namedscope.js","id":479,"lineOffset":0,"columnOffset":0,"lineCount":72,"source":"(function (exports, require, module, __filename, __dirname) { var Query = require('./query');\nfunction NamedScope () {}\n\nNamedScope.prototype.query;\n\nNamedScope.prototype.where = function () {\n var q = this.query || (this.query = new Query());\n q.where.apply(q, arguments);\n return q;\n};\n\n/**\n * Decorate\n *\n * @param {NamedScope} target\n * @param {Object} getters\n * @api private\n */\n\nNamedScope.prototype.decorate = function (target, getters) {\n var name = this.name\n , block = this.block\n , query = this.query;\n if (block) {\n if (block.length === 0) {\n Object.defineProperty(target, name, {\n get: getters.block0(block)\n });\n } else {\n target[name] = getters.blockN(block);\n }\n } else {\n Object.defineProperty(target, name, {\n get: getters.basic(query)\n });\n }\n};\n\nNamedScope.prototype.compile = function (model) {\n var allScopes = this.scopesByName\n , scope;\n for (var k in allScopes) {\n scope = allScopes[k];\n scope.decorate(model, {\n block0: function (block) {\n return function () {\n var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));\n block.call(cquery);\n return this;\n };\n },\n blockN: function (block) {\n return function () {\n var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));\n block.apply(cquery, arguments);\n return this;\n };\n },\n basic: function (query) {\n return function () {\n var cquery = this._cumulativeQuery || (this._cumulativeQuery = new Query().bind(this));\n cquery.find(query);\n return this;\n };\n }\n });\n }\n};\n\nmodule.exports = NamedScope;\n\n});","sourceLength":1762,"scriptType":2,"compilationType":0,"context":{"ref":12},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/namedscope.js (lines: 72)"}],"refs":[{"handle":12,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":595,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[482]}}
{"seq":337,"request_seq":595,"type":"response","command":"scripts","success":true,"body":[{"handle":15,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schemadefault.js","id":482,"lineOffset":0,"columnOffset":0,"lineCount":36,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar Schema = require('./schema')\n\n/**\n * Default model for querying the system.profiles collection.\n *\n * @property system.profile\n * @receiver exports\n * @api private\n */\n\nexports['system.profile'] = new Schema({\n ts: Date\n , info: String // deprecated\n , millis: Number\n , op: String\n , ns: String\n , query: Schema.Types.Mixed\n , updateobj: Schema.Types.Mixed\n , ntoreturn: Number\n , nreturned: Number\n , nscanned: Number\n , responseLength: Number\n , client: String\n , user: String\n , idhack: Boolean\n , scanAndOrder: Boolean\n , keyUpdates: Number\n , cursorid: Number\n}, { noVirtualId: true, noId: true });\n\n});","sourceLength":728,"scriptType":2,"compilationType":0,"context":{"ref":14},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/schemadefault.js (lines: 36)"}],"refs":[{"handle":14,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":596,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[485]}}
{"seq":338,"request_seq":596,"type":"response","command":"scripts","success":true,"body":[{"handle":17,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/model.js","id":485,"lineOffset":0,"columnOffset":0,"lineCount":2182,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar Document = require('./document')\n , MongooseArray = require('./types/array')\n , MongooseBuffer = require('./types/buffer')\n , MongooseError = require('./error')\n , VersionError = MongooseError.VersionError\n , DivergentArrayError = MongooseError.DivergentArrayError\n , Query = require('./query')\n , Schema = require('./schema')\n , Types = require('./schema/index')\n , utils = require('./utils')\n , hasOwnProperty = utils.object.hasOwnProperty\n , isMongooseObject = utils.isMongooseObject\n , EventEmitter = require('events').EventEmitter\n , merge = utils.merge\n , Promise = require('./promise')\n , assert = require('assert')\n , tick = utils.tick\n\nvar VERSION_WHERE = 1\n , VERSION_INC = 2\n , VERSION_ALL = VERSION_WHERE | VERSION_INC;\n\n/**\n * Model constructor\n *\n * @param {Object} doc values to with which to create the document\n * @inherits Document\n * @event `error`: If listening to this Model event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model.\n * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event.\n * @api public\n */\n\nfunction Model (doc, fields, skipId) {\n Document.call(this, doc, fields, skipId);\n};\n\n/*!\n * Inherits from Document.\n *\n * All Model.prototype features are available on\n * top level (non-sub) documents.\n */\n\nModel.prototype.__proto__ = Document.prototype;\n\n/**\n * Connection the model uses.\n *\n * @api public\n * @property db\n */\n\nModel.prototype.db;\n\n/**\n * Collection the model uses.\n *\n * @api public\n * @property collection\n */\n\nModel.prototype.collection;\n\n/**\n * The name of the model\n *\n * @api public\n * @property modelName\n */\n\nModel.prototype.modelName;\n\n/*!\n * Handles doc.save() callbacks\n */\n\nfunction handleSave (promise, self) {\n return tick(function handleSave (err, result) {\n if (err) {\n // If the initial insert fails provide a second chance.\n // (If we did this all the time we would break updates)\n if (self.$__.inserting) {\n self.isNew = true;\n self.emit('isNew', true);\n }\n promise.error(err);\n promise = self = null;\n return;\n }\n\n self.$__storeShard();\n\n var numAffected;\n if (result) {\n // when inserting, the array of created docs is returned\n numAffected = result.length\n ? result.length\n : result;\n } else {\n numAffected = 0;\n }\n\n // was this an update that required a version bump?\n if (self.$__.version && !self.$__.inserting) {\n var doIncrement = VERSION_INC === (VERSION_INC & self.$__.version);\n self.$__.version = undefined;\n\n // increment version if was successful\n if (numAffected > 0) {\n if (doIncrement) {\n var key = self.schema.options.versionKey;\n var version = self.getValue(key) | 0;\n self.setValue(key, version + 1);\n }\n } else {\n // the update failed. pass an error back\n promise.error(new VersionError);\n promise = self = null;\n return;\n }\n }\n\n self.emit('save', self, numAffected);\n promise.complete(self, numAffected);\n promise = self = null;\n });\n}\n\n/**\n * Saves this document.\n *\n * ####Example:\n *\n * product.sold = Date.now();\n * product.save(function (err, product) {\n * if (err) ..\n * })\n *\n * The `fn` callback is optional. If no `fn` is passed and validation fails, the validation error will be emitted on the connection used to create this model.\n *\n * var db = mongoose.createConnection(..);\n * var schema = new Schema(..);\n * var Product = db.model('Product', schema);\n *\n * db.on('error', handleError);\n *\n * However, if you desire more local error handling you can add an `error` listener to the model and handle errors there instead.\n *\n * Product.on('error', handleError);\n *\n * @param {Function} [fn] optional callback\n * @api public\n * @see middleware http://mongoosejs.com/docs/middleware.html\n */\n\nModel.prototype.save = function save (fn) {\n var promise = new Promise(fn)\n , complete = handleSave(promise, this)\n , options = {}\n\n if (this.schema.options.safe) {\n options.safe = this.schema.options.safe;\n }\n\n if (this.isNew) {\n // send entire doc\n var obj = this.toObject({ depopulate: 1 });\n this.$__version(true, obj);\n this.collection.insert(obj, options, complete);\n this.$__reset();\n this.isNew = false;\n this.emit('isNew', false);\n // Make it possible to retry the insert\n this.$__.inserting = true;\n\n } else {\n // Make sure we don't treat it as a new object on error,\n // since it already exists\n this.$__.inserting = false;\n\n var delta = this.$__delta();\n if (delta) {\n if (delta instanceof Error) return complete(delta);\n var where = this.$__where(delta[0]);\n this.$__reset();\n this.collection.update(where, delta[1], options, complete);\n } else {\n this.$__reset();\n complete(null);\n }\n\n this.emit('isNew', false);\n }\n};\n\n/*!\n * Apply the operation to the delta (update) clause as\n * well as track versioning for our where clause.\n *\n * @param {Document} self\n * @param {Object} where\n * @param {Object} delta\n * @param {Object} data\n * @param {Mixed} val\n * @param {String} [operation]\n */\n\nfunction operand (self, where, delta, data, val, op) {\n // delta\n op || (op = '$set');\n if (!delta[op]) delta[op] = {};\n delta[op][data.path] = val;\n\n // disabled versioning?\n if (false === self.schema.options.versionKey) return;\n\n // already marked for versioning?\n if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return;\n\n switch (op) {\n case '$set':\n case '$unset':\n case '$pop':\n case '$pull':\n case '$pullAll':\n case '$push':\n case '$pushAll':\n case '$addToSet':\n break;\n default:\n // nothing to do\n return;\n }\n\n // ensure updates sent with positional notation are\n // editing the correct array element.\n // only increment the version if an array position changes.\n // modifying elements of an array is ok if position does not change.\n\n if ('$push' == op || '$pushAll' == op || '$addToSet' == op) {\n self.$__.version = VERSION_INC;\n }\n else if (/^\\$p/.test(op)) {\n // potentially changing array positions\n self.increment();\n }\n else if (Array.isArray(val)) {\n // $set an array\n self.increment();\n }\n // now handling $set, $unset\n else if (/\\.\\d+/.test(data.path)) {\n // subpath of array\n self.$__.version = VERSION_WHERE;\n }\n}\n\n/*!\n * Compiles an update and where clause for a `val` with _atomics.\n *\n * @param {Document} self\n * @param {Object} where\n * @param {Object} delta\n * @param {Object} data\n * @param {Array} value\n */\n\nfunction handleAtomics (self, where, delta, data, value) {\n if (delta.$set && delta.$set[data.path]) {\n // $set has precedence over other atomics\n return;\n }\n\n if ('function' == typeof value.$__getAtomics) {\n value.$__getAtomics().forEach(function (atomic) {\n var op = atomic[0];\n var val = atomic[1];\n operand(self, where, delta, data, val, op);\n })\n return;\n }\n\n // legacy support for plugins\n\n var atomics = value._atomics\n , ops = Object.keys(atomics)\n , i = ops.length\n , val\n , op;\n\n if (0 === i) {\n // $set\n\n if (isMongooseObject(value)) {\n value = value.toObject({ depopulate: 1 });\n } else if (value.valueOf) {\n value = value.valueOf();\n }\n\n return operand(self, where, delta, data, value);\n }\n\n while (i--) {\n op = ops[i];\n val = atomics[op];\n\n if (isMongooseObject(val)) {\n val = val.toObject({ depopulate: 1 })\n } else if (Array.isArray(val)) {\n val = val.map(function (mem) {\n return isMongooseObject(mem)\n ? mem.toObject({ depopulate: 1 })\n : mem;\n })\n } else if (val.valueOf) {\n val = val.valueOf()\n }\n\n if ('$addToSet' === op)\n val = { $each: val };\n\n operand(self, where, delta, data, val, op);\n }\n}\n\n/**\n * Produces a special query document of the modified properties used in updates.\n *\n * @api private\n * @method $__delta\n * @memberOf Model\n */\n\nModel.prototype.$__delta = function () {\n var dirty = this.$__dirty();\n if (!dirty.length) return;\n\n var where = {}\n , delta = {}\n , len = dirty.length\n , divergent = []\n , d = 0\n , val\n , obj\n\n for (; d < len; ++d) {\n var data = dirty[d]\n var value = data.value\n var schema = data.schema\n\n var match = checkDivergentArray(this, data.path, value);\n if (match) {\n divergent.push(match);\n continue;\n }\n\n if (divergent.length) continue;\n\n if (undefined === value) {\n operand(this, where, delta, data, 1, '$unset');\n\n } else if (null === value) {\n operand(this, where, delta, data, null);\n\n } else if (value._path && value._atomics) {\n // arrays and other custom types (support plugins etc)\n handleAtomics(this, where, delta, data, value);\n\n } else if (value._path && Buffer.isBuffer(value)) {\n // MongooseBuffer\n value = value.toObject();\n operand(this, where, delta, data, value);\n\n } else {\n value = utils.clone(value, { convertToId: 1 });\n operand(this, where, delta, data, value);\n }\n }\n\n if (divergent.length) {\n return new DivergentArrayError(divergent);\n }\n\n if (this.$__.version) {\n this.$__version(where, delta);\n }\n\n return [where, delta];\n}\n\n/*!\n * Determine if array was populated with some form of filter and is now\n * being updated in a manner which could overwrite data unintentionally.\n *\n * @see https://github.com/LearnBoost/mongoose/issues/1334\n * @param {Document} doc\n * @param {String} path\n * @return {String|undefined}\n */\n\nfunction checkDivergentArray (doc, path, array) {\n // see if we populated this path\n var pop = doc.populated(path, true);\n\n if (!pop && doc.$__.selected) {\n // If any array was selected using an $elemMatch projection, we deny the update.\n // NOTE: MongoDB only supports projected $elemMatch on top level array.\n var top = path.split('.')[0];\n if (doc.$__.selected[top] && doc.$__.selected[top].$elemMatch) {\n return top;\n }\n }\n\n if (!(pop && array instanceof MongooseArray)) return;\n\n // If the array was populated using options that prevented all\n // documents from being returned (match, skip, limit) or they\n // deselected the _id field, $pop and $set of the array are\n // not safe operations. If _id was deselected, we do not know\n // how to remove elements. $pop will pop off the _id from the end\n // of the array in the db which is not guaranteed to be the\n // same as the last element we have here. $set of the entire array\n // would be similarily destructive as we never received all\n // elements of the array and potentially would overwrite data.\n var check = pop.options.match ||\n pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted\n pop.options.options && pop.options.options.skip || // 0 is permitted\n pop.options.select && // deselected _id?\n (0 === pop.options.select._id ||\n /\\s?-_id\\s?/.test(pop.options.select))\n\n if (check) {\n var atomics = array._atomics;\n if (0 === Object.keys(atomics).length || atomics.$set || atomics.$pop) {\n return path;\n }\n }\n}\n\n/**\n * Appends versioning to the where and update clauses.\n *\n * @api private\n * @method $__version\n * @memberOf Model\n */\n\nModel.prototype.$__version = function (where, delta) {\n var key = this.schema.options.versionKey;\n\n if (true === where) {\n // this is an insert\n if (key) this.setValue(key, delta[key] = 0);\n return;\n }\n\n // updates\n\n // only apply versioning if our versionKey was selected. else\n // there is no way to select the correct version. we could fail\n // fast here and force them to include the versionKey but\n // thats a bit intrusive. can we do this automatically?\n if (!this.isSelected(key)) {\n return;\n }\n\n // $push $addToSet don't need the where clause set\n if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) {\n where[key] = this.getValue(key);\n }\n\n if (VERSION_INC === (VERSION_INC & this.$__.version)) {\n delta.$inc || (delta.$inc = {});\n delta.$inc[key] = 1;\n }\n}\n\n/**\n * Signal that we desire an increment of this documents version.\n *\n * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey\n * @api public\n */\n\nModel.prototype.increment = function increment () {\n this.$__.version = VERSION_ALL;\n return this;\n}\n\n/**\n * Returns a query object which applies shardkeys if they exist.\n *\n * @api private\n * @method $__where\n * @memberOf Model\n */\n\nModel.prototype.$__where = function _where (where) {\n where || (where = {});\n\n var paths\n , len\n\n if (this.$__.shardval) {\n paths = Object.keys(this.$__.shardval)\n len = paths.length\n\n for (var i = 0; i < len; ++i) {\n where[paths[i]] = this.$__.shardval[paths[i]];\n }\n }\n\n where._id = this._doc._id;\n return where;\n}\n\n/**\n * Removes this document from the db.\n *\n * ####Example:\n *\n * product.remove(function (err, product) {\n * if (err) return handleError(err);\n * Product.findById(product._id, function (err, product) {\n * console.log(product) // null\n * })\n * })\n *\n * @param {Function} [fn] optional callback\n * @api public\n */\n\nModel.prototype.remove = function remove (fn) {\n if (this.$__.removing) {\n this.$__.removing.addBack(fn);\n return this;\n }\n\n var promise = this.$__.removing = new Promise(fn)\n , where = this.$__where()\n , self = this\n , options = {}\n\n if (this.schema.options.safe) {\n options.safe = this.schema.options.safe;\n }\n\n this.collection.remove(where, options, tick(function (err) {\n if (err) {\n promise.error(err);\n promise = self = self.$__.removing = where = options = null;\n return;\n }\n self.emit('remove', self);\n promise.complete();\n promise = self = where = options = null;\n }));\n\n return this;\n};\n\n/**\n * Returns another Model instance.\n *\n * ####Example:\n *\n * var doc = new Tank;\n * doc.model('User').findById(id, callback);\n *\n * @param {String} name model name\n * @api public\n */\n\nModel.prototype.model = function model (name) {\n return this.db.model(name);\n};\n\n// Model (class) features\n\n/*!\n * Give the constructor the ability to emit events.\n */\n\nfor (var i in EventEmitter.prototype)\n Model[i] = EventEmitter.prototype[i];\n\n/**\n * Called when the model compiles.\n *\n * @api private\n */\n\nModel.init = function init () {\n if (this.schema.options.autoIndex) {\n this.ensureIndexes();\n }\n\n this.schema.emit('init', this);\n};\n\n/**\n * Sends `ensureIndex` commands to mongo for each index declared in the schema.\n *\n * ####Example:\n *\n * Event.ensureIndexes(function (err) {\n * if (err) return handleError(err);\n * });\n *\n * After completion, an `index` event is emitted on this `Model` passing an error if one occurred.\n *\n * ####Example:\n *\n * var eventSchema = new Schema({ thing: { type: 'string', unique: true }})\n * var Event = mongoose.model('Event', eventSchema);\n *\n * Event.on('index', function (err) {\n * if (err) console.error(err); // error occurred during index creation\n * })\n *\n * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._\n *\n * The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/LearnBoost/mongoose/issues/1365) for more information.\n *\n * @param {Function} [cb] optional callback\n * @api public\n */\n\nModel.ensureIndexes = function ensureIndexes (cb) {\n var indexes = this.schema.indexes();\n if (!indexes.length) {\n return cb && process.nextTick(cb);\n }\n\n // Indexes are created one-by-one to support how MongoDB < 2.4 deals\n // with background indexes.\n\n var self = this\n , safe = self.schema.options.safe\n\n function done (err) {\n self.emit('index', err);\n cb && cb(err);\n }\n\n function create () {\n var index = indexes.shift();\n if (!index) return done();\n\n var options = index[1];\n options.safe = safe;\n self.collection.ensureIndex(index[0], options, tick(function (err) {\n if (err) return done(err);\n create();\n }));\n }\n\n create();\n}\n\n/**\n * Schema the model uses.\n *\n * @property schema\n * @receiver Model\n * @api public\n */\n\nModel.schema;\n\n/*!\n * Connection instance the model uses.\n *\n * @property db\n * @receiver Model\n * @api public\n */\n\nModel.db;\n\n/*!\n * Collection the model uses.\n *\n * @property collection\n * @receiver Model\n * @api public\n */\n\nModel.collection;\n\n/**\n * Base Mongoose instance the model uses.\n *\n * @property base\n * @receiver Model\n * @api public\n */\n\nModel.base;\n\n/**\n * Removes documents from the collection.\n *\n * ####Example:\n *\n * Comment.remove({ title: 'baby born from alien father' }, function (err) {\n *\n * });\n *\n * ####Note:\n *\n * To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js):\n *\n * var query = Comment.remove({ _id: id });\n * query.exec();\n *\n * ####Note:\n *\n * This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_.\n *\n * @param {Object} conditions\n * @param {Function} [callback]\n * @return {Query}\n * @api public\n */\n\nModel.remove = function remove (conditions, callback) {\n if ('function' === typeof conditions) {\n callback = conditions;\n conditions = {};\n }\n\n var query = new Query(conditions).bind(this, 'remove');\n\n if ('undefined' === typeof callback)\n return query;\n\n this._applyNamedScope(query);\n return query.remove(callback);\n};\n\n/**\n * Finds documents\n *\n * The `conditions` are cast to their respective SchemaTypes before the command is sent.\n *\n * ####Examples:\n *\n * // named john and at least 18\n * MyModel.find({ name: 'john', age: { $gte: 18 }});\n *\n * // executes immediately, passing results to callback\n * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});\n *\n * // name LIKE john and only selecting the \"name\" and \"friends\" fields, executing immediately\n * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })\n *\n * // passing options\n * MyModel.find({ name: /john/i }, null, { skip: 10 })\n *\n * // passing options and executing immediately\n * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});\n *\n * // executing a query explicitly\n * var query = MyModel.find({ name: /john/i }, null, { skip: 10 })\n * query.exec(function (err, docs) {});\n *\n * // using the promise returned from executing a query\n * var query = MyModel.find({ name: /john/i }, null, { skip: 10 });\n * var promise = query.exec();\n * promise.addBack(function (err, docs) {});\n *\n * @param {Object} conditions\n * @param {Object} [fields] optional fields to select\n * @param {Object} [options] optional\n * @param {Function} [callback]\n * @return {Query}\n * @see field selection #query_Query-select\n * @see promise #promise-js\n * @api public\n */\n\nModel.find = function find (conditions, fields, options, callback) {\n if ('function' == typeof conditions) {\n callback = conditions;\n conditions = {};\n fields = null;\n options = null;\n } else if ('function' == typeof fields) {\n callback = fields;\n fields = null;\n options = null;\n } else if ('function' == typeof options) {\n callback = options;\n options = null;\n }\n\n var query = new Query(conditions, options);\n query.bind(this, 'find');\n query.select(fields);\n\n if ('undefined' === typeof callback)\n return query;\n\n this._applyNamedScope(query);\n return query.find(callback);\n};\n\n/**\n * Merges the current named scope query into `query`.\n *\n * @param {Query} query\n * @return {Query}\n * @api private\n */\n\nModel._applyNamedScope = function _applyNamedScope (query) {\n var cQuery = this._cumulativeQuery;\n\n if (cQuery) {\n merge(query._conditions, cQuery._conditions);\n if (query._fields && cQuery._fields)\n merge(query._fields, cQuery._fields);\n if (query.options && cQuery.options)\n merge(query.options, cQuery.options);\n delete this._cumulativeQuery;\n }\n\n return query;\n}\n\n/**\n * Finds a single document by id.\n *\n * The `id` is cast based on the Schema before sending the command.\n *\n * ####Example:\n *\n * // find adventure by id and execute immediately\n * Adventure.findById(id, function (err, adventure) {});\n *\n * // same as above\n * Adventure.findById(id).exec(callback);\n *\n * // select only the adventures name and length\n * Adventure.findById(id, 'name length', function (err, adventure) {});\n *\n * // same as above\n * Adventure.findById(id, 'name length').exec(callback);\n *\n * // include all properties except for `length`\n * Adventure.findById(id, '-length').exec(function (err, adventure) {});\n *\n * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean`\n * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});\n *\n * // same as above\n * Adventure.findById(id, 'name').lean().exec(function (err, doc) {});\n *\n * @param {ObjectId|HexId} id objectid, or a value that can be casted to one\n * @param {Object} [fields] optional fields to select\n * @param {Object} [options] optional\n * @param {Function} [callback]\n * @return {Query}\n * @see field selection #query_Query-select\n * @see lean queries #query_Query-lean\n * @api public\n */\n\nModel.findById = function findById (id, fields, options, callback) {\n return this.findOne({ _id: id }, fields, options, callback);\n};\n\n/**\n * Finds one document.\n *\n * The `conditions` are cast to their respective SchemaTypes before the command is sent.\n *\n * ####Example:\n *\n * // find one iphone adventures - iphone adventures??\n * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});\n *\n * // same as above\n * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});\n *\n * // select only the adventures name\n * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});\n *\n * // same as above\n * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});\n *\n * // specify options, in this case lean\n * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);\n *\n * // same as above\n * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);\n *\n * // chaining findOne queries (same as above)\n * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);\n *\n * @param {Object} conditions\n * @param {Object} [fields] optional fields to select\n * @param {Object} [options] optional\n * @param {Function} [callback]\n * @return {Query}\n * @see field selection #query_Query-select\n * @see lean queries #query_Query-lean\n * @api public\n */\n\nModel.findOne = function findOne (conditions, fields, options, callback) {\n if ('function' == typeof options) {\n callback = options;\n options = null;\n } else if ('function' == typeof fields) {\n callback = fields;\n fields = null;\n options = null;\n } else if ('function' == typeof conditions) {\n callback = conditions;\n conditions = {};\n fields = null;\n options = null;\n }\n\n var query = new Query(conditions, options).select(fields).bind(this, 'findOne');\n\n if ('undefined' == typeof callback)\n return query;\n\n this._applyNamedScope(query);\n return query.findOne(callback);\n};\n\n/**\n * Counts number of matching documents in a database collection.\n *\n * ####Example:\n *\n * Adventure.count({ type: 'jungle' }, function (err, count) {\n * if (err) ..\n * console.log('there are %d jungle adventures', count);\n * });\n *\n * @param {Object} conditions\n * @param {Function} [callback]\n * @return {Query}\n * @api public\n */\n\nModel.count = function count (conditions, callback) {\n if ('function' === typeof conditions)\n callback = conditions, conditions = {};\n\n var query = new Query(conditions).bind(this, 'count');\n if ('undefined' == typeof callback)\n return query;\n\n this._applyNamedScope(query);\n return query.count(callback);\n};\n\n/**\n * Executes a DISTINCT command\n *\n * @param {String} field\n * @param {Object} [conditions] optional\n * @param {Function} [callback]\n * @return {Query}\n * @api public\n */\n\nModel.distinct = function distinct (field, conditions, callback) {\n var query = new Query(conditions).bind(this, 'distinct');\n if ('undefined' == typeof callback) {\n query._distinctArg = field;\n return query;\n }\n\n this._applyNamedScope(query);\n return query.distinct(field, callback);\n};\n\n/**\n * Creates a Query, applies the passed conditions, and returns the Query.\n *\n * For example, instead of writing:\n *\n * User.find({age: {$gte: 21, $lte: 65}}, callback);\n *\n * we can instead write:\n *\n * User.where('age').gte(21).lte(65).exec(callback);\n *\n * Since the Query class also supports `where` you can continue chaining\n *\n * User\n * .where('age').gte(21).lte(65)\n * .where('name', /^b/i)\n * ... etc\n *\n * @param {String} path\n * @param {Object} [val] optional value\n * @return {Query}\n * @api public\n */\n\nModel.where = function where (path, val) {\n var q = new Query().bind(this, 'find');\n return q.where.apply(q, arguments);\n};\n\n/**\n * Creates a `Query` and specifies a `$where` condition.\n *\n * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.\n *\n * Blog.$where('this.comments.length > 5').exec(function (err, docs) {});\n *\n * @param {String|Function} argument is a javascript string or anonymous function\n * @method $where\n * @memberOf Model\n * @return {Query}\n * @see Query.$where #query_Query-%24where\n * @api public\n */\n\nModel.$where = function $where () {\n var q = new Query().bind(this, 'find');\n return q.$where.apply(q, arguments);\n};\n\n/**\n * Issues a mongodb findAndModify update command.\n *\n * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned.\n *\n * ####Options:\n *\n * - `new`: bool - true to return the modified document rather than the original. defaults to true\n * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.\n * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update\n * - `select`: sets the document fields to return\n *\n * ####Examples:\n *\n * A.findOneAndUpdate(conditions, update, options, callback) // executes\n * A.findOneAndUpdate(conditions, update, options) // returns Query\n * A.findOneAndUpdate(conditions, update, callback) // executes\n * A.findOneAndUpdate(conditions, update) // returns Query\n * A.findOneAndUpdate() // returns Query\n *\n * ####Note:\n *\n * All top level update keys which are not `atomic` operation names are treated as set operations:\n *\n * ####Example:\n *\n * var query = { name: 'borne' };\n * Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback)\n *\n * // is sent as\n * Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback)\n *\n * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`.\n *\n * ####Note:\n *\n * Although values are cast to their appropriate types when using the findAndModify helpers, the following are *not* applied:\n *\n * - defaults\n * - setters\n * - validators\n * - middleware\n *\n * If you need those features, use the traditional approach of first retrieving the document.\n *\n * Model.findOne({ name: 'borne' }, function (err, doc) {\n * if (err) ..\n * doc.name = 'jason borne';\n * doc.save(callback);\n * })\n *\n * @param {Object} [conditions]\n * @param {Object} [update]\n * @param {Object} [options]\n * @param {Function} [callback]\n * @return {Query}\n * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command\n * @api public\n */\n\nModel.findOneAndUpdate = function (conditions, update, options, callback) {\n if ('function' == typeof options) {\n callback = options;\n options = null;\n }\n else if (1 === arguments.length) {\n if ('function' == typeof conditions) {\n var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\\n\\n'\n + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\\n'\n + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\\n'\n + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\\n'\n + ' ' + this.modelName + '.findOneAndUpdate(update)\\n'\n + ' ' + this.modelName + '.findOneAndUpdate()\\n';\n throw new TypeError(msg)\n }\n update = conditions;\n conditions = undefined;\n }\n\n var fields;\n if (options && options.fields) {\n fields = options.fields;\n options.fields = undefined;\n }\n\n var query = new Query(conditions);\n query.setOptions(options);\n query.select(fields);\n query.bind(this, 'findOneAndUpdate', update);\n\n if ('undefined' == typeof callback)\n return query;\n\n this._applyNamedScope(query);\n return query.findOneAndUpdate(callback);\n}\n\n/**\n * Issues a mongodb findAndModify update command by a documents id.\n *\n * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned.\n *\n * ####Options:\n *\n * - `new`: bool - true to return the modified document rather than the original. defaults to true\n * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.\n * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update\n * - `select`: sets the document fields to return\n *\n * ####Examples:\n *\n * A.findByIdAndUpdate(id, update, options, callback) // executes\n * A.findByIdAndUpdate(id, update, options) // returns Query\n * A.findByIdAndUpdate(id, update, callback) // executes\n * A.findByIdAndUpdate(id, update) // returns Query\n * A.findByIdAndUpdate() // returns Query\n *\n * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned.\n *\n * ####Options:\n *\n * - `new`: bool - true to return the modified document rather than the original. defaults to true\n * - `upsert`: bool - creates the object if it doesn't exist. defaults to false.\n * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update\n *\n * ####Note:\n *\n * All top level update keys which are not `atomic` operation names are treated as set operations:\n *\n * ####Example:\n *\n * Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback)\n *\n * // is sent as\n * Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback)\n *\n * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`.\n *\n * ####Note:\n *\n * Although values are cast to their appropriate types when using the findAndModify helpers, the following are *not* applied:\n *\n * - defaults\n * - setters\n * - validators\n * - middleware\n *\n * If you need those features, use the traditional approach of first retrieving the document.\n *\n * Model.findById(id, function (err, doc) {\n * if (err) ..\n * doc.name = 'jason borne';\n * doc.save(callback);\n * })\n *\n * @param {ObjectId|HexId} id an ObjectId or string that can be cast to one.\n * @param {Object} [update]\n * @param {Object} [options]\n * @param {Function} [callback]\n * @return {Query}\n * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate\n * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command\n * @api public\n */\n\nModel.findByIdAndUpdate = function (id, update, options, callback) {\n var args;\n\n if (1 === arguments.length) {\n if ('function' == typeof id) {\n var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\\n\\n'\n + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\\n'\n + ' ' + this.modelName + '.findByIdAndUpdate(id)\\n'\n + ' ' + this.modelName + '.findByIdAndUpdate()\\n';\n throw new TypeError(msg)\n }\n return this.findOneAndUpdate({_id: id }, undefined);\n }\n\n args = utils.args(arguments, 1);\n args.unshift({ _id: id });\n return this.findOneAndUpdate.apply(this, args);\n}\n\n/**\n * Issue a mongodb findAndModify remove command.\n *\n * Finds a matching document, removes it, passing the found document (if any) to the callback.\n *\n * Executes immediately if `callback` is passed else a Query object is returned.\n *\n * ####Options:\n *\n * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update\n * - `select`: sets the document fields to return\n *\n * ####Examples:\n *\n * A.findOneAndRemove(conditions, options, callback) // executes\n * A.findOneAndRemove(conditions, options) // return Query\n * A.findOneAndRemove(conditions, callback) // executes\n * A.findOneAndRemove(conditions) // returns Query\n * A.findOneAndRemove() // returns Query\n *\n * @param {Object} conditions\n * @param {Object} [options]\n * @param {Function} [callback]\n * @return {Query}\n * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command\n * @api public\n */\n\nModel.findOneAndRemove = function (conditions, options, callback) {\n if (1 === arguments.length && 'function' == typeof conditions) {\n var msg = 'Model.findOneAndRemove(): First argument must not be a function.\\n\\n'\n + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\\n'\n + ' ' + this.modelName + '.findOneAndRemove(conditions)\\n'\n + ' ' + this.modelName + '.findOneAndRemove()\\n';\n throw new TypeError(msg)\n }\n\n if ('function' == typeof options) {\n callback = options;\n options = undefined;\n }\n\n var fields;\n if (options) {\n fields = options.select;\n options.select = undefined;\n }\n\n var query = new Query(conditions);\n query.setOptions(options);\n query.select(fields);\n query.bind(this, 'findOneAndRemove');\n\n if ('undefined' == typeof callback)\n return query;\n\n this._applyNamedScope(query);\n return query.findOneAndRemove(callback);\n}\n\n/**\n * Issue a mongodb findAndModify remove command by a documents id.\n *\n * Finds a matching document, removes it, passing the found document (if any) to the callback.\n *\n * Executes immediately if `callback` is passed, else a `Query` object is returned.\n *\n * ####Options:\n *\n * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update\n * - `select`: sets the document fields to return\n *\n * ####Examples:\n *\n * A.findByIdAndRemove(id, options, callback) // executes\n * A.findByIdAndRemove(id, options) // return Query\n * A.findByIdAndRemove(id, callback) // executes\n * A.findByIdAndRemove(id) // returns Query\n * A.findByIdAndRemove() // returns Query\n *\n * @param {ObjectId|HexString} id ObjectId or string that can be cast to one\n * @param {Object} [options]\n * @param {Function} [callback]\n * @return {Query}\n * @see Model.findOneAndRemove #model_Model.findOneAndRemove\n * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command\n */\n\nModel.findByIdAndRemove = function (id, options, callback) {\n if (1 === arguments.length && 'function' == typeof id) {\n var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\\n\\n'\n + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\\n'\n + ' ' + this.modelName + '.findByIdAndRemove(id)\\n'\n + ' ' + this.modelName + '.findByIdAndRemove()\\n';\n throw new TypeError(msg)\n }\n\n return this.findOneAndRemove({ _id: id }, options, callback);\n}\n\n/**\n * Shortcut for creating a new Document that is automatically saved to the db if valid.\n *\n * ####Example:\n *\n * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {\n * if (err) // ...\n * });\n *\n * var array = [{ type: 'jelly bean' }, { type: 'snickers' }];\n * Candy.create(array, function (err, jellybean, snickers) {\n * if (err) // ...\n * });\n *\n * @param {Array|Object...} doc\n * @param {Function} fn callback\n * @api public\n */\n\nModel.create = function create (doc, fn) {\n if (1 === arguments.length) {\n return 'function' === typeof doc && doc(null);\n }\n\n var self = this\n , docs = [null]\n , promise\n , count\n , args\n\n if (Array.isArray(doc)) {\n args = doc;\n } else {\n args = utils.args(arguments, 0, arguments.length - 1);\n fn = arguments[arguments.length - 1];\n }\n\n if (0 === args.length) return fn(null);\n\n promise = new Promise(fn);\n count = args.length;\n\n args.forEach(function (arg, i) {\n var doc = new self(arg);\n docs[i+1] = doc;\n doc.save(function (err) {\n if (err) return promise.error(err);\n --count || fn.apply(null, docs);\n });\n });\n};\n\n/**\n * Updates documents in the database without returning them.\n *\n * ####Examples:\n *\n * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);\n * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, numberAffected, raw) {\n * if (err) return handleError(err);\n * console.log('The number of updated documents was %d', numberAffected);\n * console.log('The raw response from Mongo was ', raw);\n * });\n *\n * ####Valid options:\n *\n * - `safe` (boolean) safe mode (defaults to value set in schema (true))\n * - `upsert` (boolean) whether to create the doc if it doesn't match (false)\n * - `multi` (boolean) whether multiple documents should be updated (false)\n * - `strict` (boolean) overrides the `strict` option for this update\n *\n * All `update` values are cast to their appropriate SchemaTypes before being sent.\n *\n * The `callback` function receives `(err, numberAffected, rawResponse)`.\n *\n * - `err` is the error if any occurred\n * - `numberAffected` is the count of updated documents Mongo reported\n * - `rawResponse` is the full response from Mongo\n *\n * ####Note:\n *\n * All top level keys which are not `atomic` operation names are treated as set operations:\n *\n * ####Example:\n *\n * var query = { name: 'borne' };\n * Model.update(query, { name: 'jason borne' }, options, callback)\n *\n * // is sent as\n * Model.update(query, { $set: { name: 'jason borne' }}, options, callback)\n *\n * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason borne' }`.\n *\n * ####Note:\n *\n * To update documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js):\n *\n * Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec();\n *\n * ####Note:\n *\n * Although values are casted to their appropriate types when using update, the following are *not* applied:\n *\n * - defaults\n * - setters\n * - validators\n * - middleware\n *\n * If you need those features, use the traditional approach of first retrieving the document.\n *\n * Model.findOne({ name: 'borne' }, function (err, doc) {\n * if (err) ..\n * doc.name = 'jason borne';\n * doc.save(callback);\n * })\n *\n * @see strict schemas http://mongoosejs.com/docs/guide.html#strict\n * @param {Object} conditions\n * @param {Object} update\n * @param {Object} [options]\n * @param {Function} [callback]\n * @return {Query}\n * @api public\n */\n\nModel.update = function update (conditions, doc, options, callback) {\n if (arguments.length < 4) {\n if ('function' === typeof options) {\n // Scenario: update(conditions, doc, callback)\n callback = options;\n options = null;\n } else if ('function' === typeof doc) {\n // Scenario: update(doc, callback);\n callback = doc;\n doc = conditions;\n conditions = {};\n options = null;\n }\n }\n\n var query = new Query(conditions, options).bind(this, 'update', doc);\n\n if ('undefined' == typeof callback)\n return query;\n\n this._applyNamedScope(query);\n return query.update(doc, callback);\n};\n\n/**\n * Executes a mapReduce command.\n *\n * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation.\n *\n * ####Example:\n *\n * var o = {};\n * o.map = function () { emit(this.name, 1) }\n * o.reduce = function (k, vals) { return vals.length }\n * User.mapReduce(o, function (err, results) {\n * console.log(results)\n * })\n *\n * ####Other options:\n *\n * - `query` {Object} query filter object.\n * - `limit` {Number} max number of documents\n * - `keeptemp` {Boolean, default:false} keep temporary data\n * - `finalize` {Function} finalize function\n * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution\n * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X\n * - `verbose` {Boolean, default:false} provide statistics on job execution time.\n * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job.\n *\n * ####* out options:\n *\n * - `{inline:1}` the results are returned in an array\n * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection\n * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions\n * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old\n *\n * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).\n *\n * ####Example:\n *\n * var o = {};\n * o.map = function () { emit(this.name, 1) }\n * o.reduce = function (k, vals) { return vals.length }\n * o.out = { replace: 'createdCollectionNameForResults' }\n * o.verbose = true;\n * User.mapReduce(o, function (err, model, stats) {\n * console.log('map reduce took %d ms', stats.processtime)\n * model.find().where('value').gt(10).exec(function (err, docs) {\n * console.log(docs);\n * });\n * })\n *\n * @param {Object} o an object specifying map-reduce options\n * @param {Function} callback\n * @see http://www.mongodb.org/display/DOCS/MapReduce\n * @api public\n */\n\nModel.mapReduce = function mapReduce (o, callback) {\n if ('function' != typeof callback) throw new Error('missing callback');\n\n var self = this;\n\n if (!Model.mapReduce.schema) {\n var opts = { noId: true, noVirtualId: true, strict: false }\n Model.mapReduce.schema = new Schema({}, opts);\n }\n\n if (!o.out) o.out = { inline: 1 };\n\n o.map = String(o.map);\n o.reduce = String(o.reduce);\n\n if (o.query) {\n var q = new Query(o.query);\n q.cast(this);\n o.query = q._conditions;\n q = undefined;\n }\n\n this.collection.mapReduce(null, null, o, function (err, ret, stats) {\n if (err) return callback(err);\n\n if (ret.findOne && ret.mapReduce) {\n // returned a collection, convert to Model\n var model = Model.compile(\n '_mapreduce_' + ret.collectionName\n , Model.mapReduce.schema\n , ret.collectionName\n , self.db\n , self.base);\n\n model._mapreduce = true;\n\n return callback(err, model, stats);\n }\n\n callback(err, ret, stats);\n });\n}\n\n/**\n * Executes an aggregate command on this models collection.\n *\n * ####Example:\n *\n * // find the max age of all users\n * Users.aggregate(\n * { $group: { _id: null, maxAge: { $max: '$age' }}}\n * , { $project: { _id: 0, maxAge: 1 }}\n * , function (err, res) {\n * if (err) return handleError(err);\n * console.log(res); // [ { maxAge: 98 } ]\n * });\n *\n * ####NOTE:\n *\n * - At this time, arguments are not cast to the schema because $project operators allow redefining the \"shape\" of the documents at any stage of the pipeline.\n * - The documents returned are plain javascript objects, not mongoose documents cast to this models schema definition (since any shape of document can be returned).\n * - Requires MongoDB >= 2.1\n *\n * @param {Array} array an array of pipeline commands\n * @param {Object} [options]\n * @param {Function} callback\n * @see aggregation http://docs.mongodb.org/manual/applications/aggregation/\n * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate\n * @api public\n */\n\nModel.aggregate = function aggregate () {\n return this.collection.aggregate.apply(this.collection, arguments);\n}\n\n/**\n * Populates document references.\n *\n * ####Available options:\n *\n * - path: space delimited path(s) to populate\n * - select: optional fields to select\n * - match: optional query conditions to match\n * - model: optional name of the model to use for population\n * - options: optional query options like sort, limit, etc\n *\n * ####Examples:\n *\n * // populates a single object\n * User.findById(id, function (err, user) {\n * var opts = [\n * { path: 'company', match: { x: 1 }, select: 'name' }\n * , { path: 'notes', options: { limit: 10 }, model: 'override' }\n * ]\n *\n * User.populate(user, opts, function (err, user) {\n * console.log(user);\n * })\n * })\n *\n * // populates an array of objects\n * User.find(match, function (err, users) {\n * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]\n *\n * User.populate(users, opts, function (err, user) {\n * console.log(user);\n * })\n * })\n *\n * // imagine a Weapon model exists with two saved documents:\n * // { _id: 389, name: 'whip' }\n * // { _id: 8921, name: 'boomerang' }\n *\n * var user = { name: 'Indiana Jones', weapon: 389 }\n * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {\n * console.log(user.weapon.name) // whip\n * })\n *\n * // populate many plain objects\n * var users = [{ name: 'Indiana Jones', weapon: 389 }]\n * users.push({ name: 'Batman', weapon: 8921 })\n * Weapon.populate(users, { path: 'weapon' }, function (err, users) {\n * users.forEach(function (user) {\n * console.log('%s uses a %s', users.name, user.weapon.name)\n * // Indiana Jones uses a whip\n * // Batman uses a boomerang\n * })\n * })\n * // Note that we didn't need to specify the Weapon model because\n * // we were already using it's populate() method.\n *\n * @param {Document|Array} docs Either a single document or array of documents to populate.\n * @param {Object} options A hash of key/val (path, options) used for population.\n * @param {Function} cb(err,doc) A callback, executed upon completion. Receives `err` and the `doc(s)`.\n * @api public\n */\n\nModel.populate = function (docs, paths, cb) {\n assert.equal('function', typeof cb);\n\n // always callback on nextTick for consistent async behavior\n function callback () {\n var args = utils.args(arguments);\n process.nextTick(function () {\n cb.apply(null, args);\n });\n }\n\n // normalized paths\n var paths = utils.populate(paths);\n var pending = paths.length;\n\n if (0 === pending) {\n return callback(null, docs);\n }\n\n // each path has its own query options and must be executed separately\n var i = pending;\n var path;\n while (i--) {\n path = paths[i];\n populate(this, docs, path, next);\n }\n\n function next (err) {\n if (next.err) return;\n if (err) return callback(next.err = err);\n if (--pending) return;\n callback(null, docs);\n }\n}\n\n/*!\n * Populates `docs`\n */\n\nfunction populate (model, docs, options, cb) {\n var select = options.select\n , match = options.match\n , path = options.path\n\n var schema = model._getSchema(path);\n var subpath;\n\n // handle document arrays\n if (schema && schema.caster) {\n schema = schema.caster;\n }\n\n // model name for the populate query\n var modelName = options.model && options.model.modelName\n || options.model // query options\n || schema && schema.options.ref // declared in schema\n || model.modelName // an ad-hoc structure\n\n var Model = model.db.model(modelName);\n\n // expose the model used\n options.model = Model;\n\n // normalize single / multiple docs passed\n if (!Array.isArray(docs)) {\n docs = [docs];\n }\n\n if (0 === docs.length || docs.every(utils.isNullOrUndefined)) {\n return cb();\n }\n\n // get all ids for all docs for a given path\n var rawIds = docs.map(function (doc) {\n if (!doc) return doc;\n\n var isDocument = !! doc.$__;\n var ret;\n\n if (isDocument && !doc.isModified(path)) {\n // it is possible a previously populated path is being\n // populated again. because users can specify matcher\n // clauses in their populate arguments we use the cached\n // _ids from the original populate call to ensure all _ids\n // are looked up, but only if the path wasn't modified which\n // signifies the users intent of the state of the path.\n ret = doc.populated(path);\n }\n\n if (!ret || Array.isArray(ret) && 0 === ret.length) {\n ret = utils.getValue(path, doc);\n }\n\n options._docs[doc._id] = Array.isArray(ret)\n ? ret.slice()\n : ret;\n\n if (isDocument) {\n // cache original populated _ids and model used\n doc.populated(path, options._docs[doc._id], options);\n }\n\n return ret;\n });\n\n var ids = utils.array.flatten(rawIds, function (item) {\n // no need to include undefined values in our query\n return undefined !== item;\n });\n\n if (0 === ids.length || ids.every(utils.isNullOrUndefined)) {\n return cb();\n }\n\n // preserve original match conditions by copying\n if (match) {\n match = utils.object.shallowCopy(match);\n } else {\n match = {};\n }\n\n match._id || (match._id = { $in: ids });\n\n var assignmentOpts = {};\n assignmentOpts.sort = options.options && options.options.sort || undefined;\n assignmentOpts.excludeId = /\\s?-_id\\s?/.test(select) || (select && 0 === select._id);\n\n if (assignmentOpts.excludeId) {\n // override the exclusion from the query so we can use the _id\n // for document matching during assignment. we'll delete the\n // _id back off before returning the result.\n if ('string' == typeof select) {\n select = null;\n } else {\n // preserve original select conditions by copying\n select = utils.object.shallowCopy(select);\n delete select._id;\n }\n }\n\n Model.find(match, select, options.options, function (err, vals) {\n if (err) return cb(err);\n\n assignVals({\n rawIds: rawIds\n , rawDocs: vals\n , docs: docs\n , path: path\n , options: assignmentOpts\n })\n\n cb();\n });\n}\n\n/*!\n * Assigns documents returned from a population query back\n * to the original document path.\n */\n\nfunction assignVals (opts) {\n var rawIds = opts.rawIds;\n var rawDocs = opts.rawDocs;\n var docs = opts.docs;\n var path = opts.path;\n var options = opts.options;\n\n assignRawDocsToIdStructure(rawIds, rawDocs, options);\n\n for (var i = 0; i < docs.length; ++i) {\n utils.setValue(path, rawIds[i], docs[i], function (val) {\n return valueFilter(val, options);\n });\n }\n}\n\n/*!\n * 1) Apply backwards compatible find/findOne behavior to sub documents\n *\n * find logic:\n * a) filter out non-documents\n * b) remove _id from sub docs when user specified\n *\n * findOne\n * a) if no doc found, set to null\n * b) remove _id from sub docs when user specified\n *\n * 2) Remove _ids when specified by users query.\n *\n * background:\n * _ids are left in the query even when user excludes them so\n * that population mapping can occur.\n */\n\nfunction valueFilter (val, assignmentOpts) {\n if (Array.isArray(val)) {\n // find logic\n var ret = [];\n for (var i = 0; i < val.length; ++i) {\n var subdoc = val[i];\n if (!isDoc(subdoc)) continue;\n maybeRemoveId(subdoc, assignmentOpts);\n ret.push(subdoc);\n }\n return ret;\n }\n\n // findOne\n if (isDoc(val)) {\n maybeRemoveId(val, assignmentOpts);\n return val;\n }\n return null;\n}\n\n/*!\n * Remove _id from `subdoc` if user specified \"lean\" query option\n */\n\nfunction maybeRemoveId (subdoc, assignmentOpts) {\n if (assignmentOpts.excludeId) {\n if ('function' == typeof subdoc.setValue) {\n subdoc.setValue('_id', undefined);\n } else {\n delete subdoc._id;\n }\n }\n}\n\n/*!\n * Determine if `doc` is a document returned\n * by a populate query.\n */\n\nfunction isDoc (doc) {\n if (null == doc)\n return false;\n\n var type = typeof doc;\n if ('string' == type)\n return false;\n\n if ('number' == type)\n return false;\n\n if (Buffer.isBuffer(doc))\n return false;\n\n if ('ObjectID' == doc.constructor.name)\n return false;\n\n // only docs\n return true;\n}\n\n/*!\n * Assign `vals` returned by mongo query to the `rawIds`\n * structure returned from utils.getVals() honoring\n * query sort order if specified by user.\n *\n * This can be optimized.\n *\n * Rules:\n *\n * if the value of the path is not an array, use findOne rules, else find.\n * for findOne the results are assigned directly to doc path (including null results).\n * for find, if user specified sort order, results are assigned directly\n * else documents are put back in original order of array if found in results\n *\n * @param {Array} rawIds\n * @param {Array} vals\n * @param {Boolean} sort\n * @api private\n */\n\nfunction assignRawDocsToIdStructure (rawIds, vals, options, recursed) {\n // honor user specified sort order\n var newOrder = [];\n var sorting = options.sort && rawIds.length > 1;\n var found;\n var doc;\n var sid;\n var id;\n\n for (var i = 0; i < rawIds.length; ++i) {\n id = rawIds[i];\n\n if (Array.isArray(id)) {\n // handle [ [id0, id2], [id3] ]\n assignRawDocsToIdStructure(id, vals, options, true);\n newOrder.push(id);\n continue;\n }\n\n if (null === id && !sorting) {\n // keep nulls for findOne unless sorting, which always\n // removes them (backward compat)\n newOrder.push(id);\n continue;\n }\n\n sid = String(id);\n found = false;\n\n if (recursed) {\n // apply find behavior\n\n // assign matching documents in original order unless sorting\n for (var f = 0; f < vals.length; ++f) {\n if (sid == String(vals[f]._id)) {\n found = true;\n if (sorting) {\n newOrder[f] = vals[f];\n } else {\n newOrder.push(vals[f]);\n }\n break;\n }\n }\n\n if (!found) {\n newOrder.push(id);\n }\n\n } else {\n // apply findOne behavior - if document in results, assign, else assign null\n\n doc = null;\n for (var f = 0; f < vals.length; ++f) {\n if (sid == String(vals[f]._id)) {\n doc = vals[f];\n break;\n }\n }\n\n newOrder[i] = doc;\n }\n }\n\n rawIds.length = 0;\n if (newOrder.length) {\n // reassign the documents based on corrected order\n\n // forEach skips over sparse entries in arrays so we\n // can safely use this to our advantage dealing with sorted\n // result sets too.\n newOrder.forEach(function (doc, i) {\n rawIds[i] = doc;\n });\n }\n}\n\n/**\n * Finds the schema for `path`. This is different than\n * calling `schema.path` as it also resolves paths with\n * positional selectors (something.$.another.$.path).\n *\n * @param {String} path\n * @return {Schema}\n * @api private\n */\n\nModel._getSchema = function _getSchema (path) {\n var schema = this.schema\n , pathschema = schema.path(path);\n\n if (pathschema)\n return pathschema;\n\n // look for arrays\n return (function search (parts, schema) {\n var p = parts.length + 1\n , foundschema\n , trypath\n\n while (p--) {\n trypath = parts.slice(0, p).join('.');\n foundschema = schema.path(trypath);\n if (foundschema) {\n if (foundschema.caster) {\n\n // array of Mixed?\n if (foundschema.caster instanceof Types.Mixed) {\n return foundschema.caster;\n }\n\n // Now that we found the array, we need to check if there\n // are remaining document paths to look up for casting.\n // Also we need to handle array.$.path since schema.path\n // doesn't work for that.\n if (p !== parts.length) {\n if ('$' === parts[p]) {\n // comments.$.comments.$.title\n return search(parts.slice(p+1), foundschema.schema);\n } else {\n // this is the last path of the selector\n return search(parts.slice(p), foundschema.schema);\n }\n }\n }\n return foundschema;\n }\n }\n })(path.split('.'), schema)\n}\n\n/*!\n * Compiler utility.\n *\n * @param {String} name model name\n * @param {Schema} schema\n * @param {String} collectionName\n * @param {Connection} connection\n * @param {Mongoose} base mongoose instance\n */\n\nModel.compile = function compile (name, schema, collectionName, connection, base) {\n var versioningEnabled = false !== schema.options.versionKey;\n\n if (versioningEnabled && !schema.paths[schema.options.versionKey]) {\n // add versioning to top level documents only\n var o = {};\n o[schema.options.versionKey] = Number;\n schema.add(o);\n }\n\n // generate new class\n function model (doc, fields, skipId) {\n if (!(this instanceof model))\n return new model(doc, fields, skipId);\n Model.call(this, doc, fields, skipId);\n };\n\n model.base = base;\n model.modelName = name;\n model.__proto__ = Model;\n model.prototype.__proto__ = Model.prototype;\n model.model = Model.prototype.model;\n model.db = model.prototype.db = connection;\n\n model.prototype.$__setSchema(schema);\n\n var collectionOptions = {\n bufferCommands: schema.options.bufferCommands\n , capped: schema.options.capped\n };\n\n model.prototype.collection = connection.collection(\n collectionName\n , collectionOptions\n );\n\n // apply methods\n for (var i in schema.methods)\n model.prototype[i] = schema.methods[i];\n\n // apply statics\n for (var i in schema.statics)\n model[i] = schema.statics[i];\n\n // apply named scopes\n if (schema.namedScopes) schema.namedScopes.compile(model);\n\n model.schema = model.prototype.schema;\n model.options = model.prototype.options;\n model.collection = model.prototype.collection;\n\n return model;\n};\n\n/*!\n * Subclass this model with `conn`, `schema`, and `collection` settings.\n *\n * @param {Connection} conn\n * @param {Schema} [schema]\n * @param {String} [collection]\n * @return {Model}\n */\n\nModel.__subclass = function subclass (conn, schema, collection) {\n // subclass model using this connection and collection name\n var model = this;\n\n var Model = function Model (doc, fields, skipId) {\n if (!(this instanceof Model)) {\n return new Model(doc, fields, skipId);\n }\n model.call(this, doc, fields, skipId);\n }\n\n Model.__proto__ = model;\n Model.prototype.__proto__ = model.prototype;\n Model.db = Model.prototype.db = conn;\n\n var s = 'string' != typeof schema\n ? schema\n : model.prototype.schema;\n\n if (!collection) {\n collection = model.prototype.schema.get('collection')\n || utils.toCollectionName(model.modelName);\n }\n\n var collectionOptions = {\n bufferCommands: s ? s.options.bufferCommands : true\n , capped: s && s.options.capped\n };\n\n Model.prototype.collection = conn.collection(collection, collectionOptions);\n Model.collection = Model.prototype.collection;\n Model.init();\n return Model;\n}\n\n/*!\n * Module exports.\n */\n\nmodule.exports = exports = Model;\n\n});","sourceLength":60806,"scriptType":2,"compilationType":0,"context":{"ref":16},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/model.js (lines: 2182)"}],"refs":[{"handle":16,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":597,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[488]}}
{"seq":339,"request_seq":597,"type":"response","command":"scripts","success":true,"body":[{"handle":19,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js","id":488,"lineOffset":0,"columnOffset":0,"lineCount":301,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar MongooseConnection = require('../../connection')\n , mongo = require('mongodb')\n , Server = mongo.Server\n , STATES = require('../../connectionstate')\n , ReplSetServers = mongo.ReplSetServers;\n\n/**\n * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation.\n *\n * @inherits Connection\n * @api private\n */\n\nfunction NativeConnection() {\n MongooseConnection.apply(this, arguments);\n this._listening = false;\n};\n\n/*!\n * Inherits from Connection.\n */\n\nNativeConnection.prototype.__proto__ = MongooseConnection.prototype;\n\n/**\n * Opens the connection to MongoDB.\n *\n * @param {Function} fn\n * @return {Connection} this\n * @api private\n */\n\nNativeConnection.prototype.doOpen = function (fn) {\n if (this.db) {\n mute(this);\n }\n\n var server = new mongo.Server(this.host, this.port, this.options.server);\n this.db = new mongo.Db(this.name, server, this.options.db);\n\n var self = this;\n this.db.open(function (err) {\n if (err) return fn(err);\n listen(self);\n fn();\n });\n\n return this;\n};\n\n/*!\n * Register listeners for important events and bubble appropriately.\n */\n\nfunction listen (conn) {\n if (conn._listening) return;\n conn._listening = true;\n\n conn.db.on('close', function(){\n if (conn._closeCalled) return;\n\n // the driver never emits an `open` event. auto_reconnect still\n // emits a `close` event but since we never get another\n // `open` we can't emit close\n if (conn.db.serverConfig.autoReconnect) {\n conn.readyState = STATES.disconnected;\n conn.emit('close');\n return;\n }\n conn.onClose();\n });\n conn.db.on('error', function(err){\n conn.emit('error', err);\n });\n conn.db.on('timeout', function(err){\n var error = new Error(err && err.err || 'connection timeout');\n conn.emit('error', error);\n });\n conn.db.on('open', function (err, db) {\n if (STATES.disconnected === conn.readyState && db && db.databaseName) {\n conn.readyState = STATES.connected;\n conn.emit('reconnected')\n }\n })\n}\n\n/*!\n * Remove listeners registered in `listen`\n */\n\nfunction mute (conn) {\n if (!conn.db) throw new Error('missing db');\n conn.db.removeAllListeners(\"close\");\n conn.db.removeAllListeners(\"error\");\n conn.db.removeAllListeners(\"timeout\");\n conn.db.removeAllListeners(\"open\");\n conn.db.removeAllListeners(\"fullsetup\");\n conn._listening = false;\n}\n\n/**\n * Opens a connection to a MongoDB ReplicaSet.\n *\n * See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers.\n *\n * @param {Function} fn\n * @api private\n * @return {Connection} this\n */\n\nNativeConnection.prototype.doOpenSet = function (fn) {\n if (this.db) {\n mute(this);\n }\n\n var servers = []\n , self = this;\n\n this.hosts.forEach(function (server) {\n var host = server.host || server.ipc;\n var port = server.port || 27017;\n servers.push(new mongo.Server(host, port, self.options.server));\n })\n\n var server = new ReplSetServers(servers, this.options.replset);\n this.db = new mongo.Db(this.name, server, this.options.db);\n\n this.db.on('fullsetup', function () {\n self.emit('fullsetup')\n });\n\n this.db.open(function (err) {\n if (err) return fn(err);\n fn();\n listen(self);\n });\n\n return this;\n};\n\n/**\n * Closes the connection\n *\n * @param {Function} fn\n * @return {Connection} this\n * @api private\n */\n\nNativeConnection.prototype.doClose = function (fn) {\n this.db.close();\n if (fn) fn();\n return this;\n}\n\n/**\n * Prepares default connection options for the node-mongodb-native driver.\n *\n * _NOTE: `passed` options take precedence over connection string options._\n *\n * @param {Object} passed options that were passed directly during connection\n * @param {Object} [connStrOptions] options that were passed in the connection string\n * @api private\n */\n\nNativeConnection.prototype.parseOptions = function (passed, connStrOpts) {\n var o = passed || {};\n o.db || (o.db = {});\n o.auth || (o.auth = {});\n o.server || (o.server = {});\n o.replset || (o.replset = {});\n o.server.socketOptions || (o.server.socketOptions = {});\n o.replset.socketOptions || (o.replset.socketOptions = {});\n\n var opts = connStrOpts || {};\n Object.keys(opts).forEach(function (name) {\n switch (name) {\n case 'poolSize':\n if ('undefined' == typeof o.server.poolSize) {\n o.server.poolSize = o.replset.poolSize = opts[name];\n }\n break;\n case 'slaveOk':\n if ('undefined' == typeof o.server.slave_ok) {\n o.server.slave_ok = opts[name];\n }\n break;\n case 'autoReconnect':\n if ('undefined' == typeof o.server.auto_reconnect) {\n o.server.auto_reconnect = opts[name];\n }\n break;\n case 'ssl':\n case 'socketTimeoutMS':\n case 'connectTimeoutMS':\n if ('undefined' == typeof o.server.socketOptions[name]) {\n o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name];\n }\n break;\n case 'authdb':\n if ('undefined' == typeof o.auth.authdb) {\n o.auth.authdb = opts[name];\n }\n break;\n case 'authSource':\n if ('undefined' == typeof o.auth.authSource) {\n o.auth.authSource = opts[name];\n }\n break;\n case 'retries':\n case 'reconnectWait':\n case 'rs_name':\n if ('undefined' == typeof o.replset[name]) {\n o.replset[name] = opts[name];\n }\n break;\n case 'replicaSet':\n if ('undefined' == typeof o.replset.rs_name) {\n o.replset.rs_name = opts[name];\n }\n break;\n case 'readSecondary':\n if ('undefined' == typeof o.replset.read_secondary) {\n o.replset.read_secondary = opts[name];\n }\n break;\n case 'nativeParser':\n if ('undefined' == typeof o.db.native_parser) {\n o.db.native_parser = opts[name];\n }\n break;\n case 'w':\n case 'safe':\n case 'fsync':\n case 'journal':\n case 'wtimeoutMS':\n if ('undefined' == typeof o.db[name]) {\n o.db[name] = opts[name];\n }\n break;\n case 'readPreference':\n if ('undefined' == typeof o.db.read_preference) {\n o.db.read_preference = opts[name];\n }\n break;\n case 'readPreferenceTags':\n if ('undefined' == typeof o.db.read_preference_tags) {\n o.db.read_preference_tags = opts[name];\n }\n break;\n }\n })\n\n if (!('auto_reconnect' in o.server)) {\n o.server.auto_reconnect = true;\n }\n\n if (!o.db.read_preference) {\n // read from primaries by default\n o.db.read_preference = 'primary';\n }\n\n // mongoose creates its own ObjectIds\n o.db.forceServerObjectId = false;\n\n // default safe using new nomenclature\n if (!('journal' in o.db || 'j' in o.db ||\n 'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) {\n o.db.w = 1;\n }\n\n validate(o);\n return o;\n}\n\n/*!\n * Validates the driver db options.\n *\n * @param {Object} o\n */\n\nfunction validate (o) {\n if (-1 === o.db.w || 0 === o.db.w) {\n if (o.db.journal || o.db.fsync || o.db.safe) {\n throw new Error(\n 'Invalid writeConcern: '\n + 'w set to -1 or 0 cannot be combined with safe|fsync|journal');\n }\n }\n}\n\n/*!\n * Module exports.\n */\n\nmodule.exports = NativeConnection;\n\n});","sourceLength":7453,"scriptType":2,"compilationType":0,"context":{"ref":18},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js (lines: 301)"}],"refs":[{"handle":18,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":598,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[491]}}
{"seq":340,"request_seq":598,"type":"response","command":"scripts","success":true,"body":[{"handle":21,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/connection.js","id":491,"lineOffset":0,"columnOffset":0,"lineCount":708,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Module dependencies.\n */\n\nvar url = require('url')\n , utils = require('./utils')\n , EventEmitter = require('events').EventEmitter\n , driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'\n , Model = require('./model')\n , Schema = require('./schema')\n , Collection = require(driver + '/collection')\n , STATES = require('./connectionstate')\n , MongooseError = require('./error')\n , assert =require('assert')\n , muri = require('muri')\n\n/*!\n * Protocol prefix regexp.\n *\n * @api private\n */\n\nvar rgxProtocol = /^(?:.)+:\\/\\//;\n\n/**\n * Connection constructor\n *\n * For practical reasons, a Connection equals a Db.\n *\n * @param {Mongoose} base a mongoose instance\n * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter\n * @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection.\n * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.\n * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models.\n * @event `disconnecting`: Emitted when `connection.close()` was executed.\n * @event `disconnected`: Emitted after getting disconnected from the db.\n * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models.\n * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection.\n * @event `error`: Emitted when an error occurs on this connection.\n * @event `fullsetup`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.\n * @api public\n */\n\nfunction Connection (base) {\n this.base = base;\n this.collections = {};\n this.models = {};\n this.replica = false;\n this.hosts = null;\n this.host = null;\n this.port = null;\n this.user = null;\n this.pass = null;\n this.name = null;\n this.options = null;\n this._readyState = STATES.disconnected;\n this._closeCalled = false;\n this._hasOpened = false;\n};\n\n/*!\n * Inherit from EventEmitter\n */\n\nConnection.prototype.__proto__ = EventEmitter.prototype;\n\n/**\n * Connection ready state\n *\n * - 0 = disconnected\n * - 1 = connected\n * - 2 = connecting\n * - 3 = disconnecting\n *\n * Each state change emits its associated event name.\n *\n * ####Example\n *\n * conn.on('connected', callback);\n * conn.on('disconnected', callback);\n *\n * @property readyState\n * @api public\n */\n\nObject.defineProperty(Connection.prototype, 'readyState', {\n get: function(){ return this._readyState; }\n , set: function (val) {\n if (!(val in STATES)) {\n throw new Error('Invalid connection state: ' + val);\n }\n\n if (this._readyState !== val) {\n this._readyState = val;\n\n if (STATES.connected === val)\n this._hasOpened = true;\n\n this.emit(STATES[val]);\n }\n }\n});\n\n/**\n * A hash of the collections associated with this connection\n *\n * @property collections\n */\n\nConnection.prototype.collections;\n\n/**\n * The mongodb.Db instance, set when the connection is opened\n *\n * @property db\n */\n\nConnection.prototype.db;\n\n/**\n * Opens the connection to MongoDB.\n *\n * `options` is a hash with the following possible properties:\n *\n * db - passed to the connection db instance\n * server - passed to the connection server instance(s)\n * replset - passed to the connection ReplSet instance\n * user - username for authentication\n * pass - password for authentication\n * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)\n *\n * ####Notes:\n *\n * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.\n * Mongoose defaults the server `auto_reconnect` options to true which can be overridden.\n * See the node-mongodb-native driver instance for options that it understands.\n *\n * _Options passed take precedence over options included in connection strings._\n *\n * @param {String} connection_string mongodb://uri or the host to which you are connecting\n * @param {String} [database] database name\n * @param {Number} [port] database port\n * @param {Object} [options] options\n * @param {Function} [callback]\n * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native\n * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate\n * @api public\n */\n\nConnection.prototype.open = function (host, database, port, options, callback) {\n var self = this\n , parsed\n , uri;\n\n if ('string' === typeof database) {\n switch (arguments.length) {\n case 2:\n port = 27017;\n case 3:\n switch (typeof port) {\n case 'function':\n callback = port, port = 27017;\n break;\n case 'object':\n options = port, port = 27017;\n break;\n }\n break;\n case 4:\n if ('function' === typeof options)\n callback = options, options = {};\n }\n } else {\n switch (typeof database) {\n case 'function':\n callback = database, database = undefined;\n break;\n case 'object':\n options = database;\n database = undefined;\n callback = port;\n break;\n }\n\n if (!rgxProtocol.test(host)) {\n host = 'mongodb://' + host;\n }\n\n try {\n parsed = muri(host);\n } catch (err) {\n this.error(err, callback);\n return this;\n }\n\n database = parsed.db;\n host = parsed.hosts[0].host || parsed.hosts[0].ipc;\n port = parsed.hosts[0].port || 27017;\n }\n\n this.options = this.parseOptions(options, parsed && parsed.options);\n\n // make sure we can open\n if (STATES.disconnected !== this.readyState) {\n var err = new Error('Trying to open unclosed connection.');\n err.state = this.readyState;\n this.error(err, callback);\n return this;\n }\n\n if (!host) {\n this.error(new Error('Missing hostname.'), callback);\n return this;\n }\n\n if (!database) {\n this.error(new Error('Missing database name.'), callback);\n return this;\n }\n\n // authentication\n if (options && options.user && options.pass) {\n this.user = options.user;\n this.pass = options.pass;\n\n } else if (parsed && parsed.auth) {\n this.user = parsed.auth.user;\n this.pass = parsed.auth.pass;\n\n // Check hostname for user/pass\n } else if (/@/.test(host) && /:/.test(host.split('@')[0])) {\n host = host.split('@');\n var auth = host.shift().split(':');\n host = host.pop();\n this.user = auth[0];\n this.pass = auth[1];\n\n } else {\n this.user = this.pass = undefined;\n }\n\n this.name = database;\n this.host = host;\n this.port = port;\n\n this._open(callback);\n return this;\n};\n\n/**\n * Opens the connection to a replica set.\n *\n * ####Example:\n *\n * var db = mongoose.createConnection();\n * db.openSet(\"mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019\");\n *\n * The database name and/or auth need only be included in one URI.\n * The `options` is a hash which is passed to the internal driver connection object.\n *\n * Valid `options`\n *\n * db - passed to the connection db instance\n * server - passed to the connection server instance(s)\n * replset - passed to the connection ReplSetServer instance\n * user - username for authentication\n * pass - password for authentication\n * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)\n *\n * _Options passed take precedence over options included in connection strings._\n *\n * ####Notes:\n *\n * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden.\n * Mongoose defaults the server `auto_reconnect` options to true which can be overridden.\n * See the node-mongodb-native driver instance for options that it understands.\n *\n * @param {String} uris comma-separated mongodb:// `URI`s\n * @param {String} [database] database name if not included in `uris`\n * @param {Object} [options] passed to the internal driver\n * @param {Function} [callback]\n * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native\n * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate\n * @api public\n */\n\nConnection.prototype.openSet = function (uris, database, options, callback) {\n if (!rgxProtocol.test(uris)) {\n uris = 'mongodb://' + uris;\n }\n\n var self = this;\n\n switch (arguments.length) {\n case 3:\n switch (typeof database) {\n case 'string':\n this.name = database;\n break;\n case 'object':\n callback = options;\n options = database;\n database = null;\n break;\n }\n\n if ('function' === typeof options) {\n callback = options;\n options = {};\n }\n break;\n case 2:\n switch (typeof database) {\n case 'string':\n this.name = database;\n break;\n case 'function':\n callback = database, database = null;\n break;\n case 'object':\n options = database, database = null;\n break;\n }\n }\n\n var parsed;\n try {\n parsed = muri(uris);\n } catch (err) {\n this.error(err, callback);\n return this;\n }\n\n if (!this.name) {\n this.name = parsed.db;\n }\n\n this.hosts = parsed.hosts;\n this.options = this.parseOptions(options, parsed && parsed.options);\n this.replica = true;\n\n if (!this.name) {\n this.error(new Error('No database name provided for replica set'), callback);\n return this;\n }\n\n // authentication\n if (options && options.user && options.pass) {\n this.user = options.user;\n this.pass = options.pass;\n\n } else if (parsed && parsed.auth) {\n this.user = parsed.auth.user;\n this.pass = parsed.auth.pass;\n\n } else {\n this.user = this.pass = undefined;\n }\n\n this._open(callback);\n return this;\n};\n\n/**\n * error\n *\n * Graceful error handling, passes error to callback\n * if available, else emits error on the connection.\n *\n * @param {Error} err\n * @param {Function} callback optional\n * @api private\n */\n\nConnection.prototype.error = function (err, callback) {\n if (callback) return callback(err);\n this.emit('error', err);\n}\n\n/**\n * Handles opening the connection with the appropriate method based on connection type.\n *\n * @param {Function} callback\n * @api private\n */\n\nConnection.prototype._open = function (callback) {\n this.readyState = STATES.connecting;\n this._closeCalled = false;\n\n var self = this;\n\n var method = this.replica\n ? 'doOpenSet'\n : 'doOpen';\n\n // open connection\n this[method](function (err) {\n if (err) {\n self.readyState = STATES.disconnected;\n if (self._hasOpened) {\n if (callback) callback(err);\n } else {\n self.error(err, callback);\n }\n return;\n }\n\n self.onOpen(callback);\n });\n}\n\n/**\n * Called when the connection is opened\n *\n * @api private\n */\n\nConnection.prototype.onOpen = function (callback) {\n var self = this;\n\n function open (err) {\n if (err) {\n self.readyState = STATES.disconnected;\n if (self._hasOpened) {\n if (callback) callback(err);\n } else {\n self.error(err, callback);\n }\n return;\n }\n\n self.readyState = STATES.connected;\n\n // avoid having the collection subscribe to our event emitter\n // to prevent 0.3 warning\n for (var i in self.collections)\n self.collections[i].onOpen();\n\n callback && callback();\n self.emit('open');\n };\n\n // re-authenticate\n if (self.user && self.pass) {\n self.db.authenticate(self.user, self.pass, self.options.auth, open);\n }\n else\n open();\n};\n\n/**\n * Closes the connection\n *\n * @param {Function} [callback] optional\n * @return {Connection} self\n * @api public\n */\n\nConnection.prototype.close = function (callback) {\n var self = this;\n this._closeCalled = true;\n\n switch (this.readyState){\n case 0: // disconnected\n callback && callback();\n break;\n\n case 1: // connected\n this.readyState = STATES.disconnecting;\n this.doClose(function(err){\n if (err){\n self.error(err, callback);\n } else {\n self.onClose();\n callback && callback();\n }\n });\n break;\n\n case 2: // connecting\n this.once('open', function(){\n self.close(callback);\n });\n break;\n\n case 3: // disconnecting\n if (!callback) break;\n this.once('close', function () {\n callback();\n });\n break;\n }\n\n return this;\n};\n\n/**\n * Called when the connection closes\n *\n * @api private\n */\n\nConnection.prototype.onClose = function () {\n this.readyState = STATES.disconnected;\n\n // avoid having the collection subscribe to our event emitter\n // to prevent 0.3 warning\n for (var i in this.collections)\n this.collections[i].onClose();\n\n this.emit('close');\n};\n\n/**\n * Retrieves a collection, creating it if not cached.\n *\n * Not typically needed by applications. Just talk to your collection through your model.\n *\n * @param {String} name of the collection\n * @param {Object} [options] optional collection options\n * @return {Collection} collection instance\n * @api public\n */\n\nConnection.prototype.collection = function (name, options) {\n if (!(name in this.collections))\n this.collections[name] = new Collection(name, this, options);\n return this.collections[name];\n};\n\n/**\n * Defines or retrieves a model.\n *\n * var mongoose = require('mongoose');\n * var db = mongoose.createConnection(..);\n * db.model('Venue', new Schema(..));\n * var Ticket = db.model('Ticket', new Schema(..));\n * var Venue = db.model('Venue');\n *\n * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._\n *\n * ####Example:\n *\n * var schema = new Schema({ name: String }, { collection: 'actor' });\n *\n * // or\n *\n * schema.set('collection', 'actor');\n *\n * // or\n *\n * var collectionName = 'actor'\n * var M = conn.model('Actor', schema, collectionName)\n *\n * @param {String} name the model name\n * @param {Schema} [schema] a schema. necessary when defining a model\n * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name\n * @see Mongoose#model #index_Mongoose-model\n * @return {Model} The compiled model\n * @api public\n */\n\nConnection.prototype.model = function (name, schema, collection) {\n // collection name discovery\n if ('string' == typeof schema) {\n collection = schema;\n schema = false;\n }\n\n if (utils.isObject(schema) && !(schema instanceof Schema)) {\n schema = new Schema(schema);\n }\n\n if (this.models[name] && !collection) {\n // model exists but we are not subclassing with custom collection\n if (schema instanceof Schema && schema != this.models[name].schema) {\n throw new MongooseError.OverwriteModelError(name);\n }\n return this.models[name];\n }\n\n var opts = { cache: false, connection: this }\n var model;\n\n if (schema instanceof Schema) {\n // compile a model\n model = this.base.model(name, schema, collection, opts)\n\n // only the first model with this name is cached to allow\n // for one-offs with custom collection names etc.\n if (!this.models[name]) {\n this.models[name] = model;\n }\n\n model.init();\n return model;\n }\n\n if (this.models[name] && collection) {\n // subclassing current model with alternate collection\n model = this.models[name];\n schema = model.prototype.schema;\n var sub = model.__subclass(this, schema, collection);\n // do not cache the sub model\n return sub;\n }\n\n // lookup model in mongoose module\n model = this.base.models[name];\n\n if (!model) {\n throw new MongooseError.MissingSchemaError(name);\n }\n\n if (this == model.prototype.db\n && (!collection || collection == model.collection.name)) {\n // model already uses this connection.\n\n // only the first model with this name is cached to allow\n // for one-offs with custom collection names etc.\n if (!this.models[name]) {\n this.models[name] = model;\n }\n\n return model;\n }\n\n return this.models[name] = model.__subclass(this, schema, collection);\n}\n\n/**\n * Returns an array of model names created on this connection.\n * @api public\n * @return {Array}\n */\n\nConnection.prototype.modelNames = function () {\n return Object.keys(this.models);\n}\n\n/**\n * Set profiling level.\n *\n * @param {Number|String} level either off (0), slow (1), or all (2)\n * @param {Number} [ms] the threshold in milliseconds above which queries will be logged when in `slow` mode. defaults to 100.\n * @param {Function} callback\n * @api public\n */\n\nConnection.prototype.setProfiling = function (level, ms, callback) {\n if (STATES.connected !== this.readyState) {\n return this.on('open', this.setProfiling.bind(this, level, ms, callback));\n }\n\n if (!callback) callback = ms, ms = 100;\n\n var cmd = {};\n\n switch (level) {\n case 0:\n case 'off':\n cmd.profile = 0;\n break;\n case 1:\n case 'slow':\n cmd.profile = 1;\n if ('number' !== typeof ms) {\n ms = parseInt(ms, 10);\n if (isNaN(ms)) ms = 100;\n }\n cmd.slowms = ms;\n break;\n case 2:\n case 'all':\n cmd.profile = 2;\n break;\n default:\n return callback(new Error('Invalid profiling level: '+ level));\n }\n\n this.db.executeDbCommand(cmd, function (err, resp) {\n if (err) return callback(err);\n\n var doc = resp.documents[0];\n\n err = 1 === doc.ok\n ? null\n : new Error('Could not set profiling level to: '+ level)\n\n callback(err, doc);\n });\n};\n\n/*!\n * Noop.\n */\n\nfunction noop () {}\n\n/*!\n * Module exports.\n */\n\nConnection.STATES = STATES;\nmodule.exports = Connection;\n\n});","sourceLength":18139,"scriptType":2,"compilationType":0,"context":{"ref":20},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/connection.js (lines: 708)"}],"refs":[{"handle":20,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":599,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[494]}}
{"seq":341,"request_seq":599,"type":"response","command":"scripts","success":true,"body":[{"handle":23,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js","id":494,"lineOffset":0,"columnOffset":0,"lineCount":213,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar MongooseCollection = require('../../collection')\n , Collection = require('mongodb').Collection\n , STATES = require('../../connectionstate')\n , utils = require('../../utils')\n\n/**\n * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation.\n *\n * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management.\n *\n * @inherits Collection\n * @api private\n */\n\nfunction NativeCollection () {\n this.collection = null;\n MongooseCollection.apply(this, arguments);\n}\n\n/*!\n * Inherit from abstract Collection.\n */\n\nNativeCollection.prototype.__proto__ = MongooseCollection.prototype;\n\n/**\n * Called when the connection opens.\n *\n * @api private\n */\n\nNativeCollection.prototype.onOpen = function () {\n var self = this;\n\n // always get a new collection in case the user changed host:port\n // of parent db instance when re-opening the connection.\n\n if (!self.opts.capped.size) {\n // non-capped\n return self.conn.db.collection(self.name, callback);\n }\n\n // capped\n return self.conn.db.collection(self.name, function (err, c) {\n if (err) return callback(err);\n\n // discover if this collection exists and if it is capped\n c.options(function (err, exists) {\n if (err) return callback(err);\n\n if (exists) {\n if (exists.capped) {\n callback(null, c);\n } else {\n var msg = 'A non-capped collection exists with this name.\\n\\n'\n + ' To use this collection as a capped collection, please '\n + 'first convert it.\\n'\n + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'\n err = new Error(msg);\n callback(err);\n }\n } else {\n // create\n var opts = utils.clone(self.opts.capped);\n opts.capped = true;\n self.conn.db.createCollection(self.name, opts, callback);\n }\n });\n });\n\n function callback (err, collection) {\n if (err) {\n // likely a strict mode error\n self.conn.emit('error', err);\n } else {\n self.collection = collection;\n MongooseCollection.prototype.onOpen.call(self);\n }\n };\n};\n\n/**\n * Called when the connection closes\n *\n * @api private\n */\n\nNativeCollection.prototype.onClose = function () {\n MongooseCollection.prototype.onClose.call(this);\n};\n\n/*!\n * Copy the collection methods and make them subject to queues\n */\n\nfor (var i in Collection.prototype) {\n (function(i){\n NativeCollection.prototype[i] = function () {\n if (this.buffer) {\n this.addQueue(i, arguments);\n return;\n }\n\n var collection = this.collection\n , args = arguments\n , self = this\n , debug = self.conn.base.options.debug;\n\n if (debug) {\n if ('function' === typeof debug) {\n debug.apply(debug\n , [self.name, i].concat(utils.args(args, 0, args.length-1)));\n } else {\n console.error('\\x1B[0;36mMongoose:\\x1B[0m %s.%s(%s) %s %s %s'\n , self.name\n , i\n , print(args[0])\n , print(args[1])\n , print(args[2])\n , print(args[3]))\n }\n }\n\n collection[i].apply(collection, args);\n };\n })(i);\n}\n\n/*!\n * Debug print helper\n */\n\nfunction print (arg) {\n var type = typeof arg;\n if ('function' === type || 'undefined' === type) return '';\n return format(arg);\n}\n\n/*!\n * Debug print helper\n */\n\nfunction format (obj, sub) {\n var x = utils.clone(obj);\n if (x) {\n if ('Binary' === x.constructor.name) {\n x = '[object Buffer]';\n } else if ('ObjectID' === x.constructor.name) {\n var representation = 'ObjectId(\"' + x.toHexString() + '\")';\n x = { inspect: function() { return representation; } };\n } else if ('Date' === x.constructor.name) {\n var representation = 'new Date(\"' + x.toUTCString() + '\")';\n x = { inspect: function() { return representation; } };\n } else if ('Object' === x.constructor.name) {\n var keys = Object.keys(x)\n , i = keys.length\n , key\n while (i--) {\n key = keys[i];\n if (x[key]) {\n if ('Binary' === x[key].constructor.name) {\n x[key] = '[object Buffer]';\n } else if ('Object' === x[key].constructor.name) {\n x[key] = format(x[key], true);\n } else if ('ObjectID' === x[key].constructor.name) {\n ;(function(x){\n var representation = 'ObjectId(\"' + x[key].toHexString() + '\")';\n x[key] = { inspect: function() { return representation; } };\n })(x)\n } else if ('Date' === x[key].constructor.name) {\n ;(function(x){\n var representation = 'new Date(\"' + x[key].toUTCString() + '\")';\n x[key] = { inspect: function() { return representation; } };\n })(x)\n } else if (Array.isArray(x[key])) {\n x[key] = x[key].map(function (o) {\n return format(o, true)\n });\n }\n }\n }\n }\n if (sub) return x;\n }\n\n return require('util')\n .inspect(x, false, 10, true)\n .replace(/\\n/g, '')\n .replace(/\\s{2,}/g, ' ')\n}\n\n/**\n * Retreives information about this collections indexes.\n *\n * @param {Function} callback\n * @method getIndexes\n * @api public\n */\n\nNativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation;\n\n/*!\n * Module exports.\n */\n\nmodule.exports = NativeCollection;\n\n});","sourceLength":5636,"scriptType":2,"compilationType":0,"context":{"ref":22},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js (lines: 213)"}],"refs":[{"handle":22,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":600,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[497]}}
{"seq":342,"request_seq":600,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/collection.js","id":497,"lineOffset":0,"columnOffset":0,"lineCount":190,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Module dependencies.\n */\n\nvar STATES = require('./connectionstate')\n\n/**\n * Abstract Collection constructor\n *\n * This is the base class that drivers inherit from and implement.\n *\n * @param {String} name name of the collection\n * @param {Connection} conn A MongooseConnection instance\n * @param {Object} opts optional collection options\n * @api public\n */\n\nfunction Collection (name, conn, opts) {\n if (undefined === opts) opts = {};\n if (undefined === opts.capped) opts.capped = {};\n\n opts.bufferCommands = undefined === opts.bufferCommands\n ? true\n : opts.bufferCommands;\n\n if ('number' == typeof opts.capped) {\n opts.capped = { size: opts.capped };\n }\n\n this.opts = opts;\n this.name = name;\n this.conn = conn;\n this.queue = [];\n this.buffer = this.opts.bufferCommands;\n\n if (STATES.connected == this.conn.readyState) {\n this.onOpen();\n }\n};\n\n/**\n * The collection name\n *\n * @api public\n * @property name\n */\n\nCollection.prototype.name;\n\n/**\n * The Connection instance\n *\n * @api public\n * @property conn\n */\n\nCollection.prototype.conn;\n\n/**\n * Called when the database connects\n *\n * @api private\n */\n\nCollection.prototype.onOpen = function () {\n var self = this;\n this.buffer = false;\n self.doQueue();\n};\n\n/**\n * Called when the database disconnects\n *\n * @api private\n */\n\nCollection.prototype.onClose = function () {\n if (this.opts.bufferCommands) {\n this.buffer = true;\n }\n};\n\n/**\n * Queues a method for later execution when its\n * database connection opens.\n *\n * @param {String} name name of the method to queue\n * @param {Array} args arguments to pass to the method when executed\n * @api private\n */\n\nCollection.prototype.addQueue = function (name, args) {\n this.queue.push([name, args]);\n return this;\n};\n\n/**\n * Executes all queued methods and clears the queue.\n *\n * @api private\n */\n\nCollection.prototype.doQueue = function () {\n for (var i = 0, l = this.queue.length; i < l; i++){\n this[this.queue[i][0]].apply(this, this.queue[i][1]);\n }\n this.queue = [];\n return this;\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.ensureIndex = function(){\n throw new Error('Collection#ensureIndex unimplemented by driver');\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.findAndModify = function(){\n throw new Error('Collection#findAndModify unimplemented by driver');\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.findOne = function(){\n throw new Error('Collection#findOne unimplemented by driver');\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.find = function(){\n throw new Error('Collection#find unimplemented by driver');\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.insert = function(){\n throw new Error('Collection#insert unimplemented by driver');\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.save = function(){\n throw new Error('Collection#save unimplemented by driver');\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.update = function(){\n throw new Error('Collection#update unimplemented by driver');\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.getIndexes = function(){\n throw new Error('Collection#getIndexes unimplemented by driver');\n};\n\n/**\n * Abstract method that drivers must implement.\n */\n\nCollection.prototype.mapReduce = function(){\n throw new Error('Collection#mapReduce unimplemented by driver');\n};\n\n/*!\n * Module exports.\n */\n\nmodule.exports = Collection;\n\n});","sourceLength":3699,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/collection.js (lines: 190)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":601,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[500]}}
{"seq":345,"request_seq":601,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/connectionstate.js","id":500,"lineOffset":0,"columnOffset":0,"lineCount":26,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Connection states\n */\n\nvar STATES = module.exports = exports = Object.create(null);\n\nvar disconnected = 'disconnected';\nvar connected = 'connected';\nvar connecting = 'connecting';\nvar disconnecting = 'disconnecting';\nvar uninitialized = 'uninitialized';\n\nSTATES[0] = disconnected;\nSTATES[1] = connected;\nSTATES[2] = connecting;\nSTATES[3] = disconnecting;\nSTATES[99] = uninitialized;\n\nSTATES[disconnected] = 0;\nSTATES[connected] = 1;\nSTATES[connecting] = 2;\nSTATES[disconnecting] = 3;\nSTATES[uninitialized] = 99;\n\n});","sourceLength":586,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/lib/connectionstate.js (lines: 26)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":602,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[503]}}
{"seq":346,"req33
uest_seq":602,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/muri/index.js","id":503,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function (exports, require, module, __filename, __dirname) { module.exports = exports = require('./lib');\n\n});","sourceLength":111,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/muri/index.js (lines: 3)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":603,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[506]}}
{"seq":350,"request_seq":603,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/muri/lib/index.js","id":506,"lineOffset":0,"columnOffset":0,"lineCount":237,"source":"(function (exports, require, module, __filename, __dirname) { // muri\n\n/**\n * MongoDB URI parser as described here:\n * http://www.mongodb.org/display/DOCS/Connections\n */\n\n/**\n * Module dependencies\n */\n\nvar qs = require('querystring');\n\n/**\n * Defaults\n */\n\nconst DEFAULT_PORT = 27017;\nconst DEFAULT_DB = 'test';\nconst ADMIN_DB = 'admin';\n\n/**\n * Muri\n */\n\nmodule.exports = exports = function muri (str) {\n if (!/^mongodb:\\/\\//.test(str)) {\n throw new Error('Invalid mongodb uri. Must begin with \"mongodb://\"'\n + '\\n Received: ' + str);\n }\n\n var ret = {\n hosts: []\n , db: DEFAULT_DB\n , options: {}\n }\n\n var match = /^mongodb:\\/\\/([^?]+)(\\??.*)$/.exec(str);\n if (!match || '/' == match[1]) {\n throw new Error('Invalid mongodb uri. Missing hostname');\n }\n\n var uris = match[1];\n var path = match[2];\n var db;\n\n uris.split(',').forEach(function (uri) {\n var o = parse(uri);\n\n if (o.host) {\n ret.hosts.push({\n host: o.host\n , port: parseInt(o.port, 10)\n })\n\n if (!db && o.db) {\n db = o.db;\n }\n } else if (o.ipc) {\n ret.hosts.push({ ipc: o.ipc });\n }\n\n if (o.auth) {\n ret.auth = {\n user: o.auth.user\n , pass: o.auth.pass\n }\n }\n })\n\n if (!ret.hosts.length) {\n throw new Error('Invalid mongodb uri. Missing hostname');\n }\n\n var parts = path.split('?');\n\n if (!db) {\n if (parts[0]) {\n db = parts[0].replace(/^\\//, '');\n } else {\n // deal with ipc formats\n db = /\\/([^\\.]+)$/.exec(match[1]);\n if (db && db[1]) {\n db = db[1];\n }\n }\n }\n\n if (db) {\n ret.db = db;\n } else if (ret.auth) {\n ret.db = ADMIN_DB;\n }\n\n if (parts[1]) {\n ret.options = options(parts[1]);\n }\n\n return ret;\n}\n\n/**\n * Parse str into key/val pairs casting values appropriately.\n */\n\nfunction options (str) {\n var sep = /;/.test(str)\n ? ';'\n : '&';\n\n var ret = qs.parse(str, sep);\n\n Object.keys(ret).forEach(function (key) {\n var val = ret[key];\n if ('readPreferenceTags' == key) {\n val = readPref(val);\n if (val) {\n ret[key] = Array.isArray(val)\n ? val\n : [val];\n }\n } else {\n ret[key] = format(val);\n }\n });\n\n return ret;\n}\n\nfunction format (val) {\n var num;\n\n if ('true' == val) {\n return true;\n } else if ('false' == val) {\n return false;\n } else {\n num = parseInt(val, 10);\n if (!isNaN(num)) {\n return num;\n }\n }\n\n return val;\n}\n\nfunction readPref (val) {\n var ret;\n\n if (Array.isArray(val)) {\n ret = val.map(readPref).filter(Boolean);\n return ret.length\n ? ret\n : undefined\n }\n\n var pair = val.split(',');\n var hasKeys;\n ret = {};\n\n pair.forEach(function (kv) {\n kv = (kv || '').trim();\n if (!kv) return;\n hasKeys = true;\n var split = kv.split(':');\n ret[split[0]] = format(split[1]);\n });\n\n return hasKeys && ret;\n}\n\nvar ipcRgx = /\\.sock/;\n\nfunction parse (uriString) {\n // do not use require('url').parse b/c it can't handle # in username or pwd\n // mongo uris are strange\n\n var uri = uriString;\n var ret = {};\n var parts;\n var auth;\n var ipcs;\n\n // skip protocol\n uri = uri.replace(/^mongodb:\\/\\//, '');\n\n // auth\n if (/@/.test(uri)) {\n parts = uri.split(/@/);\n auth = parts[0];\n uri = parts[1];\n\n parts = auth.split(':');\n ret.auth = {};\n ret.auth.user = parts[0];\n ret.auth.pass = parts[1];\n }\n\n // unix domain sockets\n if (ipcRgx.test(uri)) {\n ipcs = uri.split(ipcRgx);\n ret.ipc = ipcs[0] + '.sock';\n\n // included a database?\n if (ipcs[1]) {\n // strip leading / from database name\n ipcs[1] = ipcs[1].replace(/^\\//, '');\n\n if (ipcs[1]) {\n ret.db = ipcs[1];\n }\n }\n\n return ret;\n }\n\n // database name\n parts = uri.split('/');\n if (parts[1]) ret.db = parts[1];\n\n // host:port\n parts = parts[0].split(':');\n ret.host = parts[0];\n ret.port = parts[1] || DEFAULT_PORT;\n\n return ret;\n}\n\n/**\n * Version\n */\n\nmodule.exports.version = JSON.parse(\n require('fs').readFileSync(__dirname + '/../package.json', 'utf8')\n).version;\n\n});","sourceLength":4116,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mongoose/node_modules/muri/lib/index.js (lines: 237)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":604,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[509]}}
{"seq":351,"request_seq":604,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"console.js","id":509,"lineOffset":0,"columnOffset":0,"lineCount":110,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar util = require('util');\n\nfunction Console(stdout, stderr) {\n if (!(this instanceof Console)) {\n return new Console(stdout, stderr);\n }\n if (!stdout || typeof stdout.write !== 'function') {\n throw new TypeError('Console expects a writable stream instance');\n }\n if (!stderr) {\n stderr = stdout;\n }\n var prop = {\n writable: true,\n enumerable: false,\n configurable: true\n };\n prop.value = stdout;\n Object.defineProperty(this, '_stdout', prop);\n prop.value = stderr;\n Object.defineProperty(this, '_stderr', prop);\n prop.value = {};\n Object.defineProperty(this, '_times', prop);\n\n // bind the prototype functions to this Console instance\n Object.keys(Console.prototype).forEach(function(k) {\n this[k] = this[k].bind(this);\n }, this);\n}\n\nConsole.prototype.log = function() {\n this._stdout.write(util.format.apply(this, arguments) + '\\n');\n};\n\n\nConsole.prototype.info = Console.prototype.log;\n\n\nConsole.prototype.warn = function() {\n this._stderr.write(util.format.apply(this, arguments) + '\\n');\n};\n\n\nConsole.prototype.error = Console.prototype.warn;\n\n\nConsole.prototype.dir = function(object) {\n this._stdout.write(util.inspect(object) + '\\n');\n};\n\n\nConsole.prototype.time = function(label) {\n this._times[label] = Date.now();\n};\n\n\nConsole.prototype.timeEnd = function(label) {\n var time = this._times[label];\n if (!time) {\n throw new Error('No such label: ' + label);\n }\n var duration = Date.now() - time;\n this.log('%s: %dms', label, duration);\n};\n\n\nConsole.prototype.trace = function() {\n // TODO probably can to do this better with V8's debug object once that is\n // exposed.\n var err = new Error;\n err.name = 'Trace';\n err.message = util.format.apply(this, arguments);\n Error.captureStackTrace(err, arguments.callee);\n this.error(err.stack);\n};\n\n\nConsole.prototype.assert = function(expression) {\n if (!expression) {\n var arr = Array.prototype.slice.call(arguments, 1);\n require('assert').ok(false, util.format.apply(this, arr));\n }\n};\n\n\nmodule.exports = new Console(process.stdout, process.stderr);\nmodule.exports.Console = Console;\n\n});","sourceLength":3303,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"console.js (lines: 110)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":605,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[512]}}
{"seq":353,"request_seq":605,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"dns.js","id":512,"lineOffset":0,"columnOffset":0,"lineCount":221,"source":"(function (exports, require, module, __filename, __dirname) { // Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// 'Software'), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar cares = process.binding('cares_wrap'),\n net = require('net'),\n isIp = net.isIP;\n\n\nfunction errnoException(errorno, syscall) {\n // TODO make this more compatible with ErrnoException from src/node.cc\n // Once all of Node is using this function the ErrnoException from\n // src/node.cc should be removed.\n\n // For backwards compatibility. libuv returns ENOENT on NXDOMAIN.\n if (errorno == 'ENOENT') {\n errorno = 'ENOTFOUND';\n }\n\n var e = new Error(syscall + ' ' + errorno);\n\n e.errno = e.code = errorno;\n e.syscall = syscall;\n return e;\n}\n\n\n// c-ares invokes a callback either synchronously or asynchronously,\n// but the dns API should always invoke a callback asynchronously.\n//\n// This function makes sure that the callback is invoked asynchronously.\n// It returns a function that invokes the callback within nextTick().\n//\n// To avoid invoking unnecessary nextTick(), `immediately` property of\n// returned function should be set to true after c-ares returned.\n//\n// Usage:\n//\n// function someAPI(callback) {\n// callback = makeAsync(callback);\n// channel.someAPI(..., callback);\n// callback.immediately = true;\n// }\nfunction makeAsync(callback) {\n if (typeof callback !== 'function') {\n return callback;\n }\n return function asyncCallback() {\n if (asyncCallback.immediately) {\n // The API already returned, we can invoke the callback immediately.\n callback.apply(null, arguments);\n } else {\n var args = arguments;\n process.nextTick(function() {\n callback.apply(null, args);\n });\n }\n };\n}\n\n\n// Easy DNS A/AAAA look up\n// lookup(domain, [family,] callback)\nexports.lookup = function(domain, family, callback) {\n // parse arguments\n if (arguments.length === 2) {\n callback = family;\n family = 0;\n } else if (!family) {\n family = 0;\n } else {\n family = +family;\n if (family !== 4 && family !== 6) {\n throw new Error('invalid argument: `family` must be 4 or 6');\n }\n }\n callback = makeAsync(callback);\n\n if (!domain) {\n callback(null, null, family === 6 ? 6 : 4);\n return {};\n }\n\n // Hack required for Windows because Win7 removed the\n // localhost entry from c:\\WINDOWS\\system32\\drivers\\etc\\hosts\n // See http://daniel.haxx.se/blog/2011/02/21/localhost-hack-on-windows/\n // TODO Remove this once c-ares handles this problem.\n if (process.platform == 'win32' && domain == 'localhost') {\n callback(null, '127.0.0.1', 4);\n return {};\n }\n\n var matchedFamily = net.isIP(domain);\n if (matchedFamily) {\n callback(null, domain, matchedFamily);\n return {};\n }\n\n function onanswer(addresses) {\n if (addresses) {\n if (family) {\n callback(null, addresses[0], family);\n } else {\n callback(null, addresses[0], addresses[0].indexOf(':') >= 0 ? 6 : 4);\n }\n } else {\n callback(errnoException(process._errno, 'getaddrinfo'));\n }\n }\n\n var wrap = cares.getaddrinfo(domain, family);\n\n if (!wrap) {\n throw errnoException(process._errno, 'getaddrinfo');\n }\n\n wrap.oncomplete = onanswer;\n\n callback.immediately = true;\n return wrap;\n};\n\n\nfunction resolver(bindingName) {\n var binding = cares[bindingName];\n\n return function query(name, callback) {\n function onanswer(status, result) {\n if (!status) {\n callback(null, result);\n } else {\n callback(errnoException(process._errno, bindingName));\n }\n }\n\n callback = makeAsync(callback);\n var wrap = binding(name, onanswer);\n if (!wrap) {\n throw errnoException(process._errno, bindingName);\n }\n\n callback.immediately = true;\n return wrap;\n }\n}\n\n\nvar resolveMap = {};\nexports.resolve4 = resolveMap.A = resolver('queryA');\nexports.resolve6 = resolveMap.AAAA = resolver('queryAaaa');\nexports.resolveCname = resolveMap.CNAME = resolver('queryCname');\nexports.resolveMx = resolveMap.MX = resolver('queryMx');\nexports.resolveNs = resolveMap.NS = resolver('queryNs');\nexports.resolveTxt = resolveMap.TXT = resolver('queryTxt');\nexports.resolveSrv = resolveMap.SRV = resolver('querySrv');\nexports.resolveNaptr = resolveMap.NAPTR = resolver('queryNaptr');\nexports.reverse = resolveMap.PTR = resolver('getHostByAddr');\n\n\nexports.resolve = function(domain, type_, callback_) {\n var resolver, callback;\n if (typeof type_ == 'string') {\n resolver = resolveMap[type_];\n callback = callback_;\n } else {\n resolver = exports.resolve4;\n callback = type_;\n }\n\n if (typeof resolver === 'function') {\n return resolver(domain, callback);\n } else {\n throw new Error('Unknown type \"' + type_ + '\"');\n }\n};\n\n\n// ERROR CODES\nexports.NODATA = 'ENODATA';\nexports.FORMERR = 'EFORMERR';\nexports.SERVFAIL = 'ESERVFAIL';\nexports.NOTFOUND = 'ENOTFOUND';\nexports.NOTIMP = 'ENOTIMP';\nexports.REFUSED = 'EREFUSED';\nexports.BADQUERY = 'EBADQUERY';\nexports.ADNAME = 'EADNAME';\nexports.BADFAMILY = 'EBADFAMILY';\nexports.BADRESP = 'EBADRESP';\nexports.CONNREFUSED = 'ECONNREFUSED';\nexports.TIMEOUT = 'ETIMEOUT';\nexports.EOF = 'EOF';\nexports.FILE = 'EFILE';\nexports.NOMEM = 'ENOMEM';\nexports.DESTRUCTION = 'EDESTRUCTION';\nexports.BADSTR = 'EBADSTR';\nexports.BADFLAGS = 'EBADFLAGS';\nexports.NONAME = 'ENONAME';\nexports.BADHINTS = 'EBADHINTS';\nexports.NOTINITIALIZED = 'ENOTINITIALIZED';\nexports.LOADIPHLPAPI = 'ELOADIPHLPAPI';\nexports.ADDRGETNETWORKPARAMS = 'EADDRGETNETWORKPARAMS';\nexports.CANCELLED = 'ECANCELLED';\n\n});","sourceLength":6562,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"dns.js (lines: 221)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":606,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[515]}}
{"seq":354,"request_seq":606,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/server/models/file.js","id":515,"lineOffset":0,"columnOffset":0,"lineCount":41,"source":"(function (exports, require, module, __filename, __dirname) { var mongoose = require('mongoose'),\n fs = require('fs'),\n Schema = mongoose.Schema,\n crypto = require('crypto'),\n fileSchema;\n\nfileSchema = new Schema({\n filename: { type: String, validate: [function(value) {\n return value && value.length > 3;\n }, \"Filename is to short\"] },\n cid: { required: true, type: String },\n created: { type: Date, default: Date.now },\n size: { required: true, type: Number, min: 0 },\n filestopCId: { required: true, type: String }\n});\n\nfileSchema.methods.deleteFile = function (config, callback) {\n var filePath = config.uploadDir + \"/\" + this.filestopCId + \"/\" + this.filename;\n console.log(\"Deleting file at \" + filePath);\n fs.unlink(filePath, function (err) {\n if (err) {\n console.log(\"Error deleting file \" + filePath, err);\n }\n\n if (typeof(callback) == \"function\")\n callback(err);\n });\n}\n\nfileSchema.methods.createClientId = function (config) {\n var shasum = crypto.createHash('sha1');\n this.cid = shasum.update (this._id + config.salt, \"ascii\")\n .digest(\"base64\")\n .replace('+','')\n .replace('/','')\n .substring(0,12);\n}\n\nmongoose.model('File', fileSchema);\n\n});","sourceLength":1281,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/server/models/file.js (lines: 41)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":607,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[518]}}
{"seq":357,"request_seq":607,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/server/models/filestop.js","id":518,"lineOffset":0,"columnOffset":0,"lineCount":45,"source":"(function (exports, require, module, __filename, __dirname) { var mongoose = require('mongoose'),\n Schema = mongoose.Schema,\n crypto = require('crypto'),\n fs = require('fs'),\n filestopSchema;\n\nfilestopSchema = new Schema({\n name: { type: String, validate: [function(value) {\n return value && value.length > 3;\n }, \"Name is to short\"], default: \"Unnamed\" },\n description: { type: String, validate: [function(value) {\n return value && value.length < 500;\n }, \"Description is too long\"], default: \"\" },\n cid: {type: String},\n url: {type: String},\n created: { type: Date, default: Date.now },\n updated: { type: Date, default: Date.now },\n expires: { type: Date, default: Date.now }\n});\n\nfilestopSchema.methods.createClientId = function (config) {\n var shasum = crypto.createHash('sha1');\n this.cid = shasum.update (this._id + config.salt, \"ascii\")\n .digest(\"base64\")\n .replace('+','')\n .replace('/','')\n .substring(0,12);\n};\n\nfilestopSchema.methods.deleteFolder = function (config, callback) {\n var filestopPath = config.uploadDir + \"/\" + this.cid + \"/\";\n console.log(\"Deleting Filestop folder at \" + filestopPath);\n fs.rmdir(filestopPath, function (err) {\n if (err) {\n console.log(\"Error deleting Filestop path \" + filestopPath, err);\n }\n\n if(typeof(callback) == \"function\")\n callback(err);\n });\n};\n\nmongoose.model('Filestop', filestopSchema);\n\n});","sourceLength":1487,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/server/models/filestop.js (lines: 45)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":608,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[521]}}
{"seq":358,"request_seq":608,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/query.js","id":521,"lineOffset":0,"columnOffset":0,"lineCount":48,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Connect - query\n * Copyright(c) 2011 TJ Holowaychuk\n * Copyright(c) 2011 Sencha Inc.\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar qs = require('qs')\n , parse = require('../utils').parseUrl;\n\n/**\n * Query:\n *\n * Automatically parse the query-string when available,\n * populating the `req.query` object.\n *\n * Examples:\n *\n * connect()\n * .use(connect.query())\n * .use(function(req, res){\n * res.end(JSON.stringify(req.query));\n * });\n *\n * The `options` passed are provided to qs.parse function.\n *\n * @param {Object} options\n * @return {Function}\n * @api public\n */\n\nmodule.exports = function query(options){\n return function query(req, res, next){\n if (!req.query) {\n req.query = ~req.url.indexOf('?')\n ? qs.parse(parse(req).query, options)\n : {};\n }\n\n next();\n };\n};\n\n});","sourceLength":917,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/query.js (lines: 48)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":609,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[524]}}
{"seq":361,"request_seq":609,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/qs/index.js","id":524,"lineOffset":0,"columnOffset":0,"lineCount":3,"source":"(function (exports, require, module, __filename, __dirname) { \nmodule.exports = require('./lib/querystring');\n});","sourceLength":113,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/qs/index.js (lines: 3)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":610,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[527]}}
{"seq":362,"request_seq":610,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/qs/lib/querystring.js","id":527,"lineOffset":0,"columnOffset":0,"lineCount":264,"source":"(function (exports, require, module, __filename, __dirname) { \n/**\n * Object#toString() ref for stringify().\n */\n\nvar toString = Object.prototype.toString;\n\n/**\n * Cache non-integer test regexp.\n */\n\nvar isint = /^[0-9]+$/;\n\nfunction promote(parent, key) {\n if (parent[key].length == 0) return parent[key] = {};\n var t = {};\n for (var i in parent[key]) t[i] = parent[key][i];\n parent[key] = t;\n return t;\n}\n\nfunction parse(parts, parent, key, val) {\n var part = parts.shift();\n // end\n if (!part) {\n if (Array.isArray(parent[key])) {\n parent[key].push(val);\n } else if ('object' == typeof parent[key]) {\n parent[key] = val;\n } else if ('undefined' == typeof parent[key]) {\n parent[key] = val;\n } else {\n parent[key] = [parent[key], val];\n }\n // array\n } else {\n var obj = parent[key] = parent[key] || [];\n if (']' == part) {\n if (Array.isArray(obj)) {\n if ('' != val) obj.push(val);\n } else if ('object' == typeof obj) {\n obj[Object.keys(obj).length] = val;\n } else {\n obj = parent[key] = [parent[key], val];\n }\n // prop\n } else if (~part.indexOf(']')) {\n part = part.substr(0, part.length - 1);\n if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key);\n parse(parts, obj, part, val);\n // key\n } else {\n if (!isint.test(part) && Array.isArray(obj)) obj = promote(parent, key);\n parse(parts, obj, part, val);\n }\n }\n}\n\n/**\n * Merge parent key/val pair.\n */\n\nfunction merge(parent, key, val){\n if (~key.indexOf(']')) {\n var parts = key.split('[')\n , len = parts.length\n , last = len - 1;\n parse(parts, parent, 'base', val);\n // optimize\n } else {\n if (!isint.test(key) && Array.isArray(parent.base)) {\n var t = {};\n for (var k in parent.base) t[k] = parent.base[k];\n parent.base = t;\n }\n set(parent.base, key, val);\n }\n\n return parent;\n}\n\n/**\n * Parse the given obj.\n */\n\nfunction parseObject(obj){\n var ret = { base: {} };\n Object.keys(obj).forEach(function(name){\n merge(ret, name, obj[name]);\n });\n return ret.base;\n}\n\n/**\n * Parse the given str.\n */\n\nfunction parseString(str){\n return String(str)\n .split('&')\n .reduce(function(ret, pair){\n var eql = pair.indexOf('=')\n , brace = lastBraceInKey(pair)\n , key = pair.substr(0, brace || eql)\n , val = pair.substr(brace || eql, pair.length)\n , val = val.substr(val.indexOf('=') + 1, val.length);\n\n // ?foo\n if ('' == key) key = pair, val = '';\n\n return merge(ret, decode(key), decode(val));\n }, { base: {} }).base;\n}\n\n/**\n * Parse the given query `str` or `obj`, returning an object.\n *\n * @param {String} str | {Object} obj\n * @return {Object}\n * @api public\n */\n\nexports.parse = function(str){\n if (null == str || '' == str) return {};\n return 'object' == typeof str\n ? parseObject(str)\n : parseString(str);\n};\n\n/**\n * Turn the given `obj` into a query string\n *\n * @param {Object} obj\n * @return {String}\n * @api public\n */\n\nvar stringify = exports.stringify = function(obj, prefix) {\n if (Array.isArray(obj)) {\n return stringifyArray(obj, prefix);\n } else if ('[object Object]' == toString.call(obj)) {\n return stringifyObject(obj, prefix);\n } else if ('string' == typeof obj) {\n return stringifyString(obj, prefix);\n } else {\n return prefix + '=' + obj;\n }\n};\n\n/**\n * Stringify the given `str`.\n *\n * @param {String} str\n * @param {String} prefix\n * @return {String}\n * @api private\n */\n\nfunction stringifyString(str, prefix) {\n if (!prefix) throw new TypeError('stringify expects an object');\n return prefix + '=' + encodeURIComponent(str);\n}\n\n/**\n * Stringify the given `arr`.\n *\n * @param {Array} arr\n * @param {String} prefix\n * @return {String}\n * @api private\n */\n\nfunction stringifyArray(arr, prefix) {\n var ret = [];\n if (!prefix) throw new TypeError('stringify expects an object');\n for (var i = 0; i < arr.length; i++) {\n ret.push(stringify(arr[i], prefix + '['+i+']'));\n }\n return ret.join('&');\n}\n\n/**\n * Stringify the given `obj`.\n *\n * @param {Object} obj\n * @param {String} prefix\n * @return {String}\n * @api private\n */\n\nfunction stringifyObject(obj, prefix) {\n var ret = []\n , keys = Object.keys(obj)\n , key;\n\n for (var i = 0, len = keys.length; i < len; ++i) {\n key = keys[i];\n ret.push(stringify(obj[key], prefix\n ? prefix + '[' + encodeURIComponent(key) + ']'\n : encodeURIComponent(key)));\n }\n\n return ret.join('&');\n}\n\n/**\n * Set `obj`'s `key` to `val` respecting\n * the weird and wonderful syntax of a qs,\n * where \"foo=bar&foo=baz\" becomes an array.\n *\n * @param {Object} obj\n * @param {String} key\n * @param {String} val\n * @api private\n */\n\nfunction set(obj, key, val) {\n var v = obj[key];\n if (undefined === v) {\n obj[key] = val;\n } else if (Array.isArray(v)) {\n v.push(val);\n } else {\n obj[key] = [v, val];\n }\n}\n\n/**\n * Locate last brace in `str` within the key.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction lastBraceInKey(str) {\n var len = str.length\n , brace\n , c;\n for (var i = 0; i < len; ++i) {\n c = str[i];\n if (']' == c) brace = false;\n if ('[' == c) brace = true;\n if ('=' == c && !brace) return i;\n }\n}\n\n/**\n * Decode `str`.\n *\n * @param {String} str\n * @return {String}\n * @api private\n */\n\nfunction decode(str) {\n try {\n return decodeURIComponent(str.replace(/\\+/g, ' '));\n } catch (err) {\n return str;\n }\n}\n\n});","sourceLength":5506,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/qs/lib/querystring.js (lines: 264)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":611,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[530]}}
{"seq":365,"request_seq":611,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/server/config/express.js","id":530,"lineOffset":0,"columnOffset":0,"lineCount":17,"source":"(function (exports, require, module, __filename, __dirname) { var express = require('express');\n\nmodule.exports = function (app, config) {\n app.configure(function() {\n app.set('title', 'filestop');\n app.set('version', '0.1');\n\n app.use(express.bodyParser());\n\n app.use(express.static(__dirname + '/../../app'));\n app.use(express.logger());\n app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));\n });\n};\n\n\n});","sourceLength":476,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/server/config/express.js (lines: 17)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":612,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[533]}}
{"seq":366,"request_seq":612,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js","id":533,"lineOffset":0,"columnOffset":0,"lineCount":62,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Connect - bodyParser\n * Copyright(c) 2010 Sencha Inc.\n * Copyright(c) 2011 TJ Holowaychuk\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar multipart = require('./multipart')\n , urlencoded = require('./urlencoded')\n , json = require('./json');\n\n/**\n * Body parser:\n * \n * Parse request bodies, supports _application/json_,\n * _application/x-www-form-urlencoded_, and _multipart/form-data_.\n *\n * This is equivalent to: \n *\n * app.use(connect.json());\n * app.use(connect.urlencoded());\n * app.use(connect.multipart());\n *\n * Examples:\n *\n * connect()\n * .use(connect.bodyParser())\n * .use(function(req, res) {\n * res.end('viewing user ' + req.body.user.name);\n * });\n *\n * $ curl -d 'user[name]=tj' http://local/\n * $ curl -d '{\"user\":{\"name\":\"tj\"}}' -H \"Content-Type: application/json\" http://local/\n *\n * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info.\n *\n * @param {Object} options\n * @return {Function}\n * @api public\n */\n\nexports = module.exports = function bodyParser(options){\n var _urlencoded = urlencoded(options)\n , _multipart = multipart(options)\n , _json = json(options);\n\n return function bodyParser(req, res, next) {\n _json(req, res, function(err){\n if (err) return next(err);\n _urlencoded(req, res, function(err){\n if (err) return next(err);\n _multipart(req, res, next);\n });\n });\n }\n};\n});","sourceLength":1546,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js (lines: 62)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":613,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[536]}}
{"seq":370,"request_seq":613,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/multipart.js","id":536,"lineOffset":0,"columnOffset":0,"lineCount":133,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Connect - multipart\n * Copyright(c) 2010 Sencha Inc.\n * Copyright(c) 2011 TJ Holowaychuk\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar formidable = require('formidable')\n , _limit = require('./limit')\n , utils = require('../utils')\n , qs = require('qs');\n\n/**\n * noop middleware.\n */\n\nfunction noop(req, res, next) {\n next();\n}\n\n/**\n * Multipart:\n * \n * Parse multipart/form-data request bodies,\n * providing the parsed object as `req.body`\n * and `req.files`.\n *\n * Configuration:\n *\n * The options passed are merged with [formidable](https://github.com/felixge/node-formidable)'s\n * `IncomingForm` object, allowing you to configure the upload directory,\n * size limits, etc. For example if you wish to change the upload dir do the following.\n *\n * app.use(connect.multipart({ uploadDir: path }));\n *\n * Options:\n *\n * - `limit` byte limit defaulting to none\n * - `defer` defers processing and exposes the Formidable form object as `req.form`.\n * `next()` is called without waiting for the form's \"end\" event.\n * This option is useful if you need to bind to the \"progress\" event, for example.\n *\n * @param {Object} options\n * @return {Function}\n * @api public\n */\n\nexports = module.exports = function(options){\n options = options || {};\n\n var limit = options.limit\n ? _limit(options.limit)\n : noop;\n\n return function multipart(req, res, next) {\n if (req._body) return next();\n req.body = req.body || {};\n req.files = req.files || {};\n\n // ignore GET\n if ('GET' == req.method || 'HEAD' == req.method) return next();\n\n // check Content-Type\n if ('multipart/form-data' != utils.mime(req)) return next();\n\n // flag as parsed\n req._body = true;\n\n // parse\n limit(req, res, function(err){\n if (err) return next(err);\n\n var form = new formidable.IncomingForm\n , data = {}\n , files = {}\n , done;\n\n Object.keys(options).forEach(function(key){\n form[key] = options[key];\n });\n\n function ondata(name, val, data){\n if (Array.isArray(data[name])) {\n data[name].push(val);\n } else if (data[name]) {\n data[name] = [data[name], val];\n } else {\n data[name] = val;\n }\n }\n\n form.on('field', function(name, val){\n ondata(name, val, data);\n });\n\n form.on('file', function(name, val){\n ondata(name, val, files);\n });\n\n form.on('error', function(err){\n if (!options.defer) {\n err.status = 400;\n next(err);\n }\n done = true;\n });\n\n form.on('end', function(){\n if (done) return;\n try {\n req.body = qs.parse(data);\n req.files = qs.parse(files);\n if (!options.defer) next();\n } catch (err) {\n form.emit('error', err);\n }\n });\n\n form.parse(req);\n\n if (options.defer) {\n req.form = form;\n next();\n }\n });\n }\n};\n\n});","sourceLength":3055,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/multipart.js (lines: 133)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":614,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[539]}}
{"seq":371,"request_seq":614,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js","id":539,"lineOffset":0,"columnOffset":0,"lineCount":5,"source":"(function (exports, require, module, __filename, __dirname) { var IncomingForm = require('./incoming_form').IncomingForm;\nIncomingForm.IncomingForm = IncomingForm;\nmodule.exports = IncomingForm;\n\n});","sourceLength":199,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/index.js (lines: 5)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":615,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[542]}}
{"seq":372,"request_seq":615,"type":"response","command":"scripts","success":true,"body":[{"handle":5,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js","id":542,"lineOffset":0,"columnOffset":0,"lineCount":386,"source":"(function (exports, require, module, __filename, __dirname) { if (global.GENTLY) require = GENTLY.hijack(require);\n\nvar fs = require('fs');\nvar util = require('./util'),\n path = require('path'),\n File = require('./file'),\n MultipartParser = require('./multipart_parser').MultipartParser,\n QuerystringParser = require('./querystring_parser').QuerystringParser,\n StringDecoder = require('string_decoder').StringDecoder,\n EventEmitter = require('events').EventEmitter,\n Stream = require('stream').Stream;\n\nfunction IncomingForm(opts) { \n if (!(this instanceof IncomingForm)) return new IncomingForm;\n EventEmitter.call(this);\n\n opts=opts||{};\n \n this.error = null;\n this.ended = false;\n\n this.maxFieldsSize = opts.maxFieldsSize || 2 * 1024 * 1024;\n this.keepExtensions = opts.keepExtensions || false;\n this.uploadDir = opts.uploadDir || IncomingForm.UPLOAD_DIR;\n this.encoding = opts.encoding || 'utf-8';\n this.headers = null;\n this.type = null;\n this.hash = false;\n\n this.bytesReceived = null;\n this.bytesExpected = null;\n\n this._parser = null;\n this._flushing = 0;\n this._fieldsSize = 0;\n};\nutil.inherits(IncomingForm, EventEmitter);\nexports.IncomingForm = IncomingForm;\n\nIncomingForm.UPLOAD_DIR = (function() {\n var dirs = [process.env.TMP, '/tmp', process.cwd()];\n for (var i = 0; i < dirs.length; i++) {\n var dir = dirs[i];\n var isDirectory = false;\n\n try {\n isDirectory = fs.statSync(dir).isDirectory();\n } catch (e) {}\n\n if (isDirectory) return dir;\n }\n})();\n\nIncomingForm.prototype.parse = function(req, cb) {\n this.pause = function() {\n try {\n req.pause();\n } catch (err) {\n // the stream was destroyed\n if (!this.ended) {\n // before it was completed, crash & burn\n this._error(err);\n }\n return false;\n }\n return true;\n };\n\n this.resume = function() {\n try {\n req.resume();\n } catch (err) {\n // the stream was destroyed\n if (!this.ended) {\n // before it was completed, crash & burn\n this._error(err);\n }\n return false;\n }\n\n return true;\n };\n\n this.writeHeaders(req.headers);\n\n var self = this;\n req\n .on('error', function(err) {\n self._error(err);\n })\n .on('aborted', function() {\n self.emit('aborted');\n })\n .on('data', function(buffer) {\n self.write(buffer);\n })\n .on('end', function() {\n if (self.error) {\n return;\n }\n\n var err = self._parser.end();\n if (err) {\n self._error(err);\n }\n });\n\n if (cb) {\n var fields = {}, files = {};\n this\n .on('field', function(name, value) {\n fields[name] = value;\n })\n .on('file', function(name, file) {\n files[name] = file;\n })\n .on('error', function(err) {\n cb(err, fields, files);\n })\n .on('end', function() {\n cb(null, fields, files);\n });\n }\n\n return this;\n};\n\nIncomingForm.prototype.writeHeaders = function(headers) {\n this.headers = headers;\n this._parseContentLength();\n this._parseContentType();\n};\n\nIncomingForm.prototype.write = function(buffer) {\n if (!this._parser) {\n this._error(new Error('unintialized parser'));\n return;\n }\n\n this.bytesReceived += buffer.length;\n this.emit('progress', this.bytesReceived, this.bytesExpected);\n\n var bytesParsed = this._parser.write(buffer);\n if (bytesParsed !== buffer.length) {\n this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed'));\n }\n\n return bytesParsed;\n};\n\nIncomingForm.prototype.pause = function() {\n // this does nothing, unless overwritten in IncomingForm.parse\n return false;\n};\n\nIncomingForm.prototype.resume = function() {\n // this does nothing, unless overwritten in IncomingForm.parse\n return false;\n};\n\nIncomingForm.prototype.onPart = function(part) {\n // this method can be overwritten by the user\n this.handlePart(part);\n};\n\nIncomingForm.prototype.handlePart = function(part) {\n var self = this;\n\n if (part.filename === undefined) {\n var value = ''\n , decoder = new StringDecoder(this.encoding);\n\n part.on('data', function(buffer) {\n self._fieldsSize += buffer.length;\n if (self._fieldsSize > self.maxFieldsSize) {\n self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data'));\n return;\n }\n value += decoder.write(buffer);\n });\n\n part.on('end', function() {\n self.emit('field', part.name, value);\n });\n return;\n }\n\n this._flushing++;\n\n var file = new File({\n path: this._uploadPath(part.filename),\n name: part.filename,\n type: part.mime,\n hash: self.hash\n });\n\n this.emit('fileBegin', part.name, file);\n\n file.open();\n\n part.on('data', function(buffer) {\n self.pause();\n file.write(buffer, function() {\n self.resume();\n });\n });\n\n part.on('end', function() {\n file.end(function() {\n self._flushing--;\n self.emit('file', part.name, file);\n self._maybeEnd();\n });\n });\n};\n\nIncomingForm.prototype._parseContentType = function() {\n if (!this.headers['content-type']) {\n this._error(new Error('bad content-type header, no content-type'));\n return;\n }\n\n if (this.headers['content-type'].match(/urlencoded/i)) {\n this._initUrlencoded();\n return;\n }\n\n if (this.headers['content-type'].match(/multipart/i)) {\n var m;\n if (m = this.headers['content-type'].match(/boundary=(?:\"([^\"]+)\"|([^;]+))/i)) {\n this._initMultipart(m[1] || m[2]);\n } else {\n this._error(new Error('bad content-type header, no multipart boundary'));\n }\n return;\n }\n\n this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type']));\n};\n\nIncomingForm.prototype._error = function(err) {\n if (this.error) {\n return;\n }\n\n this.error = err;\n this.pause();\n this.emit('error', err);\n};\n\nIncomingForm.prototype._parseContentLength = function() {\n if (this.headers['content-length']) {\n this.bytesReceived = 0;\n this.bytesExpected = parseInt(this.headers['content-length'], 10);\n this.emit('progress', this.bytesReceived, this.bytesExpected);\n }\n};\n\nIncomingForm.prototype._newParser = function() {\n return new MultipartParser();\n};\n\nIncomingForm.prototype._initMultipart = function(boundary) {\n this.type = 'multipart';\n\n var parser = new MultipartParser(),\n self = this,\n headerField,\n headerValue,\n part;\n\n parser.initWithBoundary(boundary);\n\n parser.onPartBegin = function() {\n part = new Stream();\n part.readable = true;\n part.headers = {};\n part.name = null;\n part.filename = null;\n part.mime = null;\n headerField = '';\n headerValue = '';\n };\n\n parser.onHeaderField = function(b, start, end) {\n headerField += b.toString(self.encoding, start, end);\n };\n\n parser.onHeaderValue = function(b, start, end) {\n headerValue += b.toString(self.encoding, start, end);\n };\n\n parser.onHeaderEnd = function() {\n headerField = headerField.toLowerCase();\n part.headers[headerField] = headerValue;\n\n var m;\n if (headerField == 'content-disposition') {\n if (m = headerValue.match(/name=\"([^\"]+)\"/i)) {\n part.name = m[1];\n }\n\n part.filename = self._fileName(headerValue);\n } else if (headerField == 'content-type') {\n part.mime = headerValue;\n }\n\n headerField = '';\n headerValue = '';\n };\n\n parser.onHeadersEnd = function() {\n self.onPart(part);\n };\n\n parser.onPartData = function(b, start, end) {\n part.emit('data', b.slice(start, end));\n };\n\n parser.onPartEnd = function() {\n part.emit('end');\n };\n\n parser.onEnd = function() {\n self.ended = true;\n self._maybeEnd();\n };\n\n this._parser = parser;\n};\n\nIncomingForm.prototype._fileName = function(headerValue) {\n var m = headerValue.match(/filename=\"(.*?)\"($|; )/i)\n if (!m) return;\n\n var filename = m[1].substr(m[1].lastIndexOf('\\\\') + 1);\n filename = filename.replace(/%22/g, '\"');\n filename = filename.replace(/&#([\\d]{4});/g, function(m, code) {\n return String.fromCharCode(code);\n });\n return filename;\n};\n\nIncomingForm.prototype._initUrlencoded = function() {\n this.type = 'urlencoded';\n\n var parser = new QuerystringParser()\n , self = this;\n\n parser.onField = function(key, val) {\n self.emit('field', key, val);\n };\n\n parser.onEnd = function() {\n self.ended = true;\n self._maybeEnd();\n };\n\n this._parser = parser;\n};\n\nIncomingForm.prototype._uploadPath = function(filename) {\n var name = '';\n for (var i = 0; i < 32; i++) {\n name += Math.floor(Math.random() * 16).toString(16);\n }\n\n if (this.keepExtensions) {\n var ext = path.extname(filename);\n ext = ext.replace(/(\\.[a-z0-9]+).*/, '$1')\n\n name += ext;\n }\n\n return path.join(this.uploadDir, name);\n};\n\nIncomingForm.prototype._maybeEnd = function() {\n if (!this.ended || this._flushing) {\n return;\n }\n\n this.emit('end');\n};\n\n});","sourceLength":8932,"scriptType":2,"compilationType":0,"context":{"ref":4},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/incoming_form.js (lines: 386)"}],"refs":[{"handle":4,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":616,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[545]}}
{"seq":375,"request_seq":616,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js","id":545,"lineOffset":0,"columnOffset":0,"lineCount":8,"source":"(function (exports, require, module, __filename, __dirname) { // Backwards compatibility ...\ntry {\n module.exports = require('util');\n} catch (e) {\n module.exports = require('sys');\n}\n\n});","sourceLength":190,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/util.js (lines: 8)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":617,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[548]}}
{"seq":376,"request_seq":617,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js","id":548,"lineOffset":0,"columnOffset":0,"lineCount":75,"source":"(function (exports, require, module, __filename, __dirname) { if (global.GENTLY) require = GENTLY.hijack(require);\n\nvar util = require('./util'),\n WriteStream = require('fs').WriteStream,\n EventEmitter = require('events').EventEmitter,\n crypto = require('crypto');\n\nfunction File(properties) {\n EventEmitter.call(this);\n\n this.size = 0;\n this.path = null;\n this.name = null;\n this.type = null;\n this.hash = null;\n this.lastModifiedDate = null;\n\n this._writeStream = null;\n \n for (var key in properties) {\n this[key] = properties[key];\n }\n\n if(typeof this.hash === 'string') {\n this.hash = crypto.createHash(properties.hash);\n }\n\n this._backwardsCompatibility();\n}\nmodule.exports = File;\nutil.inherits(File, EventEmitter);\n\n// @todo Next release: Show error messages when accessing these\nFile.prototype._backwardsCompatibility = function() {\n var self = this;\n this.__defineGetter__('length', function() {\n return self.size;\n });\n this.__defineGetter__('filename', function() {\n return self.name;\n });\n this.__defineGetter__('mime', function() {\n return self.type;\n });\n};\n\nFile.prototype.open = function() {\n this._writeStream = new WriteStream(this.path);\n};\n\nFile.prototype.write = function(buffer, cb) {\n var self = this;\n this._writeStream.write(buffer, function() {\n if(self.hash) {\n self.hash.update(buffer);\n }\n self.lastModifiedDate = new Date();\n self.size += buffer.length;\n self.emit('progress', self.size);\n cb();\n });\n};\n\nFile.prototype.end = function(cb) {\n var self = this;\n this._writeStream.end(function() {\n if(self.hash) {\n self.hash = self.hash.digest('hex');\n }\n self.emit('end');\n cb();\n });\n};\n\n});","sourceLength":1713,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/file.js (lines: 75)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":618,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[551]}}
{"seq":379,"request_seq":618,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js","id":551,"lineOffset":0,"columnOffset":0,"lineCount":314,"source":"(function (exports, require, module, __filename, __dirname) { var Buffer = require('buffer').Buffer,\n s = 0,\n S =\n { PARSER_UNINITIALIZED: s++,\n START: s++,\n START_BOUNDARY: s++,\n HEADER_FIELD_START: s++,\n HEADER_FIELD: s++,\n HEADER_VALUE_START: s++,\n HEADER_VALUE: s++,\n HEADER_VALUE_ALMOST_DONE: s++,\n HEADERS_ALMOST_DONE: s++,\n PART_DATA_START: s++,\n PART_DATA: s++,\n PART_END: s++,\n END: s++,\n },\n\n f = 1,\n F =\n { PART_BOUNDARY: f,\n LAST_BOUNDARY: f *= 2,\n },\n\n LF = 10,\n CR = 13,\n SPACE = 32,\n HYPHEN = 45,\n COLON = 58,\n A = 97,\n Z = 122,\n\n lower = function(c) {\n return c | 0x20;\n };\n\nfor (var s in S) {\n exports[s] = S[s];\n}\n\nfunction MultipartParser() {\n this.boundary = null;\n this.boundaryChars = null;\n this.lookbehind = null;\n this.state = S.PARSER_UNINITIALIZED;\n\n this.index = null;\n this.flags = 0;\n};\nexports.MultipartParser = MultipartParser;\n\nMultipartParser.stateToString = function(stateNumber) {\n for (var state in S) {\n var number = S[state];\n if (number === stateNumber) return state;\n }\n};\n\nMultipartParser.prototype.initWithBoundary = function(str) {\n this.boundary = new Buffer(str.length+4);\n this.boundary.write('\\r\\n--', 'ascii', 0);\n this.boundary.write(str, 'ascii', 4);\n this.lookbehind = new Buffer(this.boundary.length+8);\n this.state = S.START;\n\n this.boundaryChars = {};\n for (var i = 0; i < this.boundary.length; i++) {\n this.boundaryChars[this.boundary[i]] = true;\n }\n};\n\nMultipartParser.prototype.write = function(buffer) {\n var self = this,\n i = 0,\n len = buffer.length,\n prevIndex = this.index,\n index = this.index,\n state = this.state,\n flags = this.flags,\n lookbehind = this.lookbehind,\n boundary = this.boundary,\n boundaryChars = this.boundaryChars,\n boundaryLength = this.boundary.length,\n boundaryEnd = boundaryLength - 1,\n bufferLength = buffer.length,\n c,\n cl,\n\n mark = function(name) {\n self[name+'Mark'] = i;\n },\n clear = function(name) {\n delete self[name+'Mark'];\n },\n callback = function(name, buffer, start, end) {\n if (start !== undefined && start === end) {\n return;\n }\n\n var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1);\n if (callbackSymbol in self) {\n self[callbackSymbol](buffer, start, end);\n }\n },\n dataCallback = function(name, clear) {\n var markSymbol = name+'Mark';\n if (!(markSymbol in self)) {\n return;\n }\n\n if (!clear) {\n callback(name, buffer, self[markSymbol], buffer.length);\n self[markSymbol] = 0;\n } else {\n callback(name, buffer, self[markSymbol], i);\n delete self[markSymbol];\n }\n };\n\n for (i = 0; i < len; i++) {\n c = buffer[i];\n switch (state) {\n case S.PARSER_UNINITIALIZED:\n return i;\n case S.START:\n index = 0;\n state = S.START_BOUNDARY;\n case S.START_BOUNDARY:\n if (index == boundary.length - 2) {\n if (c != CR) {\n return i;\n }\n index++;\n break;\n } else if (index - 1 == boundary.length - 2) {\n if (c != LF) {\n return i;\n }\n index = 0;\n callback('partBegin');\n state = S.HEADER_FIELD_START;\n break;\n }\n\n if (c != boundary[index+2]) {\n return i;\n }\n index++;\n break;\n case S.HEADER_FIELD_START:\n state = S.HEADER_FIELD;\n mark('headerField');\n index = 0;\n case S.HEADER_FIELD:\n if (c == CR) {\n clear('headerField');\n state = S.HEADERS_ALMOST_DONE;\n break;\n }\n\n index++;\n if (c == HYPHEN) {\n break;\n }\n\n if (c == COLON) {\n if (index == 1) {\n // empty header field\n return i;\n }\n dataCallback('headerField', true);\n state = S.HEADER_VALUE_START;\n break;\n }\n\n cl = lower(c);\n if (cl < A || cl > Z) {\n return i;\n }\n break;\n case S.HEADER_VALUE_START:\n if (c == SPACE) {\n break;\n }\n\n mark('headerValue');\n state = S.HEADER_VALUE;\n case S.HEADER_VALUE:\n if (c == CR) {\n dataCallback('headerValue', true);\n callback('headerEnd');\n state = S.HEADER_VALUE_ALMOST_DONE;\n }\n break;\n case S.HEADER_VALUE_ALMOST_DONE:\n if (c != LF) {\n return i;\n }\n state = S.HEADER_FIELD_START;\n break;\n case S.HEADERS_ALMOST_DONE:\n if (c != LF) {\n return i;\n }\n\n callback('headersEnd');\n state = S.PART_DATA_START;\n break;\n case S.PART_DATA_START:\n state = S.PART_DATA\n mark('partData');\n case S.PART_DATA:\n prevIndex = index;\n\n if (index == 0) {\n // boyer-moore derrived algorithm to safely skip non-boundary data\n i += boundaryEnd;\n while (i < bufferLength && !(buffer[i] in boundaryChars)) {\n i += boundaryLength;\n }\n i -= boundaryEnd;\n c = buffer[i];\n }\n\n if (index < boundary.length) {\n if (boundary[index] == c) {\n if (index == 0) {\n dataCallback('partData', true);\n }\n index++;\n } else {\n index = 0;\n }\n } else if (index == boundary.length) {\n index++;\n if (c == CR) {\n // CR = part boundary\n flags |= F.PART_BOUNDARY;\n } else if (c == HYPHEN) {\n // HYPHEN = end boundary\n flags |= F.LAST_BOUNDARY;\n } else {\n index = 0;\n }\n } else if (index - 1 == boundary.length) {\n if (flags & F.PART_BOUNDARY) {\n index = 0;\n if (c == LF) {\n // unset the PART_BOUNDARY flag\n flags &= ~F.PART_BOUNDARY;\n callback('partEnd');\n callback('partBegin');\n state = S.HEADER_FIELD_START;\n break;\n }\n } else if (flags & F.LAST_BOUNDARY) {\n if (c == HYPHEN) {\n callback('partEnd');\n callback('end');\n state = S.END;\n } else {\n index = 0;\n }\n } else {\n index = 0;\n }\n }\n\n if (index > 0) {\n // when matching a possible boundary, keep a lookbehind reference\n // in case it turns out to be a false lead\n lookbehind[index-1] = c;\n } else if (prevIndex > 0) {\n // if our boundary turned out to be rubbish, the captured lookbehind\n // belongs to partData\n callback('partData', lookbehind, 0, prevIndex);\n prevIndex = 0;\n mark('partData');\n\n // reconsider the current character even so it interrupted the sequence\n // it could be the beginning of a new sequence\n i--;\n }\n\n break;\n case S.END:\n break;\n default:\n return i;\n }\n }\n\n dataCallback('headerField');\n dataCallback('headerValue');\n dataCallback('partData');\n\n this.index = index;\n this.state = state;\n this.flags = flags;\n\n return len;\n};\n\nMultipartParser.prototype.end = function() {\n if (this.state != S.END) {\n return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain());\n }\n};\n\nMultipartParser.prototype.explain = function() {\n return 'state = ' + MultipartParser.stateToString(this.state);\n};\n\n});","sourceLength":7802,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/multipart_parser.js (lines: 314)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":619,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[554]}}
{"seq":381,"request_seq":619,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js","id":554,"lineOffset":0,"columnOffset":0,"lineCount":26,"source":"(function (exports, require, module, __filename, __dirname) { if (global.GENTLY) require = GENTLY.hijack(require);\n\n// This is a buffering parser, not quite as nice as the multipart one.\n// If I find time I'll rewrite this to be fully streaming as well\nvar querystring = require('querystring');\n\nfunction QuerystringParser() {\n this.buffer = '';\n};\nexports.QuerystringParser = QuerystringParser;\n\nQuerystringParser.prototype.write = function(buffer) {\n this.buffer += buffer.toString('ascii');\n return buffer.length;\n};\n\nQuerystringParser.prototype.end = function() {\n var fields = querystring.parse(this.buffer);\n for (var field in fields) {\n this.onField(field, fields[field]);\n }\n this.buffer = '';\n\n this.onEnd();\n};\n});","sourceLength":735,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/node_modules/formidable/lib/querystring_parser.js (lines: 26)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":620,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[557]}}
{"seq":382,"request_seq":620,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/limit.js","id":557,"lineOffset":0,"columnOffset":0,"lineCount":57,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Connect - limit\n * Copyright(c) 2011 TJ Holowaychuk\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar utils = require('../utils');\n\n/**\n * Limit:\n *\n * Limit request bodies to the given size in `bytes`.\n *\n * A string representation of the bytesize may also be passed,\n * for example \"5mb\", \"200kb\", \"1gb\", etc.\n *\n * connect()\n * .use(connect.limit('5.5mb'))\n * .use(handleImageUpload)\n *\n * @param {Number|String} bytes\n * @return {Function}\n * @api public\n */\n\nmodule.exports = function limit(bytes){\n if ('string' == typeof bytes) bytes = utils.parseBytes(bytes);\n if ('number' != typeof bytes) throw new Error('limit() bytes required');\n return function limit(req, res, next){\n var received = 0\n , len = req.headers['content-length']\n ? parseInt(req.headers['content-length'], 10)\n : null;\n\n // self-awareness\n if (req._limit) return next();\n req._limit = true;\n\n // limit by content-length\n if (len && len > bytes) return next(utils.error(413));\n\n // limit\n req.on('data', function(chunk){\n received += chunk.length;\n if (received > bytes) req.destroy();\n });\n\n next();\n };\n};\n\n});","sourceLength":1250,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/limit.js (lines: 57)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":621,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[560]}}
{"seq":385,"request_seq":621,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js","id":560,"lineOffset":0,"columnOffset":0,"lineCount":77,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Connect - urlencoded\n * Copyright(c) 2010 Sencha Inc.\n * Copyright(c) 2011 TJ Holowaychuk\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar utils = require('../utils')\n , _limit = require('./limit')\n , qs = require('qs');\n\n/**\n * noop middleware.\n */\n\nfunction noop(req, res, next) {\n next();\n}\n\n/**\n * Urlencoded:\n * \n * Parse x-ww-form-urlencoded request bodies,\n * providing the parsed object as `req.body`.\n *\n * Options:\n *\n * - `limit` byte limit disabled by default\n *\n * @param {Object} options\n * @return {Function}\n * @api public\n */\n\nexports = module.exports = function(options){\n options = options || {};\n\n var limit = options.limit\n ? _limit(options.limit)\n : noop;\n\n return function urlencoded(req, res, next) {\n if (req._body) return next();\n req.body = req.body || {};\n\n // check Content-Type\n if ('application/x-www-form-urlencoded' != utils.mime(req)) return next();\n\n // flag as parsed\n req._body = true;\n\n // parse\n limit(req, res, function(err){\n if (err) return next(err);\n var buf = '';\n req.setEncoding('utf8');\n req.on('data', function(chunk){ buf += chunk });\n req.on('end', function(){\n try {\n req.body = buf.length\n ? qs.parse(buf, options)\n : {};\n next();\n } catch (err){\n err.body = buf;\n next(err);\n }\n });\n });\n }\n};\n});","sourceLength":1485,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js (lines: 77)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":622,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[563]}}
{"seq":387,"request_seq":622,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/json.js","id":563,"lineOffset":0,"columnOffset":0,"lineCount":81,"source":"(function (exports, require, module, __filename, __dirname) { \n/*!\n * Connect - json\n * Copyright(c) 2010 Sencha Inc.\n * Copyright(c) 2011 TJ Holowaychuk\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar utils = require('../utils')\n , _limit = require('./limit');\n\n/**\n * noop middleware.\n */\n\nfunction noop(req, res, next) {\n next();\n}\n\n/**\n * JSON:\n *\n * Parse JSON request bodies, providing the\n * parsed object as `req.body`.\n *\n * Options:\n *\n * - `strict` when `false` anything `JSON.parse()` accepts will be parsed\n * - `reviver` used as the second \"reviver\" argument for JSON.parse\n * - `limit` byte limit disabled by default\n *\n * @param {Object} options\n * @return {Function}\n * @api public\n */\n\nexports = module.exports = function(options){\n var options = options || {}\n , strict = options.strict === false\n ? false\n : true;\n\n var limit = options.limit\n ? _limit(options.limit)\n : noop;\n\n return function json(req, res, next) {\n if (req._body) return next();\n req.body = req.body || {};\n\n // check Content-Type\n if ('application/json' != utils.mime(req)) return next();\n\n // flag as parsed\n req._body = true;\n\n // parse\n limit(req, res, function(err){\n if (err) return next(err);\n var buf = '';\n req.setEncoding('utf8');\n req.on('data', function(chunk){ buf += chunk });\n req.on('end', function(){\n if (strict && '{' != buf[0] && '[' != buf[0]) return next(utils.error(400, 'invalid json'));\n try {\n req.body = JSON.parse(buf, options.reviver);\n next();\n } catch (err){\n err.body = buf;\n err.status = 400;\n next(err);\n }\n });\n });\n }\n};\n});","sourceLength":1723,"scriptType":2,"compilationType":0,"context":{"ref":2},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/json.js (lines: 81)"}],"refs":[{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":623,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[566]}}
{"seq":390,"request_seq":623,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/logger.js","id":566,"lineOffset":0,"columnOffset":0,"lineCount":338,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Connect - logger\n * Copyright(c) 2010 Sencha Inc.\n * Copyright(c) 2011 TJ Holowaychuk\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar bytes = require('bytes');\n\n/*!\n * Log buffer.\n */\n\nvar buf = [];\n\n/*!\n * Default log buffer duration.\n */\n\nvar defaultBufferDuration = 1000;\n\n/**\n * Logger:\n *\n * Log requests with the given `options` or a `format` string.\n *\n * Options:\n *\n * - `format` Format string, see below for tokens\n * - `stream` Output stream, defaults to _stdout_\n * - `buffer` Buffer duration, defaults to 1000ms when _true_\n * - `immediate` Write log line on request instead of response (for response times)\n *\n * Tokens:\n *\n * - `:req[header]` ex: `:req[Accept]`\n * - `:res[header]` ex: `:res[Content-Length]`\n * - `:http-version`\n * - `:response-time`\n * - `:remote-addr`\n * - `:date`\n * - `:method`\n * - `:url`\n * - `:referrer`\n * - `:user-agent`\n * - `:status`\n *\n * Formats:\n *\n * Pre-defined formats that ship with connect:\n *\n * - `default` ':remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"'\n * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'\n * - `tiny` ':method :url :status :res[content-length] - :response-time ms'\n * - `dev` concise output colored by response status for development use\n *\n * Examples:\n *\n * connect.logger() // default\n * connect.logger('short')\n * connect.logger('tiny')\n * connect.logger({ immediate: true, format: 'dev' })\n * connect.logger(':method :url - :referrer')\n * connect.logger(':req[content-type] -> :res[content-type]')\n * connect.logger(function(req, res){ return 'some format string' })\n *\n * Defining Tokens:\n *\n * To define a token, simply invoke `connect.logger.token()` with the\n * name and a callback function. The value returned is then available\n * as \":type\" in this case.\n *\n * connect.logger.token('type', function(req, res){ return req.headers['content-type']; })\n *\n * Defining Formats:\n *\n * All default formats are defined this way, however it's public API as well:\n *\n * connect.logger.format('name', 'string or function')\n *\n * @param {String|Function|Object} format or options\n * @return {Function}\n * @api public\n */\n\nexports = module.exports = function logger(options) {\n if ('object' == typeof options) {\n options = options || {};\n } else if (options) {\n options = { format: options };\n } else {\n options = {};\n }\n\n // output on request instead of response\n var immediate = options.immediate;\n\n // format name\n var fmt = exports[options.format] || options.format || exports.default;\n\n // compile format\n if ('function' != typeof fmt) fmt = compile(fmt);\n\n // options\n var stream = options.stream || process.stdout\n , buffer = options.buffer;\n\n // buffering support\n if (buffer) {\n var realStream = stream\n , interval = 'number' == typeof buffer\n ? buffer\n : defaultBufferDuration;\n\n // flush interval\n setInterval(function(){\n if (buf.length) {\n realStream.write(buf.join(''));\n buf.length = 0;\n }\n }, interval); \n\n // swap the stream\n stream = {\n write: function(str){\n buf.push(str);\n }\n };\n }\n\n return function logger(req, res, next) {\n req._startTime = new Date;\n\n // immediate\n if (immediate) {\n var line = fmt(exports, req, res);\n if (null == line) return;\n stream.write(line + '\\n');\n // proxy end to output logging\n } else {\n var end = res.end;\n res.end = function(chunk, encoding){\n res.end = end;\n res.end(chunk, encoding);\n var line = fmt(exports, req, res);\n if (null == line) return;\n stream.write(line + '\\n');\n };\n }\n\n\n next();\n };\n};\n\n/**\n * Compile `fmt` into a function.\n *\n * @param {String} fmt\n * @return {Function}\n * @api private\n */\n\nfunction compile(fmt) {\n fmt = fmt.replace(/\"/g, '\\\\\"');\n var js = ' return \"' + fmt.replace(/:([-\\w]{2,})(?:\\[([^\\]]+)\\])?/g, function(_, name, arg){\n return '\"\\n + (tokens[\"' + name + '\"](req, res, \"' + arg + '\") || \"-\") + \"';\n }) + '\";'\n return new Function('tokens, req, res', js);\n};\n\n/**\n * Define a token function with the given `name`,\n * and callback `fn(req, res)`.\n *\n * @param {String} name\n * @param {Function} fn\n * @return {Object} exports for chaining\n * @api public\n */\n\nexports.token = function(name, fn) {\n exports[name] = fn;\n return this;\n};\n\n/**\n * Define a `fmt` with the given `name`.\n *\n * @param {String} name\n * @param {String|Function} fmt\n * @return {Object} exports for chaining\n * @api public\n */\n\nexports.format = function(name, str){\n exports[name] = str;\n return this;\n};\n\n/**\n * Default format.\n */\n\nexports.format('default', ':remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"');\n\n/**\n * Short format.\n */\n\nexports.format('short', ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms');\n\n/**\n * Tiny format.\n */\n\nexports.format('tiny', ':method :url :status :res[content-length] - :response-time ms');\n\n/**\n * dev (colored)\n */\n\nexports.format('dev', function(tokens, req, res){\n var status = res.statusCode\n , len = parseInt(res.getHeader('Content-Length'), 10)\n , color = 32;\n\n if (status >= 500) color = 31\n else if (status >= 400) color = 33\n else if (status >= 300) color = 36;\n\n len = isNaN(len)\n ? ''\n : len = ' - ' + bytes(len);\n\n return '\\033[90m' + req.method\n + ' ' + req.originalUrl + ' '\n + '\\033[' + color + 'm' + res.statusCode\n + ' \\033[90m'\n + (new Date - req._startTime)\n + 'ms' + len\n + '\\033[0m';\n});\n\n/**\n * request url\n */\n\nexports.token('url', function(req){\n return req.originalUrl || req.url;\n});\n\n/**\n * request method\n */\n\nexports.token('method', function(req){\n return req.method;\n});\n\n/**\n * response time in milliseconds\n */\n\nexports.token('response-time', function(req){\n return new Date - req._startTime;\n});\n\n/**\n * UTC date\n */\n\nexports.token('date', function(){\n return new Date().toUTCString();\n});\n\n/**\n * response status code\n */\n\nexports.token('status', function(req, res){\n return res.statusCode;\n});\n\n/**\n * normalized referrer\n */\n\nexports.token('referrer', function(req){\n return req.headers['referer'] || req.headers['referrer'];\n});\n\n/**\n * remote address\n */\n\nexports.token('remote-addr', function(req){\n return req.socket && (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress));\n});\n\n/**\n * HTTP version\n */\n\nexports.token('http-version', function(req){\n return req.httpVersionMajor + '.' + req.httpVersionMinor;\n});\n\n/**\n * UA string\n */\n\nexports.token('user-agent', function(req){\n return req.headers['user-agent'];\n});\n\n/**\n * request header\n */\n\nexports.token('req', function(req, res, field){\n return req.headers[field.toLowerCase()];\n});\n\n/**\n * response header\n */\n\nexports.token('res', function(req, res, field){\n return (res._headers || {})[field.toLowerCase()];\n});\n\n\n});","sourceLength":7205,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/logger.js (lines: 338)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":624,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[569]}}
{"seq":391,"request_seq":624,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","id":569,"lineOffset":0,"columnOffset":0,"lineCount":12,"source":"(function(tokens, req, res) {\n return \"\"\n + (tokens[\"remote-addr\"](req, res, \"undefined\") || \"-\") + \" - - [\"\n + (tokens[\"date\"](req, res, \"undefined\") || \"-\") + \"] \\\"\"\n + (tokens[\"method\"](req, res, \"undefined\") || \"-\") + \" \"\n + (tokens[\"url\"](req, res, \"undefined\") || \"-\") + \" HTTP/\"\n + (tokens[\"http-version\"](req, res, \"undefined\") || \"-\") + \"\\\" \"\n + (tokens[\"status\"](req, res, \"undefined\") || \"-\") + \" \"\n + (tokens[\"res\"](req, res, \"content-length\") || \"-\") + \" \\\"\"\n + (tokens[\"referrer\"](req, res, \"undefined\") || \"-\") + \"\\\" \\\"\"\n + (tokens[\"user-agent\"](req, res, \"undefined\") || \"-\") + \"\\\"\";\n})","sourceLength":630,"scriptType":2,"compilationType":1,"evalFromScript":{"ref":1},"evalFromLocation":{"line":172,"column":9},"evalFromFunctionName":{"type_":"string","value_":"compile","handle_":4},"context":{"ref":2},"text":"undefined (lines: 12)"}],"refs":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/logger.js","id":566,"lineOffset":0,"columnOffset":0,"lineCount":338,"source":"(function (exports, require, module, __filename, __dirname) { /*!\n * Connect - logger\n * Copyright(c) 2010 Sencha Inc.\n * Copyright(c) 2011 TJ Holowaychuk\n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar bytes = require('bytes');\n\n/*!\n * Log buffer.\n */\n\nvar buf = [];\n\n/*!\n * Default log buffer duration.\n */\n\nvar defaultBufferDuration = 1000;\n\n/**\n * Logger:\n *\n * Log requests with the given `options` or a `format` string.\n *\n * Options:\n *\n * - `format` Format string, see below for tokens\n * - `stream` Output stream, defaults to _stdout_\n * - `buffer` Buffer duration, defaults to 1000ms when _true_\n * - `immediate` Write log line on request instead of response (for response times)\n *\n * Tokens:\n *\n * - `:req[header]` ex: `:req[Accept]`\n * - `:res[header]` ex: `:res[Content-Length]`\n * - `:http-version`\n * - `:response-time`\n * - `:remote-addr`\n * - `:date`\n * - `:method`\n * - `:url`\n * - `:referrer`\n * - `:user-agent`\n * - `:status`\n *\n * Formats:\n *\n * Pre-defined formats that ship with connect:\n *\n * - `default` ':remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"'\n * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'\n * - `tiny` ':method :url :status :res[content-length] - :response-time ms'\n * - `dev` concise output colored by response status for development use\n *\n * Examples:\n *\n * connect.logger() // default\n * connect.logger('short')\n * connect.logger('tiny')\n * connect.logger({ immediate: true, format: 'dev' })\n * connect.logger(':method :url - :referrer')\n * connect.logger(':req[content-type] -> :res[content-type]')\n * connect.logger(function(req, res){ return 'some format string' })\n *\n * Defining Tokens:\n *\n * To define a token, simply invoke `connect.logger.token()` with the\n * name and a callback function. The value returned is then available\n * as \":type\" in this case.\n *\n * connect.logger.token('type', function(req, res){ return req.headers['content-type']; })\n *\n * Defining Formats:\n *\n * All default formats are defined this way, however it's public API as well:\n *\n * connect.logger.format('name', 'string or function')\n *\n * @param {String|Function|Object} format or options\n * @return {Function}\n * @api public\n */\n\nexports = module.exports = function logger(options) {\n if ('object' == typeof options) {\n options = options || {};\n } else if (options) {\n options = { format: options };\n } else {\n options = {};\n }\n\n // output on request instead of response\n var immediate = options.immediate;\n\n // format name\n var fmt = exports[options.format] || options.format || exports.default;\n\n // compile format\n if ('function' != typeof fmt) fmt = compile(fmt);\n\n // options\n var stream = options.stream || process.stdout\n , buffer = options.buffer;\n\n // buffering support\n if (buffer) {\n var realStream = stream\n , interval = 'number' == typeof buffer\n ? buffer\n : defaultBufferDuration;\n\n // flush interval\n setInterval(function(){\n if (buf.length) {\n realStream.write(buf.join(''));\n buf.length = 0;\n }\n }, interval); \n\n // swap the stream\n stream = {\n write: function(str){\n buf.push(str);\n }\n };\n }\n\n return function logger(req, res, next) {\n req._startTime = new Date;\n\n // immediate\n if (immediate) {\n var line = fmt(exports, req, res);\n if (null == line) return;\n stream.write(line + '\\n');\n // proxy end to output logging\n } else {\n var end = res.end;\n res.end = function(chunk, encoding){\n res.end = end;\n res.end(chunk, encoding);\n var line = fmt(exports, req, res);\n if (null == line) return;\n stream.write(line + '\\n');\n };\n }\n\n\n next();\n };\n};\n\n/**\n * Compile `fmt` into a function.\n *\n * @param {String} fmt\n * @return {Function}\n * @api private\n */\n\nfunction compile(fmt) {\n fmt = fmt.replace(/\"/g, '\\\\\"');\n var js = ' return \"' + fmt.replace(/:([-\\w]{2,})(?:\\[([^\\]]+)\\])?/g, function(_, name, arg){\n return '\"\\n + (tokens[\"' + name + '\"](req, res, \"' + arg + '\") || \"-\") + \"';\n }) + '\";'\n return new Function('tokens, req, res', js);\n};\n\n/**\n * Define a token function with the given `name`,\n * and callback `fn(req, res)`.\n *\n * @param {String} name\n * @param {Function} fn\n * @return {Object} exports for chaining\n * @api public\n */\n\nexports.token = function(name, fn) {\n exports[name] = fn;\n return this;\n};\n\n/**\n * Define a `fmt` with the given `name`.\n *\n * @param {String} name\n * @param {String|Function} fmt\n * @return {Object} exports for chaining\n * @api public\n */\n\nexports.format = function(name, str){\n exports[name] = str;\n return this;\n};\n\n/**\n * Default format.\n */\n\nexports.format('default', ':remote-addr - - [:date] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"');\n\n/**\n * Short format.\n */\n\nexports.format('short', ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms');\n\n/**\n * Tiny format.\n */\n\nexports.format('tiny', ':method :url :status :res[content-length] - :response-time ms');\n\n/**\n * dev (colored)\n */\n\nexports.format('dev', function(tokens, req, res){\n var status = res.statusCode\n , len = parseInt(res.getHeader('Content-Length'), 10)\n , color = 32;\n\n if (status >= 500) color = 31\n else if (status >= 400) color = 33\n else if (status >= 300) color = 36;\n\n len = isNaN(len)\n ? ''\n : len = ' - ' + bytes(len);\n\n return '\\033[90m' + req.method\n + ' ' + req.originalUrl + ' '\n + '\\033[' + color + 'm' + res.statusCode\n + ' \\033[90m'\n + (new Date - req._startTime)\n + 'ms' + len\n + '\\033[0m';\n});\n\n/**\n * request url\n */\n\nexports.token('url', function(req){\n return req.originalUrl || req.url;\n});\n\n/**\n * request method\n */\n\nexports.token('method', function(req){\n return req.method;\n});\n\n/**\n * response time in milliseconds\n */\n\nexports.token('response-time', function(req){\n return new Date - req._startTime;\n});\n\n/**\n * UTC date\n */\n\nexports.token('date', function(){\n return new Date().toUTCString();\n});\n\n/**\n * response status code\n */\n\nexports.token('status', function(req, res){\n return res.statusCode;\n});\n\n/**\n * normalized referrer\n */\n\nexports.token('referrer', function(req){\n return req.headers['referer'] || req.headers['referrer'];\n});\n\n/**\n * remote address\n */\n\nexports.token('remote-addr', function(req){\n return req.socket && (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress));\n});\n\n/**\n * HTTP version\n */\n\nexports.token('http-version', function(req){\n return req.httpVersionMajor + '.' + req.httpVersionMinor;\n});\n\n/**\n * UA string\n */\n\nexports.token('user-agent', function(req){\n return req.headers['user-agent'];\n});\n\n/**\n * request header\n */\n\nexports.token('req', function(req, res, field){\n return req.headers[field.toLowerCase()];\n});\n\n/**\n * response header\n */\n\nexports.token('res', function(req, res, field){\n return (res._headers || {})[field.toLowerCase()];\n});\n\n\n});","sourceLength":7205,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/express/node_modules/connect/lib/middleware/logger.js (lines: 338)"},{"handle":2,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":625,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[570]}}
{"seq":392,"request_seq":625,"type":"response","command":"scripts","success":true,"body":[{"handle":6,"type":"script","name":"/mnt/raid/var/www/tests/filestop/server/config/routes.js","id":570,"lineOffset":0,"columnOffset":0,"lineCount":25,"source":"(function (exports, require, module, __filename, __dirname) { module.exports = function (app, config) {\n\n var files = require('../controllers/files')(config);\n /*\n app.get('/files/:cid', files.get);\n app.get('/files', files.findAll);\n app.post('/files', files.create);\n app.put('/files/:cid', files.update);\n app.post('/files/upload', files.upload);\n */\n\n var filestops = require('../controllers/filestops')(config);\n app.get('/filestop/:cid', filestops.get);\n app.get('/filestop/:cid/files/:fileCid', files.download);\n app.delete('/filestop/:cid/files/:fileCid', files.delete);\n app.get('/filestop/:cid/files', filestops.getFiles);\n app.post('/filestop/:cid/files', files.downloadAll);\n app.post('/filestop/:cid/upload', files.upload);\n app.get('/filestop', filestops.findAll);\n app.post('/filestop', filestops.create);\n app.put('/filestop/:cid', filestops.update);\n app.delete ('/filestop/:cid', filestops.delete);\n};\n\n});","sourceLength":981,"scriptType":2,"compilationType":0,"context":{"ref":5},"text":"/mnt/raid/var/www/tests/filestop/server/config/routes.js (lines: 25)"}],"refs":[{"handle":5,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":626,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[573]}}
{"seq":395,"request_seq":626,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/server/controllers/files.js","id":573,"lineOffset":0,"columnOffset":0,"lineCount":179,"source":"(function (exports, require, module, __filename, __dirname) { var mongoose = require('mongoose'),\n File = mongoose.model('File'),\n fs = require('fs'),\n mkdirp = require('mkdirp'),\n mime = require('mime'),\n tinyzip = require('tinyzip');\n\nmodule.exports = function (config) {\n var exports = {};\n exports.create = function (req, res) {\n var file = new File(req.body);\n\n file.createClientId(config);\n\n file.save(function (err) {\n if (err) {\n res.send({success: false, errors: err});\n } else {\n res.send({success: 'OK', cid: file.cid});\n }\n });\n };\n exports.update = function (req, res, next) {\n var cid = req.params.cid;\n\n req.body.updated = new Date;\n\n File.findOneAndUpdate({cid: cid}, {$set: req.body}, function (err, file) {\n if (err) {\n console.log(\"Error updating File with cid \" + cid + \": \" + err);\n res.send({success: false, errors: err});\n return;\n }\n\n if (file)\n res.send({success: 'OK', cid: file.cid});\n else {\n console.log(\"Error updating File with cid \" + cid + \": not found\");\n res.send({success: false, errors: \"File not found\"});\n }\n });\n };\n exports.delete = function (req, res, next) {\n var filestop_cid = req.params.cid;\n var file_cid = req.params.fileCid;\n\n File.findOneAndRemove({cid: file_cid, filestopCId: filestop_cid}, function (err, file) {\n if (err) {\n console.log(\"Error deleting File with cid \" + file_cid + \": \" + err);\n res.send({success: false, errors: err});\n return;\n }\n\n if (file) {\n file.deleteFile(config);\n\n res.send({success: 'OK', cid: file.cid});\n } else {\n console.log(\"Error deleting File with cid \" + file_cid + \": not found\");\n res.send({success: false, errors: \"File not found\"});\n }\n\n\n });\n };\n exports.get = function (req, res) {\n var cid = req.params.cid;\n File.findOne({cid: cid}, function (err, result) {\n if (!result) {\n console.log(\"File with \" + cid + \" not found\");\n res.send(null);\n }\n res.send(result);\n });\n };\n exports.findAll = function (req, res) {\n File.find().exec(function (err, result) {\n res.send(result);\n });\n };\n exports.download = function (req, res) {\n var filestop_cid = req.params.cid;\n var file_cid = req.params.fileCid;\n File.findOne({cid: file_cid, filestopCId: filestop_cid}, function (err, result) {\n if (!result) {\n console.log(\"File with \" + file_cid + \" not found\");\n res.send(null);\n } else {\n var file = config.uploadDir + \"/\" + filestop_cid + \"/\" + result.filename;\n var filename = result.filename;\n var mimetype = mime.lookup(file);\n\n res.setHeader('Content-disposition', 'attachment; filename=' + filename);\n res.setHeader('Content-type', mimetype);\n\n var filestream = fs.createReadStream(file);\n filestream.pipe(res);\n }\n });\n\n };\n exports.downloadAll = function (req, res) {\n var filestop_cid = req.params.cid;\n var file_cids = req.body.fileCids.split(',');\n File.find({cid: {$in: file_cids}, filestopCId: filestop_cid}, function (err, result) {\n if (!result) {\n console.log(\"Files with \" + file_cids.join(', ') + \" not found\");\n res.send(null);\n } else {\n var zipFilename = \"filestop-\" + filestop_cid + \".zip\";\n res.setHeader('Content-disposition', 'attachment; filename=' + zipFilename);\n res.setHeader('Content-type', 'application/zip');\n res.setHeader('Transfer-Encoding', 'chunked');\n\n var rootpath = config.uploadDir + \"/\" + filestop_cid;\n var zip = new tinyzip.TinyZip({rootpath: rootpath, utf8: true, compress: {level: 1}, fast: true});\n for (var i in result) {\n var filename = rootpath + \"/\" + result[i].filename;\n zip.addFile({file:filename})\n }\n var zipStream = zip.getZipStream();\n zipStream.pipe(res);\n }\n });\n\n };\n exports.upload = function (req, res) {\n var filestop_cid = req.params.cid;\n var chunk = parseInt(req.body.chunk || 0) + 1;\n var chunks = req.body.chunks || 1;\n console.log(\"upload called on filestop_cid \" + filestop_cid + \" chunk \" + chunk + \"/\" + chunks);\n\n fs.readFile(req.files.file.path, function (err, data) {\n var fileDir = config.uploadDir + \"/\" + filestop_cid + \"/\";\n\n var filePath = fileDir + req.body.name;\n var filePathPart = filePath + \".part\";\n console.log(\"writing upload to \" + filePath);\n mkdirp(fileDir, 0755, function (err) {\n if (err) {\n console.log(\"Error creating directory \" + fileDir + \": \", err);\n res.send({success: false, errors: \"Upload error\"});\n return;\n }\n fs.appendFile(filePathPart, data, function (err) {\n if (err) {\n console.log(\"Error saving chunk \" + chunk + \"/\" + chunks + \": \", err);\n res.send({success: false, errors: \"Upload error\"});\n return;\n }\n\n if (chunk == chunks) {\n fs.rename(filePathPart, filePath, function (err) {\n fs.stat(filePath, function (err, stats) {\n var filesize = stats.size;\n\n var file = new File({filestopCId: filestop_cid, filename: req.body.name, size: filesize});\n\n file.createClientId(config);\n\n file.save(function (err) {\n if (!err) {\n res.send({success: \"OK\", cid: file.cid});\n return;\n }\n });\n });\n });\n } else {\n res.send({success: \"OK\"});\n }\n });\n });\n });\n };\n return exports;\n}\n\n});","sourceLength":6789,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/server/controllers/files.js (lines: 179)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":627,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[576]}}
{"seq":396,"request_seq":627,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mkdirp/index.js","id":576,"lineOffset":0,"columnOffset":0,"lineCount":84,"source":"(function (exports, require, module, __filename, __dirname) { var path = require('path');\nvar fs = require('fs');\n\nmodule.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;\n\nfunction mkdirP (p, mode, f, made) {\n if (typeof mode === 'function' || mode === undefined) {\n f = mode;\n mode = 0777 & (~process.umask());\n }\n if (!made) made = null;\n\n var cb = f || function () {};\n if (typeof mode === 'string') mode = parseInt(mode, 8);\n p = path.resolve(p);\n\n fs.mkdir(p, mode, function (er) {\n if (!er) {\n made = made || p;\n return cb(null, made);\n }\n switch (er.code) {\n case 'ENOENT':\n mkdirP(path.dirname(p), mode, function (er, made) {\n if (er) cb(er, made);\n else mkdirP(p, mode, cb, made);\n });\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n fs.stat(p, function (er2, stat) {\n // if the stat fails, then that's super weird.\n // let the original error be the failure reason.\n if (er2 || !stat.isDirectory()) cb(er, made)\n else cb(null, made);\n });\n break;\n }\n });\n}\n\nmkdirP.sync = function sync (p, mode, made) {\n if (mode === undefined) {\n mode = 0777 & (~process.umask());\n }\n if (!made) made = null;\n\n if (typeof mode === 'string') mode = parseInt(mode, 8);\n p = path.resolve(p);\n\n try {\n fs.mkdirSync(p, mode);\n made = made || p;\n }\n catch (err0) {\n switch (err0.code) {\n case 'ENOENT' :\n made = sync(path.dirname(p), mode, made);\n sync(p, mode, made);\n break;\n\n // In the case of any other error, just see if there's a dir\n // there already. If so, then hooray! If not, then something\n // is borked.\n default:\n var stat;\n try {\n stat = fs.statSync(p);\n }\n catch (err1) {\n throw err0;\n }\n if (!stat.isDirectory()) throw err0;\n break;\n }\n }\n\n return made;\n};\n\n});","sourceLength":2437,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mkdirp/index.js (lines: 84)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":628,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[579]}}
{"seq":399,"request_seq":628,"type":"response","command":"scripts","success":true,"body":[{"handle":1,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/mime/mime.js","id":579,"lineOffset":0,"columnOffset":0,"lineCount":115,"source":"(function (exports, require, module, __filename, __dirname) { var path = require('path');\nvar fs = require('fs');\n\nfunction Mime() {\n // Map of extension -> mime type\n this.types = Object.create(null);\n\n // Map of mime type -> extension\n this.extensions = Object.create(null);\n}\n\n/**\n * Define mimetype -> extension mappings. Each key is a mime-type that maps\n * to an array of extensions associated with the type. The first extension is\n * used as the default extension for the type.\n *\n * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});\n *\n * @param map (Object) type definitions\n */\nMime.prototype.define = function (map) {\n for (var type in map) {\n var exts = map[type];\n\n for (var i = 0; i < exts.length; i++) {\n if (process.env.DEBUG_MIME && this.types[exts]) {\n console.warn(this._loading.replace(/.*\\//, ''), 'changes \"' + exts[i] + '\" extension type from ' +\n this.types[exts] + ' to ' + type);\n }\n\n this.types[exts[i]] = type;\n }\n\n // Default extension is the first one we encounter\n if (!this.extensions[type]) {\n this.extensions[type] = exts[0];\n }\n }\n};\n\n/**\n * Load an Apache2-style \".types\" file\n *\n * This may be called multiple times (it's expected). Where files declare\n * overlapping types/extensions, the last file wins.\n *\n * @param file (String) path of file to load.\n */\nMime.prototype.load = function(file) {\n\n this._loading = file;\n // Read file and split into lines\n var map = {},\n content = fs.readFileSync(file, 'ascii'),\n lines = content.split(/[\\r\\n]+/);\n\n lines.forEach(function(line) {\n // Clean up whitespace/comments, and split into fields\n var fields = line.replace(/\\s*#.*|^\\s*|\\s*$/g, '').split(/\\s+/);\n map[fields.shift()] = fields;\n });\n\n this.define(map);\n\n this._loading = null;\n};\n\n/**\n * Lookup a mime type based on extension\n */\nMime.prototype.lookup = function(path, fallback) {\n var ext = path.replace(/.*[\\.\\/]/, '').toLowerCase();\n\n return this.types[ext] || fallback || this.default_type;\n};\n\n/**\n * Return file extension associated with a mime type\n */\nMime.prototype.extension = function(mimeType) {\n return this.extensions[mimeType];\n};\n\n// Default instance\nvar mime = new Mime();\n\n// Load local copy of\n// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types\nmime.load(path.join(__dirname, 'types/mime.types'));\n\n// Load additional types from node.js community\nmime.load(path.join(__dirname, 'types/node.types'));\n\n// Default type\nmime.default_type = mime.lookup('bin');\n\n//\n// Additional API specific to the default instance\n//\n\nmime.Mime = Mime;\n\n/**\n * Lookup a charset based on mime type.\n */\nmime.charsets = {\n lookup: function(mimeType, fallback) {\n // Assume text types are utf8\n return (/^text\\//).test(mimeType) ? 'UTF-8' : fallback;\n }\n};\n\nmodule.exports = mime;\n\n});","sourceLength":2856,"scriptType":2,"compilationType":0,"context":{"ref":0},"text":"/mnt/raid/var/www/tests/filestop/node_modules/mime/mime.js (lines: 115)"}],"refs":[{"handle":0,"type":"context","text":"#<ContextMirror>"}],"running":true}
{"seq":629,"type":"request","command":"scripts","arguments":{"includeSource":true,"ids":[582]}}
{"seq":400,"request_seq":629,"type":"response","command":"scripts","success":true,"body":[{"handle":3,"type":"script","name":"/mnt/raid/var/www/tests/filestop/node_modules/tinyzip/tinyzip.js","id":582,"lineOffset":0,"columnOffset":0,"lineCount":329,"source":"(function (exports, require, module, __filename, __dirname) { var fs = require('fs')\n\t, zlib = require('zlib')\n\t, path = require('path')\n\t, Stream = require('stream')\n\t, util = require('util')\n\t, _ = require('underscore')\n\t;\n\nvar ZipFile = function (opts) {\n\tthis.defOpts = _.extend({rootpath:false, utf8:true, fast:true, compress:{level:-1}},opts);\n\tthis.files = [];\n}\n\nZipFile.prototype.addFile = function (file) {\n\tvar meta = _.extend(_(this.defOpts).clone(),file);\n\tthis.files.push(meta);\n}\n\nZipFile.prototype.getZipStream = function () {\n\treturn new ZipFileStream(this);\n}\n\nZipFile.prototype._getDateTimeHeaders = function (date) {\n\tvar dosTime, dosDate;\n\t\n\tdosTime = date.getHours();\n\tdosTime = dosTime << 6;\n\tdosTime = dosTime | date.getMinutes();\n\tdosTime = dosTime << 5;\n\tdosTime = dosTime | date.getSeconds() / 2;\n\t\n\tdosDate = date.getFullYear() - 1980;\n\tdosDate = dosDate << 4;\n\tdosDate = dosDate | (date.getMonth() + 1);\n\tdosDate = dosDate << 5;\n\tdosDate = dosDate | date.getDate();\n\t\n\treturn {\n\t\tdate: dosDate,\n\t\ttime: dosTime\n\t};\n}\n\nZipFile.prototype._getFileHeader = function (file) {\n\tvar dt = this._getDateTimeHeaders(new Date());\n\t\n\tvar header = new Buffer(26);\n\tvar idx = 0;\n\t\n\t// version + bit flag\n\tidx = writeBytes(header, idx, [ 0x14, 0x00]);\n\t// compression method @todo multiple methods, this is STORE\n\t// header.writeUInt16LE(parseInt(\"0000100000000000\",2),idx); idx+=2;\n\tvar flags =0x0800;\n\tif (file.meta.utf8)\n\t\tflags |= 0x0800;\t\n\tif (file.meta.fast)\n\t\tflags |= 0x0008;\n\theader.writeUInt16LE(flags,idx); idx+=2;\t\n\tidx = writeBytes(header, idx, file.compressIndicator);\n\t// file time & date\n\theader.writeUInt16LE(parseInt(dt.time), idx); idx+=2 \n\theader.writeUInt16LE(parseInt(dt.date), idx); idx+=2\n\t// crc, and sizes are set afterwards\n\t\n\t// crc32\n\theader.writeInt32LE(file.crc32, idx); idx+=4;\n\t// compressed size\n\theader.writeInt32LE(file.compressSize, idx); idx+=4;\n\t// uncompressed size\n\theader.writeInt32LE(file.size, idx); idx+=4;\n\t// file name length\n\theader.writeInt16LE(file.name.length, idx); idx+=2\n\t// add xtra un \n\tif (file.meta.utf8) {\n\t\tvar idx1 = idx;\n\t\tfile.uc = new Buffer(2+2+1+4+file.name.length);\n\t\tidx = 0;\n\t\tfile.uc.writeInt16LE(0x7075,idx); idx+2;\n\t\tfile.uc.writeInt16LE(file.uc.length,idx); idx+=2;\n\t\tfile.uc.writeInt8(1, idx); idx++;\n\t\tfile.uc.writeInt32LE(this._crc32(file.name),idx); idx+=4;\n\t\twriteBytes(file.uc,idx, file.name);\n\t\theader.writeInt16LE(file.uc.length,idx1);\n\t} else {\n\t\theader.writeInt16LE(0,idx);\n\t}\n\treturn header;\n}\t\n\nvar table = [ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D ];\nfunction Crc32 () {\n var crc = 0 ^ -1;\n \n this.processBuffer = function (buf) {\n\t\tfor (var ix = 0; ix < buf.length; ix++) {\n\t\t\tvar offset = (crc ^ buf[ix]) & 0xFF;\n\t\t\tcrc = (crc >>> 8) ^ table[offset];\n\t\t}\n\t\treturn this;\n\t}\n\t\n\tthis.getCrc32 = function () {\n\t\treturn crc ^ -1;\n\t}\n}\n\nZipFile.prototype._crc32 = function (buf) {\n\treturn (new Crc32()).processBuffer(buf).getCrc32();\n}\n\nfunction writeBytes (target, idx, data) {\n for (var ix = 0; ix < data.length; ix++, idx++) {\n target.writeUInt8(data[ix],idx);\n }\n return idx;\n}\n\nvar ZipFileStream = function (zipFile) {\n\tvar self = this;\n\tthis.readable = true;\n\tvar state = \"FILE_START\";\n\tvar findex = 0;\n\tvar fileOffset = 0;\n\tvar dirOffset = 0\n\tvar paused = false;\n\tvar file = null;\n\tvar directory = [];\n\tvar pst = null;\n\tvar next = null;\n\tvar fast = true;\n\t\n\tthis.pause = function () {\n\t\tpaused = true;\n\t\tif (pst) \n\t\t\tpst.pause();\n\t}\n\t\n\tthis.resume = function resume() {\n\t\tpaused = false;\n\t\tif (pst)\n\t\t\tpst.resume()\n\t\telse \n\t\t\tpumpData();\n\t}\n\t\n\tfunction error(err) {\n\t\tself.readable = false;\n\t\tself.emit('error',err);\n\t\tself.emit('close');\n\t}\n\t\n\tfunction pumpData() {\n\t\tif (!self.readable || paused || pst) return;\n\t\tif (state==\"FILE_START\") {\n\t\t\tif (findex < zipFile.files.length) {\n\t\t\t\tfile = {size:0,crc32:0,compressSize:0,meta:zipFile.files[findex]};\n\t\t\t\tstate=file.meta.fast?\"FILE_SENDHEADER\":\"FILE_READ\";\n\t\t\t} else {\n\t\t\t\tstate=\"FILES_DIR\";\n\t\t\t}\n\t\t\tif (!paused) \n\t\t\t\tprocess.nextTick(pumpData);\n\t\t} else if (state==\"FILES_DIR\") {\n\t\t\tif (directory.length==0) {\n\t\t\t\tstate = \"FILES_END\"\n\t\t\t} else {\n\t\t\t\tvar dir = directory.shift();\n\t\t\t\tself.emit(\"data\", dir);\n\t\t\t\tdirOffset+=dir.length;\n\t\t\t}\n\t\t\tif (!paused) \n\t\t\t\tprocess.nextTick(pumpData);\n\t\t} else if (state==\"FILES_END\") {\n var dirEnd = new Buffer(8 + 2 + 2 + 4 + 4 + 2);\n var idx = 0;\n idx = writeBytes(dirEnd, idx, [0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00]);\n // total number of entries\n dirEnd.writeInt16LE(zipFile.files.length, idx); idx+=2;\n dirEnd.writeInt16LE(zipFile.files.length, idx); idx+=2;\n // directory lengths\n dirEnd.writeInt32LE(dirOffset,idx); idx+=4;\n // file lengths\n dirEnd.writeInt32LE(fileOffset,idx); idx+=4\n // and the end of file\n idx = writeBytes(dirEnd, idx, [0x00, 0x00]); \t\t\n self.emit(\"data\",dirEnd);\n\t\t\tself.readable = false;\n\t\t\tself.emit(\"end\");\n\t\t} else if (state==\"FILE_READ\") {\n\t\t\tfs.readFile(zipFile.files[findex].file, function (err, data) {\n\t\t\t\tif (err) return error(err);\n\t\t\t\tstate = \"FILE_COMPRESS\";\n\t\t\t\tfile.data = data;\n\t\t\t\tfile.size = data.length;\n\t\t\t\tfile.crc32 = zipFile._crc32(file.data);\n\t\t\t\tif (!paused) \n\t\t\t\t\tprocess.nextTick(pumpData);\n\t\t\t})\n\t\t} else if (state==\"FILE_COMPRESS\") {\n\t\t\tif (file.meta.compress) {\n\t\t\t\tzlib.deflateRaw(file.data, function (err, data) {\n\t\t\t\t\tif (err) return error(err) ;\n\t\t\t\t\tfile.data = data;\n\t\t\t\t\tfile.compressSize = data.length;\n\t\t\t\t\tfile.compressCrc32 = zipFile._crc32(file.data);\n\t\t\t\t\tstate = \"FILE_SENDHEADER\";\n\t\t\t\t\tif (!paused) \n\t\t\t\t\t\tprocess.nextTick(pumpData);\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tfile.compressSize = data.length;\n\t\t\t\tfile.compressCrc32 = zipFile._crc32(file.data);\n\t\t\t\tstate = \"FILE_SENDHEADER\";\n\t\t\t\tif (!paused) \n\t\t\t\t\tprocess.nextTick(pumpData);\n\t\t\t}\n\t\t} else if (state==\"FILE_SENDHEADER\") {\n\t\t\tif (!file.meta.rootpath)\n\t\t\t\tfile.name = new Buffer(file.meta.file, file.meta.utf8?'utf8':'ascii');\n\t\t\telse\n\t\t\t\tfile.name = new Buffer(path.relative(file.meta.rootpath,file.meta.file), file.meta.utf8?'utf8':'ascii')\n\t\t\t\n\t\t\tif (file.meta.compress)\n\t\t\t\tfile.compressIndicator = [ 0x08, 0x00 ];\n\t\t\telse\n\t\t\t\tfile.compressIndicator = [ 0x00, 0x00 ];\n\t\t\tself.emit(\"data\", new Buffer([0x50, 0x4b, 0x03, 0x04]));\t\n\t\t\tfile.header = zipFile._getFileHeader(file); \t\t\n\t\t\tself.emit(\"data\", file.header)\n\t\t\tself.emit(\"data\", file.name);\n\t\t\tif (file.meta.utf8) \n\t\t\t\tself.emit(\"data\", file.uc);\n\t\t\tstate = \"FILE_SENDDATA\";\n\t\t\tif (!paused) \n\t\t\t\tprocess.nextTick(pumpData);\n\t\t} else if (state==\"FILE_SENDDATA\") {\n\t\t\tif (file.meta.fast) {\n\t\t\t\tvar fi = fs.createReadStream(file.meta.file);\n\t\t\t\tvar cw = fi;\n\t\t\t\tpst = cw;\n\t\t\t\tif (file.meta.compress) {\n\t\t\t\t\tcw = zlib.createDeflateRaw(file.meta.compress);\n\t\t\t\t\tpst = cw;\n\t\t\t\t\tfi.pipe(cw);\t\n\t\t\t\t};\n\t\t\t\tvar crc32o = new Crc32();\n\t\t\t\tvar crc32i = new Crc32();\n\t\t\t\t\n\t\t\t\tvar csize = 0; var size = 0;\n\t\t\t\tfi.on('data', function(data) {\n\t\t\t\t\tcrc32o.processBuffer(data);\n\t\t\t\t\tsize+=data.length;\n\t\t\t\t})\n\t\t\t\tfi.on('end', function(data) {\n\t\t\t\t\tif (data) {\n\t\t\t\t\t\tcrc32o.processBuffer(data);\n\t\t\t\t\t\tsize+=data.length;\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tcw.on('end', function (data) {\n\t\t\t\t\tif (data) {\n\t\t\t\t\t\tcrc32i.processBuffer(data);\n\t\t\t\t\t\tself.emit(\"data\",data);\n\t\t\t\t\t\tcsize+=data.length;\n\t\t\t\t\t}\n\t\t\t\t\tstate=\"FILE_SENDSIGN\";\n\t\t\t\t\tfile.compressSize = csize;\n\t\t\t\t\tfile.size = size;\n\t\t\t\t\tfile.crc32 = crc32o.getCrc32();\n\t\t\t\t\tfile.compressCrc32 = crc32i.getCrc32();\n\t\t\t\t\tfile.header = zipFile._getFileHeader(file); \t\t\n\t\t\t\t\tpst = null;\n\t\t\t\t\tif (!paused) \n\t\t\t\t\t\tprocess.nextTick(pumpData);\n\t\t\t\t})\n\t\t\t\tcw.on('data', function(data) {\n\t\t\t\t\tcrc32i.processBuffer(data);\n\t\t\t\t\tself.emit(\"data\",data);\n\t\t\t\t\tcsize+=data.length;\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tself.emit(\"data\", file.data);\n\t\t\t\tstate=\"FILE_SENDSIGN\";\n\t\t\t\tif (!paused) \n\t\t\t\t\tprocess.nextTick(pumpData);\n\t\t\t}\n\t\t} else if (state==\"FILE_SENDSIGN\") {\n\t\t\tvar eof = new Buffer(16);\n\t\t\tvar idx = 0; \n\t\t\tidx = writeBytes(eof, idx, [ 0x08, 0x07, 0x4b, 0x50 ]);\n eof.writeInt32LE(file.compressCrc32,idx); idx+=4;\n\t\t\teof.writeInt32LE(file.compressSize,idx); idx+=4;\n\t\t\teof.writeInt32LE(file.size,idx); idx+=4;\n\t\t\tself.emit(\"data\", eof);\n\t\t\t\n // now create dir\n\t\t\tvar dirBuffer = new Buffer(4 + 2 + file.header.length + 6 + 4 + 4 + file.name.length+(file.meta.utf8?file.uc.length:0));\n\t\t\tidx = 0;\n\t\t\tidx = writeBytes(dirBuffer, idx, [0x50, 0x4b, 0x01, 0x02]);\n\t\t\tidx = writeBytes(dirBuffer, idx, [0x14, 0x00]);\n\t\t\tidx = writeBytes(dirBuffer, id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment