mirror of
https://github.com/mgerb/mywebsite
synced 2026-01-13 11:12:47 +00:00
Added files
This commit is contained in:
5
mongoui/mongoui-master/node_modules/mongodb/.travis.yml
generated
vendored
Normal file
5
mongoui/mongoui-master/node_modules/mongodb/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- 0.6
|
||||
- 0.8
|
||||
- 0.10 # development version of 0.8, may be unstable
|
||||
23
mongoui/mongoui-master/node_modules/mongodb/CONTRIBUTING.md
generated
vendored
Normal file
23
mongoui/mongoui-master/node_modules/mongodb/CONTRIBUTING.md
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
## Contributing to the driver
|
||||
|
||||
### Bugfixes
|
||||
|
||||
- Before starting to write code, look for existing [tickets](https://github.com/mongodb/node-mongodb-native/issues) or [create one](https://github.com/mongodb/node-mongodb-native/issues/new) for your specific issue. That way you avoid working on something that might not be of interest or that has been addressed already in a different branch.
|
||||
- Fork the [repo](https://github.com/mongodb/node-mongodb-native) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button.
|
||||
- Follow the general coding style of the rest of the project:
|
||||
- 2 space tabs
|
||||
- no trailing whitespace
|
||||
- comma last
|
||||
- inline documentation for new methods, class members, etc
|
||||
- 0 space between conditionals/functions, and their parenthesis and curly braces
|
||||
- `if(..) {`
|
||||
- `for(..) {`
|
||||
- `while(..) {`
|
||||
- `function(err) {`
|
||||
- Write tests and make sure they pass (execute `make test` from the cmd line to run the test suite).
|
||||
|
||||
### Documentation
|
||||
|
||||
To contribute to the [API documentation](http://mongodb.github.com/node-mongodb-native/) just make your changes to the inline documentation of the appropriate [source code](https://github.com/mongodb/node-mongodb-native/tree/master/docs) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button.
|
||||
|
||||
If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute `make generate_docs`. Make sure you have the python documentation framework sphinx installed `easy_install sphinx`. The docs are generated under `docs/build'. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the master branch with your changes.
|
||||
28
mongoui/mongoui-master/node_modules/mongodb/Makefile
generated
vendored
Normal file
28
mongoui/mongoui-master/node_modules/mongodb/Makefile
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
NODE = node
|
||||
NPM = npm
|
||||
NODEUNIT = node_modules/nodeunit/bin/nodeunit
|
||||
DOX = node_modules/dox/bin/dox
|
||||
name = all
|
||||
|
||||
total: build_native
|
||||
|
||||
test_functional:
|
||||
node test/runner.js -t functional
|
||||
|
||||
test_ssl:
|
||||
node test/runner.js -t ssl
|
||||
|
||||
test_replicaset:
|
||||
node test/runner.js -t replicaset
|
||||
|
||||
test_sharded:
|
||||
node test/runner.js -t sharded
|
||||
|
||||
test_auth:
|
||||
node test/runner.js -t auth
|
||||
|
||||
generate_docs:
|
||||
$(NODE) dev/tools/build-docs.js
|
||||
make --directory=./docs/sphinx-docs --file=Makefile html
|
||||
|
||||
.PHONY: total
|
||||
442
mongoui/mongoui-master/node_modules/mongodb/Readme.md
generated
vendored
Normal file
442
mongoui/mongoui-master/node_modules/mongodb/Readme.md
generated
vendored
Normal file
@@ -0,0 +1,442 @@
|
||||
Up to date documentation
|
||||
========================
|
||||
|
||||
[Documentation](http://mongodb.github.com/node-mongodb-native/)
|
||||
|
||||
Install
|
||||
=======
|
||||
|
||||
To install the most recent release from npm, run:
|
||||
|
||||
npm install mongodb
|
||||
|
||||
That may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version)
|
||||
|
||||
To install the latest from the repository, run::
|
||||
|
||||
npm install path/to/node-mongodb-native
|
||||
|
||||
Community
|
||||
=========
|
||||
Check out the google group [node-mongodb-native](http://groups.google.com/group/node-mongodb-native) for questions/answers from users of the driver.
|
||||
|
||||
Try it live
|
||||
============
|
||||
<a href="https://runnable.com/#mongodb/node-mongodb-native/server.js/launch" target="_blank"><img src="https://runnable.com/external/styles/assets/runnablebtn.png" style="width:67px;height:25px;"></a>
|
||||
|
||||
Introduction
|
||||
============
|
||||
|
||||
This is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/.
|
||||
|
||||
A simple example of inserting a document.
|
||||
|
||||
```javascript
|
||||
var client = new Db('test', new Server("127.0.0.1", 27017, {}), {w: 1}),
|
||||
test = function (err, collection) {
|
||||
collection.insert({a:2}, function(err, docs) {
|
||||
|
||||
collection.count(function(err, count) {
|
||||
test.assertEquals(1, count);
|
||||
});
|
||||
|
||||
// Locate all the entries using find
|
||||
collection.find().toArray(function(err, results) {
|
||||
test.assertEquals(1, results.length);
|
||||
test.assertTrue(results[0].a === 2);
|
||||
|
||||
// Let's close the db
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
client.open(function(err, p_client) {
|
||||
client.collection('test_insert', test);
|
||||
});
|
||||
```
|
||||
|
||||
Data types
|
||||
==========
|
||||
|
||||
To store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code).
|
||||
|
||||
In particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example:
|
||||
|
||||
```javascript
|
||||
// Get the objectID type
|
||||
var ObjectID = require('mongodb').ObjectID;
|
||||
|
||||
var idString = '4e4e1638c85e808431000003';
|
||||
collection.findOne({_id: new ObjectID(idString)}, console.log) // ok
|
||||
collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined
|
||||
```
|
||||
|
||||
Here are the constructors the non-Javascript BSON primitive types:
|
||||
|
||||
```javascript
|
||||
// Fetch the library
|
||||
var mongo = require('mongodb');
|
||||
// Create new instances of BSON types
|
||||
new mongo.Long(numberString)
|
||||
new mongo.ObjectID(hexString)
|
||||
new mongo.Timestamp() // the actual unique number is generated on insert.
|
||||
new mongo.DBRef(collectionName, id, dbName)
|
||||
new mongo.Binary(buffer) // takes a string or Buffer
|
||||
new mongo.Code(code, [context])
|
||||
new mongo.Symbol(string)
|
||||
new mongo.MinKey()
|
||||
new mongo.MaxKey()
|
||||
new mongo.Double(number) // Force double storage
|
||||
```
|
||||
|
||||
The C/C++ bson parser/serializer
|
||||
--------------------------------
|
||||
|
||||
If you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below
|
||||
|
||||
```javascript
|
||||
// using native_parser:
|
||||
var client = new Db('integration_tests_20',
|
||||
new Server("127.0.0.1", 27017),
|
||||
{native_parser:true});
|
||||
```
|
||||
|
||||
The C++ parser uses the js objects both for serialization and deserialization.
|
||||
|
||||
GitHub information
|
||||
==================
|
||||
|
||||
The source code is available at http://github.com/mongodb/node-mongodb-native.
|
||||
You can either clone the repository or download a tarball of the latest release.
|
||||
|
||||
Once you have the source you can test the driver by running
|
||||
|
||||
$ make test
|
||||
|
||||
in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.
|
||||
|
||||
Examples
|
||||
========
|
||||
|
||||
For examples look in the examples/ directory. You can execute the examples using node.
|
||||
|
||||
$ cd examples
|
||||
$ node queries.js
|
||||
|
||||
GridStore
|
||||
=========
|
||||
|
||||
The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.
|
||||
|
||||
For more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md)
|
||||
|
||||
Replicasets
|
||||
===========
|
||||
For more information about how to connect to a replicaset have a look at [Replicasets](https://github.com/mongodb/node-mongodb-native/blob/master/docs/replicaset.md)
|
||||
|
||||
Primary Key Factories
|
||||
---------------------
|
||||
|
||||
Defining your own primary key factory allows you to generate your own series of id's
|
||||
(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long "string".
|
||||
|
||||
Simple example below
|
||||
|
||||
```javascript
|
||||
// Custom factory (need to provide a 12 byte array);
|
||||
CustomPKFactory = function() {}
|
||||
CustomPKFactory.prototype = new Object();
|
||||
CustomPKFactory.createPk = function() {
|
||||
return new ObjectID("aaaaaaaaaaaa");
|
||||
}
|
||||
|
||||
var p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory});
|
||||
p_client.open(function(err, p_client) {
|
||||
p_client.dropDatabase(function(err, done) {
|
||||
p_client.createCollection('test_custom_key', function(err, collection) {
|
||||
collection.insert({'a':1}, function(err, docs) {
|
||||
collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) {
|
||||
cursor.toArray(function(err, items) {
|
||||
test.assertEquals(1, items.length);
|
||||
|
||||
// Let's close the db
|
||||
p_client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Strict mode
|
||||
-----------
|
||||
|
||||
Each database has an optional strict mode. If it is set then asking for a collection
|
||||
that does not exist will return an Error object in the callback. Similarly if you
|
||||
attempt to create a collection that already exists. Strict is provided for convenience.
|
||||
|
||||
```javascript
|
||||
var error_client = new Db('integration_tests_', new Server("127.0.0.1", 27017, {auto_reconnect: false}), {strict:true});
|
||||
test.assertEquals(true, error_client.strict);
|
||||
|
||||
error_client.open(function(err, error_client) {
|
||||
error_client.collection('does-not-exist', function(err, collection) {
|
||||
test.assertTrue(err instanceof Error);
|
||||
test.assertEquals("Collection does-not-exist does not exist. Currently in strict mode.", err.message);
|
||||
});
|
||||
|
||||
error_client.createCollection('test_strict_access_collection', function(err, collection) {
|
||||
error_client.collection('test_strict_access_collection', function(err, collection) {
|
||||
test.assertTrue(collection instanceof Collection);
|
||||
// Let's close the db
|
||||
error_client.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Documentation
|
||||
=============
|
||||
|
||||
If this document doesn't answer your questions, see the source of
|
||||
[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js)
|
||||
or [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js),
|
||||
or the documentation at MongoDB for query and update formats.
|
||||
|
||||
Find
|
||||
----
|
||||
|
||||
The find method is actually a factory method to create
|
||||
Cursor objects. A Cursor lazily uses the connection the first time
|
||||
you call `nextObject`, `each`, or `toArray`.
|
||||
|
||||
The basic operation on a cursor is the `nextObject` method
|
||||
that fetches the next matching document from the database. The convenience
|
||||
methods `each` and `toArray` call `nextObject` until the cursor is exhausted.
|
||||
|
||||
Signatures:
|
||||
|
||||
```javascript
|
||||
var cursor = collection.find(query, [fields], options);
|
||||
cursor.sort(fields).limit(n).skip(m).
|
||||
|
||||
cursor.nextObject(function(err, doc) {});
|
||||
cursor.each(function(err, doc) {});
|
||||
cursor.toArray(function(err, docs) {});
|
||||
|
||||
cursor.rewind() // reset the cursor to its initial state.
|
||||
```
|
||||
|
||||
Useful chainable methods of cursor. These can optionally be options of `find` instead of method calls:
|
||||
|
||||
* `.limit(n).skip(m)` to control paging.
|
||||
* `.sort(fields)` Order by the given fields. There are several equivalent syntaxes:
|
||||
* `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2.
|
||||
* `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above
|
||||
* `.sort([['field1', 'desc'], 'field2'])` same as above
|
||||
* `.sort('field1')` ascending by field1
|
||||
|
||||
Other options of `find`:
|
||||
|
||||
* `fields` the fields to fetch (to avoid transferring the entire document)
|
||||
* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors).
|
||||
* `batchSize` The number of the subset of results to request the database
|
||||
to return for every request. This should initially be greater than 1 otherwise
|
||||
the database will automatically close the cursor. The batch size can be set to 1
|
||||
with `batchSize(n, function(err){})` after performing the initial query to the database.
|
||||
* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint).
|
||||
* `explain` turns this into an explain query. You can also call
|
||||
`explain()` on any cursor to fetch the explanation.
|
||||
* `snapshot` prevents documents that are updated while the query is active
|
||||
from being returned multiple times. See more
|
||||
[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database).
|
||||
* `timeout` if false, asks MongoDb not to time out this cursor after an
|
||||
inactivity period.
|
||||
|
||||
|
||||
For information on how to create queries, see the
|
||||
[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).
|
||||
|
||||
```javascript
|
||||
var mongodb = require('mongodb');
|
||||
var server = new mongodb.Server("127.0.0.1", 27017, {});
|
||||
new mongodb.Db('test', server, {}).open(function (error, client) {
|
||||
if (error) throw error;
|
||||
var collection = new mongodb.Collection(client, 'test_collection');
|
||||
collection.find({}, {limit:10}).toArray(function(err, docs) {
|
||||
console.dir(docs);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Insert
|
||||
------
|
||||
|
||||
Signature:
|
||||
|
||||
```javascript
|
||||
collection.insert(docs, options, [callback]);
|
||||
```
|
||||
|
||||
where `docs` can be a single document or an array of documents.
|
||||
|
||||
Useful options:
|
||||
|
||||
* `safe:true` Should always set if you have a callback.
|
||||
|
||||
See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).
|
||||
|
||||
```javascript
|
||||
var mongodb = require('mongodb');
|
||||
var server = new mongodb.Server("127.0.0.1", 27017, {});
|
||||
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
|
||||
if (error) throw error;
|
||||
var collection = new mongodb.Collection(client, 'test_collection');
|
||||
collection.insert({hello: 'world'}, {safe:true},
|
||||
function(err, objects) {
|
||||
if (err) console.warn(err.message);
|
||||
if (err && err.message.indexOf('E11000 ') !== -1) {
|
||||
// this _id was already inserted in the database
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Note that there's no reason to pass a callback to the insert or update commands
|
||||
unless you use the `safe:true` option. If you don't specify `safe:true`, then
|
||||
your callback will be called immediately.
|
||||
|
||||
Update; update and insert (upsert)
|
||||
----------------------------------
|
||||
|
||||
The update operation will update the first document that matches your query
|
||||
(or all documents that match if you use `multi:true`).
|
||||
If `safe:true`, `upsert` is not set, and no documents match, your callback will return 0 documents updated.
|
||||
|
||||
See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for
|
||||
the modifier (`$inc`, `$set`, `$push`, etc.) formats.
|
||||
|
||||
Signature:
|
||||
|
||||
```javascript
|
||||
collection.update(criteria, objNew, options, [callback]);
|
||||
```
|
||||
|
||||
Useful options:
|
||||
|
||||
* `safe:true` Should always set if you have a callback.
|
||||
* `multi:true` If set, all matching documents are updated, not just the first.
|
||||
* `upsert:true` Atomically inserts the document if no documents matched.
|
||||
|
||||
Example for `update`:
|
||||
|
||||
```javascript
|
||||
var mongodb = require('mongodb');
|
||||
var server = new mongodb.Server("127.0.0.1", 27017, {});
|
||||
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
|
||||
if (error) throw error;
|
||||
var collection = new mongodb.Collection(client, 'test_collection');
|
||||
collection.update({hi: 'here'}, {$set: {hi: 'there'}}, {safe:true},
|
||||
function(err) {
|
||||
if (err) console.warn(err.message);
|
||||
else console.log('successfully updated');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Find and modify
|
||||
---------------
|
||||
|
||||
`findAndModify` is like `update`, but it also gives the updated document to
|
||||
your callback. But there are a few key differences between findAndModify and
|
||||
update:
|
||||
|
||||
1. The signatures differ.
|
||||
2. You can only findAndModify a single item, not multiple items.
|
||||
|
||||
Signature:
|
||||
|
||||
```javascript
|
||||
collection.findAndModify(query, sort, update, options, callback)
|
||||
```
|
||||
|
||||
The sort parameter is used to specify which object to operate on, if more than
|
||||
one document matches. It takes the same format as the cursor sort (see
|
||||
Connection.find above).
|
||||
|
||||
See the
|
||||
[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)
|
||||
for more details.
|
||||
|
||||
Useful options:
|
||||
|
||||
* `remove:true` set to a true to remove the object before returning
|
||||
* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove.
|
||||
* `upsert:true` Atomically inserts the document if no documents matched.
|
||||
|
||||
Example for `findAndModify`:
|
||||
|
||||
```javascript
|
||||
var mongodb = require('mongodb');
|
||||
var server = new mongodb.Server("127.0.0.1", 27017, {});
|
||||
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
|
||||
if (error) throw error;
|
||||
var collection = new mongodb.Collection(client, 'test_collection');
|
||||
collection.findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {},
|
||||
function(err, object) {
|
||||
if (err) console.warn(err.message);
|
||||
else console.dir(object); // undefined if no matching object exists.
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Save
|
||||
----
|
||||
|
||||
The `save` method is a shorthand for upsert if the document contains an
|
||||
`_id`, or an insert if there is no `_id`.
|
||||
|
||||
Sponsors
|
||||
========
|
||||
Just as Felix Geisendörfer I'm also working on the driver for my own startup and this driver is a big project that also benefits other companies who are using MongoDB.
|
||||
|
||||
If your company could benefit from a even better-engineered node.js mongodb driver I would appreciate any type of sponsorship you may be able to provide. All the sponsors will get a lifetime display in this readme, priority support and help on problems and votes on the roadmap decisions for the driver. If you are interested contact me on [christkv AT g m a i l.com](mailto:christkv@gmail.com) for details.
|
||||
|
||||
And I'm very thankful for code contributions. If you are interested in working on features please contact me so we can discuss API design and testing.
|
||||
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
See HISTORY
|
||||
|
||||
Credits
|
||||
=======
|
||||
|
||||
1. [10gen](http://github.com/mongodb/mongo-ruby-driver/)
|
||||
2. [Google Closure Library](http://code.google.com/closure/library/)
|
||||
3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser)
|
||||
|
||||
Contributors
|
||||
============
|
||||
|
||||
Aaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
Copyright 2009 - 2012 Christian Amor Kvalheim.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
1
mongoui/mongoui-master/node_modules/mongodb/index.js
generated
vendored
Executable file
1
mongoui/mongoui-master/node_modules/mongodb/index.js
generated
vendored
Executable file
@@ -0,0 +1 @@
|
||||
module.exports = require('./lib/mongodb');
|
||||
40
mongoui/mongoui-master/node_modules/mongodb/install.js
generated
vendored
Normal file
40
mongoui/mongoui-master/node_modules/mongodb/install.js
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
var spawn = require('child_process').spawn,
|
||||
exec = require('child_process').exec;
|
||||
|
||||
process.stdout.write("================================================================================\n");
|
||||
process.stdout.write("= =\n");
|
||||
process.stdout.write("= To install with C++ bson parser do <npm install mongodb --mongodb:native> =\n");
|
||||
process.stdout.write("= =\n");
|
||||
process.stdout.write("================================================================================\n");
|
||||
|
||||
// Check if we want to build the native code
|
||||
var build_native = process.env['npm_package_config_native'] != null ? process.env['npm_package_config_native'] : 'false';
|
||||
build_native = build_native == 'true' ? true : false;
|
||||
// If we are building the native bson extension ensure we use gmake if available
|
||||
if(build_native) {
|
||||
// Check if we need to use gmake
|
||||
exec('which gmake', function(err, stdout, stderr) {
|
||||
// Set up spawn command
|
||||
var make = null;
|
||||
// No gmake build using make
|
||||
if(err != null) {
|
||||
make = spawn('make', ['total']);
|
||||
} else {
|
||||
make = spawn('gmake', ['total']);
|
||||
}
|
||||
|
||||
// Execute spawn
|
||||
make.stdout.on('data', function(data) {
|
||||
process.stdout.write(data);
|
||||
})
|
||||
|
||||
make.stderr.on('data', function(data) {
|
||||
process.stdout.write(data);
|
||||
})
|
||||
|
||||
make.on('exit', function(code) {
|
||||
process.stdout.write('child process exited with code ' + code + "\n");
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
339
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/admin.js
generated
vendored
Normal file
339
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/admin.js
generated
vendored
Normal file
@@ -0,0 +1,339 @@
|
||||
/*!
|
||||
* Module dependencies.
|
||||
*/
|
||||
var Collection = require('./collection').Collection,
|
||||
Cursor = require('./cursor').Cursor,
|
||||
DbCommand = require('./commands/db_command').DbCommand,
|
||||
utils = require('./utils');
|
||||
|
||||
/**
|
||||
* Allows the user to access the admin functionality of MongoDB
|
||||
*
|
||||
* @class Represents the Admin methods of MongoDB.
|
||||
* @param {Object} db Current db instance we wish to perform Admin operations on.
|
||||
* @return {Function} Constructor for Admin type.
|
||||
*/
|
||||
function Admin(db) {
|
||||
if(!(this instanceof Admin)) return new Admin(db);
|
||||
this.db = db;
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @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 buildInfo or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.buildInfo = function(callback) {
|
||||
this.serverInfo(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @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 serverInfo or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api private
|
||||
*/
|
||||
Admin.prototype.serverInfo = function(callback) {
|
||||
this.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) {
|
||||
if(err != null) return callback(err, null);
|
||||
return callback(null, doc.documents[0]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve this db's server status.
|
||||
*
|
||||
* @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 serverStatus or null if an error occured.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.serverStatus = function(callback) {
|
||||
var self = this;
|
||||
|
||||
this.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) {
|
||||
if(err == null && doc.documents[0].ok === 1) {
|
||||
callback(null, doc.documents[0]);
|
||||
} else {
|
||||
if(err) return callback(err, false);
|
||||
return callback(utils.toError(doc.documents[0]), false);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the current profiling Level for MongoDB
|
||||
*
|
||||
* @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 profilingLevel or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.profilingLevel = function(callback) {
|
||||
var self = this;
|
||||
|
||||
this.db.executeDbAdminCommand({profile:-1}, function(err, doc) {
|
||||
doc = doc.documents[0];
|
||||
|
||||
if(err == null && doc.ok === 1) {
|
||||
var was = doc.was;
|
||||
if(was == 0) return callback(null, "off");
|
||||
if(was == 1) return callback(null, "slow_only");
|
||||
if(was == 2) return callback(null, "all");
|
||||
return callback(new Error("Error: illegal profiling level value " + was), null);
|
||||
} else {
|
||||
err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Ping the MongoDB server and retrieve results
|
||||
*
|
||||
* @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 ping or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.ping = function(options, callback) {
|
||||
// Unpack calls
|
||||
var args = Array.prototype.slice.call(arguments, 0);
|
||||
callback = args.pop();
|
||||
|
||||
this.db.executeDbAdminCommand({ping: 1}, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate against MongoDB
|
||||
*
|
||||
* @param {String} username The user name for the authentication.
|
||||
* @param {String} password The password for the authentication.
|
||||
* @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 authenticate or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.authenticate = function(username, password, callback) {
|
||||
this.db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) {
|
||||
return callback(err, doc);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout current authenticated user
|
||||
*
|
||||
* @param {Object} [options] Optional parameters to the command.
|
||||
* @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.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.logout = function(callback) {
|
||||
this.db.logout({authdb: 'admin'}, function(err, doc) {
|
||||
return callback(err, doc);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a user to the MongoDB server, if the user exists it will
|
||||
* overwrite the current password
|
||||
*
|
||||
* Options
|
||||
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
|
||||
*
|
||||
* @param {String} username The user name for the authentication.
|
||||
* @param {String} password The password for the authentication.
|
||||
* @param {Object} [options] additional options during update.
|
||||
* @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.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.addUser = function(username, password, options, callback) {
|
||||
var args = Array.prototype.slice.call(arguments, 2);
|
||||
callback = args.pop();
|
||||
options = args.length ? args.shift() : {};
|
||||
|
||||
options.dbName = 'admin';
|
||||
// Add user
|
||||
this.db.addUser(username, password, options, function(err, doc) {
|
||||
return callback(err, doc);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a user from the MongoDB server
|
||||
*
|
||||
* Options
|
||||
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
|
||||
*
|
||||
* @param {String} username The user name for the authentication.
|
||||
* @param {Object} [options] additional options during update.
|
||||
* @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.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.removeUser = function(username, options, callback) {
|
||||
var self = this;
|
||||
var args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = args.pop();
|
||||
options = args.length ? args.shift() : {};
|
||||
options.dbName = 'admin';
|
||||
|
||||
this.db.removeUser(username, options, function(err, doc) {
|
||||
return callback(err, doc);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current profiling level of MongoDB
|
||||
*
|
||||
* @param {String} level The new profiling level (off, slow_only, all)
|
||||
* @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 setProfilingLevel or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.setProfilingLevel = function(level, callback) {
|
||||
var self = this;
|
||||
var command = {};
|
||||
var profile = 0;
|
||||
|
||||
if(level == "off") {
|
||||
profile = 0;
|
||||
} else if(level == "slow_only") {
|
||||
profile = 1;
|
||||
} else if(level == "all") {
|
||||
profile = 2;
|
||||
} else {
|
||||
return callback(new Error("Error: illegal profiling level value " + level));
|
||||
}
|
||||
|
||||
// Set up the profile number
|
||||
command['profile'] = profile;
|
||||
|
||||
this.db.executeDbAdminCommand(command, function(err, doc) {
|
||||
doc = doc.documents[0];
|
||||
|
||||
if(err == null && doc.ok === 1)
|
||||
return callback(null, level);
|
||||
return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrive the current profiling information for MongoDB
|
||||
*
|
||||
* @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 profilingInfo or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.profilingInfo = function(callback) {
|
||||
try {
|
||||
new Cursor(this.db, new Collection(this.db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}, {}, {dbName: 'admin'}).toArray(function(err, items) {
|
||||
return callback(err, items);
|
||||
});
|
||||
} catch (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Execute a db command against the Admin database
|
||||
*
|
||||
* @param {Object} command A command object `{ping:1}`.
|
||||
* @param {Object} [options] Optional parameters to the command.
|
||||
* @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.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.command = function(command, options, callback) {
|
||||
var self = this;
|
||||
var args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = args.pop();
|
||||
options = args.length ? args.shift() : {};
|
||||
|
||||
// Execute a command
|
||||
this.db.executeDbAdminCommand(command, options, function(err, doc) {
|
||||
// Ensure change before event loop executes
|
||||
return callback != null ? callback(err, doc) : null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an existing collection
|
||||
*
|
||||
* @param {String} collectionName The name of the collection to validate.
|
||||
* @param {Object} [options] Optional parameters to the command.
|
||||
* @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 validateCollection or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.validateCollection = function(collectionName, options, callback) {
|
||||
var args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = args.pop();
|
||||
options = args.length ? args.shift() : {};
|
||||
|
||||
var self = this;
|
||||
var command = {validate: collectionName};
|
||||
var keys = Object.keys(options);
|
||||
|
||||
// Decorate command with extra options
|
||||
for(var i = 0; i < keys.length; i++) {
|
||||
if(options.hasOwnProperty(keys[i])) {
|
||||
command[keys[i]] = options[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
this.db.executeDbCommand(command, function(err, doc) {
|
||||
if(err != null) return callback(err, null);
|
||||
doc = doc.documents[0];
|
||||
|
||||
if(doc.ok === 0)
|
||||
return callback(new Error("Error with validate command"), null);
|
||||
if(doc.result != null && doc.result.constructor != String)
|
||||
return callback(new Error("Error with validation data"), null);
|
||||
if(doc.result != null && doc.result.match(/exception|corrupt/) != null)
|
||||
return callback(new Error("Error: invalid collection " + collectionName), null);
|
||||
if(doc.valid != null && !doc.valid)
|
||||
return callback(new Error("Error: invalid collection " + collectionName), null);
|
||||
|
||||
return callback(null, doc);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* List the available databases
|
||||
*
|
||||
* @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 listDatabases or null if an error occured.
|
||||
* @return {null} Returns no result
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.listDatabases = function(callback) {
|
||||
// Execute the listAllDatabases command
|
||||
this.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) {
|
||||
if(err != null) return callback(err, null);
|
||||
return callback(null, doc.documents[0]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ReplicaSet status
|
||||
*
|
||||
* @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 replSetGetStatus or null if an error occured.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Admin.prototype.replSetGetStatus = function(callback) {
|
||||
var self = this;
|
||||
|
||||
this.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) {
|
||||
if(err == null && doc.documents[0].ok === 1)
|
||||
return callback(null, doc.documents[0]);
|
||||
if(err) return callback(err, false);
|
||||
return callback(utils.toError(doc.documents[0]), false);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports.Admin = Admin;
|
||||
1762
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/collection.js
generated
vendored
Normal file
1762
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/collection.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
29
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/base_command.js
generated
vendored
Normal file
29
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/base_command.js
generated
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
Base object used for common functionality
|
||||
**/
|
||||
var BaseCommand = exports.BaseCommand = function BaseCommand() {
|
||||
};
|
||||
|
||||
var id = 1;
|
||||
BaseCommand.prototype.getRequestId = function getRequestId() {
|
||||
if (!this.requestId) this.requestId = id++;
|
||||
return this.requestId;
|
||||
};
|
||||
|
||||
BaseCommand.prototype.setMongosReadPreference = function setMongosReadPreference(readPreference, tags) {}
|
||||
|
||||
BaseCommand.prototype.updateRequestId = function() {
|
||||
this.requestId = id++;
|
||||
return this.requestId;
|
||||
};
|
||||
|
||||
// OpCodes
|
||||
BaseCommand.OP_REPLY = 1;
|
||||
BaseCommand.OP_MSG = 1000;
|
||||
BaseCommand.OP_UPDATE = 2001;
|
||||
BaseCommand.OP_INSERT = 2002;
|
||||
BaseCommand.OP_GET_BY_OID = 2003;
|
||||
BaseCommand.OP_QUERY = 2004;
|
||||
BaseCommand.OP_GET_MORE = 2005;
|
||||
BaseCommand.OP_DELETE = 2006;
|
||||
BaseCommand.OP_KILL_CURSORS = 2007;
|
||||
241
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/db_command.js
generated
vendored
Normal file
241
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/db_command.js
generated
vendored
Normal file
@@ -0,0 +1,241 @@
|
||||
var QueryCommand = require('./query_command').QueryCommand,
|
||||
InsertCommand = require('./insert_command').InsertCommand,
|
||||
inherits = require('util').inherits,
|
||||
utils = require('../utils'),
|
||||
crypto = require('crypto');
|
||||
|
||||
/**
|
||||
Db Command
|
||||
**/
|
||||
var DbCommand = exports.DbCommand = function(dbInstance, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) {
|
||||
QueryCommand.call(this);
|
||||
this.collectionName = collectionName;
|
||||
this.queryOptions = queryOptions;
|
||||
this.numberToSkip = numberToSkip;
|
||||
this.numberToReturn = numberToReturn;
|
||||
this.query = query;
|
||||
this.returnFieldSelector = returnFieldSelector;
|
||||
this.db = dbInstance;
|
||||
|
||||
// Make sure we don't get a null exception
|
||||
options = options == null ? {} : options;
|
||||
// Let us defined on a command basis if we want functions to be serialized or not
|
||||
if(options['serializeFunctions'] != null && options['serializeFunctions']) {
|
||||
this.serializeFunctions = true;
|
||||
}
|
||||
};
|
||||
|
||||
inherits(DbCommand, QueryCommand);
|
||||
|
||||
// Constants
|
||||
DbCommand.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
|
||||
DbCommand.SYSTEM_INDEX_COLLECTION = "system.indexes";
|
||||
DbCommand.SYSTEM_PROFILE_COLLECTION = "system.profile";
|
||||
DbCommand.SYSTEM_USER_COLLECTION = "system.users";
|
||||
DbCommand.SYSTEM_COMMAND_COLLECTION = "$cmd";
|
||||
DbCommand.SYSTEM_JS_COLLECTION = "system.js";
|
||||
|
||||
// New commands
|
||||
DbCommand.NcreateIsMasterCommand = function(db, databaseName) {
|
||||
return new DbCommand(db, databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null);
|
||||
};
|
||||
|
||||
// Provide constructors for different db commands
|
||||
DbCommand.createIsMasterCommand = function(db) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null);
|
||||
};
|
||||
|
||||
DbCommand.createCollectionInfoCommand = function(db, selector) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_NAMESPACE_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, 0, selector, null);
|
||||
};
|
||||
|
||||
DbCommand.createGetNonceCommand = function(db, options) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'getnonce':1}, null);
|
||||
};
|
||||
|
||||
DbCommand.createAuthenticationCommand = function(db, username, password, nonce, authdb) {
|
||||
// Use node md5 generator
|
||||
var md5 = crypto.createHash('md5');
|
||||
// Generate keys used for authentication
|
||||
md5.update(username + ":mongo:" + password);
|
||||
var hash_password = md5.digest('hex');
|
||||
// Final key
|
||||
md5 = crypto.createHash('md5');
|
||||
md5.update(nonce + username + hash_password);
|
||||
var key = md5.digest('hex');
|
||||
// Creat selector
|
||||
var selector = {'authenticate':1, 'user':username, 'nonce':nonce, 'key':key};
|
||||
// Create db command
|
||||
return new DbCommand(db, authdb + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NONE, 0, -1, selector, null);
|
||||
};
|
||||
|
||||
DbCommand.createLogoutCommand = function(db) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'logout':1}, null);
|
||||
};
|
||||
|
||||
DbCommand.createCreateCollectionCommand = function(db, collectionName, options) {
|
||||
var selector = {'create':collectionName};
|
||||
// Modify the options to ensure correct behaviour
|
||||
for(var name in options) {
|
||||
if(options[name] != null && options[name].constructor != Function) selector[name] = options[name];
|
||||
}
|
||||
// Execute the command
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, selector, null);
|
||||
};
|
||||
|
||||
DbCommand.createDropCollectionCommand = function(db, collectionName) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'drop':collectionName}, null);
|
||||
};
|
||||
|
||||
DbCommand.createRenameCollectionCommand = function(db, fromCollectionName, toCollectionName, options) {
|
||||
var renameCollection = db.databaseName + "." + fromCollectionName;
|
||||
var toCollection = db.databaseName + "." + toCollectionName;
|
||||
var dropTarget = options && options.dropTarget ? options.dropTarget : false;
|
||||
return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}, null);
|
||||
};
|
||||
|
||||
DbCommand.createGetLastErrorCommand = function(options, db) {
|
||||
|
||||
if (typeof db === 'undefined') {
|
||||
db = options;
|
||||
options = {};
|
||||
}
|
||||
// Final command
|
||||
var command = {'getlasterror':1};
|
||||
// If we have an options Object let's merge in the fields (fsync/wtimeout/w)
|
||||
if('object' === typeof options) {
|
||||
for(var name in options) {
|
||||
command[name] = options[name]
|
||||
}
|
||||
}
|
||||
|
||||
// Special case for w == 1, remove the w
|
||||
if(1 == command.w) {
|
||||
delete command.w;
|
||||
}
|
||||
|
||||
// Execute command
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command, null);
|
||||
};
|
||||
|
||||
DbCommand.createGetLastStatusCommand = DbCommand.createGetLastErrorCommand;
|
||||
|
||||
DbCommand.createGetPreviousErrorsCommand = function(db) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'getpreverror':1}, null);
|
||||
};
|
||||
|
||||
DbCommand.createResetErrorHistoryCommand = function(db) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'reseterror':1}, null);
|
||||
};
|
||||
|
||||
DbCommand.createCreateIndexCommand = function(db, collectionName, fieldOrSpec, options) {
|
||||
var fieldHash = {};
|
||||
var indexes = [];
|
||||
var keys;
|
||||
|
||||
// Get all the fields accordingly
|
||||
if('string' == typeof fieldOrSpec) {
|
||||
// 'type'
|
||||
indexes.push(fieldOrSpec + '_' + 1);
|
||||
fieldHash[fieldOrSpec] = 1;
|
||||
|
||||
} else if(utils.isArray(fieldOrSpec)) {
|
||||
|
||||
fieldOrSpec.forEach(function(f) {
|
||||
if('string' == typeof f) {
|
||||
// [{location:'2d'}, 'type']
|
||||
indexes.push(f + '_' + 1);
|
||||
fieldHash[f] = 1;
|
||||
} else if(utils.isArray(f)) {
|
||||
// [['location', '2d'],['type', 1]]
|
||||
indexes.push(f[0] + '_' + (f[1] || 1));
|
||||
fieldHash[f[0]] = f[1] || 1;
|
||||
} else if(utils.isObject(f)) {
|
||||
// [{location:'2d'}, {type:1}]
|
||||
keys = Object.keys(f);
|
||||
keys.forEach(function(k) {
|
||||
indexes.push(k + '_' + f[k]);
|
||||
fieldHash[k] = f[k];
|
||||
});
|
||||
} else {
|
||||
// undefined (ignore)
|
||||
}
|
||||
});
|
||||
|
||||
} else if(utils.isObject(fieldOrSpec)) {
|
||||
// {location:'2d', type:1}
|
||||
keys = Object.keys(fieldOrSpec);
|
||||
keys.forEach(function(key) {
|
||||
indexes.push(key + '_' + fieldOrSpec[key]);
|
||||
fieldHash[key] = fieldOrSpec[key];
|
||||
});
|
||||
}
|
||||
|
||||
// Generate the index name
|
||||
var indexName = typeof options.name == 'string'
|
||||
? options.name
|
||||
: indexes.join("_");
|
||||
|
||||
var selector = {
|
||||
'ns': db.databaseName + "." + collectionName,
|
||||
'key': fieldHash,
|
||||
'name': indexName
|
||||
}
|
||||
|
||||
// Ensure we have a correct finalUnique
|
||||
var finalUnique = options == null || 'object' === typeof options
|
||||
? false
|
||||
: options;
|
||||
|
||||
// Set up options
|
||||
options = options == null || typeof options == 'boolean'
|
||||
? {}
|
||||
: options;
|
||||
|
||||
// Add all the options
|
||||
var keys = Object.keys(options);
|
||||
for(var i = 0; i < keys.length; i++) {
|
||||
selector[keys[i]] = options[keys[i]];
|
||||
}
|
||||
|
||||
if(selector['unique'] == null)
|
||||
selector['unique'] = finalUnique;
|
||||
|
||||
var name = db.databaseName + "." + DbCommand.SYSTEM_INDEX_COLLECTION;
|
||||
var cmd = new InsertCommand(db, name, false);
|
||||
return cmd.add(selector);
|
||||
};
|
||||
|
||||
DbCommand.logoutCommand = function(db, command_hash, options) {
|
||||
var dbName = options != null && options['authdb'] != null ? options['authdb'] : db.databaseName;
|
||||
// Create logout command
|
||||
return new DbCommand(db, dbName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null);
|
||||
}
|
||||
|
||||
DbCommand.createDropIndexCommand = function(db, collectionName, indexName) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'deleteIndexes':collectionName, 'index':indexName}, null);
|
||||
};
|
||||
|
||||
DbCommand.createReIndexCommand = function(db, collectionName) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'reIndex':collectionName}, null);
|
||||
};
|
||||
|
||||
DbCommand.createDropDatabaseCommand = function(db) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'dropDatabase':1}, null);
|
||||
};
|
||||
|
||||
DbCommand.createDbCommand = function(db, command_hash, options) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null, options);
|
||||
};
|
||||
|
||||
DbCommand.createAdminDbCommand = function(db, command_hash) {
|
||||
return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null);
|
||||
};
|
||||
|
||||
DbCommand.createAdminDbCommandSlaveOk = function(db, command_hash) {
|
||||
return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null);
|
||||
};
|
||||
|
||||
DbCommand.createDbSlaveOkCommand = function(db, command_hash, options) {
|
||||
return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null, options);
|
||||
};
|
||||
114
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/delete_command.js
generated
vendored
Normal file
114
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/delete_command.js
generated
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
var BaseCommand = require('./base_command').BaseCommand,
|
||||
inherits = require('util').inherits;
|
||||
|
||||
/**
|
||||
Insert Document Command
|
||||
**/
|
||||
var DeleteCommand = exports.DeleteCommand = function(db, collectionName, selector, flags) {
|
||||
BaseCommand.call(this);
|
||||
|
||||
// Validate correctness off the selector
|
||||
var object = selector;
|
||||
if(Buffer.isBuffer(object)) {
|
||||
var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
|
||||
if(object_size != object.length) {
|
||||
var error = new Error("delete raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
|
||||
error.name = 'MongoError';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
this.flags = flags;
|
||||
this.collectionName = collectionName;
|
||||
this.selector = selector;
|
||||
this.db = db;
|
||||
};
|
||||
|
||||
inherits(DeleteCommand, BaseCommand);
|
||||
|
||||
DeleteCommand.OP_DELETE = 2006;
|
||||
|
||||
/*
|
||||
struct {
|
||||
MsgHeader header; // standard message header
|
||||
int32 ZERO; // 0 - reserved for future use
|
||||
cstring fullCollectionName; // "dbname.collectionname"
|
||||
int32 ZERO; // 0 - reserved for future use
|
||||
mongo.BSON selector; // query object. See below for details.
|
||||
}
|
||||
*/
|
||||
DeleteCommand.prototype.toBinary = function() {
|
||||
// Calculate total length of the document
|
||||
var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.selector, false, true) + (4 * 4);
|
||||
// Let's build the single pass buffer command
|
||||
var _index = 0;
|
||||
var _command = new Buffer(totalLengthOfCommand);
|
||||
// Write the header information to the buffer
|
||||
_command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
|
||||
_command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
|
||||
_command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
|
||||
_command[_index] = totalLengthOfCommand & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write the request ID
|
||||
_command[_index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_command[_index] = this.requestId & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
// Write the op_code for the command
|
||||
_command[_index + 3] = (DeleteCommand.OP_DELETE >> 24) & 0xff;
|
||||
_command[_index + 2] = (DeleteCommand.OP_DELETE >> 16) & 0xff;
|
||||
_command[_index + 1] = (DeleteCommand.OP_DELETE >> 8) & 0xff;
|
||||
_command[_index] = DeleteCommand.OP_DELETE & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
|
||||
// Write the collection name to the command
|
||||
_index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
|
||||
_command[_index - 1] = 0;
|
||||
|
||||
// Write the flags
|
||||
_command[_index + 3] = (this.flags >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.flags >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.flags >> 8) & 0xff;
|
||||
_command[_index] = this.flags & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Document binary length
|
||||
var documentLength = 0
|
||||
|
||||
// Serialize the selector
|
||||
// If we are passing a raw buffer, do minimal validation
|
||||
if(Buffer.isBuffer(this.selector)) {
|
||||
documentLength = this.selector.length;
|
||||
// Copy the data into the current buffer
|
||||
this.selector.copy(_command, _index);
|
||||
} else {
|
||||
documentLength = this.db.bson.serializeWithBufferAndIndex(this.selector, this.checkKeys, _command, _index) - _index + 1;
|
||||
}
|
||||
|
||||
// Write the length to the document
|
||||
_command[_index + 3] = (documentLength >> 24) & 0xff;
|
||||
_command[_index + 2] = (documentLength >> 16) & 0xff;
|
||||
_command[_index + 1] = (documentLength >> 8) & 0xff;
|
||||
_command[_index] = documentLength & 0xff;
|
||||
// Update index in buffer
|
||||
_index = _index + documentLength;
|
||||
// Add terminating 0 for the object
|
||||
_command[_index - 1] = 0;
|
||||
return _command;
|
||||
};
|
||||
83
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/get_more_command.js
generated
vendored
Normal file
83
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/get_more_command.js
generated
vendored
Normal file
@@ -0,0 +1,83 @@
|
||||
var BaseCommand = require('./base_command').BaseCommand,
|
||||
inherits = require('util').inherits,
|
||||
binaryutils = require('../utils');
|
||||
|
||||
/**
|
||||
Get More Document Command
|
||||
**/
|
||||
var GetMoreCommand = exports.GetMoreCommand = function(db, collectionName, numberToReturn, cursorId) {
|
||||
BaseCommand.call(this);
|
||||
|
||||
this.collectionName = collectionName;
|
||||
this.numberToReturn = numberToReturn;
|
||||
this.cursorId = cursorId;
|
||||
this.db = db;
|
||||
};
|
||||
|
||||
inherits(GetMoreCommand, BaseCommand);
|
||||
|
||||
GetMoreCommand.OP_GET_MORE = 2005;
|
||||
|
||||
GetMoreCommand.prototype.toBinary = function() {
|
||||
// Calculate total length of the document
|
||||
var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 8 + (4 * 4);
|
||||
// Let's build the single pass buffer command
|
||||
var _index = 0;
|
||||
var _command = new Buffer(totalLengthOfCommand);
|
||||
// Write the header information to the buffer
|
||||
_command[_index++] = totalLengthOfCommand & 0xff;
|
||||
_command[_index++] = (totalLengthOfCommand >> 8) & 0xff;
|
||||
_command[_index++] = (totalLengthOfCommand >> 16) & 0xff;
|
||||
_command[_index++] = (totalLengthOfCommand >> 24) & 0xff;
|
||||
|
||||
// Write the request ID
|
||||
_command[_index++] = this.requestId & 0xff;
|
||||
_command[_index++] = (this.requestId >> 8) & 0xff;
|
||||
_command[_index++] = (this.requestId >> 16) & 0xff;
|
||||
_command[_index++] = (this.requestId >> 24) & 0xff;
|
||||
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
|
||||
// Write the op_code for the command
|
||||
_command[_index++] = GetMoreCommand.OP_GET_MORE & 0xff;
|
||||
_command[_index++] = (GetMoreCommand.OP_GET_MORE >> 8) & 0xff;
|
||||
_command[_index++] = (GetMoreCommand.OP_GET_MORE >> 16) & 0xff;
|
||||
_command[_index++] = (GetMoreCommand.OP_GET_MORE >> 24) & 0xff;
|
||||
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
|
||||
// Write the collection name to the command
|
||||
_index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
|
||||
_command[_index - 1] = 0;
|
||||
|
||||
// Number of documents to return
|
||||
_command[_index++] = this.numberToReturn & 0xff;
|
||||
_command[_index++] = (this.numberToReturn >> 8) & 0xff;
|
||||
_command[_index++] = (this.numberToReturn >> 16) & 0xff;
|
||||
_command[_index++] = (this.numberToReturn >> 24) & 0xff;
|
||||
|
||||
// Encode the cursor id
|
||||
var low_bits = this.cursorId.getLowBits();
|
||||
// Encode low bits
|
||||
_command[_index++] = low_bits & 0xff;
|
||||
_command[_index++] = (low_bits >> 8) & 0xff;
|
||||
_command[_index++] = (low_bits >> 16) & 0xff;
|
||||
_command[_index++] = (low_bits >> 24) & 0xff;
|
||||
|
||||
var high_bits = this.cursorId.getHighBits();
|
||||
// Encode high bits
|
||||
_command[_index++] = high_bits & 0xff;
|
||||
_command[_index++] = (high_bits >> 8) & 0xff;
|
||||
_command[_index++] = (high_bits >> 16) & 0xff;
|
||||
_command[_index++] = (high_bits >> 24) & 0xff;
|
||||
// Return command
|
||||
return _command;
|
||||
};
|
||||
147
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/insert_command.js
generated
vendored
Normal file
147
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/insert_command.js
generated
vendored
Normal file
@@ -0,0 +1,147 @@
|
||||
var BaseCommand = require('./base_command').BaseCommand,
|
||||
inherits = require('util').inherits;
|
||||
|
||||
/**
|
||||
Insert Document Command
|
||||
**/
|
||||
var InsertCommand = exports.InsertCommand = function(db, collectionName, checkKeys, options) {
|
||||
BaseCommand.call(this);
|
||||
|
||||
this.collectionName = collectionName;
|
||||
this.documents = [];
|
||||
this.checkKeys = checkKeys == null ? true : checkKeys;
|
||||
this.db = db;
|
||||
this.flags = 0;
|
||||
this.serializeFunctions = false;
|
||||
|
||||
// Ensure valid options hash
|
||||
options = options == null ? {} : options;
|
||||
|
||||
// Check if we have keepGoing set -> set flag if it's the case
|
||||
if(options['keepGoing'] != null && options['keepGoing']) {
|
||||
// This will finish inserting all non-index violating documents even if it returns an error
|
||||
this.flags = 1;
|
||||
}
|
||||
|
||||
// Check if we have keepGoing set -> set flag if it's the case
|
||||
if(options['continueOnError'] != null && options['continueOnError']) {
|
||||
// This will finish inserting all non-index violating documents even if it returns an error
|
||||
this.flags = 1;
|
||||
}
|
||||
|
||||
// Let us defined on a command basis if we want functions to be serialized or not
|
||||
if(options['serializeFunctions'] != null && options['serializeFunctions']) {
|
||||
this.serializeFunctions = true;
|
||||
}
|
||||
};
|
||||
|
||||
inherits(InsertCommand, BaseCommand);
|
||||
|
||||
// OpCodes
|
||||
InsertCommand.OP_INSERT = 2002;
|
||||
|
||||
InsertCommand.prototype.add = function(document) {
|
||||
if(Buffer.isBuffer(document)) {
|
||||
var object_size = document[0] | document[1] << 8 | document[2] << 16 | document[3] << 24;
|
||||
if(object_size != document.length) {
|
||||
var error = new Error("insert raw message size does not match message header size [" + document.length + "] != [" + object_size + "]");
|
||||
error.name = 'MongoError';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
this.documents.push(document);
|
||||
return this;
|
||||
};
|
||||
|
||||
/*
|
||||
struct {
|
||||
MsgHeader header; // standard message header
|
||||
int32 ZERO; // 0 - reserved for future use
|
||||
cstring fullCollectionName; // "dbname.collectionname"
|
||||
BSON[] documents; // one or more documents to insert into the collection
|
||||
}
|
||||
*/
|
||||
InsertCommand.prototype.toBinary = function() {
|
||||
// Calculate total length of the document
|
||||
var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + (4 * 4);
|
||||
// var docLength = 0
|
||||
for(var i = 0; i < this.documents.length; i++) {
|
||||
if(Buffer.isBuffer(this.documents[i])) {
|
||||
totalLengthOfCommand += this.documents[i].length;
|
||||
} else {
|
||||
// Calculate size of document
|
||||
totalLengthOfCommand += this.db.bson.calculateObjectSize(this.documents[i], this.serializeFunctions, true);
|
||||
}
|
||||
}
|
||||
|
||||
// Let's build the single pass buffer command
|
||||
var _index = 0;
|
||||
var _command = new Buffer(totalLengthOfCommand);
|
||||
// Write the header information to the buffer
|
||||
_command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
|
||||
_command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
|
||||
_command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
|
||||
_command[_index] = totalLengthOfCommand & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write the request ID
|
||||
_command[_index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_command[_index] = this.requestId & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
// Write the op_code for the command
|
||||
_command[_index + 3] = (InsertCommand.OP_INSERT >> 24) & 0xff;
|
||||
_command[_index + 2] = (InsertCommand.OP_INSERT >> 16) & 0xff;
|
||||
_command[_index + 1] = (InsertCommand.OP_INSERT >> 8) & 0xff;
|
||||
_command[_index] = InsertCommand.OP_INSERT & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write flags if any
|
||||
_command[_index + 3] = (this.flags >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.flags >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.flags >> 8) & 0xff;
|
||||
_command[_index] = this.flags & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write the collection name to the command
|
||||
_index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
|
||||
_command[_index - 1] = 0;
|
||||
|
||||
// Write all the bson documents to the buffer at the index offset
|
||||
for(var i = 0; i < this.documents.length; i++) {
|
||||
// Document binary length
|
||||
var documentLength = 0
|
||||
var object = this.documents[i];
|
||||
|
||||
// Serialize the selector
|
||||
// If we are passing a raw buffer, do minimal validation
|
||||
if(Buffer.isBuffer(object)) {
|
||||
documentLength = object.length;
|
||||
// Copy the data into the current buffer
|
||||
object.copy(_command, _index);
|
||||
} else {
|
||||
// Serialize the document straight to the buffer
|
||||
documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1;
|
||||
}
|
||||
|
||||
// Write the length to the document
|
||||
_command[_index + 3] = (documentLength >> 24) & 0xff;
|
||||
_command[_index + 2] = (documentLength >> 16) & 0xff;
|
||||
_command[_index + 1] = (documentLength >> 8) & 0xff;
|
||||
_command[_index] = documentLength & 0xff;
|
||||
// Update index in buffer
|
||||
_index = _index + documentLength;
|
||||
// Add terminating 0 for the object
|
||||
_command[_index - 1] = 0;
|
||||
}
|
||||
|
||||
return _command;
|
||||
};
|
||||
98
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js
generated
vendored
Normal file
98
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js
generated
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
var BaseCommand = require('./base_command').BaseCommand,
|
||||
inherits = require('util').inherits,
|
||||
binaryutils = require('../utils');
|
||||
|
||||
/**
|
||||
Insert Document Command
|
||||
**/
|
||||
var KillCursorCommand = exports.KillCursorCommand = function(db, cursorIds) {
|
||||
BaseCommand.call(this);
|
||||
|
||||
this.cursorIds = cursorIds;
|
||||
this.db = db;
|
||||
};
|
||||
|
||||
inherits(KillCursorCommand, BaseCommand);
|
||||
|
||||
KillCursorCommand.OP_KILL_CURSORS = 2007;
|
||||
|
||||
/*
|
||||
struct {
|
||||
MsgHeader header; // standard message header
|
||||
int32 ZERO; // 0 - reserved for future use
|
||||
int32 numberOfCursorIDs; // number of cursorIDs in message
|
||||
int64[] cursorIDs; // array of cursorIDs to close
|
||||
}
|
||||
*/
|
||||
KillCursorCommand.prototype.toBinary = function() {
|
||||
// Calculate total length of the document
|
||||
var totalLengthOfCommand = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8);
|
||||
// Let's build the single pass buffer command
|
||||
var _index = 0;
|
||||
var _command = new Buffer(totalLengthOfCommand);
|
||||
// Write the header information to the buffer
|
||||
_command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
|
||||
_command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
|
||||
_command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
|
||||
_command[_index] = totalLengthOfCommand & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write the request ID
|
||||
_command[_index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_command[_index] = this.requestId & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
// Write the op_code for the command
|
||||
_command[_index + 3] = (KillCursorCommand.OP_KILL_CURSORS >> 24) & 0xff;
|
||||
_command[_index + 2] = (KillCursorCommand.OP_KILL_CURSORS >> 16) & 0xff;
|
||||
_command[_index + 1] = (KillCursorCommand.OP_KILL_CURSORS >> 8) & 0xff;
|
||||
_command[_index] = KillCursorCommand.OP_KILL_CURSORS & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
|
||||
// Number of cursors to kill
|
||||
var numberOfCursors = this.cursorIds.length;
|
||||
_command[_index + 3] = (numberOfCursors >> 24) & 0xff;
|
||||
_command[_index + 2] = (numberOfCursors >> 16) & 0xff;
|
||||
_command[_index + 1] = (numberOfCursors >> 8) & 0xff;
|
||||
_command[_index] = numberOfCursors & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Encode all the cursors
|
||||
for(var i = 0; i < this.cursorIds.length; i++) {
|
||||
// Encode the cursor id
|
||||
var low_bits = this.cursorIds[i].getLowBits();
|
||||
// Encode low bits
|
||||
_command[_index + 3] = (low_bits >> 24) & 0xff;
|
||||
_command[_index + 2] = (low_bits >> 16) & 0xff;
|
||||
_command[_index + 1] = (low_bits >> 8) & 0xff;
|
||||
_command[_index] = low_bits & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
var high_bits = this.cursorIds[i].getHighBits();
|
||||
// Encode high bits
|
||||
_command[_index + 3] = (high_bits >> 24) & 0xff;
|
||||
_command[_index + 2] = (high_bits >> 16) & 0xff;
|
||||
_command[_index + 1] = (high_bits >> 8) & 0xff;
|
||||
_command[_index] = high_bits & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
}
|
||||
|
||||
return _command;
|
||||
};
|
||||
261
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/query_command.js
generated
vendored
Normal file
261
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/query_command.js
generated
vendored
Normal file
@@ -0,0 +1,261 @@
|
||||
var BaseCommand = require('./base_command').BaseCommand,
|
||||
inherits = require('util').inherits;
|
||||
|
||||
/**
|
||||
Insert Document Command
|
||||
**/
|
||||
var QueryCommand = exports.QueryCommand = function(db, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) {
|
||||
BaseCommand.call(this);
|
||||
|
||||
// Validate correctness off the selector
|
||||
var object = query,
|
||||
object_size;
|
||||
if(Buffer.isBuffer(object)) {
|
||||
object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
|
||||
if(object_size != object.length) {
|
||||
var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
|
||||
error.name = 'MongoError';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
object = returnFieldSelector;
|
||||
if(Buffer.isBuffer(object)) {
|
||||
object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
|
||||
if(object_size != object.length) {
|
||||
var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
|
||||
error.name = 'MongoError';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Make sure we don't get a null exception
|
||||
options = options == null ? {} : options;
|
||||
// Set up options
|
||||
this.collectionName = collectionName;
|
||||
this.queryOptions = queryOptions;
|
||||
this.numberToSkip = numberToSkip;
|
||||
this.numberToReturn = numberToReturn;
|
||||
|
||||
// Ensure we have no null query
|
||||
query = query == null ? {} : query;
|
||||
// Wrap query in the $query parameter so we can add read preferences for mongos
|
||||
this.query = query;
|
||||
this.returnFieldSelector = returnFieldSelector;
|
||||
this.db = db;
|
||||
|
||||
// Let us defined on a command basis if we want functions to be serialized or not
|
||||
if(options['serializeFunctions'] != null && options['serializeFunctions']) {
|
||||
this.serializeFunctions = true;
|
||||
}
|
||||
};
|
||||
|
||||
inherits(QueryCommand, BaseCommand);
|
||||
|
||||
QueryCommand.OP_QUERY = 2004;
|
||||
|
||||
/*
|
||||
* Adds the read prefrence to the current command
|
||||
*/
|
||||
QueryCommand.prototype.setMongosReadPreference = function(readPreference, tags) {
|
||||
// If we have readPreference set to true set to secondary prefered
|
||||
if(readPreference == true) {
|
||||
readPreference = 'secondaryPreferred';
|
||||
} else if(readPreference == 'false') {
|
||||
readPreference = 'primary';
|
||||
}
|
||||
|
||||
// Force the slave ok flag to be set if we are not using primary read preference
|
||||
if(readPreference != false && readPreference != 'primary') {
|
||||
this.queryOptions |= QueryCommand.OPTS_SLAVE;
|
||||
}
|
||||
|
||||
// Backward compatibility, ensure $query only set on read preference so 1.8.X works
|
||||
if((readPreference != null || tags != null) && this.query['$query'] == null) {
|
||||
this.query = {'$query': this.query};
|
||||
}
|
||||
|
||||
// If we have no readPreference set and no tags, check if the slaveOk bit is set
|
||||
if(readPreference == null && tags == null) {
|
||||
// If we have a slaveOk bit set the read preference for MongoS
|
||||
if(this.queryOptions & QueryCommand.OPTS_SLAVE) {
|
||||
this.query['$readPreference'] = {mode: 'secondary'}
|
||||
} else {
|
||||
this.query['$readPreference'] = {mode: 'primary'}
|
||||
}
|
||||
}
|
||||
|
||||
// Build read preference object
|
||||
if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') {
|
||||
this.query['$readPreference'] = readPreference.toObject();
|
||||
} else if(readPreference != null) {
|
||||
// Add the read preference
|
||||
this.query['$readPreference'] = {mode: readPreference};
|
||||
|
||||
// If we have tags let's add them
|
||||
if(tags != null) {
|
||||
this.query['$readPreference']['tags'] = tags;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
struct {
|
||||
MsgHeader header; // standard message header
|
||||
int32 opts; // query options. See below for details.
|
||||
cstring fullCollectionName; // "dbname.collectionname"
|
||||
int32 numberToSkip; // number of documents to skip when returning results
|
||||
int32 numberToReturn; // number of documents to return in the first OP_REPLY
|
||||
BSON query ; // query object. See below for details.
|
||||
[ BSON returnFieldSelector; ] // OPTIONAL : selector indicating the fields to return. See below for details.
|
||||
}
|
||||
*/
|
||||
QueryCommand.prototype.toBinary = function() {
|
||||
// Total length of the command
|
||||
var totalLengthOfCommand = 0;
|
||||
// Calculate total length of the document
|
||||
if(Buffer.isBuffer(this.query)) {
|
||||
totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.query.length + (4 * 4);
|
||||
} else {
|
||||
totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.db.bson.calculateObjectSize(this.query, this.serializeFunctions, true) + (4 * 4);
|
||||
}
|
||||
|
||||
// Calculate extra fields size
|
||||
if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) {
|
||||
if(Object.keys(this.returnFieldSelector).length > 0) {
|
||||
totalLengthOfCommand += this.db.bson.calculateObjectSize(this.returnFieldSelector, this.serializeFunctions, true);
|
||||
}
|
||||
} else if(Buffer.isBuffer(this.returnFieldSelector)) {
|
||||
totalLengthOfCommand += this.returnFieldSelector.length;
|
||||
}
|
||||
|
||||
// Let's build the single pass buffer command
|
||||
var _index = 0;
|
||||
var _command = new Buffer(totalLengthOfCommand);
|
||||
// Write the header information to the buffer
|
||||
_command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
|
||||
_command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
|
||||
_command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
|
||||
_command[_index] = totalLengthOfCommand & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write the request ID
|
||||
_command[_index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_command[_index] = this.requestId & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
// Write the op_code for the command
|
||||
_command[_index + 3] = (QueryCommand.OP_QUERY >> 24) & 0xff;
|
||||
_command[_index + 2] = (QueryCommand.OP_QUERY >> 16) & 0xff;
|
||||
_command[_index + 1] = (QueryCommand.OP_QUERY >> 8) & 0xff;
|
||||
_command[_index] = QueryCommand.OP_QUERY & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Write the query options
|
||||
_command[_index + 3] = (this.queryOptions >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.queryOptions >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.queryOptions >> 8) & 0xff;
|
||||
_command[_index] = this.queryOptions & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Write the collection name to the command
|
||||
_index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
|
||||
_command[_index - 1] = 0;
|
||||
|
||||
// Write the number of documents to skip
|
||||
_command[_index + 3] = (this.numberToSkip >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.numberToSkip >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.numberToSkip >> 8) & 0xff;
|
||||
_command[_index] = this.numberToSkip & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Write the number of documents to return
|
||||
_command[_index + 3] = (this.numberToReturn >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.numberToReturn >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.numberToReturn >> 8) & 0xff;
|
||||
_command[_index] = this.numberToReturn & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Document binary length
|
||||
var documentLength = 0
|
||||
var object = this.query;
|
||||
|
||||
// Serialize the selector
|
||||
if(Buffer.isBuffer(object)) {
|
||||
documentLength = object.length;
|
||||
// Copy the data into the current buffer
|
||||
object.copy(_command, _index);
|
||||
} else {
|
||||
// Serialize the document straight to the buffer
|
||||
documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1;
|
||||
}
|
||||
|
||||
// Write the length to the document
|
||||
_command[_index + 3] = (documentLength >> 24) & 0xff;
|
||||
_command[_index + 2] = (documentLength >> 16) & 0xff;
|
||||
_command[_index + 1] = (documentLength >> 8) & 0xff;
|
||||
_command[_index] = documentLength & 0xff;
|
||||
// Update index in buffer
|
||||
_index = _index + documentLength;
|
||||
// Add terminating 0 for the object
|
||||
_command[_index - 1] = 0;
|
||||
|
||||
// Push field selector if available
|
||||
if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) {
|
||||
if(Object.keys(this.returnFieldSelector).length > 0) {
|
||||
var documentLength = this.db.bson.serializeWithBufferAndIndex(this.returnFieldSelector, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1;
|
||||
// Write the length to the document
|
||||
_command[_index + 3] = (documentLength >> 24) & 0xff;
|
||||
_command[_index + 2] = (documentLength >> 16) & 0xff;
|
||||
_command[_index + 1] = (documentLength >> 8) & 0xff;
|
||||
_command[_index] = documentLength & 0xff;
|
||||
// Update index in buffer
|
||||
_index = _index + documentLength;
|
||||
// Add terminating 0 for the object
|
||||
_command[_index - 1] = 0;
|
||||
}
|
||||
} if(this.returnFieldSelector != null && Buffer.isBuffer(this.returnFieldSelector)) {
|
||||
// Document binary length
|
||||
var documentLength = 0
|
||||
var object = this.returnFieldSelector;
|
||||
|
||||
// Serialize the selector
|
||||
documentLength = object.length;
|
||||
// Copy the data into the current buffer
|
||||
object.copy(_command, _index);
|
||||
|
||||
// Write the length to the document
|
||||
_command[_index + 3] = (documentLength >> 24) & 0xff;
|
||||
_command[_index + 2] = (documentLength >> 16) & 0xff;
|
||||
_command[_index + 1] = (documentLength >> 8) & 0xff;
|
||||
_command[_index] = documentLength & 0xff;
|
||||
// Update index in buffer
|
||||
_index = _index + documentLength;
|
||||
// Add terminating 0 for the object
|
||||
_command[_index - 1] = 0;
|
||||
}
|
||||
|
||||
// Return finished command
|
||||
return _command;
|
||||
};
|
||||
|
||||
// Constants
|
||||
QueryCommand.OPTS_NONE = 0;
|
||||
QueryCommand.OPTS_TAILABLE_CURSOR = 2;
|
||||
QueryCommand.OPTS_SLAVE = 4;
|
||||
QueryCommand.OPTS_OPLOG_REPLY = 8;
|
||||
QueryCommand.OPTS_NO_CURSOR_TIMEOUT = 16;
|
||||
QueryCommand.OPTS_AWAIT_DATA = 32;
|
||||
QueryCommand.OPTS_EXHAUST = 64;
|
||||
QueryCommand.OPTS_PARTIAL = 128;
|
||||
174
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/update_command.js
generated
vendored
Normal file
174
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/commands/update_command.js
generated
vendored
Normal file
@@ -0,0 +1,174 @@
|
||||
var BaseCommand = require('./base_command').BaseCommand,
|
||||
inherits = require('util').inherits;
|
||||
|
||||
/**
|
||||
Update Document Command
|
||||
**/
|
||||
var UpdateCommand = exports.UpdateCommand = function(db, collectionName, spec, document, options) {
|
||||
BaseCommand.call(this);
|
||||
|
||||
var object = spec;
|
||||
if(Buffer.isBuffer(object)) {
|
||||
var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
|
||||
if(object_size != object.length) {
|
||||
var error = new Error("update spec raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
|
||||
error.name = 'MongoError';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
var object = document;
|
||||
if(Buffer.isBuffer(object)) {
|
||||
var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
|
||||
if(object_size != object.length) {
|
||||
var error = new Error("update document raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
|
||||
error.name = 'MongoError';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
this.collectionName = collectionName;
|
||||
this.spec = spec;
|
||||
this.document = document;
|
||||
this.db = db;
|
||||
this.serializeFunctions = false;
|
||||
|
||||
// Generate correct flags
|
||||
var db_upsert = 0;
|
||||
var db_multi_update = 0;
|
||||
db_upsert = options != null && options['upsert'] != null ? (options['upsert'] == true ? 1 : 0) : db_upsert;
|
||||
db_multi_update = options != null && options['multi'] != null ? (options['multi'] == true ? 1 : 0) : db_multi_update;
|
||||
|
||||
// Flags
|
||||
this.flags = parseInt(db_multi_update.toString() + db_upsert.toString(), 2);
|
||||
// Let us defined on a command basis if we want functions to be serialized or not
|
||||
if(options['serializeFunctions'] != null && options['serializeFunctions']) {
|
||||
this.serializeFunctions = true;
|
||||
}
|
||||
};
|
||||
|
||||
inherits(UpdateCommand, BaseCommand);
|
||||
|
||||
UpdateCommand.OP_UPDATE = 2001;
|
||||
|
||||
/*
|
||||
struct {
|
||||
MsgHeader header; // standard message header
|
||||
int32 ZERO; // 0 - reserved for future use
|
||||
cstring fullCollectionName; // "dbname.collectionname"
|
||||
int32 flags; // bit vector. see below
|
||||
BSON spec; // the query to select the document
|
||||
BSON document; // the document data to update with or insert
|
||||
}
|
||||
*/
|
||||
UpdateCommand.prototype.toBinary = function() {
|
||||
// Calculate total length of the document
|
||||
var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.spec, false, true) +
|
||||
this.db.bson.calculateObjectSize(this.document, this.serializeFunctions, true) + (4 * 4);
|
||||
|
||||
// Let's build the single pass buffer command
|
||||
var _index = 0;
|
||||
var _command = new Buffer(totalLengthOfCommand);
|
||||
// Write the header information to the buffer
|
||||
_command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff;
|
||||
_command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff;
|
||||
_command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff;
|
||||
_command[_index] = totalLengthOfCommand & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write the request ID
|
||||
_command[_index + 3] = (this.requestId >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.requestId >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.requestId >> 8) & 0xff;
|
||||
_command[_index] = this.requestId & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
// Write the op_code for the command
|
||||
_command[_index + 3] = (UpdateCommand.OP_UPDATE >> 24) & 0xff;
|
||||
_command[_index + 2] = (UpdateCommand.OP_UPDATE >> 16) & 0xff;
|
||||
_command[_index + 1] = (UpdateCommand.OP_UPDATE >> 8) & 0xff;
|
||||
_command[_index] = UpdateCommand.OP_UPDATE & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Write zero
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
_command[_index++] = 0;
|
||||
|
||||
// Write the collection name to the command
|
||||
_index = _index + _command.write(this.collectionName, _index, 'utf8') + 1;
|
||||
_command[_index - 1] = 0;
|
||||
|
||||
// Write the update flags
|
||||
_command[_index + 3] = (this.flags >> 24) & 0xff;
|
||||
_command[_index + 2] = (this.flags >> 16) & 0xff;
|
||||
_command[_index + 1] = (this.flags >> 8) & 0xff;
|
||||
_command[_index] = this.flags & 0xff;
|
||||
// Adjust index
|
||||
_index = _index + 4;
|
||||
|
||||
// Document binary length
|
||||
var documentLength = 0
|
||||
var object = this.spec;
|
||||
|
||||
// Serialize the selector
|
||||
// If we are passing a raw buffer, do minimal validation
|
||||
if(Buffer.isBuffer(object)) {
|
||||
var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
|
||||
if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
|
||||
documentLength = object.length;
|
||||
// Copy the data into the current buffer
|
||||
object.copy(_command, _index);
|
||||
} else {
|
||||
documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, false) - _index + 1;
|
||||
}
|
||||
|
||||
// Write the length to the document
|
||||
_command[_index + 3] = (documentLength >> 24) & 0xff;
|
||||
_command[_index + 2] = (documentLength >> 16) & 0xff;
|
||||
_command[_index + 1] = (documentLength >> 8) & 0xff;
|
||||
_command[_index] = documentLength & 0xff;
|
||||
// Update index in buffer
|
||||
_index = _index + documentLength;
|
||||
// Add terminating 0 for the object
|
||||
_command[_index - 1] = 0;
|
||||
|
||||
// Document binary length
|
||||
var documentLength = 0
|
||||
var object = this.document;
|
||||
|
||||
// Serialize the document
|
||||
// If we are passing a raw buffer, do minimal validation
|
||||
if(Buffer.isBuffer(object)) {
|
||||
var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
|
||||
if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
|
||||
documentLength = object.length;
|
||||
// Copy the data into the current buffer
|
||||
object.copy(_command, _index);
|
||||
} else {
|
||||
documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1;
|
||||
}
|
||||
|
||||
// Write the length to the document
|
||||
_command[_index + 3] = (documentLength >> 24) & 0xff;
|
||||
_command[_index + 2] = (documentLength >> 16) & 0xff;
|
||||
_command[_index + 1] = (documentLength >> 8) & 0xff;
|
||||
_command[_index] = documentLength & 0xff;
|
||||
// Update index in buffer
|
||||
_index = _index + documentLength;
|
||||
// Add terminating 0 for the object
|
||||
_command[_index - 1] = 0;
|
||||
|
||||
return _command;
|
||||
};
|
||||
|
||||
// Constants
|
||||
UpdateCommand.DB_UPSERT = 0;
|
||||
UpdateCommand.DB_MULTI_UPDATE = 1;
|
||||
169
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/base.js
generated
vendored
Normal file
169
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/base.js
generated
vendored
Normal file
@@ -0,0 +1,169 @@
|
||||
var EventEmitter = require('events').EventEmitter
|
||||
, inherits = require('util').inherits;
|
||||
|
||||
/**
|
||||
* Internal class for callback storage
|
||||
* @ignore
|
||||
*/
|
||||
var CallbackStore = function() {
|
||||
// Make class an event emitter
|
||||
EventEmitter.call(this);
|
||||
// Add a info about call variable
|
||||
this._notReplied = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
inherits(CallbackStore, EventEmitter);
|
||||
|
||||
var Base = function Base() {
|
||||
EventEmitter.call(this);
|
||||
|
||||
// Callback store is part of connection specification
|
||||
if(Base._callBackStore == null) {
|
||||
Base._callBackStore = new CallbackStore();
|
||||
}
|
||||
|
||||
// this._callBackStore = Base._callBackStore;
|
||||
this._callBackStore = new CallbackStore();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
inherits(Base, EventEmitter);
|
||||
|
||||
/**
|
||||
* Fire all the errors
|
||||
* @ignore
|
||||
*/
|
||||
Base.prototype.__executeAllCallbacksWithError = function(err) {
|
||||
// Check all callbacks
|
||||
var keys = Object.keys(this._callBackStore._notReplied);
|
||||
// For each key check if it's a callback that needs to be returned
|
||||
for(var j = 0; j < keys.length; j++) {
|
||||
var info = this._callBackStore._notReplied[keys[j]];
|
||||
// Check if we have a chained command (findAndModify)
|
||||
if(info && info['chained'] && Array.isArray(info['chained']) && info['chained'].length > 0) {
|
||||
var chained = info['chained'];
|
||||
// Only callback once and the last one is the right one
|
||||
var finalCallback = chained.pop();
|
||||
// Emit only the last event
|
||||
this._callBackStore.emit(finalCallback, err, null);
|
||||
|
||||
// Put back the final callback to ensure we don't call all commands in the chain
|
||||
chained.push(finalCallback);
|
||||
|
||||
// Remove all chained callbacks
|
||||
for(var i = 0; i < chained.length; i++) {
|
||||
delete this._callBackStore._notReplied[chained[i]];
|
||||
}
|
||||
} else {
|
||||
this._callBackStore.emit(keys[j], err, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a handler
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Base.prototype._registerHandler = function(db_command, raw, connection, exhaust, callback) {
|
||||
// If we have an array of commands, chain them
|
||||
var chained = Array.isArray(db_command);
|
||||
|
||||
// Check if we have exhausted
|
||||
if(typeof exhaust == 'function') {
|
||||
callback = exhaust;
|
||||
exhaust = false;
|
||||
}
|
||||
|
||||
// If they are chained we need to add a special handler situation
|
||||
if(chained) {
|
||||
// List off chained id's
|
||||
var chainedIds = [];
|
||||
// Add all id's
|
||||
for(var i = 0; i < db_command.length; i++) chainedIds.push(db_command[i].getRequestId().toString());
|
||||
// Register all the commands together
|
||||
for(var i = 0; i < db_command.length; i++) {
|
||||
var command = db_command[i];
|
||||
// Add the callback to the store
|
||||
this._callBackStore.once(command.getRequestId(), callback);
|
||||
// Add the information about the reply
|
||||
this._callBackStore._notReplied[command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, chained:chainedIds, connection:connection, exhaust:false};
|
||||
}
|
||||
} else {
|
||||
// Add the callback to the list of handlers
|
||||
this._callBackStore.once(db_command.getRequestId(), callback);
|
||||
// Add the information about the reply
|
||||
this._callBackStore._notReplied[db_command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, connection:connection, exhaust:exhaust};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-Register a handler, on the cursor id f.ex
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Base.prototype._reRegisterHandler = function(newId, object, callback) {
|
||||
// Add the callback to the list of handlers
|
||||
this._callBackStore.once(newId, object.callback.listener);
|
||||
// Add the information about the reply
|
||||
this._callBackStore._notReplied[newId] = object.info;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Base.prototype._callHandler = function(id, document, err) {
|
||||
// If there is a callback peform it
|
||||
if(this._callBackStore.listeners(id).length >= 1) {
|
||||
// Get info object
|
||||
var info = this._callBackStore._notReplied[id];
|
||||
// Delete the current object
|
||||
delete this._callBackStore._notReplied[id];
|
||||
// Emit to the callback of the object
|
||||
this._callBackStore.emit(id, err, document, info.connection);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Base.prototype._hasHandler = function(id) {
|
||||
// If there is a callback peform it
|
||||
return this._callBackStore.listeners(id).length >= 1;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Base.prototype._removeHandler = function(id) {
|
||||
// Remove the information
|
||||
if(this._callBackStore._notReplied[id] != null) delete this._callBackStore._notReplied[id];
|
||||
// Remove the callback if it's registered
|
||||
this._callBackStore.removeAllListeners(id);
|
||||
// Force cleanup _events, node.js seems to set it as a null value
|
||||
if(this._callBackStore._events != null) delete this._callBackStore._events[id];
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Base.prototype._findHandler = function(id) {
|
||||
var info = this._callBackStore._notReplied[id];
|
||||
// Return the callback
|
||||
return {info:info, callback:(this._callBackStore.listeners(id).length >= 1) ? this._callBackStore.listeners(id)[0] : null}
|
||||
}
|
||||
|
||||
exports.Base = Base;
|
||||
504
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/connection.js
generated
vendored
Normal file
504
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/connection.js
generated
vendored
Normal file
@@ -0,0 +1,504 @@
|
||||
var utils = require('./connection_utils'),
|
||||
inherits = require('util').inherits,
|
||||
net = require('net'),
|
||||
EventEmitter = require('events').EventEmitter,
|
||||
inherits = require('util').inherits,
|
||||
binaryutils = require('../utils'),
|
||||
tls = require('tls');
|
||||
|
||||
var Connection = exports.Connection = function(id, socketOptions) {
|
||||
// Set up event emitter
|
||||
EventEmitter.call(this);
|
||||
// Store all socket options
|
||||
this.socketOptions = socketOptions ? socketOptions : {host:'localhost', port:27017, domainSocket:false};
|
||||
// Set keep alive default if not overriden
|
||||
if(this.socketOptions.keepAlive == null && (process.platform !== "sunos" || process.platform !== "win32")) this.socketOptions.keepAlive = 100;
|
||||
// Id for the connection
|
||||
this.id = id;
|
||||
// State of the connection
|
||||
this.connected = false;
|
||||
// Set if this is a domain socket
|
||||
this.domainSocket = this.socketOptions.domainSocket;
|
||||
|
||||
//
|
||||
// Connection parsing state
|
||||
//
|
||||
this.maxBsonSize = socketOptions.maxBsonSize ? socketOptions.maxBsonSize : Connection.DEFAULT_MAX_BSON_SIZE;
|
||||
this.maxMessageSizeBytes = socketOptions.maxMessageSizeBytes ? socketOptions.maxMessageSizeBytes : Connection.DEFAULT_MAX_MESSAGE_SIZE;
|
||||
// Contains the current message bytes
|
||||
this.buffer = null;
|
||||
// Contains the current message size
|
||||
this.sizeOfMessage = 0;
|
||||
// Contains the readIndex for the messaage
|
||||
this.bytesRead = 0;
|
||||
// Contains spill over bytes from additional messages
|
||||
this.stubBuffer = 0;
|
||||
|
||||
// Just keeps list of events we allow
|
||||
this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[], end:[]};
|
||||
|
||||
// Just keeps list of events we allow
|
||||
resetHandlers(this, false);
|
||||
}
|
||||
|
||||
// Set max bson size
|
||||
Connection.DEFAULT_MAX_BSON_SIZE = 1024 * 1024 * 4;
|
||||
// Set default to max bson to avoid overflow or bad guesses
|
||||
Connection.DEFAULT_MAX_MESSAGE_SIZE = Connection.DEFAULT_MAX_BSON_SIZE;
|
||||
|
||||
// Inherit event emitter so we can emit stuff wohoo
|
||||
inherits(Connection, EventEmitter);
|
||||
|
||||
Connection.prototype.start = function() {
|
||||
var self = this;
|
||||
|
||||
// If we have a normal connection
|
||||
if(this.socketOptions.ssl) {
|
||||
// Create new connection instance
|
||||
if(this.domainSocket) {
|
||||
this.connection = net.createConnection(this.socketOptions.host);
|
||||
} else {
|
||||
this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
|
||||
}
|
||||
if(this.logger != null && this.logger.doDebug){
|
||||
this.logger.debug("opened connection", this.socketOptions);
|
||||
}
|
||||
// Set options on the socket
|
||||
this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout);
|
||||
// Work around for 0.4.X
|
||||
if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay);
|
||||
// Set keep alive if defined
|
||||
if(process.version.indexOf("v0.4") == -1) {
|
||||
if(this.socketOptions.keepAlive > 0) {
|
||||
this.connection.setKeepAlive(true, this.socketOptions.keepAlive);
|
||||
} else {
|
||||
this.connection.setKeepAlive(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the driver should validate the certificate
|
||||
var validate_certificates = this.socketOptions.sslValidate == true ? true : false;
|
||||
|
||||
// Create options for the tls connection
|
||||
var tls_options = {
|
||||
socket: this.connection
|
||||
, rejectUnauthorized: false
|
||||
}
|
||||
|
||||
// If we wish to validate the certificate we have provided a ca store
|
||||
if(validate_certificates) {
|
||||
tls_options.ca = this.socketOptions.sslCA;
|
||||
}
|
||||
|
||||
// If we have a certificate to present
|
||||
if(this.socketOptions.sslCert) {
|
||||
tls_options.cert = this.socketOptions.sslCert;
|
||||
tls_options.key = this.socketOptions.sslKey;
|
||||
}
|
||||
|
||||
// If the driver has been provided a private key password
|
||||
if(this.socketOptions.sslPass) {
|
||||
tls_options.passphrase = this.socketOptions.sslPass;
|
||||
}
|
||||
|
||||
// Contains the cleartext stream
|
||||
var cleartext = null;
|
||||
// Attempt to establish a TLS connection to the server
|
||||
try {
|
||||
cleartext = tls.connect(this.socketOptions.port, this.socketOptions.host, tls_options, function() {
|
||||
// If we have a ssl certificate validation error return an error
|
||||
if(cleartext.authorizationError && validate_certificates) {
|
||||
// Emit an error
|
||||
return self.emit("error", cleartext.authorizationError, self, {ssl:true});
|
||||
}
|
||||
|
||||
// Connect to the server
|
||||
connectHandler(self)();
|
||||
})
|
||||
} catch(err) {
|
||||
return self.emit("error", "SSL connection failed", self, {ssl:true});
|
||||
}
|
||||
|
||||
// Save the output stream
|
||||
this.writeSteam = cleartext;
|
||||
|
||||
// Set up data handler for the clear stream
|
||||
cleartext.on("data", createDataHandler(this));
|
||||
// Do any handling of end event of the stream
|
||||
cleartext.on("end", endHandler(this));
|
||||
cleartext.on("error", errorHandler(this));
|
||||
|
||||
// Handle any errors
|
||||
this.connection.on("error", errorHandler(this));
|
||||
// Handle timeout
|
||||
this.connection.on("timeout", timeoutHandler(this));
|
||||
// Handle drain event
|
||||
this.connection.on("drain", drainHandler(this));
|
||||
// Handle the close event
|
||||
this.connection.on("close", closeHandler(this));
|
||||
} else {
|
||||
// Create new connection instance
|
||||
if(this.domainSocket) {
|
||||
this.connection = net.createConnection(this.socketOptions.host);
|
||||
} else {
|
||||
this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host);
|
||||
}
|
||||
if(this.logger != null && this.logger.doDebug){
|
||||
this.logger.debug("opened connection", this.socketOptions);
|
||||
}
|
||||
|
||||
// Set options on the socket
|
||||
this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout);
|
||||
// Work around for 0.4.X
|
||||
if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay);
|
||||
// Set keep alive if defined
|
||||
if(process.version.indexOf("v0.4") == -1) {
|
||||
if(this.socketOptions.keepAlive > 0) {
|
||||
this.connection.setKeepAlive(true, this.socketOptions.keepAlive);
|
||||
} else {
|
||||
this.connection.setKeepAlive(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Set up write stream
|
||||
this.writeSteam = this.connection;
|
||||
// Add handlers
|
||||
this.connection.on("error", errorHandler(this));
|
||||
// Add all handlers to the socket to manage it
|
||||
this.connection.on("connect", connectHandler(this));
|
||||
// this.connection.on("end", endHandler(this));
|
||||
this.connection.on("data", createDataHandler(this));
|
||||
this.connection.on("timeout", timeoutHandler(this));
|
||||
this.connection.on("drain", drainHandler(this));
|
||||
this.connection.on("close", closeHandler(this));
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the sockets are live
|
||||
Connection.prototype.isConnected = function() {
|
||||
return this.connected && !this.connection.destroyed && this.connection.writable && this.connection.readable;
|
||||
}
|
||||
|
||||
// Write the data out to the socket
|
||||
Connection.prototype.write = function(command, callback) {
|
||||
try {
|
||||
// If we have a list off commands to be executed on the same socket
|
||||
if(Array.isArray(command)) {
|
||||
for(var i = 0; i < command.length; i++) {
|
||||
var binaryCommand = command[i].toBinary()
|
||||
|
||||
if(!this.socketOptions['disableDriverBSONSizeCheck'] && binaryCommand.length > this.maxBsonSize)
|
||||
return callback(new Error("Document exceeds maximum allowed bson size of " + this.maxBsonSize + " bytes"));
|
||||
|
||||
if(this.socketOptions['disableDriverBSONSizeCheck'] && binaryCommand.length > this.maxMessageSizeBytes) {
|
||||
return callback(new Error("Command exceeds maximum message size of " + this.maxMessageSizeBytes + " bytes"));
|
||||
}
|
||||
|
||||
if(this.logger != null && this.logger.doDebug)
|
||||
this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]});
|
||||
|
||||
var r = this.writeSteam.write(binaryCommand);
|
||||
}
|
||||
} else {
|
||||
var binaryCommand = command.toBinary()
|
||||
|
||||
if(!this.socketOptions['disableDriverBSONSizeCheck'] && binaryCommand.length > this.maxBsonSize)
|
||||
return callback(new Error("Document exceeds maximum allowed bson size of " + this.maxBsonSize + " bytes"));
|
||||
|
||||
if(this.socketOptions['disableDriverBSONSizeCheck'] && binaryCommand.length > this.maxMessageSizeBytes) {
|
||||
return callback(new Error("Command exceeds maximum message size of " + this.maxMessageSizeBytes + " bytes"));
|
||||
}
|
||||
|
||||
if(this.logger != null && this.logger.doDebug)
|
||||
this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command});
|
||||
|
||||
var r = this.writeSteam.write(binaryCommand);
|
||||
}
|
||||
} catch (err) {
|
||||
if(typeof callback === 'function') callback(err);
|
||||
}
|
||||
}
|
||||
|
||||
// Force the closure of the connection
|
||||
Connection.prototype.close = function() {
|
||||
// clear out all the listeners
|
||||
resetHandlers(this, true);
|
||||
// Add a dummy error listener to catch any weird last moment errors (and ignore them)
|
||||
this.connection.on("error", function() {})
|
||||
// destroy connection
|
||||
this.connection.destroy();
|
||||
if(this.logger != null && this.logger.doDebug){
|
||||
this.logger.debug("closed connection", this.connection);
|
||||
}
|
||||
}
|
||||
|
||||
// Reset all handlers
|
||||
var resetHandlers = function(self, clearListeners) {
|
||||
self.eventHandlers = {error:[], connect:[], close:[], end:[], timeout:[], parseError:[], message:[]};
|
||||
|
||||
// If we want to clear all the listeners
|
||||
if(clearListeners && self.connection != null) {
|
||||
var keys = Object.keys(self.eventHandlers);
|
||||
// Remove all listeners
|
||||
for(var i = 0; i < keys.length; i++) {
|
||||
self.connection.removeAllListeners(keys[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Handlers
|
||||
//
|
||||
|
||||
// Connect handler
|
||||
var connectHandler = function(self) {
|
||||
return function(data) {
|
||||
// Set connected
|
||||
self.connected = true;
|
||||
// Now that we are connected set the socket timeout
|
||||
self.connection.setTimeout(self.socketOptions.socketTimeoutMS != null ? self.socketOptions.socketTimeoutMS : self.socketOptions.timeout);
|
||||
// Emit the connect event with no error
|
||||
self.emit("connect", null, self);
|
||||
}
|
||||
}
|
||||
|
||||
var createDataHandler = exports.Connection.createDataHandler = function(self) {
|
||||
// We need to handle the parsing of the data
|
||||
// and emit the messages when there is a complete one
|
||||
return function(data) {
|
||||
// Parse until we are done with the data
|
||||
while(data.length > 0) {
|
||||
// If we still have bytes to read on the current message
|
||||
if(self.bytesRead > 0 && self.sizeOfMessage > 0) {
|
||||
// Calculate the amount of remaining bytes
|
||||
var remainingBytesToRead = self.sizeOfMessage - self.bytesRead;
|
||||
// Check if the current chunk contains the rest of the message
|
||||
if(remainingBytesToRead > data.length) {
|
||||
// Copy the new data into the exiting buffer (should have been allocated when we know the message size)
|
||||
data.copy(self.buffer, self.bytesRead);
|
||||
// Adjust the number of bytes read so it point to the correct index in the buffer
|
||||
self.bytesRead = self.bytesRead + data.length;
|
||||
|
||||
// Reset state of buffer
|
||||
data = new Buffer(0);
|
||||
} else {
|
||||
// Copy the missing part of the data into our current buffer
|
||||
data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead);
|
||||
// Slice the overflow into a new buffer that we will then re-parse
|
||||
data = data.slice(remainingBytesToRead);
|
||||
|
||||
// Emit current complete message
|
||||
try {
|
||||
var emitBuffer = self.buffer;
|
||||
// Reset state of buffer
|
||||
self.buffer = null;
|
||||
self.sizeOfMessage = 0;
|
||||
self.bytesRead = 0;
|
||||
self.stubBuffer = null;
|
||||
// Emit the buffer
|
||||
self.emit("message", emitBuffer, self);
|
||||
} catch(err) {
|
||||
var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{
|
||||
sizeOfMessage:self.sizeOfMessage,
|
||||
bytesRead:self.bytesRead,
|
||||
stubBuffer:self.stubBuffer}};
|
||||
if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
|
||||
// We got a parse Error fire it off then keep going
|
||||
self.emit("parseError", errorObject, self);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Stub buffer is kept in case we don't get enough bytes to determine the
|
||||
// size of the message (< 4 bytes)
|
||||
if(self.stubBuffer != null && self.stubBuffer.length > 0) {
|
||||
|
||||
// If we have enough bytes to determine the message size let's do it
|
||||
if(self.stubBuffer.length + data.length > 4) {
|
||||
// Prepad the data
|
||||
var newData = new Buffer(self.stubBuffer.length + data.length);
|
||||
self.stubBuffer.copy(newData, 0);
|
||||
data.copy(newData, self.stubBuffer.length);
|
||||
// Reassign for parsing
|
||||
data = newData;
|
||||
|
||||
// Reset state of buffer
|
||||
self.buffer = null;
|
||||
self.sizeOfMessage = 0;
|
||||
self.bytesRead = 0;
|
||||
self.stubBuffer = null;
|
||||
|
||||
} else {
|
||||
|
||||
// Add the the bytes to the stub buffer
|
||||
var newStubBuffer = new Buffer(self.stubBuffer.length + data.length);
|
||||
// Copy existing stub buffer
|
||||
self.stubBuffer.copy(newStubBuffer, 0);
|
||||
// Copy missing part of the data
|
||||
data.copy(newStubBuffer, self.stubBuffer.length);
|
||||
// Exit parsing loop
|
||||
data = new Buffer(0);
|
||||
}
|
||||
} else {
|
||||
if(data.length > 4) {
|
||||
// Retrieve the message size
|
||||
var sizeOfMessage = binaryutils.decodeUInt32(data, 0);
|
||||
// If we have a negative sizeOfMessage emit error and return
|
||||
if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonSize) {
|
||||
var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{
|
||||
sizeOfMessage: sizeOfMessage,
|
||||
bytesRead: self.bytesRead,
|
||||
stubBuffer: self.stubBuffer}};
|
||||
if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
|
||||
// We got a parse Error fire it off then keep going
|
||||
self.emit("parseError", errorObject, self);
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure that the size of message is larger than 0 and less than the max allowed
|
||||
if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage > data.length) {
|
||||
self.buffer = new Buffer(sizeOfMessage);
|
||||
// Copy all the data into the buffer
|
||||
data.copy(self.buffer, 0);
|
||||
// Update bytes read
|
||||
self.bytesRead = data.length;
|
||||
// Update sizeOfMessage
|
||||
self.sizeOfMessage = sizeOfMessage;
|
||||
// Ensure stub buffer is null
|
||||
self.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = new Buffer(0);
|
||||
|
||||
} else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage == data.length) {
|
||||
try {
|
||||
var emitBuffer = data;
|
||||
// Reset state of buffer
|
||||
self.buffer = null;
|
||||
self.sizeOfMessage = 0;
|
||||
self.bytesRead = 0;
|
||||
self.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = new Buffer(0);
|
||||
// Emit the message
|
||||
self.emit("message", emitBuffer, self);
|
||||
} catch (err) {
|
||||
var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{
|
||||
sizeOfMessage:self.sizeOfMessage,
|
||||
bytesRead:self.bytesRead,
|
||||
stubBuffer:self.stubBuffer}};
|
||||
if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
|
||||
// We got a parse Error fire it off then keep going
|
||||
self.emit("parseError", errorObject, self);
|
||||
}
|
||||
} else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonSize) {
|
||||
var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{
|
||||
sizeOfMessage:sizeOfMessage,
|
||||
bytesRead:0,
|
||||
buffer:null,
|
||||
stubBuffer:null}};
|
||||
if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
|
||||
// We got a parse Error fire it off then keep going
|
||||
self.emit("parseError", errorObject, self);
|
||||
|
||||
// Clear out the state of the parser
|
||||
self.buffer = null;
|
||||
self.sizeOfMessage = 0;
|
||||
self.bytesRead = 0;
|
||||
self.stubBuffer = null;
|
||||
// Exit parsing loop
|
||||
data = new Buffer(0);
|
||||
|
||||
} else {
|
||||
try {
|
||||
var emitBuffer = data.slice(0, sizeOfMessage);
|
||||
// Reset state of buffer
|
||||
self.buffer = null;
|
||||
self.sizeOfMessage = 0;
|
||||
self.bytesRead = 0;
|
||||
self.stubBuffer = null;
|
||||
// Copy rest of message
|
||||
data = data.slice(sizeOfMessage);
|
||||
// Emit the message
|
||||
self.emit("message", emitBuffer, self);
|
||||
} catch (err) {
|
||||
var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{
|
||||
sizeOfMessage:sizeOfMessage,
|
||||
bytesRead:self.bytesRead,
|
||||
stubBuffer:self.stubBuffer}};
|
||||
if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject);
|
||||
// We got a parse Error fire it off then keep going
|
||||
self.emit("parseError", errorObject, self);
|
||||
}
|
||||
|
||||
}
|
||||
} else {
|
||||
// Create a buffer that contains the space for the non-complete message
|
||||
self.stubBuffer = new Buffer(data.length)
|
||||
// Copy the data to the stub buffer
|
||||
data.copy(self.stubBuffer, 0);
|
||||
// Exit parsing loop
|
||||
data = new Buffer(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var endHandler = function(self) {
|
||||
return function() {
|
||||
// Set connected to false
|
||||
self.connected = false;
|
||||
// Emit end event
|
||||
self.emit("end", {err: 'connection received Fin packet from [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self);
|
||||
}
|
||||
}
|
||||
|
||||
var timeoutHandler = function(self) {
|
||||
return function() {
|
||||
// Set connected to false
|
||||
self.connected = false;
|
||||
// Emit timeout event
|
||||
self.emit("timeout", {err: 'connection to [' + self.socketOptions.host + ':' + self.socketOptions.port + '] timed out'}, self);
|
||||
}
|
||||
}
|
||||
|
||||
var drainHandler = function(self) {
|
||||
return function() {
|
||||
}
|
||||
}
|
||||
|
||||
var errorHandler = function(self) {
|
||||
return function(err) {
|
||||
// Set connected to false
|
||||
self.connected = false;
|
||||
// Emit error
|
||||
self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self);
|
||||
}
|
||||
}
|
||||
|
||||
var closeHandler = function(self) {
|
||||
return function(hadError) {
|
||||
// If we have an error during the connection phase
|
||||
if(hadError && !self.connected) {
|
||||
// Set disconnected
|
||||
self.connected = false;
|
||||
// Emit error
|
||||
self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self);
|
||||
} else {
|
||||
// Set disconnected
|
||||
self.connected = false;
|
||||
// Emit close
|
||||
self.emit("close", {err: 'connection closed to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Some basic defaults
|
||||
Connection.DEFAULT_PORT = 27017;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
293
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/connection_pool.js
generated
vendored
Normal file
293
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/connection_pool.js
generated
vendored
Normal file
@@ -0,0 +1,293 @@
|
||||
var utils = require('./connection_utils'),
|
||||
inherits = require('util').inherits,
|
||||
net = require('net'),
|
||||
timers = require('timers'),
|
||||
EventEmitter = require('events').EventEmitter,
|
||||
inherits = require('util').inherits,
|
||||
MongoReply = require("../responses/mongo_reply").MongoReply,
|
||||
Connection = require("./connection").Connection;
|
||||
|
||||
// Set processor, setImmediate if 0.10 otherwise nextTick
|
||||
var processor = timers.setImmediate ? timers.setImmediate : process.nextTick;
|
||||
processor = process.nextTick
|
||||
|
||||
var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) {
|
||||
if(typeof host !== 'string') {
|
||||
throw new Error("host must be specified [" + host + "]");
|
||||
}
|
||||
|
||||
// Set up event emitter
|
||||
EventEmitter.call(this);
|
||||
|
||||
// Keep all options for the socket in a specific collection allowing the user to specify the
|
||||
// Wished upon socket connection parameters
|
||||
this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {};
|
||||
this.socketOptions.host = host;
|
||||
this.socketOptions.port = port;
|
||||
this.socketOptions.domainSocket = false;
|
||||
this.bson = bson;
|
||||
// PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc)
|
||||
this.poolSize = poolSize;
|
||||
this.minPoolSize = Math.floor(this.poolSize / 2) + 1;
|
||||
|
||||
// Check if the host is a socket
|
||||
if(host.match(/^\//)) {
|
||||
this.socketOptions.domainSocket = true;
|
||||
} else if(typeof port === 'string') {
|
||||
try {
|
||||
port = parseInt(port, 10);
|
||||
} catch(err) {
|
||||
new Error("port must be specified or valid integer[" + port + "]");
|
||||
}
|
||||
} else if(typeof port !== 'number') {
|
||||
throw new Error("port must be specified [" + port + "]");
|
||||
}
|
||||
|
||||
// Set default settings for the socket options
|
||||
utils.setIntegerParameter(this.socketOptions, 'timeout', 0);
|
||||
// Delay before writing out the data to the server
|
||||
utils.setBooleanParameter(this.socketOptions, 'noDelay', true);
|
||||
// Delay before writing out the data to the server
|
||||
utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0);
|
||||
// Set the encoding of the data read, default is binary == null
|
||||
utils.setStringParameter(this.socketOptions, 'encoding', null);
|
||||
// Allows you to set a throttling bufferSize if you need to stop overflows
|
||||
utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0);
|
||||
|
||||
// Internal structures
|
||||
this.openConnections = [];
|
||||
// Assign connection id's
|
||||
this.connectionId = 0;
|
||||
|
||||
// Current index for selection of pool connection
|
||||
this.currentConnectionIndex = 0;
|
||||
// The pool state
|
||||
this._poolState = 'disconnected';
|
||||
// timeout control
|
||||
this._timeout = false;
|
||||
// Time to wait between connections for the pool
|
||||
this._timeToWait = 10;
|
||||
}
|
||||
|
||||
inherits(ConnectionPool, EventEmitter);
|
||||
|
||||
ConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) {
|
||||
if(maxBsonSize == null){
|
||||
maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE;
|
||||
}
|
||||
|
||||
for(var i = 0; i < this.openConnections.length; i++) {
|
||||
this.openConnections[i].maxBsonSize = maxBsonSize;
|
||||
}
|
||||
}
|
||||
|
||||
ConnectionPool.prototype.setMaxMessageSizeBytes = function(maxMessageSizeBytes) {
|
||||
if(maxMessageSizeBytes == null){
|
||||
maxMessageSizeBytes = Connection.DEFAULT_MAX_MESSAGE_SIZE;
|
||||
}
|
||||
|
||||
for(var i = 0; i < this.openConnections.length; i++) {
|
||||
this.openConnections[i].maxMessageSizeBytes = maxMessageSizeBytes;
|
||||
}
|
||||
}
|
||||
|
||||
// Start a function
|
||||
var _connect = function(_self) {
|
||||
// return new function() {
|
||||
// Create a new connection instance
|
||||
var connection = new Connection(_self.connectionId++, _self.socketOptions);
|
||||
// Set logger on pool
|
||||
connection.logger = _self.logger;
|
||||
// Connect handler
|
||||
connection.on("connect", function(err, connection) {
|
||||
// Add connection to list of open connections
|
||||
_self.openConnections.push(connection);
|
||||
// If the number of open connections is equal to the poolSize signal ready pool
|
||||
if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') {
|
||||
// Set connected
|
||||
_self._poolState = 'connected';
|
||||
// Emit pool ready
|
||||
_self.emit("poolReady");
|
||||
} else if(_self.openConnections.length < _self.poolSize) {
|
||||
// Wait a little bit of time to let the close event happen if the server closes the connection
|
||||
// so we don't leave hanging connections around
|
||||
if(typeof _self._timeToWait == 'number') {
|
||||
setTimeout(function() {
|
||||
// If we are still connecting (no close events fired in between start another connection)
|
||||
if(_self._poolState == 'connecting') {
|
||||
_connect(_self);
|
||||
}
|
||||
}, _self._timeToWait);
|
||||
} else {
|
||||
processor(function() {
|
||||
// If we are still connecting (no close events fired in between start another connection)
|
||||
if(_self._poolState == 'connecting') {
|
||||
_connect(_self);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var numberOfErrors = 0
|
||||
|
||||
// Error handler
|
||||
connection.on("error", function(err, connection, error_options) {
|
||||
numberOfErrors++;
|
||||
// If we are already disconnected ignore the event
|
||||
if(_self._poolState != 'disconnected' && _self.listeners("error").length > 0) {
|
||||
_self.emit("error", err, connection, error_options);
|
||||
}
|
||||
|
||||
// Close the connection
|
||||
connection.close();
|
||||
// Set pool as disconnected
|
||||
_self._poolState = 'disconnected';
|
||||
// Stop the pool
|
||||
_self.stop();
|
||||
});
|
||||
|
||||
// Close handler
|
||||
connection.on("close", function() {
|
||||
// If we are already disconnected ignore the event
|
||||
if(_self._poolState !== 'disconnected' && _self.listeners("close").length > 0) {
|
||||
_self.emit("close");
|
||||
}
|
||||
|
||||
// Set disconnected
|
||||
_self._poolState = 'disconnected';
|
||||
// Stop
|
||||
_self.stop();
|
||||
});
|
||||
|
||||
// Timeout handler
|
||||
connection.on("timeout", function(err, connection) {
|
||||
// If we are already disconnected ignore the event
|
||||
if(_self._poolState !== 'disconnected' && _self.listeners("timeout").length > 0) {
|
||||
_self.emit("timeout", err);
|
||||
}
|
||||
|
||||
// Close the connection
|
||||
connection.close();
|
||||
// Set disconnected
|
||||
_self._poolState = 'disconnected';
|
||||
_self.stop();
|
||||
});
|
||||
|
||||
// Parse error, needs a complete shutdown of the pool
|
||||
connection.on("parseError", function() {
|
||||
// If we are already disconnected ignore the event
|
||||
if(_self._poolState !== 'disconnected' && _self.listeners("parseError").length > 0) {
|
||||
_self.emit("parseError", new Error("parseError occured"));
|
||||
}
|
||||
|
||||
// Set disconnected
|
||||
_self._poolState = 'disconnected';
|
||||
_self.stop();
|
||||
});
|
||||
|
||||
connection.on("message", function(message) {
|
||||
_self.emit("message", message);
|
||||
});
|
||||
|
||||
// Start connection in the next tick
|
||||
connection.start();
|
||||
// }();
|
||||
}
|
||||
|
||||
|
||||
// Start method, will throw error if no listeners are available
|
||||
// Pass in an instance of the listener that contains the api for
|
||||
// finding callbacks for a given message etc.
|
||||
ConnectionPool.prototype.start = function() {
|
||||
var markerDate = new Date().getTime();
|
||||
var self = this;
|
||||
|
||||
if(this.listeners("poolReady").length == 0) {
|
||||
throw "pool must have at least one listener ready that responds to the [poolReady] event";
|
||||
}
|
||||
|
||||
// Set pool state to connecting
|
||||
this._poolState = 'connecting';
|
||||
this._timeout = false;
|
||||
|
||||
_connect(self);
|
||||
}
|
||||
|
||||
// Restart a connection pool (on a close the pool might be in a wrong state)
|
||||
ConnectionPool.prototype.restart = function() {
|
||||
// Close all connections
|
||||
this.stop(false);
|
||||
// Now restart the pool
|
||||
this.start();
|
||||
}
|
||||
|
||||
// Stop the connections in the pool
|
||||
ConnectionPool.prototype.stop = function(removeListeners) {
|
||||
removeListeners = removeListeners == null ? true : removeListeners;
|
||||
// Set disconnected
|
||||
this._poolState = 'disconnected';
|
||||
|
||||
// Clear all listeners if specified
|
||||
if(removeListeners) {
|
||||
this.removeAllEventListeners();
|
||||
}
|
||||
|
||||
// Close all connections
|
||||
for(var i = 0; i < this.openConnections.length; i++) {
|
||||
this.openConnections[i].close();
|
||||
}
|
||||
|
||||
// Clean up
|
||||
this.openConnections = [];
|
||||
}
|
||||
|
||||
// Check the status of the connection
|
||||
ConnectionPool.prototype.isConnected = function() {
|
||||
return this._poolState === 'connected';
|
||||
}
|
||||
|
||||
// Checkout a connection from the pool for usage, or grab a specific pool instance
|
||||
ConnectionPool.prototype.checkoutConnection = function(id) {
|
||||
var index = (this.currentConnectionIndex++ % (this.openConnections.length));
|
||||
var connection = this.openConnections[index];
|
||||
return connection;
|
||||
}
|
||||
|
||||
ConnectionPool.prototype.getAllConnections = function() {
|
||||
return this.openConnections;
|
||||
}
|
||||
|
||||
// Remove all non-needed event listeners
|
||||
ConnectionPool.prototype.removeAllEventListeners = function() {
|
||||
this.removeAllListeners("close");
|
||||
this.removeAllListeners("error");
|
||||
this.removeAllListeners("timeout");
|
||||
this.removeAllListeners("connect");
|
||||
this.removeAllListeners("end");
|
||||
this.removeAllListeners("parseError");
|
||||
this.removeAllListeners("message");
|
||||
this.removeAllListeners("poolReady");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
23
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/connection_utils.js
generated
vendored
Normal file
23
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/connection_utils.js
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
exports.setIntegerParameter = function(object, field, defaultValue) {
|
||||
if(object[field] == null) {
|
||||
object[field] = defaultValue;
|
||||
} else if(typeof object[field] !== "number" && object[field] !== parseInt(object[field], 10)) {
|
||||
throw "object field [" + field + "] must be a numeric integer value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]";
|
||||
}
|
||||
}
|
||||
|
||||
exports.setBooleanParameter = function(object, field, defaultValue) {
|
||||
if(object[field] == null) {
|
||||
object[field] = defaultValue;
|
||||
} else if(typeof object[field] !== "boolean") {
|
||||
throw "object field [" + field + "] must be a boolean value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]";
|
||||
}
|
||||
}
|
||||
|
||||
exports.setStringParameter = function(object, field, defaultValue) {
|
||||
if(object[field] == null) {
|
||||
object[field] = defaultValue;
|
||||
} else if(typeof object[field] !== "string") {
|
||||
throw "object field [" + field + "] must be a string value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]";
|
||||
}
|
||||
}
|
||||
357
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/mongos.js
generated
vendored
Normal file
357
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/mongos.js
generated
vendored
Normal file
@@ -0,0 +1,357 @@
|
||||
var ReadPreference = require('./read_preference').ReadPreference
|
||||
, Base = require('./base').Base
|
||||
, inherits = require('util').inherits;
|
||||
|
||||
/**
|
||||
* Mongos constructor provides a connection to a mongos proxy including failover to additional servers
|
||||
*
|
||||
* Options
|
||||
* - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))
|
||||
* - **ha** {Boolean, default:true}, turn on high availability, attempts to reconnect to down proxies
|
||||
* - **haInterval** {Number, default:2000}, time between each replicaset status check.
|
||||
*
|
||||
* @class Represents a Mongos connection with failover to backup proxies
|
||||
* @param {Array} list of mongos server objects
|
||||
* @param {Object} [options] additional options for the mongos connection
|
||||
*/
|
||||
var Mongos = function Mongos(servers, options) {
|
||||
// Set up basic
|
||||
if(!(this instanceof Mongos))
|
||||
return new Mongos(servers, options);
|
||||
|
||||
// Set up event emitter
|
||||
Base.call(this);
|
||||
|
||||
// Throw error on wrong setup
|
||||
if(servers == null || !Array.isArray(servers) || servers.length == 0)
|
||||
throw new Error("At least one mongos proxy must be in the array");
|
||||
|
||||
// Ensure we have at least an empty options object
|
||||
this.options = options == null ? {} : options;
|
||||
// Set default connection pool options
|
||||
this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
|
||||
// Enabled ha
|
||||
this.haEnabled = this.options['ha'] == null ? true : this.options['ha'];
|
||||
// How often are we checking for new servers in the replicaset
|
||||
this.mongosStatusCheckInterval = this.options['haInterval'] == null ? 2000 : this.options['haInterval'];
|
||||
// Save all the server connections
|
||||
this.servers = servers;
|
||||
// Servers we need to attempt reconnect with
|
||||
this.downServers = [];
|
||||
// Just contains the current lowest ping time and server
|
||||
this.lowestPingTimeServer = null;
|
||||
this.lowestPingTime = 0;
|
||||
|
||||
// Connection timeout
|
||||
this._connectTimeoutMS = this.socketOptions.connectTimeoutMS
|
||||
? this.socketOptions.connectTimeoutMS
|
||||
: 1000;
|
||||
|
||||
// Add options to servers
|
||||
for(var i = 0; i < this.servers.length; i++) {
|
||||
var server = this.servers[i];
|
||||
server._callBackStore = this._callBackStore;
|
||||
// Default empty socket options object
|
||||
var socketOptions = {host: server.host, port: server.port};
|
||||
// If a socket option object exists clone it
|
||||
if(this.socketOptions != null) {
|
||||
var keys = Object.keys(this.socketOptions);
|
||||
for(var k = 0; k < keys.length;k++) socketOptions[keys[i]] = this.socketOptions[keys[i]];
|
||||
}
|
||||
// Set socket options
|
||||
server.socketOptions = socketOptions;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
inherits(Mongos, Base);
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Mongos.prototype.isMongos = function() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Mongos.prototype.connect = function(db, options, callback) {
|
||||
if('function' === typeof options) callback = options, options = {};
|
||||
if(options == null) options = {};
|
||||
if(!('function' === typeof callback)) callback = null;
|
||||
var self = this;
|
||||
|
||||
// Keep reference to parent
|
||||
this.db = db;
|
||||
// Set server state to connecting
|
||||
this._serverState = 'connecting';
|
||||
// Number of total servers that need to initialized (known servers)
|
||||
this._numberOfServersLeftToInitialize = this.servers.length;
|
||||
// Default to the first proxy server as the first one to use
|
||||
this._currentMongos = this.servers[0];
|
||||
|
||||
// Connect handler
|
||||
var connectHandler = function(_server) {
|
||||
return function(err, result) {
|
||||
self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1;
|
||||
|
||||
if(self._numberOfServersLeftToInitialize == 0) {
|
||||
// Start ha function if it exists
|
||||
if(self.haEnabled) {
|
||||
// Setup the ha process
|
||||
self._replicasetTimeoutId = setTimeout(self.mongosCheckFunction, self.mongosStatusCheckInterval);
|
||||
}
|
||||
|
||||
// Set the mongos to connected
|
||||
self._serverState = "connected";
|
||||
// Emit the open event
|
||||
self.db.emit("open", null, self.db);
|
||||
// Callback
|
||||
callback(null, self.db);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Error handler
|
||||
var errorOrCloseHandler = function(_server) {
|
||||
return function(err, result) {
|
||||
// Create current mongos comparision
|
||||
var currentUrl = self._currentMongos.host + ":" + self._currentMongos.port;
|
||||
var serverUrl = this.host + ":" + this.port;
|
||||
// We need to check if the server that closed is the actual current proxy we are using, otherwise
|
||||
// just ignore
|
||||
if(currentUrl == serverUrl) {
|
||||
// Remove the server from the list
|
||||
if(self.servers.indexOf(_server) != -1) {
|
||||
self.servers.splice(self.servers.indexOf(_server), 1);
|
||||
}
|
||||
|
||||
// Pick the next one on the list if there is one
|
||||
for(var i = 0; i < self.servers.length; i++) {
|
||||
// Grab the server out of the array (making sure there is no servers in the list if none available)
|
||||
var server = self.servers[i];
|
||||
// Generate url for comparision
|
||||
var serverUrl = server.host + ":" + server.port;
|
||||
// It's not the current one and connected set it as the current db
|
||||
if(currentUrl != serverUrl && server.isConnected()) {
|
||||
self._currentMongos = server;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure we don't store the _server twice
|
||||
if(self.downServers.indexOf(_server) == -1) {
|
||||
// Add the server instances
|
||||
self.downServers.push(_server);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mongo function
|
||||
this.mongosCheckFunction = function() {
|
||||
// If we have down servers let's attempt a reconnect
|
||||
if(self.downServers.length > 0) {
|
||||
var numberOfServersLeft = self.downServers.length;
|
||||
// Attempt to reconnect
|
||||
for(var i = 0; i < self.downServers.length; i++) {
|
||||
var downServer = self.downServers.pop();
|
||||
|
||||
// Configuration
|
||||
var options = {
|
||||
slaveOk: true,
|
||||
poolSize: 1,
|
||||
socketOptions: { connectTimeoutMS: self._connectTimeoutMS },
|
||||
returnIsMasterResults: true
|
||||
}
|
||||
|
||||
// Attemp to reconnect
|
||||
downServer.connect(self.db, options, function(_server) {
|
||||
// Return a function to check for the values
|
||||
return function(err, result) {
|
||||
// Adjust the number of servers left
|
||||
numberOfServersLeft = numberOfServersLeft - 1;
|
||||
|
||||
if(err != null) {
|
||||
self.downServers.push(_server);
|
||||
} else {
|
||||
// Add server event handlers
|
||||
_server.on("close", errorOrCloseHandler(_server));
|
||||
_server.on("error", errorOrCloseHandler(_server));
|
||||
// Add to list of servers
|
||||
self.servers.push(_server);
|
||||
}
|
||||
|
||||
if(numberOfServersLeft <= 0) {
|
||||
// Perfom another ha
|
||||
self._replicasetTimeoutId = setTimeout(self.mongosCheckFunction, self.mongosStatusCheckInterval);
|
||||
}
|
||||
}
|
||||
}(downServer));
|
||||
}
|
||||
} else if(self.servers.length > 0) {
|
||||
var numberOfServersLeft = self.servers.length;
|
||||
var _s = new Date().getTime()
|
||||
|
||||
// Else let's perform a ping command
|
||||
for(var i = 0; i < self.servers.length; i++) {
|
||||
var executePing = function(_server) {
|
||||
// Get a read connection
|
||||
var _connection = _server.checkoutReader();
|
||||
// Execute ping command
|
||||
self.db.command({ping:1}, {failFast:true, connection:_connection}, function(err, result) {
|
||||
var pingTime = new Date().getTime() - _s;
|
||||
// If no server set set the first one, otherwise check
|
||||
// the lowest ping time and assign the server if it's got a lower ping time
|
||||
if(self.lowestPingTimeServer == null) {
|
||||
self.lowestPingTimeServer = _server;
|
||||
self.lowestPingTime = pingTime;
|
||||
self._currentMongos = _server;
|
||||
} else if(self.lowestPingTime > pingTime
|
||||
&& (_server.host != self.lowestPingTimeServer.host || _server.port != self.lowestPingTimeServer.port)) {
|
||||
self.lowestPingTimeServer = _server;
|
||||
self.lowestPingTime = pingTime;
|
||||
self._currentMongos = _server;
|
||||
}
|
||||
|
||||
// Number of servers left
|
||||
numberOfServersLeft = numberOfServersLeft - 1;
|
||||
// All active mongos's pinged
|
||||
if(numberOfServersLeft == 0) {
|
||||
// Perfom another ha
|
||||
self._replicasetTimeoutId = setTimeout(self.mongosCheckFunction, self.mongosStatusCheckInterval);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Execute the function
|
||||
executePing(self.servers[i]);
|
||||
}
|
||||
} else {
|
||||
self._replicasetTimeoutId = setTimeout(self.mongosCheckFunction, self.mongosStatusCheckInterval);
|
||||
}
|
||||
}
|
||||
|
||||
// Connect all the server instances
|
||||
for(var i = 0; i < this.servers.length; i++) {
|
||||
// Get the connection
|
||||
var server = this.servers[i];
|
||||
server.mongosInstance = this;
|
||||
// Add server event handlers
|
||||
server.on("close", errorOrCloseHandler(server));
|
||||
server.on("timeout", errorOrCloseHandler(server));
|
||||
server.on("error", errorOrCloseHandler(server));
|
||||
// Configuration
|
||||
var options = {
|
||||
slaveOk: true,
|
||||
poolSize: 1,
|
||||
socketOptions: { connectTimeoutMS: self._connectTimeoutMS },
|
||||
returnIsMasterResults: true
|
||||
}
|
||||
|
||||
// Connect the instance
|
||||
server.connect(self.db, options, connectHandler(server));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* Just return the currently picked active connection
|
||||
*/
|
||||
Mongos.prototype.allServerInstances = function() {
|
||||
return this.servers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Always ourselves
|
||||
* @ignore
|
||||
*/
|
||||
Mongos.prototype.setReadPreference = function() {}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Mongos.prototype.allRawConnections = function() {
|
||||
// Neeed to build a complete list of all raw connections, start with master server
|
||||
var allConnections = [];
|
||||
// Add all connections
|
||||
for(var i = 0; i < this.servers.length; i++) {
|
||||
allConnections = allConnections.concat(this.servers[i].allRawConnections());
|
||||
}
|
||||
|
||||
// Return all the conections
|
||||
return allConnections;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Mongos.prototype.isConnected = function() {
|
||||
return this._serverState == "connected";
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Mongos.prototype.checkoutWriter = function() {
|
||||
// No current mongo, just pick first server
|
||||
if(this._currentMongos == null && this.servers.length > 0) {
|
||||
return this.servers[0].checkoutWriter();
|
||||
}
|
||||
return this._currentMongos.checkoutWriter();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Mongos.prototype.checkoutReader = function(read) {
|
||||
// If we have a read preference object unpack it
|
||||
if(typeof read == 'object' && read['_type'] == 'ReadPreference') {
|
||||
// Validate if the object is using a valid mode
|
||||
if(!read.isValid()) throw new Error("Illegal readPreference mode specified, " + read.mode);
|
||||
} else if(!ReadPreference.isValid(read)) {
|
||||
throw new Error("Illegal readPreference mode specified, " + read);
|
||||
}
|
||||
|
||||
// No current mongo, just pick first server
|
||||
if(this._currentMongos == null && this.servers.length > 0) {
|
||||
return this.servers[0].checkoutReader();
|
||||
}
|
||||
return this._currentMongos.checkoutReader();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Mongos.prototype.close = function(callback) {
|
||||
var self = this;
|
||||
// Set server status as disconnected
|
||||
this._serverState = 'disconnected';
|
||||
// Number of connections to close
|
||||
var numberOfConnectionsToClose = self.servers.length;
|
||||
// If we have a ha process running kill it
|
||||
if(self._replicasetTimeoutId != null) clearTimeout(self._replicasetTimeoutId);
|
||||
// Close all proxy connections
|
||||
for(var i = 0; i < self.servers.length; i++) {
|
||||
self.servers[i].close(function(err, result) {
|
||||
numberOfConnectionsToClose = numberOfConnectionsToClose - 1;
|
||||
// Callback if we have one defined
|
||||
if(numberOfConnectionsToClose == 0 && typeof callback == 'function') {
|
||||
callback(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* Return the used state
|
||||
*/
|
||||
Mongos.prototype._isUsed = function() {
|
||||
return this._used;
|
||||
}
|
||||
|
||||
exports.Mongos = Mongos;
|
||||
66
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/read_preference.js
generated
vendored
Normal file
66
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/read_preference.js
generated
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* A class representation of the Read Preference.
|
||||
*
|
||||
* Read Preferences
|
||||
* - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.).
|
||||
* - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary.
|
||||
* - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error.
|
||||
* - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary.
|
||||
* - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection.
|
||||
*
|
||||
* @class Represents a Read Preference.
|
||||
* @param {String} the read preference type
|
||||
* @param {Object} tags
|
||||
* @return {ReadPreference}
|
||||
*/
|
||||
var ReadPreference = function(mode, tags) {
|
||||
if(!(this instanceof ReadPreference))
|
||||
return new ReadPreference(mode, tags);
|
||||
this._type = 'ReadPreference';
|
||||
this.mode = mode;
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
ReadPreference.isValid = function(_mode) {
|
||||
return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED
|
||||
|| _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED
|
||||
|| _mode == ReadPreference.NEAREST);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
ReadPreference.prototype.isValid = function(mode) {
|
||||
var _mode = typeof mode == 'string' ? mode : this.mode;
|
||||
return ReadPreference.isValid(_mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
ReadPreference.prototype.toObject = function() {
|
||||
var object = {mode:this.mode};
|
||||
|
||||
if(this.tags != null) {
|
||||
object['tags'] = this.tags;
|
||||
}
|
||||
|
||||
return object;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
ReadPreference.PRIMARY = 'primary';
|
||||
ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred';
|
||||
ReadPreference.SECONDARY = 'secondary';
|
||||
ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred';
|
||||
ReadPreference.NEAREST = 'nearest'
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports.ReadPreference = ReadPreference;
|
||||
1471
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/repl_set.js
generated
vendored
Normal file
1471
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/repl_set.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
905
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/server.js
generated
vendored
Normal file
905
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/server.js
generated
vendored
Normal file
@@ -0,0 +1,905 @@
|
||||
var Connection = require('./connection').Connection,
|
||||
ReadPreference = require('./read_preference').ReadPreference,
|
||||
DbCommand = require('../commands/db_command').DbCommand,
|
||||
MongoReply = require('../responses/mongo_reply').MongoReply,
|
||||
ConnectionPool = require('./connection_pool').ConnectionPool,
|
||||
EventEmitter = require('events').EventEmitter,
|
||||
Base = require('./base').Base,
|
||||
utils = require('../utils'),
|
||||
timers = require('timers'),
|
||||
inherits = require('util').inherits;
|
||||
|
||||
// Set processor, setImmediate if 0.10 otherwise nextTick
|
||||
var processor = timers.setImmediate ? timers.setImmediate : process.nextTick;
|
||||
processor = process.nextTick
|
||||
|
||||
/**
|
||||
* Class representing a single MongoDB Server connection
|
||||
*
|
||||
* Options
|
||||
* - **readPreference** {String, default:null}, set's the read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
|
||||
* - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support)
|
||||
* - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
|
||||
* - **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)
|
||||
* - **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)
|
||||
* - **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)
|
||||
* - **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)
|
||||
* - **poolSize** {Number, default:5}, number of connections in the connection pool, set to 5 as default for legacy reasons.
|
||||
* - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))
|
||||
* - **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) {}})**.
|
||||
* - **auto_reconnect** {Boolean, default:false}, reconnect on error.
|
||||
* - **disableDriverBSONSizeCheck** {Boolean, default:false}, force the server to error if the BSON message is to big
|
||||
*
|
||||
* @class Represents a Server connection.
|
||||
* @param {String} host the server host
|
||||
* @param {Number} port the server port
|
||||
* @param {Object} [options] optional options for insert command
|
||||
*/
|
||||
function Server(host, port, options) {
|
||||
// Set up Server instance
|
||||
if(!(this instanceof Server)) return new Server(host, port, options);
|
||||
|
||||
// Set up event emitter
|
||||
Base.call(this);
|
||||
|
||||
// Ensure correct values
|
||||
if(port != null && typeof port == 'object') {
|
||||
options = port;
|
||||
port = Connection.DEFAULT_PORT;
|
||||
}
|
||||
|
||||
var self = this;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.options = options == null ? {} : options;
|
||||
this.internalConnection;
|
||||
this.internalMaster = false;
|
||||
this.connected = false;
|
||||
this.poolSize = this.options.poolSize == null ? 5 : this.options.poolSize;
|
||||
this.disableDriverBSONSizeCheck = this.options.disableDriverBSONSizeCheck != null ? this.options.disableDriverBSONSizeCheck : false;
|
||||
this.slaveOk = this.options["slave_ok"] ? this.options["slave_ok"] : this.options["slaveOk"];
|
||||
this._used = false;
|
||||
this.replicasetInstance = null;
|
||||
|
||||
// Set ssl as connection method
|
||||
this.ssl = this.options.ssl == null ? false : this.options.ssl;
|
||||
// Set ssl validation
|
||||
this.sslValidate = this.options.sslValidate == null ? false : this.options.sslValidate;
|
||||
// Set the ssl certificate authority (array of Buffer/String keys)
|
||||
this.sslCA = Array.isArray(this.options.sslCA) ? this.options.sslCA : null;
|
||||
// Certificate to present to the server
|
||||
this.sslCert = this.options.sslCert;
|
||||
// Certificate private key if in separate file
|
||||
this.sslKey = this.options.sslKey;
|
||||
// Password to unlock private key
|
||||
this.sslPass = this.options.sslPass;
|
||||
|
||||
// Ensure we are not trying to validate with no list of certificates
|
||||
if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) {
|
||||
throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate");
|
||||
}
|
||||
|
||||
// Get the readPreference
|
||||
var readPreference = this.options['readPreference'];
|
||||
// If readPreference is an object get the mode string
|
||||
var validateReadPreference = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference;
|
||||
// Read preference setting
|
||||
if(validateReadPreference != null) {
|
||||
if(validateReadPreference != ReadPreference.PRIMARY && validateReadPreference != ReadPreference.SECONDARY && validateReadPreference != ReadPreference.NEAREST
|
||||
&& validateReadPreference != ReadPreference.SECONDARY_PREFERRED && validateReadPreference != ReadPreference.PRIMARY_PREFERRED) {
|
||||
throw new Error("Illegal readPreference mode specified, " + validateReadPreference);
|
||||
}
|
||||
|
||||
// Set read Preference
|
||||
this._readPreference = readPreference;
|
||||
} else {
|
||||
this._readPreference = null;
|
||||
}
|
||||
|
||||
// Contains the isMaster information returned from the server
|
||||
this.isMasterDoc;
|
||||
|
||||
// Set default connection pool options
|
||||
this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
|
||||
if(this.disableDriverBSONSizeCheck) this.socketOptions.disableDriverBSONSizeCheck = this.disableDriverBSONSizeCheck;
|
||||
|
||||
// Set ssl up if it's defined
|
||||
if(this.ssl) {
|
||||
this.socketOptions.ssl = true;
|
||||
// Set ssl validation
|
||||
this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate;
|
||||
// Set the ssl certificate authority (array of Buffer/String keys)
|
||||
this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null;
|
||||
// Set certificate to present
|
||||
this.socketOptions.sslCert = this.sslCert;
|
||||
// Set certificate to present
|
||||
this.socketOptions.sslKey = this.sslKey;
|
||||
// Password to unlock private key
|
||||
this.socketOptions.sslPass = this.sslPass;
|
||||
}
|
||||
|
||||
// Set up logger if any set
|
||||
this.logger = this.options.logger != null
|
||||
&& (typeof this.options.logger.debug == 'function')
|
||||
&& (typeof this.options.logger.error == 'function')
|
||||
&& (typeof this.options.logger.log == 'function')
|
||||
? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};
|
||||
|
||||
// Just keeps list of events we allow
|
||||
this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]};
|
||||
// Internal state of server connection
|
||||
this._serverState = 'disconnected';
|
||||
// this._timeout = false;
|
||||
// Contains state information about server connection
|
||||
this._state = {'runtimeStats': {'queryStats':new RunningStats()}};
|
||||
// Do we record server stats or not
|
||||
this.recordQueryStats = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
inherits(Server, Base);
|
||||
|
||||
//
|
||||
// Deprecated, USE ReadPreferences class
|
||||
//
|
||||
Server.READ_PRIMARY = ReadPreference.PRIMARY;
|
||||
Server.READ_SECONDARY = ReadPreference.SECONDARY_PREFERRED;
|
||||
Server.READ_SECONDARY_ONLY = ReadPreference.SECONDARY;
|
||||
|
||||
/**
|
||||
* Always ourselves
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.setReadPreference = function() {}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.isMongos = function() {
|
||||
return this.isMasterDoc != null && this.isMasterDoc['msg'] == "isdbgrid" ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype._isUsed = function() {
|
||||
return this._used;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.close = function(callback) {
|
||||
// Remove all local listeners
|
||||
this.removeAllListeners();
|
||||
|
||||
if(this.connectionPool != null) {
|
||||
// Remove all the listeners on the pool so it does not fire messages all over the place
|
||||
this.connectionPool.removeAllEventListeners();
|
||||
// Close the connection if it's open
|
||||
this.connectionPool.stop(true);
|
||||
}
|
||||
|
||||
// Set server status as disconnected
|
||||
this._serverState = 'disconnected';
|
||||
// Peform callback if present
|
||||
if(typeof callback === 'function') callback(null);
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.isConnected = function() {
|
||||
return this._serverState == 'connected';
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.allServerInstances = function() {
|
||||
return [this];
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.isSetMember = function() {
|
||||
return this.replicasetInstance != null || this.mongosInstance != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns a replica set to this `server`.
|
||||
*
|
||||
* @param {ReplSet} replset
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.assignReplicaSet = function (replset) {
|
||||
this.replicasetInstance = replset;
|
||||
this.inheritReplSetOptionsFrom(replset);
|
||||
this.enableRecordQueryStats(replset.recordQueryStats);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes needed options from `replset` and overwrites
|
||||
* our own options.
|
||||
*
|
||||
* @param {ReplSet} replset
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.inheritReplSetOptionsFrom = function (replset) {
|
||||
this.socketOptions = {};
|
||||
this.socketOptions.connectTimeoutMS = replset._connectTimeoutMS;
|
||||
|
||||
if(replset.ssl) {
|
||||
// Set ssl on
|
||||
this.socketOptions.ssl = true;
|
||||
// Set ssl validation
|
||||
this.socketOptions.sslValidate = replset.sslValidate == null ? false : replset.sslValidate;
|
||||
// Set the ssl certificate authority (array of Buffer/String keys)
|
||||
this.socketOptions.sslCA = Array.isArray(replset.sslCA) ? replset.sslCA : null;
|
||||
// Set certificate to present
|
||||
this.socketOptions.sslCert = replset.sslCert;
|
||||
// Set certificate to present
|
||||
this.socketOptions.sslKey = replset.sslKey;
|
||||
// Password to unlock private key
|
||||
this.socketOptions.sslPass = replset.sslPass;
|
||||
}
|
||||
|
||||
// If a socket option object exists clone it
|
||||
if(utils.isObject(replset.socketOptions)) {
|
||||
var keys = Object.keys(replset.socketOptions);
|
||||
for(var i = 0; i < keys.length; i++)
|
||||
this.socketOptions[keys[i]] = replset.socketOptions[keys[i]];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens this server connection.
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.connect = function(dbInstance, options, callback) {
|
||||
if('function' === typeof options) callback = options, options = {};
|
||||
if(options == null) options = {};
|
||||
if(!('function' === typeof callback)) callback = null;
|
||||
|
||||
// Currently needed to work around problems with multiple connections in a pool with ssl
|
||||
// TODO fix if possible
|
||||
if(this.ssl == true) {
|
||||
// Set up socket options for ssl
|
||||
this.socketOptions.ssl = true;
|
||||
// Set ssl validation
|
||||
this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate;
|
||||
// Set the ssl certificate authority (array of Buffer/String keys)
|
||||
this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null;
|
||||
// Set certificate to present
|
||||
this.socketOptions.sslCert = this.sslCert;
|
||||
// Set certificate to present
|
||||
this.socketOptions.sslKey = this.sslKey;
|
||||
// Password to unlock private key
|
||||
this.socketOptions.sslPass = this.sslPass;
|
||||
}
|
||||
|
||||
// Let's connect
|
||||
var server = this;
|
||||
// Let's us override the main receiver of events
|
||||
var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this;
|
||||
// Save reference to dbInstance
|
||||
this.db = dbInstance; // `db` property matches ReplSet and Mongos
|
||||
this.dbInstances = [dbInstance];
|
||||
|
||||
// Force connection pool if there is one
|
||||
if(server.connectionPool) server.connectionPool.stop();
|
||||
|
||||
// Set server state to connecting
|
||||
this._serverState = 'connecting';
|
||||
// Ensure dbInstance can do a slave query if it's set
|
||||
dbInstance.slaveOk = this.slaveOk ? this.slaveOk : dbInstance.slaveOk;
|
||||
// Create connection Pool instance with the current BSON serializer
|
||||
var connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions);
|
||||
// If ssl is not enabled don't wait between the pool connections
|
||||
if(this.ssl == null || !this.ssl) connectionPool._timeToWait = null;
|
||||
// Set logger on pool
|
||||
connectionPool.logger = this.logger;
|
||||
|
||||
// Set up a new pool using default settings
|
||||
server.connectionPool = connectionPool;
|
||||
|
||||
// Set basic parameters passed in
|
||||
var returnIsMasterResults = options.returnIsMasterResults == null ? false : options.returnIsMasterResults;
|
||||
|
||||
// Create a default connect handler, overriden when using replicasets
|
||||
var connectCallback = function(err, reply) {
|
||||
// ensure no callbacks get called twice
|
||||
var internalCallback = callback;
|
||||
callback = null;
|
||||
// If something close down the connection and removed the callback before
|
||||
// proxy killed connection etc, ignore the erorr as close event was isssued
|
||||
if(err != null && internalCallback == null) return;
|
||||
// Internal callback
|
||||
if(err != null) return internalCallback(err, null, server);
|
||||
server.master = reply.documents[0].ismaster == 1 ? true : false;
|
||||
server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize);
|
||||
server.connectionPool.setMaxMessageSizeBytes(reply.documents[0].maxMessageSizeBytes);
|
||||
// Set server as connected
|
||||
server.connected = true;
|
||||
// Save document returned so we can query it
|
||||
server.isMasterDoc = reply.documents[0];
|
||||
|
||||
// Emit open event
|
||||
_emitAcrossAllDbInstances(server, eventReceiver, "open", null, returnIsMasterResults ? reply : dbInstance, null);
|
||||
|
||||
// If we have it set to returnIsMasterResults
|
||||
if(returnIsMasterResults) {
|
||||
internalCallback(null, reply, server);
|
||||
} else {
|
||||
internalCallback(null, dbInstance, server);
|
||||
}
|
||||
};
|
||||
|
||||
// Let's us override the main connect callback
|
||||
var connectHandler = options.connectHandler == null ? connectCallback : options.connectHandler;
|
||||
|
||||
// Set up on connect method
|
||||
connectionPool.on("poolReady", function() {
|
||||
// Create db command and Add the callback to the list of callbacks by the request id (mapping outgoing messages to correct callbacks)
|
||||
var db_command = DbCommand.NcreateIsMasterCommand(dbInstance, dbInstance.databaseName);
|
||||
// Check out a reader from the pool
|
||||
var connection = connectionPool.checkoutConnection();
|
||||
// Set server state to connEcted
|
||||
server._serverState = 'connected';
|
||||
|
||||
// Register handler for messages
|
||||
server._registerHandler(db_command, false, connection, connectHandler);
|
||||
|
||||
// Write the command out
|
||||
connection.write(db_command);
|
||||
})
|
||||
|
||||
// Set up item connection
|
||||
connectionPool.on("message", function(message) {
|
||||
// Attempt to parse the message
|
||||
try {
|
||||
// Create a new mongo reply
|
||||
var mongoReply = new MongoReply()
|
||||
// Parse the header
|
||||
mongoReply.parseHeader(message, connectionPool.bson)
|
||||
|
||||
// If message size is not the same as the buffer size
|
||||
// something went terribly wrong somewhere
|
||||
if(mongoReply.messageLength != message.length) {
|
||||
// Emit the error
|
||||
if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", new Error("bson length is different from message length"), server);
|
||||
// Remove all listeners
|
||||
server.removeAllListeners();
|
||||
} else {
|
||||
var startDate = new Date().getTime();
|
||||
|
||||
// Callback instance
|
||||
var callbackInfo = server._findHandler(mongoReply.responseTo.toString());
|
||||
|
||||
// The command executed another request, log the handler again under that request id
|
||||
if(mongoReply.requestId > 0 && mongoReply.cursorId.toString() != "0"
|
||||
&& callbackInfo && callbackInfo.info && callbackInfo.info.exhaust) {
|
||||
server._reRegisterHandler(mongoReply.requestId, callbackInfo);
|
||||
}
|
||||
|
||||
// Only execute callback if we have a caller
|
||||
// chained is for findAndModify as it does not respect write concerns
|
||||
if(callbackInfo && callbackInfo.callback && callbackInfo.info && Array.isArray(callbackInfo.info.chained)) {
|
||||
// Check if callback has already been fired (missing chain command)
|
||||
var chained = callbackInfo.info.chained;
|
||||
var numberOfFoundCallbacks = 0;
|
||||
for(var i = 0; i < chained.length; i++) {
|
||||
if(server._hasHandler(chained[i])) numberOfFoundCallbacks++;
|
||||
}
|
||||
|
||||
// If we have already fired then clean up rest of chain and move on
|
||||
if(numberOfFoundCallbacks != chained.length) {
|
||||
for(var i = 0; i < chained.length; i++) {
|
||||
server._removeHandler(chained[i]);
|
||||
}
|
||||
|
||||
// Just return from function
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse the body
|
||||
mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) {
|
||||
if(err != null) {
|
||||
// If pool connection is already closed
|
||||
if(server._serverState === 'disconnected') return;
|
||||
// Set server state to disconnected
|
||||
server._serverState = 'disconnected';
|
||||
// Remove all listeners and close the connection pool
|
||||
server.removeAllListeners();
|
||||
connectionPool.stop(true);
|
||||
|
||||
// If we have a callback return the error
|
||||
if(typeof callback === 'function') {
|
||||
// ensure no callbacks get called twice
|
||||
var internalCallback = callback;
|
||||
callback = null;
|
||||
// Perform callback
|
||||
internalCallback(new Error("connection closed due to parseError"), null, server);
|
||||
} else if(server.isSetMember()) {
|
||||
if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", new Error("connection closed due to parseError"), server);
|
||||
} else {
|
||||
if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", new Error("connection closed due to parseError"), server);
|
||||
}
|
||||
|
||||
// If we are a single server connection fire errors correctly
|
||||
if(!server.isSetMember()) {
|
||||
// Fire all callback errors
|
||||
server.__executeAllCallbacksWithError(new Error("connection closed due to parseError"));
|
||||
// Emit error
|
||||
_emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true);
|
||||
}
|
||||
// Short cut
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch the callback
|
||||
var callbackInfo = server._findHandler(mongoReply.responseTo.toString());
|
||||
// If we have an error let's execute the callback and clean up all other
|
||||
// chained commands
|
||||
var firstResult = mongoReply && mongoReply.documents;
|
||||
|
||||
// Check for an error, if we have one let's trigger the callback and clean up
|
||||
// The chained callbacks
|
||||
if(firstResult[0].err != null || firstResult[0].errmsg != null) {
|
||||
// Trigger the callback for the error
|
||||
server._callHandler(mongoReply.responseTo, mongoReply, null);
|
||||
} else {
|
||||
var chainedIds = callbackInfo.info.chained;
|
||||
|
||||
if(chainedIds.length > 0 && chainedIds[chainedIds.length - 1] == mongoReply.responseTo) {
|
||||
// Cleanup all other chained calls
|
||||
chainedIds.pop();
|
||||
// Remove listeners
|
||||
for(var i = 0; i < chainedIds.length; i++) server._removeHandler(chainedIds[i]);
|
||||
// Call the handler
|
||||
server._callHandler(mongoReply.responseTo, callbackInfo.info.results.shift(), null);
|
||||
} else{
|
||||
// Add the results to all the results
|
||||
for(var i = 0; i < chainedIds.length; i++) {
|
||||
var handler = server._findHandler(chainedIds[i]);
|
||||
// Check if we have an object, if it's the case take the current object commands and
|
||||
// and add this one
|
||||
if(handler.info != null) {
|
||||
handler.info.results = Array.isArray(callbackInfo.info.results) ? callbackInfo.info.results : [];
|
||||
handler.info.results.push(mongoReply);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if(callbackInfo && callbackInfo.callback && callbackInfo.info) {
|
||||
// Parse the body
|
||||
mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) {
|
||||
if(err != null) {
|
||||
// If pool connection is already closed
|
||||
if(server._serverState === 'disconnected') return;
|
||||
// Set server state to disconnected
|
||||
server._serverState = 'disconnected';
|
||||
// Remove all listeners and close the connection pool
|
||||
server.removeAllListeners();
|
||||
connectionPool.stop(true);
|
||||
|
||||
// If we have a callback return the error
|
||||
if(typeof callback === 'function') {
|
||||
// ensure no callbacks get called twice
|
||||
var internalCallback = callback;
|
||||
callback = null;
|
||||
// Perform callback
|
||||
internalCallback(new Error("connection closed due to parseError"), null, server);
|
||||
} else if(server.isSetMember()) {
|
||||
if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", new Error("connection closed due to parseError"), server);
|
||||
} else {
|
||||
if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", new Error("connection closed due to parseError"), server);
|
||||
}
|
||||
|
||||
// If we are a single server connection fire errors correctly
|
||||
if(!server.isSetMember()) {
|
||||
// Fire all callback errors
|
||||
server.__executeAllCallbacksWithError(new Error("connection closed due to parseError"));
|
||||
// Emit error
|
||||
_emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true);
|
||||
}
|
||||
// Short cut
|
||||
return;
|
||||
}
|
||||
|
||||
// Let's record the stats info if it's enabled
|
||||
if(server.recordQueryStats == true && server._state['runtimeStats'] != null
|
||||
&& server._state.runtimeStats['queryStats'] instanceof RunningStats) {
|
||||
// Add data point to the running statistics object
|
||||
server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start);
|
||||
}
|
||||
|
||||
server._callHandler(mongoReply.responseTo, mongoReply, null);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// Throw error in next tick
|
||||
processor(function() {
|
||||
throw err;
|
||||
})
|
||||
}
|
||||
});
|
||||
|
||||
// Handle timeout
|
||||
connectionPool.on("timeout", function(err) {
|
||||
// If pool connection is already closed
|
||||
if(server._serverState === 'disconnected') return;
|
||||
// Set server state to disconnected
|
||||
server._serverState = 'disconnected';
|
||||
// If we have a callback return the error
|
||||
if(typeof callback === 'function') {
|
||||
// ensure no callbacks get called twice
|
||||
var internalCallback = callback;
|
||||
callback = null;
|
||||
// Perform callback
|
||||
internalCallback(err, null, server);
|
||||
} else if(server.isSetMember()) {
|
||||
if(server.listeners("timeout") && server.listeners("timeout").length > 0) server.emit("timeout", err, server);
|
||||
} else {
|
||||
if(eventReceiver.listeners("timeout") && eventReceiver.listeners("timeout").length > 0) eventReceiver.emit("timeout", err, server);
|
||||
}
|
||||
|
||||
// If we are a single server connection fire errors correctly
|
||||
if(!server.isSetMember()) {
|
||||
// Fire all callback errors
|
||||
server.__executeAllCallbacksWithError(err);
|
||||
// Emit error
|
||||
_emitAcrossAllDbInstances(server, eventReceiver, "timeout", err, server, true);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle errors
|
||||
connectionPool.on("error", function(message, connection, error_options) {
|
||||
// If pool connection is already closed
|
||||
if(server._serverState === 'disconnected') return;
|
||||
// Set server state to disconnected
|
||||
server._serverState = 'disconnected';
|
||||
// Error message
|
||||
var error_message = new Error(message && message.err ? message.err : message);
|
||||
// Error message coming from ssl
|
||||
if(error_options && error_options.ssl) error_message.ssl = true;
|
||||
// If we have a callback return the error
|
||||
if(typeof callback === 'function') {
|
||||
// ensure no callbacks get called twice
|
||||
var internalCallback = callback;
|
||||
callback = null;
|
||||
// Perform callback
|
||||
internalCallback(error_message, null, server);
|
||||
} else if(server.isSetMember()) {
|
||||
if(server.listeners("error") && server.listeners("error").length > 0) server.emit("error", error_message, server);
|
||||
} else {
|
||||
if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", error_message, server);
|
||||
}
|
||||
|
||||
// If we are a single server connection fire errors correctly
|
||||
if(!server.isSetMember()) {
|
||||
// Fire all callback errors
|
||||
server.__executeAllCallbacksWithError(error_message);
|
||||
// Emit error
|
||||
_emitAcrossAllDbInstances(server, eventReceiver, "error", error_message, server, true);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle close events
|
||||
connectionPool.on("close", function() {
|
||||
// If pool connection is already closed
|
||||
if(server._serverState === 'disconnected') return;
|
||||
// Set server state to disconnected
|
||||
server._serverState = 'disconnected';
|
||||
// If we have a callback return the error
|
||||
if(typeof callback == 'function') {
|
||||
// ensure no callbacks get called twice
|
||||
var internalCallback = callback;
|
||||
callback = null;
|
||||
// Perform callback
|
||||
internalCallback(new Error("connection closed"), null, server);
|
||||
} else if(server.isSetMember()) {
|
||||
if(server.listeners("close") && server.listeners("close").length > 0) server.emit("close", new Error("connection closed"), server);
|
||||
} else {
|
||||
if(eventReceiver.listeners("close") && eventReceiver.listeners("close").length > 0) eventReceiver.emit("close", new Error("connection closed"), server);
|
||||
}
|
||||
|
||||
// If we are a single server connection fire errors correctly
|
||||
if(!server.isSetMember()) {
|
||||
// Fire all callback errors
|
||||
server.__executeAllCallbacksWithError(new Error("connection closed"));
|
||||
// Emit error
|
||||
_emitAcrossAllDbInstances(server, eventReceiver, "close", server, null, true);
|
||||
}
|
||||
});
|
||||
|
||||
// If we have a parser error we are in an unknown state, close everything and emit
|
||||
// error
|
||||
connectionPool.on("parseError", function(message) {
|
||||
// If pool connection is already closed
|
||||
if(server._serverState === 'disconnected') return;
|
||||
// Set server state to disconnected
|
||||
server._serverState = 'disconnected';
|
||||
// If we have a callback return the error
|
||||
if(typeof callback === 'function') {
|
||||
// ensure no callbacks get called twice
|
||||
var internalCallback = callback;
|
||||
callback = null;
|
||||
// Perform callback
|
||||
internalCallback(new Error("connection closed due to parseError"), null, server);
|
||||
} else if(server.isSetMember()) {
|
||||
if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", new Error("connection closed due to parseError"), server);
|
||||
} else {
|
||||
if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", new Error("connection closed due to parseError"), server);
|
||||
}
|
||||
|
||||
// If we are a single server connection fire errors correctly
|
||||
if(!server.isSetMember()) {
|
||||
// Fire all callback errors
|
||||
server.__executeAllCallbacksWithError(new Error("connection closed due to parseError"));
|
||||
// Emit error
|
||||
_emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true);
|
||||
}
|
||||
});
|
||||
|
||||
// Boot up connection poole, pass in a locator of callbacks
|
||||
connectionPool.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
var _emitAcrossAllDbInstances = function(server, filterDb, event, message, object, resetConnection) {
|
||||
// Emit close event across all db instances sharing the sockets
|
||||
var allServerInstances = server.allServerInstances();
|
||||
// Fetch the first server instance
|
||||
var serverInstance = allServerInstances[0];
|
||||
// For all db instances signal all db instances
|
||||
if(Array.isArray(serverInstance.dbInstances) && serverInstance.dbInstances.length >= 1) {
|
||||
for(var i = 0; i < serverInstance.dbInstances.length; i++) {
|
||||
var dbInstance = serverInstance.dbInstances[i];
|
||||
// Set the parent
|
||||
if(resetConnection && typeof dbInstance.openCalled != 'undefined')
|
||||
dbInstance.openCalled = false;
|
||||
// Check if it's our current db instance and skip if it is
|
||||
if(filterDb == null || filterDb.databaseName !== dbInstance.databaseName || filterDb.tag !== dbInstance.tag) {
|
||||
// Only emit if there is a listener
|
||||
if(dbInstance.listeners(event).length > 0)
|
||||
dbInstance.emit(event, message, object);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.allRawConnections = function() {
|
||||
return this.connectionPool.getAllConnections();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a writer can be provided
|
||||
* @ignore
|
||||
*/
|
||||
var canCheckoutWriter = function(self, read) {
|
||||
// We cannot write to an arbiter or secondary server
|
||||
if(self.isMasterDoc['arbiterOnly'] == true) {
|
||||
return new Error("Cannot write to an arbiter");
|
||||
} if(self.isMasterDoc['secondary'] == true) {
|
||||
return new Error("Cannot write to a secondary");
|
||||
} else if(read == true && self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc['ismaster'] == true) {
|
||||
return new Error("Cannot read from primary when secondary only specified");
|
||||
}
|
||||
|
||||
// Return no error
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.checkoutWriter = function(read) {
|
||||
if(read == true) return this.connectionPool.checkoutConnection();
|
||||
// Check if are allowed to do a checkout (if we try to use an arbiter f.ex)
|
||||
var result = canCheckoutWriter(this, read);
|
||||
// If the result is null check out a writer
|
||||
if(result == null && this.connectionPool != null) {
|
||||
return this.connectionPool.checkoutConnection();
|
||||
} else if(result == null) {
|
||||
return null;
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a reader can be provided
|
||||
* @ignore
|
||||
*/
|
||||
var canCheckoutReader = function(self) {
|
||||
// We cannot write to an arbiter or secondary server
|
||||
if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) {
|
||||
return new Error("Cannot write to an arbiter");
|
||||
} else if(self._readPreference != null) {
|
||||
// If the read preference is Primary and the instance is not a master return an error
|
||||
if((self._readPreference == ReadPreference.PRIMARY) && self.isMasterDoc['ismaster'] != true) {
|
||||
return new Error("Read preference is Server.PRIMARY and server is not master");
|
||||
} else if(self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc['ismaster'] == true) {
|
||||
return new Error("Cannot read from primary when secondary only specified");
|
||||
}
|
||||
}
|
||||
|
||||
// Return no error
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.checkoutReader = function() {
|
||||
// Check if are allowed to do a checkout (if we try to use an arbiter f.ex)
|
||||
var result = canCheckoutReader(this);
|
||||
// If the result is null check out a writer
|
||||
if(result == null && this.connectionPool != null) {
|
||||
return this.connectionPool.checkoutConnection();
|
||||
} else if(result == null) {
|
||||
return null;
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Server.prototype.enableRecordQueryStats = function(enable) {
|
||||
this.recordQueryStats = enable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal statistics object used for calculating average and standard devitation on
|
||||
* running queries
|
||||
* @ignore
|
||||
*/
|
||||
var RunningStats = function() {
|
||||
var self = this;
|
||||
this.m_n = 0;
|
||||
this.m_oldM = 0.0;
|
||||
this.m_oldS = 0.0;
|
||||
this.m_newM = 0.0;
|
||||
this.m_newS = 0.0;
|
||||
|
||||
// Define getters
|
||||
Object.defineProperty(this, "numDataValues", { enumerable: true
|
||||
, get: function () { return this.m_n; }
|
||||
});
|
||||
|
||||
Object.defineProperty(this, "mean", { enumerable: true
|
||||
, get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; }
|
||||
});
|
||||
|
||||
Object.defineProperty(this, "variance", { enumerable: true
|
||||
, get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); }
|
||||
});
|
||||
|
||||
Object.defineProperty(this, "standardDeviation", { enumerable: true
|
||||
, get: function () { return Math.sqrt(this.variance); }
|
||||
});
|
||||
|
||||
Object.defineProperty(this, "sScore", { enumerable: true
|
||||
, get: function () {
|
||||
var bottom = this.mean + this.standardDeviation;
|
||||
if(bottom == 0) return 0;
|
||||
return ((2 * this.mean * this.standardDeviation)/(bottom));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
RunningStats.prototype.push = function(x) {
|
||||
// Update the number of samples
|
||||
this.m_n = this.m_n + 1;
|
||||
// See Knuth TAOCP vol 2, 3rd edition, page 232
|
||||
if(this.m_n == 1) {
|
||||
this.m_oldM = this.m_newM = x;
|
||||
this.m_oldS = 0.0;
|
||||
} else {
|
||||
this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n;
|
||||
this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM);
|
||||
|
||||
// set up for next iteration
|
||||
this.m_oldM = this.m_newM;
|
||||
this.m_oldS = this.m_newS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(Server.prototype, "autoReconnect", { enumerable: true
|
||||
, get: function () {
|
||||
return this.options['auto_reconnect'] == null ? false : this.options['auto_reconnect'];
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(Server.prototype, "connection", { enumerable: true
|
||||
, get: function () {
|
||||
return this.internalConnection;
|
||||
}
|
||||
, set: function(connection) {
|
||||
this.internalConnection = connection;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(Server.prototype, "master", { enumerable: true
|
||||
, get: function () {
|
||||
return this.internalMaster;
|
||||
}
|
||||
, set: function(value) {
|
||||
this.internalMaster = value;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(Server.prototype, "primary", { enumerable: true
|
||||
, get: function () {
|
||||
return this;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Getter for query Stats
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(Server.prototype, "queryStats", { enumerable: true
|
||||
, get: function () {
|
||||
return this._state.runtimeStats.queryStats;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(Server.prototype, "runtimeStats", { enumerable: true
|
||||
, get: function () {
|
||||
return this._state.runtimeStats;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Get Read Preference method
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(Server.prototype, "readPreference", { enumerable: true
|
||||
, get: function () {
|
||||
if(this._readPreference == null && this.readSecondary) {
|
||||
return Server.READ_SECONDARY;
|
||||
} else if(this._readPreference == null && !this.readSecondary) {
|
||||
return Server.READ_PRIMARY;
|
||||
} else {
|
||||
return this._readPreference;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports.Server = Server;
|
||||
290
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/strategies/ping_strategy.js
generated
vendored
Normal file
290
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/strategies/ping_strategy.js
generated
vendored
Normal file
@@ -0,0 +1,290 @@
|
||||
var Server = require("../server").Server
|
||||
, format = require('util').format;
|
||||
|
||||
// The ping strategy uses pings each server and records the
|
||||
// elapsed time for the server so it can pick a server based on lowest
|
||||
// return time for the db command {ping:true}
|
||||
var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) {
|
||||
this.replicaset = replicaset;
|
||||
this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS;
|
||||
this.state = 'disconnected';
|
||||
this.pingInterval = 5000;
|
||||
// Class instance
|
||||
this.Db = require("../../db").Db;
|
||||
// Active db connections
|
||||
this.dbs = {};
|
||||
// Logger api
|
||||
this.Logger = null;
|
||||
}
|
||||
|
||||
// Starts any needed code
|
||||
PingStrategy.prototype.start = function(callback) {
|
||||
// already running?
|
||||
if ('connected' == this.state) return;
|
||||
|
||||
this.state = 'connected';
|
||||
|
||||
// Start ping server
|
||||
this._pingServer(callback);
|
||||
}
|
||||
|
||||
// Stops and kills any processes running
|
||||
PingStrategy.prototype.stop = function(callback) {
|
||||
// Stop the ping process
|
||||
this.state = 'disconnected';
|
||||
|
||||
// Stop all the server instances
|
||||
for(var key in this.dbs) {
|
||||
this.dbs[key].close();
|
||||
}
|
||||
|
||||
// optional callback
|
||||
callback && callback(null, null);
|
||||
}
|
||||
|
||||
PingStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) {
|
||||
// Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
|
||||
// Create a list of candidat servers, containing the primary if available
|
||||
var candidateServers = [];
|
||||
var self = this;
|
||||
|
||||
// If we have not provided a list of candidate servers use the default setup
|
||||
if(!Array.isArray(secondaryCandidates)) {
|
||||
candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
|
||||
// Add all the secondaries
|
||||
var keys = Object.keys(this.replicaset._state.secondaries);
|
||||
for(var i = 0; i < keys.length; i++) {
|
||||
candidateServers.push(this.replicaset._state.secondaries[keys[i]])
|
||||
}
|
||||
} else {
|
||||
candidateServers = secondaryCandidates;
|
||||
}
|
||||
|
||||
// Final list of eligable server
|
||||
var finalCandidates = [];
|
||||
|
||||
// If we have tags filter by tags
|
||||
if(tags != null && typeof tags == 'object') {
|
||||
// If we have an array or single tag selection
|
||||
var tagObjects = Array.isArray(tags) ? tags : [tags];
|
||||
// Iterate over all tags until we find a candidate server
|
||||
for(var _i = 0; _i < tagObjects.length; _i++) {
|
||||
// Grab a tag object
|
||||
var tagObject = tagObjects[_i];
|
||||
// Matching keys
|
||||
var matchingKeys = Object.keys(tagObject);
|
||||
// Remove any that are not tagged correctly
|
||||
for(var i = 0; i < candidateServers.length; i++) {
|
||||
var server = candidateServers[i];
|
||||
// If we have tags match
|
||||
if(server.tags != null) {
|
||||
var matching = true;
|
||||
|
||||
// Ensure we have all the values
|
||||
for(var j = 0; j < matchingKeys.length; j++) {
|
||||
if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
|
||||
matching = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If we have a match add it to the list of matching servers
|
||||
if(matching) {
|
||||
finalCandidates.push(server);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Final array candidates
|
||||
var finalCandidates = candidateServers;
|
||||
}
|
||||
|
||||
// Sort by ping time
|
||||
finalCandidates.sort(function(a, b) {
|
||||
return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs'];
|
||||
});
|
||||
|
||||
if(0 === finalCandidates.length)
|
||||
return new Error("No replica set members available for query");
|
||||
|
||||
// find lowest server with a ping time
|
||||
var lowest = finalCandidates.filter(function (server) {
|
||||
return undefined != server.runtimeStats.pingMs;
|
||||
})[0];
|
||||
|
||||
if(!lowest) {
|
||||
lowest = finalCandidates[0];
|
||||
}
|
||||
|
||||
// convert to integer
|
||||
var lowestPing = lowest.runtimeStats.pingMs | 0;
|
||||
|
||||
// determine acceptable latency
|
||||
var acceptable = lowestPing + this.secondaryAcceptableLatencyMS;
|
||||
|
||||
// remove any server responding slower than acceptable
|
||||
var len = finalCandidates.length;
|
||||
while(len--) {
|
||||
if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) {
|
||||
finalCandidates.splice(len, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if(self.logger && self.logger.debug) {
|
||||
self.logger.debug("Ping strategy selection order for tags", tags);
|
||||
finalCandidates.forEach(function(c) {
|
||||
self.logger.debug(format("%s:%s = %s ms", c.host, c.port, c.runtimeStats['pingMs']), null);
|
||||
})
|
||||
}
|
||||
|
||||
// If no candidates available return an error
|
||||
if(finalCandidates.length == 0)
|
||||
return new Error("No replica set members available for query");
|
||||
|
||||
// Pick a random acceptable server
|
||||
var connection = finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();
|
||||
if(self.logger && self.logger.debug) {
|
||||
if(connection)
|
||||
self.logger.debug("picked server %s:%s", connection.socketOptions.host, connection.socketOptions.port);
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
PingStrategy.prototype._pingServer = function(callback) {
|
||||
var self = this;
|
||||
|
||||
// Ping server function
|
||||
var pingFunction = function() {
|
||||
if(self.state == 'disconnected') return;
|
||||
|
||||
// Create a list of all servers we can send the ismaster command to
|
||||
var allServers = self.replicaset._state.master != null ? [self.replicaset._state.master] : [];
|
||||
|
||||
// Secondary keys
|
||||
var keys = Object.keys(self.replicaset._state.secondaries);
|
||||
// Add all secondaries
|
||||
for(var i = 0; i < keys.length; i++) {
|
||||
allServers.push(self.replicaset._state.secondaries[keys[i]]);
|
||||
}
|
||||
|
||||
// Number of server entries
|
||||
var numberOfEntries = allServers.length;
|
||||
|
||||
// We got keys
|
||||
for(var i = 0; i < allServers.length; i++) {
|
||||
|
||||
// We got a server instance
|
||||
var server = allServers[i];
|
||||
|
||||
// Create a new server object, avoid using internal connections as they might
|
||||
// be in an illegal state
|
||||
new function(serverInstance) {
|
||||
var _db = self.dbs[serverInstance.host + ":" + serverInstance.port];
|
||||
// If we have a db
|
||||
if(_db != null) {
|
||||
// Startup time of the command
|
||||
var startTime = Date.now();
|
||||
|
||||
// Execute ping command in own scope
|
||||
var _ping = function(__db, __serverInstance) {
|
||||
// Execute ping on this connection
|
||||
__db.executeDbCommand({ping:1}, {failFast:true}, function(err) {
|
||||
if(err) {
|
||||
delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
|
||||
__db.close();
|
||||
return done();
|
||||
}
|
||||
|
||||
if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {
|
||||
__serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
};
|
||||
// Ping
|
||||
_ping(_db, serverInstance);
|
||||
} else {
|
||||
// Create a new master connection
|
||||
var _server = new Server(serverInstance.host, serverInstance.port, {
|
||||
auto_reconnect: false,
|
||||
returnIsMasterResults: true,
|
||||
slaveOk: true,
|
||||
poolSize: 1,
|
||||
socketOptions: { connectTimeoutMS: self.replicaset._connectTimeoutMS },
|
||||
ssl: self.replicaset.ssl,
|
||||
sslValidate: self.replicaset.sslValidate,
|
||||
sslCA: self.replicaset.sslCA,
|
||||
sslCert: self.replicaset.sslCert,
|
||||
sslKey: self.replicaset.sslKey,
|
||||
sslPass: self.replicaset.sslPass
|
||||
});
|
||||
|
||||
// Create Db instance
|
||||
var _db = new self.Db(self.replicaset.db.databaseName, _server, { safe: true });
|
||||
_db.on("close", function() {
|
||||
delete self.dbs[this.serverConfig.host + ":" + this.serverConfig.port];
|
||||
})
|
||||
|
||||
var _ping = function(__db, __serverInstance) {
|
||||
if(self.state == 'disconnected') {
|
||||
self.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
__db.open(function(err, db) {
|
||||
if(self.state == 'disconnected' && __db != null) {
|
||||
return __db.close();
|
||||
}
|
||||
|
||||
if(err) {
|
||||
delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
|
||||
__db.close();
|
||||
return done();
|
||||
}
|
||||
|
||||
// Save instance
|
||||
self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port] = __db;
|
||||
|
||||
// Startup time of the command
|
||||
var startTime = Date.now();
|
||||
|
||||
// Execute ping on this connection
|
||||
__db.executeDbCommand({ping:1}, {failFast:true}, function(err) {
|
||||
if(err) {
|
||||
delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
|
||||
__db.close();
|
||||
return done();
|
||||
}
|
||||
|
||||
if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {
|
||||
__serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;
|
||||
}
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
_ping(_db, serverInstance);
|
||||
}
|
||||
|
||||
function done() {
|
||||
// Adjust the number of checks
|
||||
numberOfEntries--;
|
||||
|
||||
// If we are done with all results coming back trigger ping again
|
||||
if(0 === numberOfEntries && 'connected' == self.state) {
|
||||
setTimeout(pingFunction, self.pingInterval);
|
||||
}
|
||||
}
|
||||
}(server);
|
||||
}
|
||||
}
|
||||
|
||||
// Start pingFunction
|
||||
pingFunction();
|
||||
|
||||
callback && callback(null);
|
||||
}
|
||||
80
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/strategies/statistics_strategy.js
generated
vendored
Normal file
80
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/strategies/statistics_strategy.js
generated
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
// The Statistics strategy uses the measure of each end-start time for each
|
||||
// query executed against the db to calculate the mean, variance and standard deviation
|
||||
// and pick the server which the lowest mean and deviation
|
||||
var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) {
|
||||
this.replicaset = replicaset;
|
||||
// Logger api
|
||||
this.Logger = null;
|
||||
}
|
||||
|
||||
// Starts any needed code
|
||||
StatisticsStrategy.prototype.start = function(callback) {
|
||||
callback && callback(null, null);
|
||||
}
|
||||
|
||||
StatisticsStrategy.prototype.stop = function(callback) {
|
||||
callback && callback(null, null);
|
||||
}
|
||||
|
||||
StatisticsStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) {
|
||||
// Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
|
||||
// Create a list of candidat servers, containing the primary if available
|
||||
var candidateServers = [];
|
||||
|
||||
// If we have not provided a list of candidate servers use the default setup
|
||||
if(!Array.isArray(secondaryCandidates)) {
|
||||
candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
|
||||
// Add all the secondaries
|
||||
var keys = Object.keys(this.replicaset._state.secondaries);
|
||||
for(var i = 0; i < keys.length; i++) {
|
||||
candidateServers.push(this.replicaset._state.secondaries[keys[i]])
|
||||
}
|
||||
} else {
|
||||
candidateServers = secondaryCandidates;
|
||||
}
|
||||
|
||||
// Final list of eligable server
|
||||
var finalCandidates = [];
|
||||
|
||||
// If we have tags filter by tags
|
||||
if(tags != null && typeof tags == 'object') {
|
||||
// If we have an array or single tag selection
|
||||
var tagObjects = Array.isArray(tags) ? tags : [tags];
|
||||
// Iterate over all tags until we find a candidate server
|
||||
for(var _i = 0; _i < tagObjects.length; _i++) {
|
||||
// Grab a tag object
|
||||
var tagObject = tagObjects[_i];
|
||||
// Matching keys
|
||||
var matchingKeys = Object.keys(tagObject);
|
||||
// Remove any that are not tagged correctly
|
||||
for(var i = 0; i < candidateServers.length; i++) {
|
||||
var server = candidateServers[i];
|
||||
// If we have tags match
|
||||
if(server.tags != null) {
|
||||
var matching = true;
|
||||
|
||||
// Ensure we have all the values
|
||||
for(var j = 0; j < matchingKeys.length; j++) {
|
||||
if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
|
||||
matching = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If we have a match add it to the list of matching servers
|
||||
if(matching) {
|
||||
finalCandidates.push(server);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Final array candidates
|
||||
var finalCandidates = candidateServers;
|
||||
}
|
||||
|
||||
// If no candidates available return an error
|
||||
if(finalCandidates.length == 0) return new Error("No replica set members available for query");
|
||||
// Pick a random server
|
||||
return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();
|
||||
}
|
||||
225
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/url_parser.js
generated
vendored
Normal file
225
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/connection/url_parser.js
generated
vendored
Normal file
@@ -0,0 +1,225 @@
|
||||
var fs = require('fs'),
|
||||
ReadPreference = require('./read_preference').ReadPreference;
|
||||
|
||||
exports.parse = function(url, options) {
|
||||
// Ensure we have a default options object if none set
|
||||
options = options || {};
|
||||
// Variables
|
||||
var connection_part = '';
|
||||
var auth_part = '';
|
||||
var query_string_part = '';
|
||||
var dbName = 'admin';
|
||||
|
||||
// Must start with mongodb
|
||||
if(url.indexOf("mongodb://") != 0)
|
||||
throw Error("URL must be in the format mongodb://user:pass@host:port/dbname");
|
||||
// If we have a ? mark cut the query elements off
|
||||
if(url.indexOf("?") != -1) {
|
||||
query_string_part = url.substr(url.indexOf("?") + 1);
|
||||
connection_part = url.substring("mongodb://".length, url.indexOf("?"))
|
||||
} else {
|
||||
connection_part = url.substring("mongodb://".length);
|
||||
}
|
||||
|
||||
// Check if we have auth params
|
||||
if(connection_part.indexOf("@") != -1) {
|
||||
auth_part = connection_part.split("@")[0];
|
||||
connection_part = connection_part.split("@")[1];
|
||||
}
|
||||
|
||||
// Check if the connection string has a db
|
||||
if(connection_part.indexOf(".sock") != -1) {
|
||||
if(connection_part.indexOf(".sock/") != -1) {
|
||||
dbName = connection_part.split(".sock/")[1];
|
||||
connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length);
|
||||
}
|
||||
} else if(connection_part.indexOf("/") != -1) {
|
||||
dbName = connection_part.split("/")[1];
|
||||
connection_part = connection_part.split("/")[0];
|
||||
}
|
||||
|
||||
// Result object
|
||||
var object = {};
|
||||
|
||||
// Pick apart the authentication part of the string
|
||||
var authPart = auth_part || '';
|
||||
var auth = authPart.split(':', 2);
|
||||
if(options['uri_decode_auth']){
|
||||
auth[0] = decodeURIComponent(auth[0]);
|
||||
if(auth[1]){
|
||||
auth[1] = decodeURIComponent(auth[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// Add auth to final object if we have 2 elements
|
||||
if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]};
|
||||
|
||||
// Variables used for temporary storage
|
||||
var hostPart;
|
||||
var urlOptions;
|
||||
var servers;
|
||||
var serverOptions = {socketOptions: {}};
|
||||
var dbOptions = {read_preference_tags: []};
|
||||
var replSetServersOptions = {socketOptions: {}};
|
||||
// Add server options to final object
|
||||
object.server_options = serverOptions;
|
||||
object.db_options = dbOptions;
|
||||
object.rs_options = replSetServersOptions;
|
||||
object.mongos_options = {};
|
||||
|
||||
// Let's check if we are using a domain socket
|
||||
if(url.match(/\.sock/)) {
|
||||
// Split out the socket part
|
||||
var domainSocket = url.substring(
|
||||
url.indexOf("mongodb://") + "mongodb://".length
|
||||
, url.lastIndexOf(".sock") + ".sock".length);
|
||||
// Clean out any auth stuff if any
|
||||
if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1];
|
||||
servers = [{domain_socket: domainSocket}];
|
||||
} else {
|
||||
// Split up the db
|
||||
hostPart = connection_part;
|
||||
// Parse all server results
|
||||
servers = hostPart.split(',').map(function(h) {
|
||||
var hostPort = h.split(':', 2);
|
||||
var _host = hostPort[0] || 'localhost';
|
||||
var _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017;
|
||||
// Check for localhost?safe=true style case
|
||||
if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0];
|
||||
|
||||
// Return the mapped object
|
||||
return {host: _host, port: _port};
|
||||
});
|
||||
}
|
||||
|
||||
// Get the db name
|
||||
object.dbName = dbName || 'admin';
|
||||
// Split up all the options
|
||||
urlOptions = (query_string_part || '').split(/[&;]/);
|
||||
// Ugh, we have to figure out which options go to which constructor manually.
|
||||
urlOptions.forEach(function(opt) {
|
||||
if(!opt) return;
|
||||
var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1];
|
||||
// Options implementations
|
||||
switch(name) {
|
||||
case 'slaveOk':
|
||||
case 'slave_ok':
|
||||
serverOptions.slave_ok = (value == 'true');
|
||||
break;
|
||||
case 'maxPoolSize':
|
||||
case 'poolSize':
|
||||
serverOptions.poolSize = parseInt(value, 10);
|
||||
replSetServersOptions.poolSize = parseInt(value, 10);
|
||||
break;
|
||||
case 'autoReconnect':
|
||||
case 'auto_reconnect':
|
||||
serverOptions.auto_reconnect = (value == 'true');
|
||||
break;
|
||||
case 'minPoolSize':
|
||||
throw new Error("minPoolSize not supported");
|
||||
case 'maxIdleTimeMS':
|
||||
throw new Error("maxIdleTimeMS not supported");
|
||||
case 'waitQueueMultiple':
|
||||
throw new Error("waitQueueMultiple not supported");
|
||||
case 'waitQueueTimeoutMS':
|
||||
throw new Error("waitQueueTimeoutMS not supported");
|
||||
case 'uuidRepresentation':
|
||||
throw new Error("uuidRepresentation not supported");
|
||||
case 'ssl':
|
||||
if(value == 'prefer') {
|
||||
serverOptions.ssl = value;
|
||||
replSetServersOptions.ssl = value;
|
||||
break;
|
||||
}
|
||||
serverOptions.ssl = (value == 'true');
|
||||
replSetServersOptions.ssl = (value == 'true');
|
||||
break;
|
||||
case 'replicaSet':
|
||||
case 'rs_name':
|
||||
replSetServersOptions.rs_name = value;
|
||||
break;
|
||||
case 'reconnectWait':
|
||||
replSetServersOptions.reconnectWait = parseInt(value, 10);
|
||||
break;
|
||||
case 'retries':
|
||||
replSetServersOptions.retries = parseInt(value, 10);
|
||||
break;
|
||||
case 'readSecondary':
|
||||
case 'read_secondary':
|
||||
replSetServersOptions.read_secondary = (value == 'true');
|
||||
break;
|
||||
case 'fsync':
|
||||
dbOptions.fsync = (value == 'true');
|
||||
break;
|
||||
case 'journal':
|
||||
dbOptions.journal = (value == 'true');
|
||||
break;
|
||||
case 'safe':
|
||||
dbOptions.safe = (value == 'true');
|
||||
break;
|
||||
case 'nativeParser':
|
||||
case 'native_parser':
|
||||
dbOptions.native_parser = (value == 'true');
|
||||
break;
|
||||
case 'connectTimeoutMS':
|
||||
serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);
|
||||
replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10);
|
||||
break;
|
||||
case 'socketTimeoutMS':
|
||||
serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);
|
||||
replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10);
|
||||
break;
|
||||
case 'w':
|
||||
dbOptions.w = parseInt(value, 10);
|
||||
break;
|
||||
case 'authSource':
|
||||
dbOptions.authSource = value;
|
||||
case 'wtimeoutMS':
|
||||
dbOptions.wtimeoutMS = parseInt(value, 10);
|
||||
break;
|
||||
case 'readPreference':
|
||||
if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest");
|
||||
dbOptions.read_preference = value;
|
||||
break;
|
||||
case 'readPreferenceTags':
|
||||
// Contains the tag object
|
||||
var tagObject = {};
|
||||
if(value == null || value == '') {
|
||||
dbOptions.read_preference_tags.push(tagObject);
|
||||
break;
|
||||
}
|
||||
|
||||
// Split up the tags
|
||||
var tags = value.split(/\,/);
|
||||
for(var i = 0; i < tags.length; i++) {
|
||||
var parts = tags[i].trim().split(/\:/);
|
||||
tagObject[parts[0]] = parts[1];
|
||||
}
|
||||
|
||||
// Set the preferences tags
|
||||
dbOptions.read_preference_tags.push(tagObject);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
// No tags: should be null (not [])
|
||||
if(dbOptions.read_preference_tags.length === 0) {
|
||||
dbOptions.read_preference_tags = null;
|
||||
}
|
||||
|
||||
// Validate if there are an invalid write concern combinations
|
||||
if((dbOptions.w == -1 || dbOptions.w == 0) && (
|
||||
dbOptions.journal == true
|
||||
|| dbOptions.fsync == true
|
||||
|| dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync")
|
||||
|
||||
// If no read preference set it to primary
|
||||
if(!dbOptions.read_preference) dbOptions.read_preference = 'primary';
|
||||
|
||||
// Add servers to result
|
||||
object.servers = servers;
|
||||
// Returned parsed object
|
||||
return object;
|
||||
}
|
||||
988
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/cursor.js
generated
vendored
Normal file
988
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/cursor.js
generated
vendored
Normal file
@@ -0,0 +1,988 @@
|
||||
var QueryCommand = require('./commands/query_command').QueryCommand,
|
||||
GetMoreCommand = require('./commands/get_more_command').GetMoreCommand,
|
||||
KillCursorCommand = require('./commands/kill_cursor_command').KillCursorCommand,
|
||||
Long = require('bson').Long,
|
||||
ReadPreference = require('./connection/read_preference').ReadPreference,
|
||||
CursorStream = require('./cursorstream'),
|
||||
timers = require('timers'),
|
||||
utils = require('./utils');
|
||||
|
||||
// Set processor, setImmediate if 0.10 otherwise nextTick
|
||||
var processor = timers.setImmediate ? timers.setImmediate : process.nextTick;
|
||||
|
||||
/**
|
||||
* Constructor for a cursor object that handles all the operations on query result
|
||||
* using find. This cursor object is unidirectional and cannot traverse backwards. Clients should not be creating a cursor directly,
|
||||
* but use find to acquire a cursor. (INTERNAL TYPE)
|
||||
*
|
||||
* Options
|
||||
* - **skip** {Number} skip number of documents to skip.
|
||||
* - **limit** {Number}, limit the number of results to return. -1 has a special meaning and is used by Db.eval. A value of 1 will also be treated as if it were -1.
|
||||
* - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
|
||||
* - **hint** {Object}, hint force the query to use a specific index.
|
||||
* - **explain** {Boolean}, explain return the explaination of the query.
|
||||
* - **snapshot** {Boolean}, snapshot Snapshot mode assures no duplicates are returned.
|
||||
* - **timeout** {Boolean}, timeout allow the query to timeout.
|
||||
* - **tailable** {Boolean}, tailable allow the cursor to be tailable.
|
||||
* - **awaitdata** {Boolean}, awaitdata allow the cursor to wait for data, only applicable for tailable cursor.
|
||||
* - **batchSize** {Number}, batchSize the number of the subset of results to request the database to return for every request. This should initially be greater than 1 otherwise the database will automatically close the cursor. The batch size can be set to 1 with cursorInstance.batchSize after performing the initial query to the database.
|
||||
* - **raw** {Boolean}, raw return all query documents as raw buffers (default false).
|
||||
* - **read** {Boolean}, read specify override of read from source (primary/secondary).
|
||||
* - **slaveOk** {Boolean}, slaveOk, sets the slaveOk flag on the query wire protocol for secondaries.
|
||||
* - **returnKey** {Boolean}, returnKey only return the index key.
|
||||
* - **maxScan** {Number}, maxScan limit the number of items to scan.
|
||||
* - **min** {Number}, min set index bounds.
|
||||
* - **max** {Number}, max set index bounds.
|
||||
* - **showDiskLoc** {Boolean}, showDiskLoc show disk location of results.
|
||||
* - **comment** {String}, comment you can put a $comment field on a query to make looking in the profiler logs simpler.
|
||||
* - **numberOfRetries** {Number}, numberOfRetries if using awaidata specifies the number of times to retry on timeout.
|
||||
* - **dbName** {String}, dbName override the default dbName.
|
||||
* - **tailableRetryInterval** {Number}, tailableRetryInterval specify the miliseconds between getMores on tailable cursor.
|
||||
* - **exhaust** {Boolean}, exhaust have the server send all the documents at once as getMore packets.
|
||||
* - **partial** {Boolean}, partial have the sharded system return a partial result from mongos.
|
||||
*
|
||||
* @class Represents a Cursor.
|
||||
* @param {Db} db the database object to work with.
|
||||
* @param {Collection} collection the collection to query.
|
||||
* @param {Object} selector the query selector.
|
||||
* @param {Object} fields an object containing what fields to include or exclude from objects returned.
|
||||
* @param {Object} [options] additional options for the collection.
|
||||
*/
|
||||
function Cursor(db, collection, selector, fields, options) {
|
||||
this.db = db;
|
||||
this.collection = collection;
|
||||
this.selector = selector;
|
||||
this.fields = fields;
|
||||
options = !options ? {} : options;
|
||||
|
||||
this.skipValue = options.skip == null ? 0 : options.skip;
|
||||
this.limitValue = options.limit == null ? 0 : options.limit;
|
||||
this.sortValue = options.sort;
|
||||
this.hint = options.hint;
|
||||
this.explainValue = options.explain;
|
||||
this.snapshot = options.snapshot;
|
||||
this.timeout = options.timeout == null ? true : options.timeout;
|
||||
this.tailable = options.tailable;
|
||||
this.awaitdata = options.awaitdata;
|
||||
this.numberOfRetries = options.numberOfRetries == null ? 5 : options.numberOfRetries;
|
||||
this.currentNumberOfRetries = this.numberOfRetries;
|
||||
this.batchSizeValue = options.batchSize == null ? 0 : options.batchSize;
|
||||
this.slaveOk = options.slaveOk == null ? collection.slaveOk : options.slaveOk;
|
||||
this.raw = options.raw == null ? false : options.raw;
|
||||
this.read = options.read == null ? ReadPreference.PRIMARY : options.read;
|
||||
this.returnKey = options.returnKey;
|
||||
this.maxScan = options.maxScan;
|
||||
this.min = options.min;
|
||||
this.max = options.max;
|
||||
this.showDiskLoc = options.showDiskLoc;
|
||||
this.comment = options.comment;
|
||||
this.tailableRetryInterval = options.tailableRetryInterval || 100;
|
||||
this.exhaust = options.exhaust || false;
|
||||
this.partial = options.partial || false;
|
||||
|
||||
this.totalNumberOfRecords = 0;
|
||||
this.items = [];
|
||||
this.cursorId = Long.fromInt(0);
|
||||
|
||||
// This name
|
||||
this.dbName = options.dbName;
|
||||
|
||||
// State variables for the cursor
|
||||
this.state = Cursor.INIT;
|
||||
// Keep track of the current query run
|
||||
this.queryRun = false;
|
||||
this.getMoreTimer = false;
|
||||
|
||||
// If we are using a specific db execute against it
|
||||
if(this.dbName != null) {
|
||||
this.collectionName = this.dbName + "." + this.collection.collectionName;
|
||||
} else {
|
||||
this.collectionName = (this.db.databaseName ? this.db.databaseName + "." : '') + this.collection.collectionName;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Resets this cursor to its initial state. All settings like the query string,
|
||||
* tailable, batchSizeValue, skipValue and limits are preserved.
|
||||
*
|
||||
* @return {Cursor} returns itself with rewind applied.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.rewind = function() {
|
||||
var self = this;
|
||||
|
||||
if (self.state != Cursor.INIT) {
|
||||
if (self.state != Cursor.CLOSED) {
|
||||
self.close(function() {});
|
||||
}
|
||||
|
||||
self.numberOfReturned = 0;
|
||||
self.totalNumberOfRecords = 0;
|
||||
self.items = [];
|
||||
self.cursorId = Long.fromInt(0);
|
||||
self.state = Cursor.INIT;
|
||||
self.queryRun = false;
|
||||
}
|
||||
|
||||
return self;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Returns an array of documents. The caller is responsible for making sure that there
|
||||
* is enough memory to store the results. Note that the array only contain partial
|
||||
* results when this cursor had been previouly accessed. In that case,
|
||||
* cursor.rewind() can be used to reset the cursor.
|
||||
*
|
||||
* @param {Function} callback This will be called after executing this method successfully. The first parameter will contain the Error object if an error occured, or null otherwise. The second parameter will contain an array of BSON deserialized objects as a result of the query.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.toArray = function(callback) {
|
||||
var self = this;
|
||||
|
||||
if(!callback) {
|
||||
throw new Error('callback is mandatory');
|
||||
}
|
||||
|
||||
if(this.tailable) {
|
||||
callback(new Error("Tailable cursor cannot be converted to array"), null);
|
||||
} else if(this.state != Cursor.CLOSED) {
|
||||
// return toArrayExhaust(self, callback);
|
||||
// If we are using exhaust we can't use the quick fire method
|
||||
if(self.exhaust) return toArrayExhaust(self, callback);
|
||||
// Quick fire using trampoline to avoid nextTick
|
||||
self.nextObject({noReturn: true}, function(err, result) {
|
||||
if(err) return callback(utils.toError(err), null);
|
||||
if(self.cursorId.toString() == "0") {
|
||||
self.state = Cursor.CLOSED;
|
||||
return callback(null, self.items);
|
||||
}
|
||||
|
||||
// Let's issue getMores until we have no more records waiting
|
||||
getAllByGetMore(self, function(err, done) {
|
||||
self.state = Cursor.CLOSED;
|
||||
if(err) return callback(utils.toError(err), null);
|
||||
callback(null, self.items);
|
||||
});
|
||||
})
|
||||
|
||||
} else {
|
||||
callback(new Error("Cursor is closed"), null);
|
||||
}
|
||||
}
|
||||
|
||||
var toArrayExhaust = function(self, callback) {
|
||||
var items = [];
|
||||
|
||||
self.each(function(err, item) {
|
||||
if(err != null) {
|
||||
return callback(utils.toError(err), null);
|
||||
}
|
||||
|
||||
if(item != null && Array.isArray(items)) {
|
||||
items.push(item);
|
||||
} else {
|
||||
var resultItems = items;
|
||||
items = null;
|
||||
self.items = [];
|
||||
callback(null, resultItems);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var getAllByGetMore = function(self, callback) {
|
||||
getMore(self, {noReturn: true}, function(err, result) {
|
||||
if(err) return callback(utils.toError(err));
|
||||
if(result == null) return callback(null, null);
|
||||
if(self.cursorId.toString() == "0") return callback(null, null);
|
||||
getAllByGetMore(self, callback);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
|
||||
* not all of the elements will be iterated if this cursor had been previouly accessed.
|
||||
* In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
|
||||
* **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
|
||||
* at any given time if batch size is specified. Otherwise, the caller is responsible
|
||||
* for making sure that the entire result can fit the memory.
|
||||
*
|
||||
* @param {Function} callback this will be called for while iterating every document of the query result. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the document.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.each = function(callback) {
|
||||
var self = this;
|
||||
var fn;
|
||||
|
||||
if (!callback) {
|
||||
throw new Error('callback is mandatory');
|
||||
}
|
||||
|
||||
if(this.state != Cursor.CLOSED) {
|
||||
// If we are using exhaust we can't use the quick fire method
|
||||
if(self.exhaust) return eachExhaust(self, callback);
|
||||
// Quick fire using trampoline to avoid nextTick
|
||||
if(this.items.length > 0) {
|
||||
// Trampoline all the entries
|
||||
while(fn = loop(self, callback)) fn(self, callback);
|
||||
// Call each again
|
||||
self.each(callback);
|
||||
} else {
|
||||
self.nextObject(function(err, item) {
|
||||
|
||||
if(err) {
|
||||
self.state = Cursor.CLOSED;
|
||||
return callback(utils.toError(err), item);
|
||||
}
|
||||
|
||||
if(item == null) return callback(null, null);
|
||||
callback(null, item);
|
||||
self.each(callback);
|
||||
})
|
||||
}
|
||||
} else {
|
||||
callback(new Error("Cursor is closed"), null);
|
||||
}
|
||||
}
|
||||
|
||||
// Special for exhaust command as we don't initiate the actual result sets
|
||||
// the server just sends them as they arrive meaning we need to get the IO event
|
||||
// loop happen so we can receive more data from the socket or we return to early
|
||||
// after the first fetch and loose all the incoming getMore's automatically issued
|
||||
// from the server.
|
||||
var eachExhaust = function(self, callback) {
|
||||
//FIX: stack overflow (on deep callback) (cred: https://github.com/limp/node-mongodb-native/commit/27da7e4b2af02035847f262b29837a94bbbf6ce2)
|
||||
processor(function(){
|
||||
// Fetch the next object until there is no more objects
|
||||
self.nextObject(function(err, item) {
|
||||
if(err != null) return callback(err, null);
|
||||
if(item != null) {
|
||||
callback(null, item);
|
||||
eachExhaust(self, callback);
|
||||
} else {
|
||||
// Close the cursor if done
|
||||
self.state = Cursor.CLOSED;
|
||||
callback(err, null);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Trampoline emptying the number of retrieved items
|
||||
// without incurring a nextTick operation
|
||||
var loop = function(self, callback) {
|
||||
// No more items we are done
|
||||
if(self.items.length == 0) return;
|
||||
// Get the next document
|
||||
var doc = self.items.shift();
|
||||
// Callback
|
||||
callback(null, doc);
|
||||
// Loop
|
||||
return loop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines how many result the query for this cursor will return
|
||||
*
|
||||
* @param {Boolean} applySkipLimit if set to true will apply the skip and limits set on the cursor. Defaults to false.
|
||||
* @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 number of results or null if an error occured.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.count = function(applySkipLimit, callback) {
|
||||
if(typeof applySkipLimit == 'function') {
|
||||
callback = applySkipLimit;
|
||||
applySkipLimit = false;
|
||||
}
|
||||
|
||||
var options = {};
|
||||
if(applySkipLimit) {
|
||||
if(typeof this.skipValue == 'number') options.skip = this.skipValue;
|
||||
if(typeof this.limitValue == 'number') options.limit = this.limitValue;
|
||||
}
|
||||
|
||||
// Call count command
|
||||
this.collection.count(this.selector, options, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the sort parameter of this cursor to the given value.
|
||||
*
|
||||
* This method has the following method signatures:
|
||||
* (keyOrList, callback)
|
||||
* (keyOrList, direction, callback)
|
||||
*
|
||||
* @param {String|Array|Object} keyOrList This can be a string or an array. If passed as a string, the string will be the field to sort. If passed an array, each element will represent a field to be sorted and should be an array that contains the format [string, direction].
|
||||
* @param {String|Number} direction this determines how the results are sorted. "asc", "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending order. Note that the strings are case insensitive.
|
||||
* @param {Function} callback this will be called after executing this method. The first parameter will contain an error object when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
|
||||
* @return {Cursor} an instance of this object.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.sort = function(keyOrList, direction, callback) {
|
||||
callback = callback || function(){};
|
||||
if(typeof direction === "function") { callback = direction; direction = null; }
|
||||
|
||||
if(this.tailable) {
|
||||
callback(new Error("Tailable cursor doesn't support sorting"), null);
|
||||
} else if(this.queryRun == true || this.state == Cursor.CLOSED) {
|
||||
callback(new Error("Cursor is closed"), null);
|
||||
} else {
|
||||
var order = keyOrList;
|
||||
|
||||
if(direction != null) {
|
||||
order = [[keyOrList, direction]];
|
||||
}
|
||||
|
||||
this.sortValue = order;
|
||||
callback(null, this);
|
||||
}
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the limit parameter of this cursor to the given value.
|
||||
*
|
||||
* @param {Number} limit the new limit.
|
||||
* @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the limit given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
|
||||
* @return {Cursor} an instance of this object.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.limit = function(limit, callback) {
|
||||
if(this.tailable) {
|
||||
if(callback) {
|
||||
callback(new Error("Tailable cursor doesn't support limit"), null);
|
||||
} else {
|
||||
throw new Error("Tailable cursor doesn't support limit");
|
||||
}
|
||||
} else if(this.queryRun == true || this.state == Cursor.CLOSED) {
|
||||
if(callback) {
|
||||
callback(new Error("Cursor is closed"), null);
|
||||
} else {
|
||||
throw new Error("Cursor is closed");
|
||||
}
|
||||
} else {
|
||||
if(limit != null && limit.constructor != Number) {
|
||||
if(callback) {
|
||||
callback(new Error("limit requires an integer"), null);
|
||||
} else {
|
||||
throw new Error("limit requires an integer");
|
||||
}
|
||||
} else {
|
||||
this.limitValue = limit;
|
||||
if(callback) return callback(null, this);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the read preference for the cursor
|
||||
*
|
||||
* @param {String} the read preference for the cursor, one of Server.READ_PRIMARY, Server.READ_SECONDARY, Server.READ_SECONDARY_ONLY
|
||||
* @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the read preference given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
|
||||
* @return {Cursor} an instance of this object.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.setReadPreference = function(readPreference, tags, callback) {
|
||||
if(typeof tags == 'function') callback = tags;
|
||||
|
||||
var _mode = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference;
|
||||
|
||||
if(this.queryRun == true || this.state == Cursor.CLOSED) {
|
||||
if(callback == null) throw new Error("Cannot change read preference on executed query or closed cursor");
|
||||
callback(new Error("Cannot change read preference on executed query or closed cursor"));
|
||||
} else if(_mode != null && _mode != 'primary'
|
||||
&& _mode != 'secondaryOnly' && _mode != 'secondary'
|
||||
&& _mode != 'nearest' && _mode != 'primaryPreferred' && _mode != 'secondaryPreferred') {
|
||||
if(callback == null) throw new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported");
|
||||
callback(new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported"));
|
||||
} else {
|
||||
this.read = readPreference;
|
||||
if(callback != null) callback(null, this);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the skip parameter of this cursor to the given value.
|
||||
*
|
||||
* @param {Number} skip the new skip value.
|
||||
* @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the skip value given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
|
||||
* @return {Cursor} an instance of this object.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.skip = function(skip, callback) {
|
||||
callback = callback || function(){};
|
||||
|
||||
if(this.tailable) {
|
||||
callback(new Error("Tailable cursor doesn't support skip"), null);
|
||||
} else if(this.queryRun == true || this.state == Cursor.CLOSED) {
|
||||
callback(new Error("Cursor is closed"), null);
|
||||
} else {
|
||||
if(skip != null && skip.constructor != Number) {
|
||||
callback(new Error("skip requires an integer"), null);
|
||||
} else {
|
||||
this.skipValue = skip;
|
||||
callback(null, this);
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the batch size parameter of this cursor to the given value.
|
||||
*
|
||||
* @param {Number} batchSize the new batch size.
|
||||
* @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the batchSize given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution.
|
||||
* @return {Cursor} an instance of this object.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.batchSize = function(batchSize, callback) {
|
||||
if(this.state == Cursor.CLOSED) {
|
||||
if(callback != null) {
|
||||
return callback(new Error("Cursor is closed"), null);
|
||||
} else {
|
||||
throw new Error("Cursor is closed");
|
||||
}
|
||||
} else if(batchSize != null && batchSize.constructor != Number) {
|
||||
if(callback != null) {
|
||||
return callback(new Error("batchSize requires an integer"), null);
|
||||
} else {
|
||||
throw new Error("batchSize requires an integer");
|
||||
}
|
||||
} else {
|
||||
this.batchSizeValue = batchSize;
|
||||
if(callback != null) return callback(null, this);
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* The limit used for the getMore command
|
||||
*
|
||||
* @return {Number} The number of records to request per batch.
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var limitRequest = function(self) {
|
||||
var requestedLimit = self.limitValue;
|
||||
var absLimitValue = Math.abs(self.limitValue);
|
||||
var absBatchValue = Math.abs(self.batchSizeValue);
|
||||
|
||||
if(absLimitValue > 0) {
|
||||
if (absBatchValue > 0) {
|
||||
requestedLimit = Math.min(absLimitValue, absBatchValue);
|
||||
}
|
||||
} else {
|
||||
requestedLimit = self.batchSizeValue;
|
||||
}
|
||||
|
||||
return requestedLimit;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Generates a QueryCommand object using the parameters of this cursor.
|
||||
*
|
||||
* @return {QueryCommand} The command object
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var generateQueryCommand = function(self) {
|
||||
// Unpack the options
|
||||
var queryOptions = QueryCommand.OPTS_NONE;
|
||||
if(!self.timeout) {
|
||||
queryOptions |= QueryCommand.OPTS_NO_CURSOR_TIMEOUT;
|
||||
}
|
||||
|
||||
if(self.tailable != null) {
|
||||
queryOptions |= QueryCommand.OPTS_TAILABLE_CURSOR;
|
||||
self.skipValue = self.limitValue = 0;
|
||||
|
||||
// if awaitdata is set
|
||||
if(self.awaitdata != null) {
|
||||
queryOptions |= QueryCommand.OPTS_AWAIT_DATA;
|
||||
}
|
||||
}
|
||||
|
||||
if(self.exhaust) {
|
||||
queryOptions |= QueryCommand.OPTS_EXHAUST;
|
||||
}
|
||||
|
||||
if(self.slaveOk) {
|
||||
queryOptions |= QueryCommand.OPTS_SLAVE;
|
||||
}
|
||||
|
||||
if(self.partial) {
|
||||
queryOptions |= QueryCommand.OPTS_PARTIAL;
|
||||
}
|
||||
|
||||
// limitValue of -1 is a special case used by Db#eval
|
||||
var numberToReturn = self.limitValue == -1 ? -1 : limitRequest(self);
|
||||
|
||||
// Check if we need a special selector
|
||||
if(self.sortValue != null || self.explainValue != null || self.hint != null || self.snapshot != null
|
||||
|| self.returnKey != null || self.maxScan != null || self.min != null || self.max != null
|
||||
|| self.showDiskLoc != null || self.comment != null) {
|
||||
|
||||
// Build special selector
|
||||
var specialSelector = {'$query':self.selector};
|
||||
if(self.sortValue != null) specialSelector['orderby'] = utils.formattedOrderClause(self.sortValue);
|
||||
if(self.hint != null && self.hint.constructor == Object) specialSelector['$hint'] = self.hint;
|
||||
if(self.snapshot != null) specialSelector['$snapshot'] = true;
|
||||
if(self.returnKey != null) specialSelector['$returnKey'] = self.returnKey;
|
||||
if(self.maxScan != null) specialSelector['$maxScan'] = self.maxScan;
|
||||
if(self.min != null) specialSelector['$min'] = self.min;
|
||||
if(self.max != null) specialSelector['$max'] = self.max;
|
||||
if(self.showDiskLoc != null) specialSelector['$showDiskLoc'] = self.showDiskLoc;
|
||||
if(self.comment != null) specialSelector['$comment'] = self.comment;
|
||||
// If we have explain set only return a single document with automatic cursor close
|
||||
if(self.explainValue != null) {
|
||||
numberToReturn = (-1)*Math.abs(numberToReturn);
|
||||
specialSelector['$explain'] = true;
|
||||
}
|
||||
|
||||
// Return the query
|
||||
return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, specialSelector, self.fields);
|
||||
} else {
|
||||
return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, self.selector, self.fields);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @return {Object} Returns an object containing the sort value of this cursor with
|
||||
* the proper formatting that can be used internally in this cursor.
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Cursor.prototype.formattedOrderClause = function() {
|
||||
return utils.formattedOrderClause(this.sortValue);
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts the value of the sort direction into its equivalent numerical value.
|
||||
*
|
||||
* @param sortDirection {String|number} Range of acceptable values:
|
||||
* 'ascending', 'descending', 'asc', 'desc', 1, -1
|
||||
*
|
||||
* @return {number} The equivalent numerical value
|
||||
* @throws Error if the given sortDirection is invalid
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Cursor.prototype.formatSortValue = function(sortDirection) {
|
||||
return utils.formatSortValue(sortDirection);
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the next document from the cursor.
|
||||
*
|
||||
* @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.nextObject = function(options, callback) {
|
||||
var self = this;
|
||||
|
||||
if(typeof options == 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
if(self.state == Cursor.INIT) {
|
||||
var cmd;
|
||||
try {
|
||||
cmd = generateQueryCommand(self);
|
||||
} catch (err) {
|
||||
return callback(err, null);
|
||||
}
|
||||
|
||||
// Execute command
|
||||
var commandHandler = function(err, result) {
|
||||
self.state = Cursor.OPEN;
|
||||
if(err != null && result == null) return callback(utils.toError(err), null);
|
||||
|
||||
if(!err && result.documents[0] && result.documents[0]['$err']) {
|
||||
return self.close(function() {callback(utils.toError(result.documents[0]['$err']), null);});
|
||||
}
|
||||
|
||||
self.queryRun = true;
|
||||
self.state = Cursor.OPEN; // Adjust the state of the cursor
|
||||
self.cursorId = result.cursorId;
|
||||
self.totalNumberOfRecords = result.numberReturned;
|
||||
|
||||
// Add the new documents to the list of items, using forloop to avoid
|
||||
// new array allocations and copying
|
||||
for(var i = 0; i < result.documents.length; i++) {
|
||||
self.items.push(result.documents[i]);
|
||||
}
|
||||
|
||||
// If we have noReturn set just return (not modifying the internal item list)
|
||||
// used for toArray
|
||||
if(options.noReturn) {
|
||||
return callback(null, true);
|
||||
}
|
||||
|
||||
// Ignore callbacks until the cursor is dead for exhausted
|
||||
if(self.exhaust && result.cursorId.toString() == "0") {
|
||||
self.nextObject(callback);
|
||||
} else if(self.exhaust == false || self.exhaust == null) {
|
||||
self.nextObject(callback);
|
||||
}
|
||||
};
|
||||
|
||||
// If we have no connection set on this cursor check one out
|
||||
if(self.connection == null) {
|
||||
try {
|
||||
self.connection = this.read == null ? self.db.serverConfig.checkoutWriter() : self.db.serverConfig.checkoutReader(this.read);
|
||||
} catch(err) {
|
||||
return callback(utils.toError(err), null);
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the command
|
||||
self.db._executeQueryCommand(cmd, {exhaust: self.exhaust, raw:self.raw, read:self.read, connection:self.connection}, commandHandler);
|
||||
// Set the command handler to null
|
||||
commandHandler = null;
|
||||
} else if(self.items.length) {
|
||||
callback(null, self.items.shift());
|
||||
} else if(self.cursorId.greaterThan(Long.fromInt(0))) {
|
||||
getMore(self, callback);
|
||||
} else {
|
||||
// Force cursor to stay open
|
||||
return self.close(function() {callback(null, null);});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets more results from the database if any.
|
||||
*
|
||||
* @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results.
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var getMore = function(self, options, callback) {
|
||||
var limit = 0;
|
||||
|
||||
if(typeof options == 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
if(self.state == Cursor.GET_MORE) return callback(null, null);
|
||||
|
||||
// Set get more in progress
|
||||
self.state = Cursor.GET_MORE;
|
||||
|
||||
// Set options
|
||||
if (!self.tailable && self.limitValue > 0) {
|
||||
limit = self.limitValue - self.totalNumberOfRecords;
|
||||
if (limit < 1) {
|
||||
self.close(function() {callback(null, null);});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
var getMoreCommand = new GetMoreCommand(
|
||||
self.db
|
||||
, self.collectionName
|
||||
, limitRequest(self)
|
||||
, self.cursorId
|
||||
);
|
||||
|
||||
// Set up options
|
||||
var command_options = {read: self.read, raw: self.raw, connection:self.connection };
|
||||
|
||||
// Execute the command
|
||||
self.db._executeQueryCommand(getMoreCommand, command_options, function(err, result) {
|
||||
var cbValue;
|
||||
|
||||
// Get more done
|
||||
self.state = Cursor.OPEN;
|
||||
|
||||
if(err != null) {
|
||||
return callback(utils.toError(err), null);
|
||||
}
|
||||
|
||||
try {
|
||||
var isDead = 1 === result.responseFlag && result.cursorId.isZero();
|
||||
|
||||
self.cursorId = result.cursorId;
|
||||
self.totalNumberOfRecords += result.numberReturned;
|
||||
|
||||
// Determine if there's more documents to fetch
|
||||
if(result.numberReturned > 0) {
|
||||
if (self.limitValue > 0) {
|
||||
var excessResult = self.totalNumberOfRecords - self.limitValue;
|
||||
|
||||
if (excessResult > 0) {
|
||||
result.documents.splice(-1 * excessResult, excessResult);
|
||||
}
|
||||
}
|
||||
|
||||
// Reset the tries for awaitdata if we are using it
|
||||
self.currentNumberOfRetries = self.numberOfRetries;
|
||||
// Get the documents
|
||||
for(var i = 0; i < result.documents.length; i++) {
|
||||
self.items.push(result.documents[i]);
|
||||
}
|
||||
|
||||
// Don's shift a document out as we need it for toArray
|
||||
if(options.noReturn) {
|
||||
cbValue = true;
|
||||
} else {
|
||||
cbValue = self.items.shift();
|
||||
}
|
||||
} else if(self.tailable && !isDead && self.awaitdata) {
|
||||
// Excute the tailable cursor once more, will timeout after ~4 sec if awaitdata used
|
||||
self.currentNumberOfRetries = self.currentNumberOfRetries - 1;
|
||||
if(self.currentNumberOfRetries == 0) {
|
||||
self.close(function() {
|
||||
callback(new Error("tailable cursor timed out"), null);
|
||||
});
|
||||
} else {
|
||||
getMore(self, callback);
|
||||
}
|
||||
} else if(self.tailable && !isDead) {
|
||||
self.getMoreTimer = setTimeout(function() { getMore(self, callback); }, self.tailableRetryInterval);
|
||||
} else {
|
||||
self.close(function() {callback(null, null); });
|
||||
}
|
||||
|
||||
result = null;
|
||||
} catch(err) {
|
||||
callback(utils.toError(err), null);
|
||||
}
|
||||
if (cbValue != null) callback(null, cbValue);
|
||||
});
|
||||
|
||||
getMoreCommand = null;
|
||||
} catch(err) {
|
||||
// Get more done
|
||||
self.state = Cursor.OPEN;
|
||||
|
||||
var handleClose = function() {
|
||||
callback(utils.toError(err), null);
|
||||
};
|
||||
|
||||
self.close(handleClose);
|
||||
handleClose = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a detailed information about how the query is performed on this cursor and how
|
||||
* long it took the database to process it.
|
||||
*
|
||||
* @param {Function} callback this will be called after executing this method. The first parameter will always be null while the second parameter will be an object containing the details.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.explain = function(callback) {
|
||||
var limit = (-1)*Math.abs(this.limitValue);
|
||||
|
||||
// Create a new cursor and fetch the plan
|
||||
var cursor = new Cursor(this.db, this.collection, this.selector, this.fields, {
|
||||
skip: this.skipValue
|
||||
, limit:limit
|
||||
, sort: this.sortValue
|
||||
, hint: this.hint
|
||||
, explain: true
|
||||
, snapshot: this.snapshot
|
||||
, timeout: this.timeout
|
||||
, tailable: this.tailable
|
||||
, batchSize: this.batchSizeValue
|
||||
, slaveOk: this.slaveOk
|
||||
, raw: this.raw
|
||||
, read: this.read
|
||||
, returnKey: this.returnKey
|
||||
, maxScan: this.maxScan
|
||||
, min: this.min
|
||||
, max: this.max
|
||||
, showDiskLoc: this.showDiskLoc
|
||||
, comment: this.comment
|
||||
, awaitdata: this.awaitdata
|
||||
, numberOfRetries: this.numberOfRetries
|
||||
, dbName: this.dbName
|
||||
});
|
||||
|
||||
// Fetch the explaination document
|
||||
cursor.nextObject(function(err, item) {
|
||||
if(err != null) return callback(utils.toError(err), null);
|
||||
// close the cursor
|
||||
cursor.close(function(err, result) {
|
||||
if(err != null) return callback(utils.toError(err), null);
|
||||
callback(null, item);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Cursor.prototype.streamRecords = function(options) {
|
||||
console.log("[WARNING] streamRecords method is deprecated, please use stream method which is much faster");
|
||||
var args = Array.prototype.slice.call(arguments, 0);
|
||||
options = args.length ? args.shift() : {};
|
||||
|
||||
var
|
||||
self = this,
|
||||
stream = new process.EventEmitter(),
|
||||
recordLimitValue = this.limitValue || 0,
|
||||
emittedRecordCount = 0,
|
||||
queryCommand = generateQueryCommand(self);
|
||||
|
||||
// see http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol
|
||||
queryCommand.numberToReturn = options.fetchSize ? options.fetchSize : 500;
|
||||
// Execute the query
|
||||
execute(queryCommand);
|
||||
|
||||
function execute(command) {
|
||||
self.db._executeQueryCommand(command, {exhaust: self.exhaust, read:self.read, raw:self.raw, connection:self.connection}, function(err,result) {
|
||||
if(err) {
|
||||
stream.emit('error', err);
|
||||
self.close(function(){});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.queryRun && result) {
|
||||
self.queryRun = true;
|
||||
self.cursorId = result.cursorId;
|
||||
self.state = Cursor.OPEN;
|
||||
self.getMoreCommand = new GetMoreCommand(self.db, self.collectionName, queryCommand.numberToReturn, result.cursorId);
|
||||
}
|
||||
|
||||
var resflagsMap = {
|
||||
CursorNotFound:1<<0,
|
||||
QueryFailure:1<<1,
|
||||
ShardConfigStale:1<<2,
|
||||
AwaitCapable:1<<3
|
||||
};
|
||||
|
||||
if(result.documents && result.documents.length && !(result.responseFlag & resflagsMap.QueryFailure)) {
|
||||
try {
|
||||
result.documents.forEach(function(doc){
|
||||
if(recordLimitValue && emittedRecordCount>=recordLimitValue) {
|
||||
throw("done");
|
||||
}
|
||||
emittedRecordCount++;
|
||||
stream.emit('data', doc);
|
||||
});
|
||||
} catch(err) {
|
||||
if (err != "done") { throw err; }
|
||||
else {
|
||||
self.close(function(){
|
||||
stream.emit('end', recordLimitValue);
|
||||
});
|
||||
self.close(function(){});
|
||||
return;
|
||||
}
|
||||
}
|
||||
// rinse & repeat
|
||||
execute(self.getMoreCommand);
|
||||
} else {
|
||||
self.close(function(){
|
||||
stream.emit('end', recordLimitValue);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return stream;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Node ReadStream interface for this cursor.
|
||||
*
|
||||
* Options
|
||||
* - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting.
|
||||
*
|
||||
* @return {CursorStream} returns a stream object.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.stream = function stream(options) {
|
||||
return new CursorStream(this, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the cursor.
|
||||
*
|
||||
* @param {Function} callback this will be called after executing this method. The first parameter will always contain null while the second parameter will contain a reference to this cursor.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.close = function(callback) {
|
||||
var self = this
|
||||
this.getMoreTimer && clearTimeout(this.getMoreTimer);
|
||||
// Close the cursor if not needed
|
||||
if(this.cursorId instanceof Long && this.cursorId.greaterThan(Long.fromInt(0))) {
|
||||
try {
|
||||
var command = new KillCursorCommand(this.db, [this.cursorId]);
|
||||
// Added an empty callback to ensure we don't throw any null exceptions
|
||||
this.db._executeQueryCommand(command, {read:self.read, raw:self.raw, connection:self.connection}, function() {});
|
||||
} catch(err) {}
|
||||
}
|
||||
|
||||
// Null out the connection
|
||||
self.connection = null;
|
||||
// Reset cursor id
|
||||
this.cursorId = Long.fromInt(0);
|
||||
// Set to closed status
|
||||
this.state = Cursor.CLOSED;
|
||||
|
||||
if(callback) {
|
||||
callback(null, self);
|
||||
self.items = [];
|
||||
}
|
||||
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if the cursor is closed or open.
|
||||
*
|
||||
* @return {Boolean} returns the state of the cursor.
|
||||
* @api public
|
||||
*/
|
||||
Cursor.prototype.isClosed = function() {
|
||||
return this.state == Cursor.CLOSED ? true : false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Init state
|
||||
*
|
||||
* @classconstant INIT
|
||||
**/
|
||||
Cursor.INIT = 0;
|
||||
|
||||
/**
|
||||
* Cursor open
|
||||
*
|
||||
* @classconstant OPEN
|
||||
**/
|
||||
Cursor.OPEN = 1;
|
||||
|
||||
/**
|
||||
* Cursor closed
|
||||
*
|
||||
* @classconstant CLOSED
|
||||
**/
|
||||
Cursor.CLOSED = 2;
|
||||
|
||||
/**
|
||||
* Cursor performing a get more
|
||||
*
|
||||
* @classconstant OPEN
|
||||
**/
|
||||
Cursor.GET_MORE = 3;
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
exports.Cursor = Cursor;
|
||||
164
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/cursorstream.js
generated
vendored
Normal file
164
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/cursorstream.js
generated
vendored
Normal file
@@ -0,0 +1,164 @@
|
||||
var timers = require('timers');
|
||||
|
||||
// Set processor, setImmediate if 0.10 otherwise nextTick
|
||||
var processor = timers.setImmediate ? timers.setImmediate : process.nextTick;
|
||||
|
||||
/**
|
||||
* Module dependecies.
|
||||
*/
|
||||
var Stream = require('stream').Stream;
|
||||
|
||||
/**
|
||||
* CursorStream
|
||||
*
|
||||
* Returns a stream interface for the **cursor**.
|
||||
*
|
||||
* Options
|
||||
* - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting.
|
||||
*
|
||||
* Events
|
||||
* - **data** {function(item) {}} the data event triggers when a document is ready.
|
||||
* - **error** {function(err) {}} the error event triggers if an error happens.
|
||||
* - **close** {function() {}} the end event triggers when there is no more documents available.
|
||||
*
|
||||
* @class Represents a CursorStream.
|
||||
* @param {Cursor} cursor a cursor object that the stream wraps.
|
||||
* @return {Stream}
|
||||
*/
|
||||
function CursorStream(cursor, options) {
|
||||
if(!(this instanceof CursorStream)) return new CursorStream(cursor);
|
||||
options = options ? options : {};
|
||||
|
||||
Stream.call(this);
|
||||
|
||||
this.readable = true;
|
||||
this.paused = false;
|
||||
this._cursor = cursor;
|
||||
this._destroyed = null;
|
||||
this.options = options;
|
||||
|
||||
// give time to hook up events
|
||||
var self = this;
|
||||
process.nextTick(function() {
|
||||
self._init();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherit from Stream
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
CursorStream.prototype.__proto__ = Stream.prototype;
|
||||
|
||||
/**
|
||||
* Flag stating whether or not this stream is readable.
|
||||
*/
|
||||
CursorStream.prototype.readable;
|
||||
|
||||
/**
|
||||
* Flag stating whether or not this stream is paused.
|
||||
*/
|
||||
CursorStream.prototype.paused;
|
||||
|
||||
/**
|
||||
* Initialize the cursor.
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
CursorStream.prototype._init = function () {
|
||||
if (this._destroyed) return;
|
||||
this._next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull the next document from the cursor.
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
CursorStream.prototype._next = function () {
|
||||
if(this.paused || this._destroyed) return;
|
||||
|
||||
var self = this;
|
||||
// Get the next object
|
||||
processor(function() {
|
||||
if(self.paused || self._destroyed) return;
|
||||
|
||||
self._cursor.nextObject(function (err, doc) {
|
||||
self._onNextObject(err, doc);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle each document as its returned from the cursor.
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
CursorStream.prototype._onNextObject = function (err, doc) {
|
||||
if(err) return this.destroy(err);
|
||||
|
||||
// when doc is null we hit the end of the cursor
|
||||
if(!doc && (this._cursor.state == 1 || this._cursor.state == 2)) {
|
||||
this.emit('end')
|
||||
return this.destroy();
|
||||
} else if(doc) {
|
||||
var data = typeof this.options.transform == 'function' ? this.options.transform(doc) : doc;
|
||||
this.emit('data', data);
|
||||
this._next();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pauses the stream.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
CursorStream.prototype.pause = function () {
|
||||
this.paused = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes the stream.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
CursorStream.prototype.resume = function () {
|
||||
var self = this;
|
||||
|
||||
// Don't do anything if we are not paused
|
||||
if(!this.paused) return;
|
||||
if(!this._cursor.state == 3) return;
|
||||
|
||||
process.nextTick(function() {
|
||||
self.paused = false;
|
||||
// Only trigger more fetching if the cursor is open
|
||||
self._next();
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys the stream, closing the underlying
|
||||
* cursor. No more events will be emitted.
|
||||
*
|
||||
* @api public
|
||||
*/
|
||||
CursorStream.prototype.destroy = function (err) {
|
||||
if (this._destroyed) return;
|
||||
this._destroyed = true;
|
||||
this.readable = false;
|
||||
|
||||
this._cursor.close();
|
||||
|
||||
if(err) {
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
this.emit('close');
|
||||
}
|
||||
|
||||
// TODO - maybe implement the raw option to pass binary?
|
||||
//CursorStream.prototype.setEncoding = function () {
|
||||
//}
|
||||
|
||||
module.exports = exports = CursorStream;
|
||||
2147
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/db.js
generated
vendored
Normal file
2147
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/db.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
213
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/gridfs/chunk.js
generated
vendored
Normal file
213
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/gridfs/chunk.js
generated
vendored
Normal file
@@ -0,0 +1,213 @@
|
||||
var Binary = require('bson').Binary,
|
||||
ObjectID = require('bson').ObjectID;
|
||||
|
||||
/**
|
||||
* Class for representing a single chunk in GridFS.
|
||||
*
|
||||
* @class
|
||||
*
|
||||
* @param file {GridStore} The {@link GridStore} object holding this chunk.
|
||||
* @param mongoObject {object} The mongo object representation of this chunk.
|
||||
*
|
||||
* @throws Error when the type of data field for {@link mongoObject} is not
|
||||
* supported. Currently supported types for data field are instances of
|
||||
* {@link String}, {@link Array}, {@link Binary} and {@link Binary}
|
||||
* from the bson module
|
||||
*
|
||||
* @see Chunk#buildMongoObject
|
||||
*/
|
||||
var Chunk = exports.Chunk = function(file, mongoObject) {
|
||||
if(!(this instanceof Chunk)) return new Chunk(file, mongoObject);
|
||||
|
||||
this.file = file;
|
||||
var self = this;
|
||||
var mongoObjectFinal = mongoObject == null ? {} : mongoObject;
|
||||
|
||||
this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id;
|
||||
this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n;
|
||||
this.data = new Binary();
|
||||
|
||||
if(mongoObjectFinal.data == null) {
|
||||
} else if(typeof mongoObjectFinal.data == "string") {
|
||||
var buffer = new Buffer(mongoObjectFinal.data.length);
|
||||
buffer.write(mongoObjectFinal.data, 'binary', 0);
|
||||
this.data = new Binary(buffer);
|
||||
} else if(Array.isArray(mongoObjectFinal.data)) {
|
||||
var buffer = new Buffer(mongoObjectFinal.data.length);
|
||||
buffer.write(mongoObjectFinal.data.join(''), 'binary', 0);
|
||||
this.data = new Binary(buffer);
|
||||
} else if(mongoObjectFinal.data instanceof Binary || Object.prototype.toString.call(mongoObjectFinal.data) == "[object Binary]") {
|
||||
this.data = mongoObjectFinal.data;
|
||||
} else if(Buffer.isBuffer(mongoObjectFinal.data)) {
|
||||
} else {
|
||||
throw Error("Illegal chunk format");
|
||||
}
|
||||
// Update position
|
||||
this.internalPosition = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes a data to this object and advance the read/write head.
|
||||
*
|
||||
* @param data {string} the data to write
|
||||
* @param callback {function(*, GridStore)} 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.
|
||||
*/
|
||||
Chunk.prototype.write = function(data, callback) {
|
||||
this.data.write(data, this.internalPosition);
|
||||
this.internalPosition = this.data.length();
|
||||
if(callback != null) return callback(null, this);
|
||||
return this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads data and advances the read/write head.
|
||||
*
|
||||
* @param length {number} The length of data to read.
|
||||
*
|
||||
* @return {string} The data read if the given length will not exceed the end of
|
||||
* the chunk. Returns an empty String otherwise.
|
||||
*/
|
||||
Chunk.prototype.read = function(length) {
|
||||
// Default to full read if no index defined
|
||||
length = length == null || length == 0 ? this.length() : length;
|
||||
|
||||
if(this.length() - this.internalPosition + 1 >= length) {
|
||||
var data = this.data.read(this.internalPosition, length);
|
||||
this.internalPosition = this.internalPosition + length;
|
||||
return data;
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
Chunk.prototype.readSlice = function(length) {
|
||||
if ((this.length() - this.internalPosition) >= length) {
|
||||
var data = null;
|
||||
if (this.data.buffer != null) { //Pure BSON
|
||||
data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length);
|
||||
} else { //Native BSON
|
||||
data = new Buffer(length);
|
||||
length = this.data.readInto(data, this.internalPosition);
|
||||
}
|
||||
this.internalPosition = this.internalPosition + length;
|
||||
return data;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if the read/write head is at the end.
|
||||
*
|
||||
* @return {boolean} Whether the read/write head has reached the end of this
|
||||
* chunk.
|
||||
*/
|
||||
Chunk.prototype.eof = function() {
|
||||
return this.internalPosition == this.length() ? true : false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads one character from the data of this chunk and advances the read/write
|
||||
* head.
|
||||
*
|
||||
* @return {string} a single character data read if the the read/write head is
|
||||
* not at the end of the chunk. Returns an empty String otherwise.
|
||||
*/
|
||||
Chunk.prototype.getc = function() {
|
||||
return this.read(1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Clears the contents of the data in this chunk and resets the read/write head
|
||||
* to the initial position.
|
||||
*/
|
||||
Chunk.prototype.rewind = function() {
|
||||
this.internalPosition = 0;
|
||||
this.data = new Binary();
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves this chunk to the database. Also overwrites existing entries having the
|
||||
* same id as this chunk.
|
||||
*
|
||||
* @param callback {function(*, GridStore)} 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.
|
||||
*/
|
||||
Chunk.prototype.save = function(callback) {
|
||||
var self = this;
|
||||
|
||||
self.file.chunkCollection(function(err, collection) {
|
||||
if(err) return callback(err);
|
||||
|
||||
collection.remove({'_id':self.objectId}, {safe:true}, function(err, result) {
|
||||
if(err) return callback(err);
|
||||
|
||||
if(self.data.length() > 0) {
|
||||
self.buildMongoObject(function(mongoObject) {
|
||||
collection.insert(mongoObject, {safe:true}, function(err, collection) {
|
||||
callback(err, self);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
callback(null, self);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a mongoDB object representation of this chunk.
|
||||
*
|
||||
* @param callback {function(Object)} This will be called after executing this
|
||||
* method. The object will be passed to the first parameter and will have
|
||||
* the structure:
|
||||
*
|
||||
* <pre><code>
|
||||
* {
|
||||
* '_id' : , // {number} id for this chunk
|
||||
* 'files_id' : , // {number} foreign key to the file collection
|
||||
* 'n' : , // {number} chunk number
|
||||
* 'data' : , // {bson#Binary} the chunk data itself
|
||||
* }
|
||||
* </code></pre>
|
||||
*
|
||||
* @see <a href="http://www.mongodb.org/display/DOCS/GridFS+Specification#GridFSSpecification-{{chunks}}">MongoDB GridFS Chunk Object Structure</a>
|
||||
*/
|
||||
Chunk.prototype.buildMongoObject = function(callback) {
|
||||
var mongoObject = {'_id': this.objectId,
|
||||
'files_id': this.file.fileId,
|
||||
'n': this.chunkNumber,
|
||||
'data': this.data};
|
||||
callback(mongoObject);
|
||||
};
|
||||
|
||||
/**
|
||||
* @return {number} the length of the data
|
||||
*/
|
||||
Chunk.prototype.length = function() {
|
||||
return this.data.length();
|
||||
};
|
||||
|
||||
/**
|
||||
* The position of the read/write head
|
||||
* @name position
|
||||
* @lends Chunk#
|
||||
* @field
|
||||
*/
|
||||
Object.defineProperty(Chunk.prototype, "position", { enumerable: true
|
||||
, get: function () {
|
||||
return this.internalPosition;
|
||||
}
|
||||
, set: function(value) {
|
||||
this.internalPosition = value;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The default chunk size
|
||||
* @constant
|
||||
*/
|
||||
Chunk.DEFAULT_CHUNK_SIZE = 1024 * 256;
|
||||
103
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/gridfs/grid.js
generated
vendored
Normal file
103
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/gridfs/grid.js
generated
vendored
Normal file
@@ -0,0 +1,103 @@
|
||||
var GridStore = require('./gridstore').GridStore,
|
||||
ObjectID = require('bson').ObjectID;
|
||||
|
||||
/**
|
||||
* A class representation of a simple Grid interface.
|
||||
*
|
||||
* @class Represents the Grid.
|
||||
* @param {Db} db A database instance to interact with.
|
||||
* @param {String} [fsName] optional different root collection for GridFS.
|
||||
* @return {Grid}
|
||||
*/
|
||||
function Grid(db, fsName) {
|
||||
|
||||
if(!(this instanceof Grid)) return new Grid(db, fsName);
|
||||
|
||||
this.db = db;
|
||||
this.fsName = fsName == null ? GridStore.DEFAULT_ROOT_COLLECTION : fsName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts binary data to the grid
|
||||
*
|
||||
* Options
|
||||
* - **_id** {Any}, unique id for this file
|
||||
* - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
|
||||
* - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**.
|
||||
* - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**.
|
||||
* - **metadata** {Object}, arbitrary data the user wants to store.
|
||||
*
|
||||
* @param {Buffer} data buffer with Binary Data.
|
||||
* @param {Object} [options] the options for the files.
|
||||
* @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.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Grid.prototype.put = function(data, options, callback) {
|
||||
var self = this;
|
||||
var args = Array.prototype.slice.call(arguments, 1);
|
||||
callback = args.pop();
|
||||
options = args.length ? args.shift() : {};
|
||||
// If root is not defined add our default one
|
||||
options['root'] = options['root'] == null ? this.fsName : options['root'];
|
||||
|
||||
// Return if we don't have a buffer object as data
|
||||
if(!(Buffer.isBuffer(data))) return callback(new Error("Data object must be a buffer object"), null);
|
||||
// Get filename if we are using it
|
||||
var filename = options['filename'] || null;
|
||||
// Get id if we are using it
|
||||
var id = options['_id'] || null;
|
||||
// Create gridstore
|
||||
var gridStore = new GridStore(this.db, id, filename, "w", options);
|
||||
gridStore.open(function(err, gridStore) {
|
||||
if(err) return callback(err, null);
|
||||
|
||||
gridStore.write(data, function(err, result) {
|
||||
if(err) return callback(err, null);
|
||||
|
||||
gridStore.close(function(err, result) {
|
||||
if(err) return callback(err, null);
|
||||
callback(null, result);
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get binary data to the grid
|
||||
*
|
||||
* @param {Any} id for file.
|
||||
* @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.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Grid.prototype.get = function(id, callback) {
|
||||
// Create gridstore
|
||||
var gridStore = new GridStore(this.db, id, null, "r", {root:this.fsName});
|
||||
gridStore.open(function(err, gridStore) {
|
||||
if(err) return callback(err, null);
|
||||
|
||||
// Return the data
|
||||
gridStore.read(function(err, data) {
|
||||
return callback(err, data)
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete file from grid
|
||||
*
|
||||
* @param {Any} id for file.
|
||||
* @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.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
Grid.prototype.delete = function(id, callback) {
|
||||
// Create gridstore
|
||||
GridStore.unlink(this.db, id, {root:this.fsName}, function(err, result) {
|
||||
if(err) return callback(err, false);
|
||||
return callback(null, true);
|
||||
});
|
||||
}
|
||||
|
||||
exports.Grid = Grid;
|
||||
1476
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js
generated
vendored
Normal file
1476
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
193
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/gridfs/readstream.js
generated
vendored
Normal file
193
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/gridfs/readstream.js
generated
vendored
Normal file
@@ -0,0 +1,193 @@
|
||||
var Stream = require('stream').Stream,
|
||||
timers = require('timers'),
|
||||
util = require('util');
|
||||
|
||||
// Set processor, setImmediate if 0.10 otherwise nextTick
|
||||
var processor = timers.setImmediate ? timers.setImmediate : process.nextTick;
|
||||
processor = process.nextTick
|
||||
|
||||
/**
|
||||
* ReadStream
|
||||
*
|
||||
* Returns a stream interface for the **file**.
|
||||
*
|
||||
* Events
|
||||
* - **data** {function(item) {}} the data event triggers when a document is ready.
|
||||
* - **end** {function() {}} the end event triggers when there is no more documents available.
|
||||
* - **close** {function() {}} the close event triggers when the stream is closed.
|
||||
* - **error** {function(err) {}} the error event triggers if an error happens.
|
||||
*
|
||||
* @class Represents a GridFS File Stream.
|
||||
* @param {Boolean} autoclose automatically close file when the stream reaches the end.
|
||||
* @param {GridStore} cursor a cursor object that the stream wraps.
|
||||
* @return {ReadStream}
|
||||
*/
|
||||
function ReadStream(autoclose, gstore) {
|
||||
if (!(this instanceof ReadStream)) return new ReadStream(autoclose, gstore);
|
||||
Stream.call(this);
|
||||
|
||||
this.autoclose = !!autoclose;
|
||||
this.gstore = gstore;
|
||||
|
||||
this.finalLength = gstore.length - gstore.position;
|
||||
this.completedLength = 0;
|
||||
this.currentChunkNumber = gstore.currentChunk.chunkNumber;
|
||||
|
||||
this.paused = false;
|
||||
this.readable = true;
|
||||
this.pendingChunk = null;
|
||||
this.executing = false;
|
||||
|
||||
// Calculate the number of chunks
|
||||
this.numberOfChunks = Math.ceil(gstore.length/gstore.chunkSize);
|
||||
|
||||
// This seek start position inside the current chunk
|
||||
this.seekStartPosition = gstore.position - (this.currentChunkNumber * gstore.chunkSize);
|
||||
|
||||
var self = this;
|
||||
processor(function() {
|
||||
self._execute();
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Inherit from Stream
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
ReadStream.prototype.__proto__ = Stream.prototype;
|
||||
|
||||
/**
|
||||
* Flag stating whether or not this stream is readable.
|
||||
*/
|
||||
ReadStream.prototype.readable;
|
||||
|
||||
/**
|
||||
* Flag stating whether or not this stream is paused.
|
||||
*/
|
||||
ReadStream.prototype.paused;
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
ReadStream.prototype._execute = function() {
|
||||
if(this.paused === true || this.readable === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
var gstore = this.gstore;
|
||||
var self = this;
|
||||
// Set that we are executing
|
||||
this.executing = true;
|
||||
|
||||
var last = false;
|
||||
var toRead = 0;
|
||||
|
||||
if(gstore.currentChunk.chunkNumber >= (this.numberOfChunks - 1)) {
|
||||
self.executing = false;
|
||||
last = true;
|
||||
}
|
||||
|
||||
// Data setup
|
||||
var data = null;
|
||||
|
||||
// Read a slice (with seek set if none)
|
||||
if(this.seekStartPosition > 0 && (gstore.currentChunk.length() - this.seekStartPosition) > 0) {
|
||||
data = gstore.currentChunk.readSlice(gstore.currentChunk.length() - this.seekStartPosition);
|
||||
this.seekStartPosition = 0;
|
||||
} else {
|
||||
data = gstore.currentChunk.readSlice(gstore.currentChunk.length());
|
||||
}
|
||||
|
||||
// Return the data
|
||||
if(data != null && gstore.currentChunk.chunkNumber == self.currentChunkNumber) {
|
||||
self.currentChunkNumber = self.currentChunkNumber + 1;
|
||||
self.completedLength += data.length;
|
||||
self.pendingChunk = null;
|
||||
self.emit("data", data);
|
||||
}
|
||||
|
||||
if(last === true) {
|
||||
self.readable = false;
|
||||
self.emit("end");
|
||||
|
||||
if(self.autoclose === true) {
|
||||
if(gstore.mode[0] == "w") {
|
||||
gstore.close(function(err, doc) {
|
||||
if (err) {
|
||||
self.emit("error", err);
|
||||
return;
|
||||
}
|
||||
self.readable = false;
|
||||
self.emit("close", doc);
|
||||
});
|
||||
} else {
|
||||
self.readable = false;
|
||||
self.emit("close");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
gstore._nthChunk(gstore.currentChunk.chunkNumber + 1, function(err, chunk) {
|
||||
if(err) {
|
||||
self.readable = false;
|
||||
self.emit("error", err);
|
||||
self.executing = false;
|
||||
return;
|
||||
}
|
||||
|
||||
self.pendingChunk = chunk;
|
||||
if(self.paused === true) {
|
||||
self.executing = false;
|
||||
return;
|
||||
}
|
||||
|
||||
gstore.currentChunk = self.pendingChunk;
|
||||
self._execute();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Pauses this stream, then no farther events will be fired.
|
||||
*
|
||||
* @ignore
|
||||
* @api public
|
||||
*/
|
||||
ReadStream.prototype.pause = function() {
|
||||
if(!this.executing) {
|
||||
this.paused = true;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Destroys the stream, then no farther events will be fired.
|
||||
*
|
||||
* @ignore
|
||||
* @api public
|
||||
*/
|
||||
ReadStream.prototype.destroy = function() {
|
||||
this.readable = false;
|
||||
// Emit close event
|
||||
this.emit("close");
|
||||
};
|
||||
|
||||
/**
|
||||
* Resumes this stream.
|
||||
*
|
||||
* @ignore
|
||||
* @api public
|
||||
*/
|
||||
ReadStream.prototype.resume = function() {
|
||||
if(this.paused === false || !this.readable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.paused = false;
|
||||
var self = this;
|
||||
processor(function() {
|
||||
self._execute();
|
||||
});
|
||||
};
|
||||
|
||||
exports.ReadStream = ReadStream;
|
||||
69
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/index.js
generated
vendored
Normal file
69
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/index.js
generated
vendored
Normal file
@@ -0,0 +1,69 @@
|
||||
try {
|
||||
exports.BSONPure = require('bson').BSONPure;
|
||||
exports.BSONNative = require('bson').BSONNative;
|
||||
} catch(err) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
[ 'commands/base_command'
|
||||
, 'admin'
|
||||
, 'collection'
|
||||
, 'connection/read_preference'
|
||||
, 'connection/connection'
|
||||
, 'connection/server'
|
||||
, 'connection/mongos'
|
||||
, 'connection/repl_set'
|
||||
, 'mongo_client'
|
||||
, 'cursor'
|
||||
, 'db'
|
||||
, 'mongo_client'
|
||||
, 'gridfs/grid'
|
||||
, 'gridfs/chunk'
|
||||
, 'gridfs/gridstore'].forEach(function (path) {
|
||||
var module = require('./' + path);
|
||||
for (var i in module) {
|
||||
exports[i] = module[i];
|
||||
}
|
||||
|
||||
// backwards compat
|
||||
exports.ReplSetServers = exports.ReplSet;
|
||||
|
||||
// Add BSON Classes
|
||||
exports.Binary = require('bson').Binary;
|
||||
exports.Code = require('bson').Code;
|
||||
exports.DBRef = require('bson').DBRef;
|
||||
exports.Double = require('bson').Double;
|
||||
exports.Long = require('bson').Long;
|
||||
exports.MinKey = require('bson').MinKey;
|
||||
exports.MaxKey = require('bson').MaxKey;
|
||||
exports.ObjectID = require('bson').ObjectID;
|
||||
exports.Symbol = require('bson').Symbol;
|
||||
exports.Timestamp = require('bson').Timestamp;
|
||||
|
||||
// Add BSON Parser
|
||||
exports.BSON = require('bson').BSONPure.BSON;
|
||||
|
||||
});
|
||||
|
||||
// Get the Db object
|
||||
var Db = require('./db').Db;
|
||||
// Set up the connect function
|
||||
var connect = Db.connect;
|
||||
var obj = connect;
|
||||
// Map all values to the exports value
|
||||
for(var name in exports) {
|
||||
obj[name] = exports[name];
|
||||
}
|
||||
|
||||
// Add the pure and native backward compatible functions
|
||||
exports.pure = exports.native = function() {
|
||||
return obj;
|
||||
}
|
||||
|
||||
// Map all values to the exports value
|
||||
for(var name in exports) {
|
||||
connect[name] = exports[name];
|
||||
}
|
||||
|
||||
// Set our exports to be the connect function
|
||||
module.exports = connect;
|
||||
116
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/mongo_client.js
generated
vendored
Normal file
116
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/mongo_client.js
generated
vendored
Normal file
@@ -0,0 +1,116 @@
|
||||
var Db = require('./db').Db;
|
||||
|
||||
/**
|
||||
* Create a new MongoClient instance.
|
||||
*
|
||||
* Options
|
||||
* - **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
|
||||
* - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
|
||||
* - **fsync**, (Boolean, default:false) write waits for fsync before returning
|
||||
* - **journal**, (Boolean, default:false) write waits for journal sync before returning
|
||||
* - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
|
||||
* - **native_parser** {Boolean, default:false}, use c++ bson parser.
|
||||
* - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client.
|
||||
* - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
|
||||
* - **serializeFunctions** {Boolean, default:false}, serialize functions.
|
||||
* - **raw** {Boolean, default:false}, peform operations using raw bson buffers.
|
||||
* - **recordQueryStats** {Boolean, default:false}, record query statistics during execution.
|
||||
* - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries.
|
||||
* - **numberOfRetries** {Number, default:5}, number of retries off connection.
|
||||
*
|
||||
* Deprecated Options
|
||||
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
|
||||
*
|
||||
* @class Represents a MongoClient
|
||||
* @param {Object} serverConfig server config object.
|
||||
* @param {Object} [options] additional options for the collection.
|
||||
*/
|
||||
function MongoClient(serverConfig, options) {
|
||||
options = options == null ? {} : options;
|
||||
// If no write concern is set set the default to w:1
|
||||
if(options != null && !options.journal && !options.w && !options.fsync) {
|
||||
options.w = 1;
|
||||
}
|
||||
|
||||
// The internal db instance we are wrapping
|
||||
this._db = new Db('test', serverConfig, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the database connection.
|
||||
*
|
||||
* @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.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
MongoClient.prototype.open = function(callback) {
|
||||
// Self reference
|
||||
var self = this;
|
||||
|
||||
this._db.open(function(err, db) {
|
||||
if(err) return callback(err, null);
|
||||
callback(null, self);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the current db connection, including all the child db instances. Emits close event if no callback is provided.
|
||||
*
|
||||
* @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.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
MongoClient.prototype.close = function(callback) {
|
||||
this._db.close(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new Db instance sharing the current socket connections.
|
||||
*
|
||||
* @param {String} dbName the name of the database we want to use.
|
||||
* @return {Db} a db instance using the new database.
|
||||
* @api public
|
||||
*/
|
||||
MongoClient.prototype.db = function(dbName) {
|
||||
return this._db.db(dbName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to MongoDB using a url as documented at
|
||||
*
|
||||
* docs.mongodb.org/manual/reference/connection-string/
|
||||
*
|
||||
* Options
|
||||
* - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication
|
||||
* - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor**
|
||||
* - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor**
|
||||
* - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor**
|
||||
* - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor**
|
||||
*
|
||||
* @param {String} url connection url for MongoDB.
|
||||
* @param {Object} [options] optional options for insert command
|
||||
* @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.
|
||||
* @return {null}
|
||||
* @api public
|
||||
*/
|
||||
MongoClient.connect = function(url, options, callback) {
|
||||
if(typeof options == 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
}
|
||||
|
||||
Db.connect(url, options, function(err, db) {
|
||||
if(err) return callback(err, null);
|
||||
|
||||
if(db.options !== null && !db.options.safe && !db.options.journal
|
||||
&& !db.options.w && !db.options.fsync && typeof db.options.w != 'number'
|
||||
&& (db.options.safe == false && url.indexOf("safe=") == -1)) {
|
||||
db.options.w = 1;
|
||||
}
|
||||
|
||||
// Return the db
|
||||
callback(null, db);
|
||||
});
|
||||
}
|
||||
|
||||
exports.MongoClient = MongoClient;
|
||||
145
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js
generated
vendored
Normal file
145
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js
generated
vendored
Normal file
@@ -0,0 +1,145 @@
|
||||
var Long = require('bson').Long
|
||||
, timers = require('timers');
|
||||
|
||||
// Set processor, setImmediate if 0.10 otherwise nextTick
|
||||
var processor = timers.setImmediate ? timers.setImmediate : process.nextTick;
|
||||
processor = process.nextTick
|
||||
|
||||
/**
|
||||
Reply message from mongo db
|
||||
**/
|
||||
var MongoReply = exports.MongoReply = function() {
|
||||
this.documents = [];
|
||||
this.index = 0;
|
||||
};
|
||||
|
||||
MongoReply.prototype.parseHeader = function(binary_reply, bson) {
|
||||
// Unpack the standard header first
|
||||
this.messageLength = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
|
||||
this.index = this.index + 4;
|
||||
// Fetch the request id for this reply
|
||||
this.requestId = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
|
||||
this.index = this.index + 4;
|
||||
// Fetch the id of the request that triggered the response
|
||||
this.responseTo = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
|
||||
// Skip op-code field
|
||||
this.index = this.index + 4 + 4;
|
||||
// Unpack the reply message
|
||||
this.responseFlag = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
|
||||
this.index = this.index + 4;
|
||||
// Unpack the cursor id (a 64 bit long integer)
|
||||
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;
|
||||
this.index = this.index + 4;
|
||||
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;
|
||||
this.index = this.index + 4;
|
||||
this.cursorId = new Long(low_bits, high_bits);
|
||||
// Unpack the starting from
|
||||
this.startingFrom = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
|
||||
this.index = this.index + 4;
|
||||
// Unpack the number of objects returned
|
||||
this.numberReturned = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
|
||||
this.index = this.index + 4;
|
||||
}
|
||||
|
||||
MongoReply.prototype.parseBody = function(binary_reply, bson, raw, callback) {
|
||||
raw = raw == null ? false : raw;
|
||||
// Just set a doc limit for deserializing
|
||||
var docLimitSize = 1024*20;
|
||||
|
||||
// If our message length is very long, let's switch to process.nextTick for messages
|
||||
if(this.messageLength > docLimitSize) {
|
||||
var batchSize = this.numberReturned;
|
||||
this.documents = new Array(this.numberReturned);
|
||||
|
||||
// Just walk down until we get a positive number >= 1
|
||||
for(var i = 50; i > 0; i--) {
|
||||
if((this.numberReturned/i) >= 1) {
|
||||
batchSize = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Actual main creator of the processFunction setting internal state to control the flow
|
||||
var parseFunction = function(_self, _binary_reply, _batchSize, _numberReturned) {
|
||||
var object_index = 0;
|
||||
// Internal loop process that will use nextTick to ensure we yield some time
|
||||
var processFunction = function() {
|
||||
// Adjust batchSize if we have less results left than batchsize
|
||||
if((_numberReturned - object_index) < _batchSize) {
|
||||
_batchSize = _numberReturned - object_index;
|
||||
}
|
||||
|
||||
// If raw just process the entries
|
||||
if(raw) {
|
||||
// Iterate over the batch
|
||||
for(var i = 0; i < _batchSize; i++) {
|
||||
// Are we done ?
|
||||
if(object_index <= _numberReturned) {
|
||||
// Read the size of the bson object
|
||||
var bsonObjectSize = _binary_reply[_self.index] | _binary_reply[_self.index + 1] << 8 | _binary_reply[_self.index + 2] << 16 | _binary_reply[_self.index + 3] << 24;
|
||||
// If we are storing the raw responses to pipe straight through
|
||||
_self.documents[object_index] = binary_reply.slice(_self.index, _self.index + bsonObjectSize);
|
||||
// Adjust binary index to point to next block of binary bson data
|
||||
_self.index = _self.index + bsonObjectSize;
|
||||
// Update number of docs parsed
|
||||
object_index = object_index + 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
// Parse documents
|
||||
_self.index = bson.deserializeStream(binary_reply, _self.index, _batchSize, _self.documents, object_index);
|
||||
// Adjust index
|
||||
object_index = object_index + _batchSize;
|
||||
} catch (err) {
|
||||
return callback(err);
|
||||
}
|
||||
}
|
||||
|
||||
// If we hav more documents process NextTick
|
||||
if(object_index < _numberReturned) {
|
||||
processor(processFunction);
|
||||
} else {
|
||||
callback(null);
|
||||
}
|
||||
}
|
||||
|
||||
// Return the process function
|
||||
return processFunction;
|
||||
}(this, binary_reply, batchSize, this.numberReturned)();
|
||||
} else {
|
||||
try {
|
||||
// Let's unpack all the bson documents, deserialize them and store them
|
||||
for(var object_index = 0; object_index < this.numberReturned; object_index++) {
|
||||
// Read the size of the bson object
|
||||
var bsonObjectSize = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24;
|
||||
// If we are storing the raw responses to pipe straight through
|
||||
if(raw) {
|
||||
// Deserialize the object and add to the documents array
|
||||
this.documents.push(binary_reply.slice(this.index, this.index + bsonObjectSize));
|
||||
} else {
|
||||
// Deserialize the object and add to the documents array
|
||||
this.documents.push(bson.deserialize(binary_reply.slice(this.index, this.index + bsonObjectSize)));
|
||||
}
|
||||
// Adjust binary index to point to next block of binary bson data
|
||||
this.index = this.index + bsonObjectSize;
|
||||
}
|
||||
} catch(err) {
|
||||
return callback(err);
|
||||
}
|
||||
|
||||
// No error return
|
||||
callback(null);
|
||||
}
|
||||
}
|
||||
|
||||
MongoReply.prototype.is_error = function(){
|
||||
if(this.documents.length == 1) {
|
||||
return this.documents[0].ok == 1 ? false : true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
MongoReply.prototype.error_message = function() {
|
||||
return this.documents.length == 1 && this.documents[0].ok == 1 ? '' : this.documents[0].errmsg;
|
||||
};
|
||||
121
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/utils.js
generated
vendored
Normal file
121
mongoui/mongoui-master/node_modules/mongodb/lib/mongodb/utils.js
generated
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Sort functions, Normalize and prepare sort parameters
|
||||
*/
|
||||
var formatSortValue = exports.formatSortValue = function(sortDirection) {
|
||||
var value = ("" + sortDirection).toLowerCase();
|
||||
|
||||
switch (value) {
|
||||
case 'ascending':
|
||||
case 'asc':
|
||||
case '1':
|
||||
return 1;
|
||||
case 'descending':
|
||||
case 'desc':
|
||||
case '-1':
|
||||
return -1;
|
||||
default:
|
||||
throw new Error("Illegal sort clause, must be of the form "
|
||||
+ "[['field1', '(ascending|descending)'], "
|
||||
+ "['field2', '(ascending|descending)']]");
|
||||
}
|
||||
};
|
||||
|
||||
var formattedOrderClause = exports.formattedOrderClause = function(sortValue) {
|
||||
var orderBy = {};
|
||||
|
||||
if (Array.isArray(sortValue)) {
|
||||
for(var i = 0; i < sortValue.length; i++) {
|
||||
if(sortValue[i].constructor == String) {
|
||||
orderBy[sortValue[i]] = 1;
|
||||
} else {
|
||||
orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]);
|
||||
}
|
||||
}
|
||||
} else if(Object.prototype.toString.call(sortValue) === '[object Object]') {
|
||||
orderBy = sortValue;
|
||||
} else if (sortValue.constructor == String) {
|
||||
orderBy[sortValue] = 1;
|
||||
} else {
|
||||
throw new Error("Illegal sort clause, must be of the form " +
|
||||
"[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");
|
||||
}
|
||||
|
||||
return orderBy;
|
||||
};
|
||||
|
||||
exports.encodeInt = function(value) {
|
||||
var buffer = new Buffer(4);
|
||||
buffer[3] = (value >> 24) & 0xff;
|
||||
buffer[2] = (value >> 16) & 0xff;
|
||||
buffer[1] = (value >> 8) & 0xff;
|
||||
buffer[0] = value & 0xff;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
exports.encodeIntInPlace = function(value, buffer, index) {
|
||||
buffer[index + 3] = (value >> 24) & 0xff;
|
||||
buffer[index + 2] = (value >> 16) & 0xff;
|
||||
buffer[index + 1] = (value >> 8) & 0xff;
|
||||
buffer[index] = value & 0xff;
|
||||
}
|
||||
|
||||
exports.encodeCString = function(string) {
|
||||
var buf = new Buffer(string, 'utf8');
|
||||
return [buf, new Buffer([0])];
|
||||
}
|
||||
|
||||
exports.decodeUInt32 = function(array, index) {
|
||||
return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24;
|
||||
}
|
||||
|
||||
// Decode the int
|
||||
exports.decodeUInt8 = function(array, index) {
|
||||
return array[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Context insensitive type checks
|
||||
*/
|
||||
|
||||
var toString = Object.prototype.toString;
|
||||
|
||||
exports.isObject = function (arg) {
|
||||
return '[object Object]' == toString.call(arg)
|
||||
}
|
||||
|
||||
exports.isArray = function (arg) {
|
||||
return Array.isArray(arg) ||
|
||||
'object' == typeof arg && '[object Array]' == toString.call(arg)
|
||||
}
|
||||
|
||||
exports.isDate = function (arg) {
|
||||
return 'object' == typeof arg && '[object Date]' == toString.call(arg)
|
||||
}
|
||||
|
||||
exports.isRegExp = function (arg) {
|
||||
return 'object' == typeof arg && '[object RegExp]' == toString.call(arg)
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a Mongo error document in an Error instance
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
exports.toError = function(error) {
|
||||
if (error instanceof Error) return error;
|
||||
|
||||
var msg = error.err || error.errmsg || error;
|
||||
var e = new Error(msg);
|
||||
e.name = 'MongoError';
|
||||
|
||||
// Get all object keys
|
||||
var keys = typeof error == 'object'
|
||||
? Object.keys(error)
|
||||
: [];
|
||||
|
||||
for(var i = 0; i < keys.length; i++) {
|
||||
e[keys[i]] = error[keys[i]];
|
||||
}
|
||||
|
||||
return e;
|
||||
}
|
||||
5
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/.travis.yml
generated
vendored
Normal file
5
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/.travis.yml
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- 0.6
|
||||
- 0.8
|
||||
- 0.9 # development version of 0.8, may be unstable
|
||||
19
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/Makefile
generated
vendored
Normal file
19
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/Makefile
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
NODE = node
|
||||
NPM = npm
|
||||
NODEUNIT = node_modules/nodeunit/bin/nodeunit
|
||||
|
||||
all: clean node_gyp
|
||||
|
||||
test: clean node_gyp
|
||||
npm test
|
||||
|
||||
node_gyp: clean
|
||||
node-gyp configure build
|
||||
|
||||
clean:
|
||||
node-gyp clean
|
||||
|
||||
browserify:
|
||||
node_modules/.bin/onejs build browser_build/package.json browser_build/bson.js
|
||||
|
||||
.PHONY: all
|
||||
1
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/README.md
generated
vendored
Normal file
1
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/README.md
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
A JS/C++ Bson parser for node, used in the MongoDB Native driver
|
||||
130
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/benchmarks/benchmarks.js
generated
vendored
Normal file
130
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/benchmarks/benchmarks.js
generated
vendored
Normal file
@@ -0,0 +1,130 @@
|
||||
// var BSON = require('../../lib/mongodb').BSONNative.BSON,
|
||||
// ObjectID = require('../../lib/mongodb').BSONNative.ObjectID,
|
||||
// Code = require('../../lib/mongodb').BSONNative.Code,
|
||||
// Long = require('../../lib/mongodb').BSONNative.Long,
|
||||
// Binary = require('../../lib/mongodb').BSONNative.Binary,
|
||||
// debug = require('util').debug,
|
||||
// inspect = require('util').inspect,
|
||||
//
|
||||
// Long = require('../../lib/mongodb').Long,
|
||||
// ObjectID = require('../../lib/mongodb').ObjectID,
|
||||
// Binary = require('../../lib/mongodb').Binary,
|
||||
// Code = require('../../lib/mongodb').Code,
|
||||
// DBRef = require('../../lib/mongodb').DBRef,
|
||||
// Symbol = require('../../lib/mongodb').Symbol,
|
||||
// Double = require('../../lib/mongodb').Double,
|
||||
// MaxKey = require('../../lib/mongodb').MaxKey,
|
||||
// MinKey = require('../../lib/mongodb').MinKey,
|
||||
// Timestamp = require('../../lib/mongodb').Timestamp;
|
||||
|
||||
|
||||
// var BSON = require('../../lib/mongodb').BSONPure.BSON,
|
||||
// ObjectID = require('../../lib/mongodb').BSONPure.ObjectID,
|
||||
// Code = require('../../lib/mongodb').BSONPure.Code,
|
||||
// Long = require('../../lib/mongodb').BSONPure.Long,
|
||||
// Binary = require('../../lib/mongodb').BSONPure.Binary;
|
||||
|
||||
var BSON = require('../lib/bson').BSONNative.BSON,
|
||||
Long = require('../lib/bson').Long,
|
||||
ObjectID = require('../lib/bson').ObjectID,
|
||||
Binary = require('../lib/bson').Binary,
|
||||
Code = require('../lib/bson').Code,
|
||||
DBRef = require('../lib/bson').DBRef,
|
||||
Symbol = require('../lib/bson').Symbol,
|
||||
Double = require('../lib/bson').Double,
|
||||
MaxKey = require('../lib/bson').MaxKey,
|
||||
MinKey = require('../lib/bson').MinKey,
|
||||
Timestamp = require('../lib/bson').Timestamp;
|
||||
|
||||
// console.dir(require('../lib/bson'))
|
||||
|
||||
var COUNT = 1000;
|
||||
var COUNT = 100;
|
||||
|
||||
var object = {
|
||||
string: "Strings are great",
|
||||
decimal: 3.14159265,
|
||||
bool: true,
|
||||
integer: 5,
|
||||
date: new Date(),
|
||||
double: new Double(1.4),
|
||||
id: new ObjectID(),
|
||||
min: new MinKey(),
|
||||
max: new MaxKey(),
|
||||
symbol: new Symbol('hello'),
|
||||
long: Long.fromNumber(100),
|
||||
bin: new Binary(new Buffer(100)),
|
||||
|
||||
subObject: {
|
||||
moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.",
|
||||
longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin."
|
||||
},
|
||||
|
||||
subArray: [1,2,3,4,5,6,7,8,9,10],
|
||||
anotherString: "another string",
|
||||
code: new Code("function() {}", {i:1})
|
||||
}
|
||||
|
||||
// Number of objects
|
||||
var numberOfObjects = 10000;
|
||||
var bson = new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
|
||||
console.log("---------------------- 1")
|
||||
var s = new Date()
|
||||
// Object serialized
|
||||
for(var i = 0; i < numberOfObjects; i++) {
|
||||
objectBSON = bson.serialize(object, null, true)
|
||||
}
|
||||
console.log("====================== " + (new Date().getTime() - s.getTime()) + " :: " + ((new Date().getTime() - s.getTime()))/numberOfObjects)
|
||||
|
||||
console.log("---------------------- 2")
|
||||
var s = new Date()
|
||||
// Object serialized
|
||||
for(var i = 0; i < numberOfObjects; i++) {
|
||||
bson.deserialize(objectBSON);
|
||||
}
|
||||
console.log("====================== " + (new Date().getTime() - s.getTime()) + " :: " + ((new Date().getTime() - s.getTime()))/numberOfObjects)
|
||||
|
||||
// // Buffer With copies of the objectBSON
|
||||
// var data = new Buffer(objectBSON.length * numberOfObjects);
|
||||
// var index = 0;
|
||||
//
|
||||
// // Copy the buffer 1000 times to create a strea m of objects
|
||||
// for(var i = 0; i < numberOfObjects; i++) {
|
||||
// // Copy data
|
||||
// objectBSON.copy(data, index);
|
||||
// // Adjust index
|
||||
// index = index + objectBSON.length;
|
||||
// }
|
||||
//
|
||||
// // console.log("-----------------------------------------------------------------------------------")
|
||||
// // console.dir(objectBSON)
|
||||
//
|
||||
// var x, start, end, j
|
||||
// var objectBSON, objectJSON
|
||||
//
|
||||
// // Allocate the return array (avoid concatinating everything)
|
||||
// var results = new Array(numberOfObjects);
|
||||
//
|
||||
// console.log(COUNT + "x (objectBSON = BSON.serialize(object))")
|
||||
// start = new Date
|
||||
//
|
||||
// // var objects = BSON.deserializeStream(data, 0, numberOfObjects);
|
||||
// // console.log("----------------------------------------------------------------------------------- 0")
|
||||
// // var objects = BSON.deserialize(data);
|
||||
// // console.log("----------------------------------------------------------------------------------- 1")
|
||||
// // console.dir(objects)
|
||||
//
|
||||
// for (j=COUNT; --j>=0; ) {
|
||||
// var nextIndex = BSON.deserializeStream(data, 0, numberOfObjects, results, 0);
|
||||
// }
|
||||
//
|
||||
// end = new Date
|
||||
// var opsprsecond = COUNT / ((end - start)/1000);
|
||||
// console.log("bson size (bytes): ", objectBSON.length);
|
||||
// console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec");
|
||||
// console.log("MB/s = " + ((opsprsecond*objectBSON.length)/1024));
|
||||
//
|
||||
// // console.dir(nextIndex)
|
||||
// // console.dir(results)
|
||||
|
||||
|
||||
17
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/binding.gyp
generated
vendored
Normal file
17
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/binding.gyp
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
'targets': [
|
||||
{
|
||||
'target_name': 'bson',
|
||||
'sources': [ 'ext/bson.cc' ],
|
||||
'cflags!': [ '-fno-exceptions' ],
|
||||
'cflags_cc!': [ '-fno-exceptions' ],
|
||||
'conditions': [
|
||||
['OS=="mac"', {
|
||||
'xcode_settings': {
|
||||
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'
|
||||
}
|
||||
}]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
4814
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/browser_build/bson.js
generated
vendored
Normal file
4814
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/browser_build/bson.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
8
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/browser_build/package.json
generated
vendored
Normal file
8
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/browser_build/package.json
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
{ "name" : "bson"
|
||||
, "description" : "A bson parser for node.js and the browser"
|
||||
, "main": "../lib/bson/bson"
|
||||
, "directories" : { "lib" : "../lib/bson" }
|
||||
, "engines" : { "node" : ">=0.6.0" }
|
||||
, "licenses" : [ { "type" : "Apache License, Version 2.0"
|
||||
, "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ]
|
||||
}
|
||||
355
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Makefile
generated
vendored
Normal file
355
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Makefile
generated
vendored
Normal file
@@ -0,0 +1,355 @@
|
||||
# We borrow heavily from the kernel build setup, though we are simpler since
|
||||
# we don't have Kconfig tweaking settings on us.
|
||||
|
||||
# The implicit make rules have it looking for RCS files, among other things.
|
||||
# We instead explicitly write all the rules we care about.
|
||||
# It's even quicker (saves ~200ms) to pass -r on the command line.
|
||||
MAKEFLAGS=-r
|
||||
|
||||
# The source directory tree.
|
||||
srcdir := ..
|
||||
abs_srcdir := $(abspath $(srcdir))
|
||||
|
||||
# The name of the builddir.
|
||||
builddir_name ?= .
|
||||
|
||||
# The V=1 flag on command line makes us verbosely print command lines.
|
||||
ifdef V
|
||||
quiet=
|
||||
else
|
||||
quiet=quiet_
|
||||
endif
|
||||
|
||||
# Specify BUILDTYPE=Release on the command line for a release build.
|
||||
BUILDTYPE ?= Release
|
||||
|
||||
# Directory all our build output goes into.
|
||||
# Note that this must be two directories beneath src/ for unit tests to pass,
|
||||
# as they reach into the src/ directory for data with relative paths.
|
||||
builddir ?= $(builddir_name)/$(BUILDTYPE)
|
||||
abs_builddir := $(abspath $(builddir))
|
||||
depsdir := $(builddir)/.deps
|
||||
|
||||
# Object output directory.
|
||||
obj := $(builddir)/obj
|
||||
abs_obj := $(abspath $(obj))
|
||||
|
||||
# We build up a list of every single one of the targets so we can slurp in the
|
||||
# generated dependency rule Makefiles in one pass.
|
||||
all_deps :=
|
||||
|
||||
|
||||
|
||||
# C++ apps need to be linked with g++.
|
||||
#
|
||||
# Note: flock is used to seralize linking. Linking is a memory-intensive
|
||||
# process so running parallel links can often lead to thrashing. To disable
|
||||
# the serialization, override LINK via an envrionment variable as follows:
|
||||
#
|
||||
# export LINK=g++
|
||||
#
|
||||
# This will allow make to invoke N linker processes as specified in -jN.
|
||||
LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX)
|
||||
|
||||
CC.target ?= $(CC)
|
||||
CFLAGS.target ?= $(CFLAGS)
|
||||
CXX.target ?= $(CXX)
|
||||
CXXFLAGS.target ?= $(CXXFLAGS)
|
||||
LINK.target ?= $(LINK)
|
||||
LDFLAGS.target ?= $(LDFLAGS)
|
||||
AR.target ?= $(AR)
|
||||
|
||||
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
|
||||
# to replicate this environment fallback in make as well.
|
||||
CC.host ?= gcc
|
||||
CFLAGS.host ?=
|
||||
CXX.host ?= g++
|
||||
CXXFLAGS.host ?=
|
||||
LINK.host ?= g++
|
||||
LDFLAGS.host ?=
|
||||
AR.host ?= ar
|
||||
|
||||
# Define a dir function that can handle spaces.
|
||||
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
|
||||
# "leading spaces cannot appear in the text of the first argument as written.
|
||||
# These characters can be put into the argument value by variable substitution."
|
||||
empty :=
|
||||
space := $(empty) $(empty)
|
||||
|
||||
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
|
||||
replace_spaces = $(subst $(space),?,$1)
|
||||
unreplace_spaces = $(subst ?,$(space),$1)
|
||||
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
|
||||
|
||||
# Flags to make gcc output dependency info. Note that you need to be
|
||||
# careful here to use the flags that ccache and distcc can understand.
|
||||
# We write to a dep file on the side first and then rename at the end
|
||||
# so we can't end up with a broken dep file.
|
||||
depfile = $(depsdir)/$(call replace_spaces,$@).d
|
||||
DEPFLAGS = -MMD -MF $(depfile).raw
|
||||
|
||||
# We have to fixup the deps output in a few ways.
|
||||
# (1) the file output should mention the proper .o file.
|
||||
# ccache or distcc lose the path to the target, so we convert a rule of
|
||||
# the form:
|
||||
# foobar.o: DEP1 DEP2
|
||||
# into
|
||||
# path/to/foobar.o: DEP1 DEP2
|
||||
# (2) we want missing files not to cause us to fail to build.
|
||||
# We want to rewrite
|
||||
# foobar.o: DEP1 DEP2 \
|
||||
# DEP3
|
||||
# to
|
||||
# DEP1:
|
||||
# DEP2:
|
||||
# DEP3:
|
||||
# so if the files are missing, they're just considered phony rules.
|
||||
# We have to do some pretty insane escaping to get those backslashes
|
||||
# and dollar signs past make, the shell, and sed at the same time.
|
||||
# Doesn't work with spaces, but that's fine: .d files have spaces in
|
||||
# their names replaced with other characters.
|
||||
define fixup_dep
|
||||
# The depfile may not exist if the input file didn't have any #includes.
|
||||
touch $(depfile).raw
|
||||
# Fixup path as in (1).
|
||||
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
|
||||
# Add extra rules as in (2).
|
||||
# We remove slashes and replace spaces with new lines;
|
||||
# remove blank lines;
|
||||
# delete the first line and append a colon to the remaining lines.
|
||||
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
|
||||
grep -v '^$$' |\
|
||||
sed -e 1d -e 's|$$|:|' \
|
||||
>> $(depfile)
|
||||
rm $(depfile).raw
|
||||
endef
|
||||
|
||||
# Command definitions:
|
||||
# - cmd_foo is the actual command to run;
|
||||
# - quiet_cmd_foo is the brief-output summary of the command.
|
||||
|
||||
quiet_cmd_cc = CC($(TOOLSET)) $@
|
||||
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
|
||||
|
||||
quiet_cmd_cxx = CXX($(TOOLSET)) $@
|
||||
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
|
||||
|
||||
quiet_cmd_objc = CXX($(TOOLSET)) $@
|
||||
cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
|
||||
|
||||
quiet_cmd_objcxx = CXX($(TOOLSET)) $@
|
||||
cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
|
||||
|
||||
# Commands for precompiled header files.
|
||||
quiet_cmd_pch_c = CXX($(TOOLSET)) $@
|
||||
cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
|
||||
quiet_cmd_pch_cc = CXX($(TOOLSET)) $@
|
||||
cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
|
||||
quiet_cmd_pch_m = CXX($(TOOLSET)) $@
|
||||
cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $<
|
||||
quiet_cmd_pch_mm = CXX($(TOOLSET)) $@
|
||||
cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $<
|
||||
|
||||
# gyp-mac-tool is written next to the root Makefile by gyp.
|
||||
# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd
|
||||
# already.
|
||||
quiet_cmd_mac_tool = MACTOOL $(4) $<
|
||||
cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@"
|
||||
|
||||
quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@
|
||||
cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4)
|
||||
|
||||
quiet_cmd_infoplist = INFOPLIST $@
|
||||
cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@"
|
||||
|
||||
quiet_cmd_touch = TOUCH $@
|
||||
cmd_touch = touch $@
|
||||
|
||||
quiet_cmd_copy = COPY $@
|
||||
# send stderr to /dev/null to ignore messages when linking directories.
|
||||
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
|
||||
|
||||
quiet_cmd_alink = LIBTOOL-STATIC $@
|
||||
cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^)
|
||||
|
||||
quiet_cmd_link = LINK($(TOOLSET)) $@
|
||||
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
|
||||
|
||||
# TODO(thakis): Find out and document the difference between shared_library and
|
||||
# loadable_module on mac.
|
||||
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
|
||||
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS)
|
||||
|
||||
# TODO(thakis): The solink_module rule is likely wrong. Xcode seems to pass
|
||||
# -bundle -single_module here (for osmesa.so).
|
||||
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
|
||||
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS)
|
||||
|
||||
|
||||
# Define an escape_quotes function to escape single quotes.
|
||||
# This allows us to handle quotes properly as long as we always use
|
||||
# use single quotes and escape_quotes.
|
||||
escape_quotes = $(subst ','\'',$(1))
|
||||
# This comment is here just to include a ' to unconfuse syntax highlighting.
|
||||
# Define an escape_vars function to escape '$' variable syntax.
|
||||
# This allows us to read/write command lines with shell variables (e.g.
|
||||
# $LD_LIBRARY_PATH), without triggering make substitution.
|
||||
escape_vars = $(subst $$,$$$$,$(1))
|
||||
# Helper that expands to a shell command to echo a string exactly as it is in
|
||||
# make. This uses printf instead of echo because printf's behaviour with respect
|
||||
# to escape sequences is more portable than echo's across different shells
|
||||
# (e.g., dash, bash).
|
||||
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
|
||||
|
||||
# Helper to compare the command we're about to run against the command
|
||||
# we logged the last time we ran the command. Produces an empty
|
||||
# string (false) when the commands match.
|
||||
# Tricky point: Make has no string-equality test function.
|
||||
# The kernel uses the following, but it seems like it would have false
|
||||
# positives, where one string reordered its arguments.
|
||||
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
|
||||
# $(filter-out $(cmd_$@), $(cmd_$(1))))
|
||||
# We instead substitute each for the empty string into the other, and
|
||||
# say they're equal if both substitutions produce the empty string.
|
||||
# .d files contain ? instead of spaces, take that into account.
|
||||
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
|
||||
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
|
||||
|
||||
# Helper that is non-empty when a prerequisite changes.
|
||||
# Normally make does this implicitly, but we force rules to always run
|
||||
# so we can check their command lines.
|
||||
# $? -- new prerequisites
|
||||
# $| -- order-only dependencies
|
||||
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
|
||||
|
||||
# Helper that executes all postbuilds, and deletes the output file when done
|
||||
# if any of the postbuilds failed.
|
||||
define do_postbuilds
|
||||
@E=0;\
|
||||
for p in $(POSTBUILDS); do\
|
||||
eval $$p;\
|
||||
F=$$?;\
|
||||
if [ $$F -ne 0 ]; then\
|
||||
E=$$F;\
|
||||
fi;\
|
||||
done;\
|
||||
if [ $$E -ne 0 ]; then\
|
||||
rm -rf "$@";\
|
||||
exit $$E;\
|
||||
fi
|
||||
endef
|
||||
|
||||
# do_cmd: run a command via the above cmd_foo names, if necessary.
|
||||
# Should always run for a given target to handle command-line changes.
|
||||
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
|
||||
# Third argument, if non-zero, makes it do POSTBUILDS processing.
|
||||
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
|
||||
# spaces already and dirx strips the ? characters.
|
||||
define do_cmd
|
||||
$(if $(or $(command_changed),$(prereq_changed)),
|
||||
@$(call exact_echo, $($(quiet)cmd_$(1)))
|
||||
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
|
||||
$(if $(findstring flock,$(word 2,$(cmd_$1))),
|
||||
@$(cmd_$(1))
|
||||
@echo " $(quiet_cmd_$(1)): Finished",
|
||||
@$(cmd_$(1))
|
||||
)
|
||||
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
|
||||
@$(if $(2),$(fixup_dep))
|
||||
$(if $(and $(3), $(POSTBUILDS)),
|
||||
$(call do_postbuilds)
|
||||
)
|
||||
)
|
||||
endef
|
||||
|
||||
# Declare the "all" target first so it is the default,
|
||||
# even though we don't have the deps yet.
|
||||
.PHONY: all
|
||||
all:
|
||||
|
||||
# make looks for ways to re-generate included makefiles, but in our case, we
|
||||
# don't have a direct way. Explicitly telling make that it has nothing to do
|
||||
# for them makes it go faster.
|
||||
%.d: ;
|
||||
|
||||
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
|
||||
# do_cmd.
|
||||
.PHONY: FORCE_DO_CMD
|
||||
FORCE_DO_CMD:
|
||||
|
||||
TOOLSET := target
|
||||
# Suffix rules, putting all outputs into $(obj).
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD
|
||||
@$(call do_cmd,objc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD
|
||||
@$(call do_cmd,objcxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
|
||||
# Try building from generated source, too.
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD
|
||||
@$(call do_cmd,objc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD
|
||||
@$(call do_cmd,objcxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD
|
||||
@$(call do_cmd,objc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD
|
||||
@$(call do_cmd,objcxx,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
|
||||
@$(call do_cmd,cc,1)
|
||||
|
||||
|
||||
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
|
||||
$(findstring $(join ^,$(prefix)),\
|
||||
$(join ^,bson.target.mk)))),)
|
||||
include bson.target.mk
|
||||
endif
|
||||
|
||||
quiet_cmd_regen_makefile = ACTION Regenerating $@
|
||||
cmd_regen_makefile = /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/Users/azat/Documents/Development/mongoui/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/azat/.node-gyp/0.10.12/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/azat/.node-gyp/0.10.12" "-Dmodule_root_dir=/Users/azat/Documents/Development/mongoui/node_modules/mongodb/node_modules/bson" binding.gyp
|
||||
Makefile: $(srcdir)/../../../../../../../.node-gyp/0.10.12/common.gypi $(srcdir)/../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
|
||||
$(call do_cmd,regen_makefile)
|
||||
|
||||
# "all" is a concatenation of the "all" targets from all the included
|
||||
# sub-makefiles. This is just here to clarify.
|
||||
all:
|
||||
|
||||
# Add in dependency-tracking rules. $(all_deps) is the list of every single
|
||||
# target in our tree. Only consider the ones with .d (dependency) info:
|
||||
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
|
||||
ifneq ($(d_files),)
|
||||
include $(d_files)
|
||||
endif
|
||||
1
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d
generated
vendored
Normal file
1
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
cmd_Release/bson.node := ./gyp-mac-tool flock ./Release/linker.lock c++ -shared -Wl,-search_paths_first -mmacosx-version-min=10.5 -arch x86_64 -L./Release -install_name @rpath/bson.node -o Release/bson.node Release/obj.target/bson/ext/bson.o -undefined dynamic_lookup
|
||||
24
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d
generated
vendored
Normal file
24
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
cmd_Release/obj.target/bson/ext/bson.o := c++ '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/Users/azat/.node-gyp/0.10.12/src -I/Users/azat/.node-gyp/0.10.12/deps/uv/include -I/Users/azat/.node-gyp/0.10.12/deps/v8/include -Os -gdwarf-2 -mmacosx-version-min=10.5 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -fno-rtti -fno-threadsafe-statics -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/bson/ext/bson.o.d.raw -c -o Release/obj.target/bson/ext/bson.o ../ext/bson.cc
|
||||
Release/obj.target/bson/ext/bson.o: ../ext/bson.cc \
|
||||
/Users/azat/.node-gyp/0.10.12/deps/v8/include/v8.h \
|
||||
/Users/azat/.node-gyp/0.10.12/deps/v8/include/v8stdint.h \
|
||||
/Users/azat/.node-gyp/0.10.12/src/node.h \
|
||||
/Users/azat/.node-gyp/0.10.12/deps/uv/include/uv.h \
|
||||
/Users/azat/.node-gyp/0.10.12/deps/uv/include/uv-private/uv-unix.h \
|
||||
/Users/azat/.node-gyp/0.10.12/deps/uv/include/uv-private/ngx-queue.h \
|
||||
/Users/azat/.node-gyp/0.10.12/deps/uv/include/uv-private/uv-darwin.h \
|
||||
/Users/azat/.node-gyp/0.10.12/src/node_object_wrap.h \
|
||||
/Users/azat/.node-gyp/0.10.12/src/node_version.h \
|
||||
/Users/azat/.node-gyp/0.10.12/src/node_buffer.h ../ext/bson.h
|
||||
../ext/bson.cc:
|
||||
/Users/azat/.node-gyp/0.10.12/deps/v8/include/v8.h:
|
||||
/Users/azat/.node-gyp/0.10.12/deps/v8/include/v8stdint.h:
|
||||
/Users/azat/.node-gyp/0.10.12/src/node.h:
|
||||
/Users/azat/.node-gyp/0.10.12/deps/uv/include/uv.h:
|
||||
/Users/azat/.node-gyp/0.10.12/deps/uv/include/uv-private/uv-unix.h:
|
||||
/Users/azat/.node-gyp/0.10.12/deps/uv/include/uv-private/ngx-queue.h:
|
||||
/Users/azat/.node-gyp/0.10.12/deps/uv/include/uv-private/uv-darwin.h:
|
||||
/Users/azat/.node-gyp/0.10.12/src/node_object_wrap.h:
|
||||
/Users/azat/.node-gyp/0.10.12/src/node_version.h:
|
||||
/Users/azat/.node-gyp/0.10.12/src/node_buffer.h:
|
||||
../ext/bson.h:
|
||||
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/bson.node
generated
vendored
Executable file
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/bson.node
generated
vendored
Executable file
Binary file not shown.
0
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/linker.lock
generated
vendored
Normal file
0
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/linker.lock
generated
vendored
Normal file
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o
generated
vendored
Normal file
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o
generated
vendored
Normal file
Binary file not shown.
6
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/binding.Makefile
generated
vendored
Normal file
6
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/binding.Makefile
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
# This file is generated by gyp; do not edit.
|
||||
|
||||
export builddir_name ?= build/./.
|
||||
.PHONY: all
|
||||
all:
|
||||
$(MAKE) bson
|
||||
154
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/bson.target.mk
generated
vendored
Normal file
154
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/bson.target.mk
generated
vendored
Normal file
@@ -0,0 +1,154 @@
|
||||
# This file is generated by gyp; do not edit.
|
||||
|
||||
TOOLSET := target
|
||||
TARGET := bson
|
||||
DEFS_Debug := \
|
||||
'-D_DARWIN_USE_64_BIT_INODE=1' \
|
||||
'-D_LARGEFILE_SOURCE' \
|
||||
'-D_FILE_OFFSET_BITS=64' \
|
||||
'-DBUILDING_NODE_EXTENSION' \
|
||||
'-DDEBUG' \
|
||||
'-D_DEBUG'
|
||||
|
||||
# Flags passed to all source files.
|
||||
CFLAGS_Debug := \
|
||||
-O0 \
|
||||
-gdwarf-2 \
|
||||
-mmacosx-version-min=10.5 \
|
||||
-arch x86_64 \
|
||||
-Wall \
|
||||
-Wendif-labels \
|
||||
-W \
|
||||
-Wno-unused-parameter
|
||||
|
||||
# Flags passed to only C files.
|
||||
CFLAGS_C_Debug := \
|
||||
-fno-strict-aliasing
|
||||
|
||||
# Flags passed to only C++ files.
|
||||
CFLAGS_CC_Debug := \
|
||||
-fno-rtti \
|
||||
-fno-threadsafe-statics \
|
||||
-fno-strict-aliasing
|
||||
|
||||
# Flags passed to only ObjC files.
|
||||
CFLAGS_OBJC_Debug :=
|
||||
|
||||
# Flags passed to only ObjC++ files.
|
||||
CFLAGS_OBJCC_Debug :=
|
||||
|
||||
INCS_Debug := \
|
||||
-I/Users/azat/.node-gyp/0.10.12/src \
|
||||
-I/Users/azat/.node-gyp/0.10.12/deps/uv/include \
|
||||
-I/Users/azat/.node-gyp/0.10.12/deps/v8/include
|
||||
|
||||
DEFS_Release := \
|
||||
'-D_DARWIN_USE_64_BIT_INODE=1' \
|
||||
'-D_LARGEFILE_SOURCE' \
|
||||
'-D_FILE_OFFSET_BITS=64' \
|
||||
'-DBUILDING_NODE_EXTENSION'
|
||||
|
||||
# Flags passed to all source files.
|
||||
CFLAGS_Release := \
|
||||
-Os \
|
||||
-gdwarf-2 \
|
||||
-mmacosx-version-min=10.5 \
|
||||
-arch x86_64 \
|
||||
-Wall \
|
||||
-Wendif-labels \
|
||||
-W \
|
||||
-Wno-unused-parameter
|
||||
|
||||
# Flags passed to only C files.
|
||||
CFLAGS_C_Release := \
|
||||
-fno-strict-aliasing
|
||||
|
||||
# Flags passed to only C++ files.
|
||||
CFLAGS_CC_Release := \
|
||||
-fno-rtti \
|
||||
-fno-threadsafe-statics \
|
||||
-fno-strict-aliasing
|
||||
|
||||
# Flags passed to only ObjC files.
|
||||
CFLAGS_OBJC_Release :=
|
||||
|
||||
# Flags passed to only ObjC++ files.
|
||||
CFLAGS_OBJCC_Release :=
|
||||
|
||||
INCS_Release := \
|
||||
-I/Users/azat/.node-gyp/0.10.12/src \
|
||||
-I/Users/azat/.node-gyp/0.10.12/deps/uv/include \
|
||||
-I/Users/azat/.node-gyp/0.10.12/deps/v8/include
|
||||
|
||||
OBJS := \
|
||||
$(obj).target/$(TARGET)/ext/bson.o
|
||||
|
||||
# Add to the list of files we specially track dependencies for.
|
||||
all_deps += $(OBJS)
|
||||
|
||||
# CFLAGS et al overrides must be target-local.
|
||||
# See "Target-specific Variable Values" in the GNU Make manual.
|
||||
$(OBJS): TOOLSET := $(TOOLSET)
|
||||
$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE))
|
||||
$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE))
|
||||
$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))
|
||||
$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))
|
||||
|
||||
# Suffix rules, putting all outputs into $(obj).
|
||||
|
||||
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
|
||||
# Try building from generated source, too.
|
||||
|
||||
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
|
||||
$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD
|
||||
@$(call do_cmd,cxx,1)
|
||||
|
||||
# End of this set of suffix rules
|
||||
### Rules for final target.
|
||||
LDFLAGS_Debug := \
|
||||
-Wl,-search_paths_first \
|
||||
-mmacosx-version-min=10.5 \
|
||||
-arch x86_64 \
|
||||
-L$(builddir) \
|
||||
-install_name @rpath/bson.node
|
||||
|
||||
LIBTOOLFLAGS_Debug := \
|
||||
-Wl,-search_paths_first
|
||||
|
||||
LDFLAGS_Release := \
|
||||
-Wl,-search_paths_first \
|
||||
-mmacosx-version-min=10.5 \
|
||||
-arch x86_64 \
|
||||
-L$(builddir) \
|
||||
-install_name @rpath/bson.node
|
||||
|
||||
LIBTOOLFLAGS_Release := \
|
||||
-Wl,-search_paths_first
|
||||
|
||||
LIBS := \
|
||||
-undefined dynamic_lookup
|
||||
|
||||
$(builddir)/bson.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))
|
||||
$(builddir)/bson.node: LIBS := $(LIBS)
|
||||
$(builddir)/bson.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))
|
||||
$(builddir)/bson.node: TOOLSET := $(TOOLSET)
|
||||
$(builddir)/bson.node: $(OBJS) FORCE_DO_CMD
|
||||
$(call do_cmd,solink_module)
|
||||
|
||||
all_deps += $(builddir)/bson.node
|
||||
# Add target alias
|
||||
.PHONY: bson
|
||||
bson: $(builddir)/bson.node
|
||||
|
||||
# Short alias for building this executable.
|
||||
.PHONY: bson.node
|
||||
bson.node: $(builddir)/bson.node
|
||||
|
||||
# Add executable to "all" target.
|
||||
.PHONY: all
|
||||
all: $(builddir)/bson.node
|
||||
|
||||
114
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/config.gypi
generated
vendored
Normal file
114
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/config.gypi
generated
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
# Do not edit. File was generated by node-gyp's "configure" step
|
||||
{
|
||||
"target_defaults": {
|
||||
"cflags": [],
|
||||
"default_configuration": "Release",
|
||||
"defines": [],
|
||||
"include_dirs": [],
|
||||
"libraries": []
|
||||
},
|
||||
"variables": {
|
||||
"clang": 0,
|
||||
"gcc_version": 42,
|
||||
"host_arch": "x64",
|
||||
"node_install_npm": "true",
|
||||
"node_prefix": "",
|
||||
"node_shared_cares": "false",
|
||||
"node_shared_http_parser": "false",
|
||||
"node_shared_libuv": "false",
|
||||
"node_shared_openssl": "false",
|
||||
"node_shared_v8": "false",
|
||||
"node_shared_zlib": "false",
|
||||
"node_tag": "",
|
||||
"node_unsafe_optimizations": 0,
|
||||
"node_use_dtrace": "true",
|
||||
"node_use_etw": "false",
|
||||
"node_use_openssl": "true",
|
||||
"node_use_perfctr": "false",
|
||||
"python": "/usr/bin/python",
|
||||
"target_arch": "x64",
|
||||
"v8_enable_gdbjit": 0,
|
||||
"v8_no_strict_aliasing": 1,
|
||||
"v8_use_snapshot": "false",
|
||||
"nodedir": "/Users/azat/.node-gyp/0.10.12",
|
||||
"copy_dev_lib": "true",
|
||||
"standalone_static_library": 1,
|
||||
"save_dev": "",
|
||||
"browser": "",
|
||||
"viewer": "man",
|
||||
"rollback": "true",
|
||||
"usage": "",
|
||||
"globalignorefile": "/usr/local/etc/npmignore",
|
||||
"init_author_url": "",
|
||||
"shell": "/bin/zsh",
|
||||
"parseable": "",
|
||||
"shrinkwrap": "true",
|
||||
"email": "hi@azat.co",
|
||||
"userignorefile": "/Users/azat/.npmignore",
|
||||
"cache_max": "null",
|
||||
"init_author_email": "",
|
||||
"sign_git_tag": "",
|
||||
"ignore": "",
|
||||
"long": "",
|
||||
"registry": "https://registry.npmjs.org/",
|
||||
"fetch_retries": "2",
|
||||
"npat": "",
|
||||
"message": "%s",
|
||||
"versions": "",
|
||||
"globalconfig": "/usr/local/etc/npmrc",
|
||||
"always_auth": "",
|
||||
"cache_lock_retries": "10",
|
||||
"fetch_retry_mintimeout": "10000",
|
||||
"proprietary_attribs": "true",
|
||||
"coverage": "",
|
||||
"json": "",
|
||||
"pre": "",
|
||||
"description": "true",
|
||||
"engine_strict": "",
|
||||
"https_proxy": "",
|
||||
"init_module": "/Users/azat/.npm-init.js",
|
||||
"userconfig": "/Users/azat/.npmrc",
|
||||
"npaturl": "http://npat.npmjs.org/",
|
||||
"node_version": "v0.10.12",
|
||||
"user": "",
|
||||
"editor": "vi",
|
||||
"save": "",
|
||||
"tag": "latest",
|
||||
"global": "",
|
||||
"username": "azat",
|
||||
"optional": "true",
|
||||
"bin_links": "true",
|
||||
"force": "",
|
||||
"searchopts": "",
|
||||
"depth": "null",
|
||||
"rebuild_bundle": "true",
|
||||
"searchsort": "name",
|
||||
"unicode": "true",
|
||||
"yes": "",
|
||||
"fetch_retry_maxtimeout": "60000",
|
||||
"strict_ssl": "true",
|
||||
"dev": "",
|
||||
"fetch_retry_factor": "10",
|
||||
"group": "20",
|
||||
"cache_lock_stale": "60000",
|
||||
"version": "",
|
||||
"cache_min": "10",
|
||||
"cache": "/Users/azat/.npm",
|
||||
"searchexclude": "",
|
||||
"color": "true",
|
||||
"save_optional": "",
|
||||
"user_agent": "node/v0.10.12 darwin x64",
|
||||
"cache_lock_wait": "10000",
|
||||
"production": "",
|
||||
"save_bundle": "",
|
||||
"init_version": "0.0.0",
|
||||
"umask": "18",
|
||||
"git": "git",
|
||||
"init_author_name": "",
|
||||
"onload_script": "",
|
||||
"tmp": "/var/folders/q5/0zn95nld30b7fnhz5yywb52m0000gn/T/",
|
||||
"unsafe_perm": "true",
|
||||
"link": "",
|
||||
"prefix": "/usr/local"
|
||||
}
|
||||
}
|
||||
211
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool
generated
vendored
Executable file
211
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build/gyp-mac-tool
generated
vendored
Executable file
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python
|
||||
# Generated by gyp. Do not edit.
|
||||
# Copyright (c) 2012 Google Inc. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""Utility functions to perform Xcode-style build steps.
|
||||
|
||||
These functions are executed via gyp-mac-tool when using the Makefile generator.
|
||||
"""
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import plistlib
|
||||
import re
|
||||
import shutil
|
||||
import string
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main(args):
|
||||
executor = MacTool()
|
||||
exit_code = executor.Dispatch(args)
|
||||
if exit_code is not None:
|
||||
sys.exit(exit_code)
|
||||
|
||||
|
||||
class MacTool(object):
|
||||
"""This class performs all the Mac tooling steps. The methods can either be
|
||||
executed directly, or dispatched from an argument list."""
|
||||
|
||||
def Dispatch(self, args):
|
||||
"""Dispatches a string command to a method."""
|
||||
if len(args) < 1:
|
||||
raise Exception("Not enough arguments")
|
||||
|
||||
method = "Exec%s" % self._CommandifyName(args[0])
|
||||
return getattr(self, method)(*args[1:])
|
||||
|
||||
def _CommandifyName(self, name_string):
|
||||
"""Transforms a tool name like copy-info-plist to CopyInfoPlist"""
|
||||
return name_string.title().replace('-', '')
|
||||
|
||||
def ExecCopyBundleResource(self, source, dest):
|
||||
"""Copies a resource file to the bundle/Resources directory, performing any
|
||||
necessary compilation on each resource."""
|
||||
extension = os.path.splitext(source)[1].lower()
|
||||
if os.path.isdir(source):
|
||||
# Copy tree.
|
||||
if os.path.exists(dest):
|
||||
shutil.rmtree(dest)
|
||||
shutil.copytree(source, dest)
|
||||
elif extension == '.xib':
|
||||
return self._CopyXIBFile(source, dest)
|
||||
elif extension == '.strings':
|
||||
self._CopyStringsFile(source, dest)
|
||||
else:
|
||||
shutil.copyfile(source, dest)
|
||||
|
||||
def _CopyXIBFile(self, source, dest):
|
||||
"""Compiles a XIB file with ibtool into a binary plist in the bundle."""
|
||||
tools_dir = os.environ.get('DEVELOPER_BIN_DIR', '/usr/bin')
|
||||
args = [os.path.join(tools_dir, 'ibtool'), '--errors', '--warnings',
|
||||
'--notices', '--output-format', 'human-readable-text', '--compile',
|
||||
dest, source]
|
||||
ibtool_section_re = re.compile(r'/\*.*\*/')
|
||||
ibtool_re = re.compile(r'.*note:.*is clipping its content')
|
||||
ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE)
|
||||
current_section_header = None
|
||||
for line in ibtoolout.stdout:
|
||||
if ibtool_section_re.match(line):
|
||||
current_section_header = line
|
||||
elif not ibtool_re.match(line):
|
||||
if current_section_header:
|
||||
sys.stdout.write(current_section_header)
|
||||
current_section_header = None
|
||||
sys.stdout.write(line)
|
||||
return ibtoolout.returncode
|
||||
|
||||
def _CopyStringsFile(self, source, dest):
|
||||
"""Copies a .strings file using iconv to reconvert the input into UTF-16."""
|
||||
input_code = self._DetectInputEncoding(source) or "UTF-8"
|
||||
fp = open(dest, 'w')
|
||||
args = ['/usr/bin/iconv', '--from-code', input_code, '--to-code',
|
||||
'UTF-16', source]
|
||||
subprocess.call(args, stdout=fp)
|
||||
fp.close()
|
||||
|
||||
def _DetectInputEncoding(self, file_name):
|
||||
"""Reads the first few bytes from file_name and tries to guess the text
|
||||
encoding. Returns None as a guess if it can't detect it."""
|
||||
fp = open(file_name, 'rb')
|
||||
try:
|
||||
header = fp.read(3)
|
||||
except e:
|
||||
fp.close()
|
||||
return None
|
||||
fp.close()
|
||||
if header.startswith("\xFE\xFF"):
|
||||
return "UTF-16BE"
|
||||
elif header.startswith("\xFF\xFE"):
|
||||
return "UTF-16LE"
|
||||
elif header.startswith("\xEF\xBB\xBF"):
|
||||
return "UTF-8"
|
||||
else:
|
||||
return None
|
||||
|
||||
def ExecCopyInfoPlist(self, source, dest):
|
||||
"""Copies the |source| Info.plist to the destination directory |dest|."""
|
||||
# Read the source Info.plist into memory.
|
||||
fd = open(source, 'r')
|
||||
lines = fd.read()
|
||||
fd.close()
|
||||
|
||||
# Go through all the environment variables and replace them as variables in
|
||||
# the file.
|
||||
for key in os.environ:
|
||||
if key.startswith('_'):
|
||||
continue
|
||||
evar = '${%s}' % key
|
||||
lines = string.replace(lines, evar, os.environ[key])
|
||||
|
||||
# Write out the file with variables replaced.
|
||||
fd = open(dest, 'w')
|
||||
fd.write(lines)
|
||||
fd.close()
|
||||
|
||||
# Now write out PkgInfo file now that the Info.plist file has been
|
||||
# "compiled".
|
||||
self._WritePkgInfo(dest)
|
||||
|
||||
def _WritePkgInfo(self, info_plist):
|
||||
"""This writes the PkgInfo file from the data stored in Info.plist."""
|
||||
plist = plistlib.readPlist(info_plist)
|
||||
if not plist:
|
||||
return
|
||||
|
||||
# Only create PkgInfo for executable types.
|
||||
package_type = plist['CFBundlePackageType']
|
||||
if package_type != 'APPL':
|
||||
return
|
||||
|
||||
# The format of PkgInfo is eight characters, representing the bundle type
|
||||
# and bundle signature, each four characters. If that is missing, four
|
||||
# '?' characters are used instead.
|
||||
signature_code = plist.get('CFBundleSignature', '????')
|
||||
if len(signature_code) != 4: # Wrong length resets everything, too.
|
||||
signature_code = '?' * 4
|
||||
|
||||
dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo')
|
||||
fp = open(dest, 'w')
|
||||
fp.write('%s%s' % (package_type, signature_code))
|
||||
fp.close()
|
||||
|
||||
def ExecFlock(self, lockfile, *cmd_list):
|
||||
"""Emulates the most basic behavior of Linux's flock(1)."""
|
||||
# Rely on exception handling to report errors.
|
||||
fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666)
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
return subprocess.call(cmd_list)
|
||||
|
||||
def ExecFilterLibtool(self, *cmd_list):
|
||||
"""Calls libtool and filters out 'libtool: file: foo.o has no symbols'."""
|
||||
libtool_re = re.compile(r'^libtool: file: .* has no symbols$')
|
||||
libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE)
|
||||
_, err = libtoolout.communicate()
|
||||
for line in err.splitlines():
|
||||
if not libtool_re.match(line):
|
||||
print >>sys.stderr, line
|
||||
return libtoolout.returncode
|
||||
|
||||
def ExecPackageFramework(self, framework, version):
|
||||
"""Takes a path to Something.framework and the Current version of that and
|
||||
sets up all the symlinks."""
|
||||
# Find the name of the binary based on the part before the ".framework".
|
||||
binary = os.path.basename(framework).split('.')[0]
|
||||
|
||||
CURRENT = 'Current'
|
||||
RESOURCES = 'Resources'
|
||||
VERSIONS = 'Versions'
|
||||
|
||||
if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)):
|
||||
# Binary-less frameworks don't seem to contain symlinks (see e.g.
|
||||
# chromium's out/Debug/org.chromium.Chromium.manifest/ bundle).
|
||||
return
|
||||
|
||||
# Move into the framework directory to set the symlinks correctly.
|
||||
pwd = os.getcwd()
|
||||
os.chdir(framework)
|
||||
|
||||
# Set up the Current version.
|
||||
self._Relink(version, os.path.join(VERSIONS, CURRENT))
|
||||
|
||||
# Set up the root symlinks.
|
||||
self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary)
|
||||
self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES)
|
||||
|
||||
# Back to where we were before!
|
||||
os.chdir(pwd)
|
||||
|
||||
def _Relink(self, dest, link):
|
||||
"""Creates a symlink to |dest| named |link|. If |link| already exists,
|
||||
it is overwritten."""
|
||||
if os.path.lexists(link):
|
||||
os.remove(link)
|
||||
os.symlink(dest, link)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
7
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build_browser.js
generated
vendored
Normal file
7
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/build_browser.js
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
require('one');
|
||||
|
||||
one('./package.json')
|
||||
.tie('bson', BSON)
|
||||
// .exclude('buffer')
|
||||
.tie('buffer', {})
|
||||
.save('./browser_build/bson.js')
|
||||
0
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/builderror.log
generated
vendored
Normal file
0
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/builderror.log
generated
vendored
Normal file
28
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/Makefile
generated
vendored
Normal file
28
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/Makefile
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
NODE = node
|
||||
name = all
|
||||
JOBS = 1
|
||||
|
||||
all:
|
||||
rm -rf build .lock-wscript bson.node
|
||||
node-waf configure build
|
||||
cp -R ./build/Release/bson.node . || true
|
||||
|
||||
all_debug:
|
||||
rm -rf build .lock-wscript bson.node
|
||||
node-waf --debug configure build
|
||||
cp -R ./build/Release/bson.node . || true
|
||||
|
||||
clang:
|
||||
rm -rf build .lock-wscript bson.node
|
||||
CXX=clang node-waf configure build
|
||||
cp -R ./build/Release/bson.node . || true
|
||||
|
||||
clang_debug:
|
||||
rm -rf build .lock-wscript bson.node
|
||||
CXX=clang node-waf --debug configure build
|
||||
cp -R ./build/Release/bson.node . || true
|
||||
|
||||
clean:
|
||||
rm -rf build .lock-wscript bson.node
|
||||
|
||||
.PHONY: all
|
||||
1006
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/bson.cc
generated
vendored
Normal file
1006
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/bson.cc
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
273
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/bson.h
generated
vendored
Normal file
273
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/bson.h
generated
vendored
Normal file
@@ -0,0 +1,273 @@
|
||||
//===========================================================================
|
||||
|
||||
#ifndef BSON_H_
|
||||
#define BSON_H_
|
||||
|
||||
//===========================================================================
|
||||
|
||||
#define USE_MISALIGNED_MEMORY_ACCESS 1
|
||||
|
||||
#include <node.h>
|
||||
#include <node_object_wrap.h>
|
||||
#include <v8.h>
|
||||
|
||||
using namespace v8;
|
||||
using namespace node;
|
||||
|
||||
//===========================================================================
|
||||
|
||||
enum BsonType
|
||||
{
|
||||
BSON_TYPE_NUMBER = 1,
|
||||
BSON_TYPE_STRING = 2,
|
||||
BSON_TYPE_OBJECT = 3,
|
||||
BSON_TYPE_ARRAY = 4,
|
||||
BSON_TYPE_BINARY = 5,
|
||||
BSON_TYPE_UNDEFINED = 6,
|
||||
BSON_TYPE_OID = 7,
|
||||
BSON_TYPE_BOOLEAN = 8,
|
||||
BSON_TYPE_DATE = 9,
|
||||
BSON_TYPE_NULL = 10,
|
||||
BSON_TYPE_REGEXP = 11,
|
||||
BSON_TYPE_CODE = 13,
|
||||
BSON_TYPE_SYMBOL = 14,
|
||||
BSON_TYPE_CODE_W_SCOPE = 15,
|
||||
BSON_TYPE_INT = 16,
|
||||
BSON_TYPE_TIMESTAMP = 17,
|
||||
BSON_TYPE_LONG = 18,
|
||||
BSON_TYPE_MAX_KEY = 0x7f,
|
||||
BSON_TYPE_MIN_KEY = 0xff
|
||||
};
|
||||
|
||||
//===========================================================================
|
||||
|
||||
template<typename T> class BSONSerializer;
|
||||
|
||||
class BSON : public ObjectWrap {
|
||||
public:
|
||||
BSON();
|
||||
~BSON() {}
|
||||
|
||||
static void Initialize(Handle<Object> target);
|
||||
static Handle<Value> BSONDeserializeStream(const Arguments &args);
|
||||
|
||||
// JS based objects
|
||||
static Handle<Value> BSONSerialize(const Arguments &args);
|
||||
static Handle<Value> BSONDeserialize(const Arguments &args);
|
||||
|
||||
// Calculate size of function
|
||||
static Handle<Value> CalculateObjectSize(const Arguments &args);
|
||||
static Handle<Value> SerializeWithBufferAndIndex(const Arguments &args);
|
||||
|
||||
// Constructor used for creating new BSON objects from C++
|
||||
static Persistent<FunctionTemplate> constructor_template;
|
||||
|
||||
private:
|
||||
static Handle<Value> New(const Arguments &args);
|
||||
static Handle<Value> deserialize(BSON *bson, char *data, uint32_t dataLength, uint32_t startIndex, bool is_array_item);
|
||||
|
||||
// BSON type instantiate functions
|
||||
Persistent<Function> longConstructor;
|
||||
Persistent<Function> objectIDConstructor;
|
||||
Persistent<Function> binaryConstructor;
|
||||
Persistent<Function> codeConstructor;
|
||||
Persistent<Function> dbrefConstructor;
|
||||
Persistent<Function> symbolConstructor;
|
||||
Persistent<Function> doubleConstructor;
|
||||
Persistent<Function> timestampConstructor;
|
||||
Persistent<Function> minKeyConstructor;
|
||||
Persistent<Function> maxKeyConstructor;
|
||||
|
||||
// Equality Objects
|
||||
Persistent<String> longString;
|
||||
Persistent<String> objectIDString;
|
||||
Persistent<String> binaryString;
|
||||
Persistent<String> codeString;
|
||||
Persistent<String> dbrefString;
|
||||
Persistent<String> symbolString;
|
||||
Persistent<String> doubleString;
|
||||
Persistent<String> timestampString;
|
||||
Persistent<String> minKeyString;
|
||||
Persistent<String> maxKeyString;
|
||||
|
||||
// Equality speed up comparison objects
|
||||
Persistent<String> _bsontypeString;
|
||||
Persistent<String> _longLowString;
|
||||
Persistent<String> _longHighString;
|
||||
Persistent<String> _objectIDidString;
|
||||
Persistent<String> _binaryPositionString;
|
||||
Persistent<String> _binarySubTypeString;
|
||||
Persistent<String> _binaryBufferString;
|
||||
Persistent<String> _doubleValueString;
|
||||
Persistent<String> _symbolValueString;
|
||||
|
||||
Persistent<String> _dbRefRefString;
|
||||
Persistent<String> _dbRefIdRefString;
|
||||
Persistent<String> _dbRefDbRefString;
|
||||
Persistent<String> _dbRefNamespaceString;
|
||||
Persistent<String> _dbRefDbString;
|
||||
Persistent<String> _dbRefOidString;
|
||||
|
||||
Persistent<String> _codeCodeString;
|
||||
Persistent<String> _codeScopeString;
|
||||
Persistent<String> _toBSONString;
|
||||
|
||||
Local<Object> GetSerializeObject(const Handle<Value>& object);
|
||||
|
||||
template<typename T> friend class BSONSerializer;
|
||||
friend class BSONDeserializer;
|
||||
};
|
||||
|
||||
//===========================================================================
|
||||
|
||||
class CountStream
|
||||
{
|
||||
public:
|
||||
CountStream() : count(0) { }
|
||||
|
||||
void WriteByte(int value) { ++count; }
|
||||
void WriteByte(const Handle<Object>&, const Handle<String>&) { ++count; }
|
||||
void WriteBool(const Handle<Value>& value) { ++count; }
|
||||
void WriteInt32(int32_t value) { count += 4; }
|
||||
void WriteInt32(const Handle<Value>& value) { count += 4; }
|
||||
void WriteInt32(const Handle<Object>& object, const Handle<String>& key) { count += 4; }
|
||||
void WriteInt64(int64_t value) { count += 8; }
|
||||
void WriteInt64(const Handle<Value>& value) { count += 8; }
|
||||
void WriteDouble(double value) { count += 8; }
|
||||
void WriteDouble(const Handle<Value>& value) { count += 8; }
|
||||
void WriteDouble(const Handle<Object>&, const Handle<String>&) { count += 8; }
|
||||
void WriteUInt32String(uint32_t name) { char buffer[32]; count += sprintf(buffer, "%u", name) + 1; }
|
||||
void WriteLengthPrefixedString(const Local<String>& value) { count += value->Utf8Length()+5; }
|
||||
void WriteObjectId(const Handle<Object>& object, const Handle<String>& key) { count += 12; }
|
||||
void WriteString(const Local<String>& value) { count += value->Utf8Length() + 1; } // This returns the number of bytes exclusive of the NULL terminator
|
||||
void WriteData(const char* data, size_t length) { count += length; }
|
||||
|
||||
void* BeginWriteType() { ++count; return NULL; }
|
||||
void CommitType(void*, BsonType) { }
|
||||
void* BeginWriteSize() { count += 4; return NULL; }
|
||||
void CommitSize(void*) { }
|
||||
|
||||
size_t GetSerializeSize() const { return count; }
|
||||
|
||||
// Do nothing. CheckKey is implemented for DataStream
|
||||
void CheckKey(const Local<String>&) { }
|
||||
|
||||
private:
|
||||
size_t count;
|
||||
};
|
||||
|
||||
class DataStream
|
||||
{
|
||||
public:
|
||||
DataStream(char* aDestinationBuffer) : destinationBuffer(aDestinationBuffer), p(aDestinationBuffer) { }
|
||||
|
||||
void WriteByte(int value) { *p++ = value; }
|
||||
void WriteByte(const Handle<Object>& object, const Handle<String>& key) { *p++ = object->Get(key)->Int32Value(); }
|
||||
#if USE_MISALIGNED_MEMORY_ACCESS
|
||||
void WriteInt32(int32_t value) { *reinterpret_cast<int32_t*>(p) = value; p += 4; }
|
||||
void WriteInt64(int64_t value) { *reinterpret_cast<int64_t*>(p) = value; p += 8; }
|
||||
void WriteDouble(double value) { *reinterpret_cast<double*>(p) = value; p += 8; }
|
||||
#else
|
||||
void WriteInt32(int32_t value) { memcpy(p, &value, 4); p += 4; }
|
||||
void WriteInt64(int64_t value) { memcpy(p, &value, 8); p += 8; }
|
||||
void WriteDouble(double value) { memcpy(p, &value, 8); p += 8; }
|
||||
#endif
|
||||
void WriteBool(const Handle<Value>& value) { WriteByte(value->BooleanValue() ? 1 : 0); }
|
||||
void WriteInt32(const Handle<Value>& value) { WriteInt32(value->Int32Value()); }
|
||||
void WriteInt32(const Handle<Object>& object, const Handle<String>& key) { WriteInt32(object->Get(key)); }
|
||||
void WriteInt64(const Handle<Value>& value) { WriteInt64(value->IntegerValue()); }
|
||||
void WriteDouble(const Handle<Value>& value) { WriteDouble(value->NumberValue()); }
|
||||
void WriteDouble(const Handle<Object>& object, const Handle<String>& key) { WriteDouble(object->Get(key)); }
|
||||
void WriteUInt32String(uint32_t name) { p += sprintf(p, "%u", name) + 1; }
|
||||
void WriteLengthPrefixedString(const Local<String>& value) { WriteInt32(value->Utf8Length()+1); WriteString(value); }
|
||||
void WriteObjectId(const Handle<Object>& object, const Handle<String>& key);
|
||||
void WriteString(const Local<String>& value) { p += value->WriteUtf8(p); } // This returns the number of bytes inclusive of the NULL terminator.
|
||||
void WriteData(const char* data, size_t length) { memcpy(p, data, length); p += length; }
|
||||
|
||||
void* BeginWriteType() { void* returnValue = p; p++; return returnValue; }
|
||||
void CommitType(void* beginPoint, BsonType value) { *reinterpret_cast<unsigned char*>(beginPoint) = value; }
|
||||
void* BeginWriteSize() { void* returnValue = p; p += 4; return returnValue; }
|
||||
|
||||
#if USE_MISALIGNED_MEMORY_ACCESS
|
||||
void CommitSize(void* beginPoint) { *reinterpret_cast<int32_t*>(beginPoint) = (int32_t) (p - (char*) beginPoint); }
|
||||
#else
|
||||
void CommitSize(void* beginPoint) { int32_t value = (int32_t) (p - (char*) beginPoint); memcpy(beginPoint, &value, 4); }
|
||||
#endif
|
||||
|
||||
size_t GetSerializeSize() const { return p - destinationBuffer; }
|
||||
|
||||
void CheckKey(const Local<String>& keyName);
|
||||
|
||||
protected:
|
||||
char *const destinationBuffer; // base, never changes
|
||||
char* p; // cursor into buffer
|
||||
};
|
||||
|
||||
template<typename T> class BSONSerializer : public T
|
||||
{
|
||||
private:
|
||||
typedef T Inherited;
|
||||
|
||||
public:
|
||||
BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions) : Inherited(), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { }
|
||||
BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions, char* parentParam) : Inherited(parentParam), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { }
|
||||
|
||||
void SerializeDocument(const Handle<Value>& value);
|
||||
void SerializeArray(const Handle<Value>& value);
|
||||
void SerializeValue(void* typeLocation, const Handle<Value>& value);
|
||||
|
||||
private:
|
||||
bool checkKeys;
|
||||
bool serializeFunctions;
|
||||
BSON* bson;
|
||||
};
|
||||
|
||||
//===========================================================================
|
||||
|
||||
class BSONDeserializer
|
||||
{
|
||||
public:
|
||||
BSONDeserializer(BSON* aBson, char* data, size_t length);
|
||||
BSONDeserializer(BSONDeserializer& parentSerializer, size_t length);
|
||||
|
||||
Handle<Value> DeserializeDocument();
|
||||
|
||||
bool HasMoreData() const { return p < pEnd; }
|
||||
Local<String> ReadCString();
|
||||
uint32_t ReadIntegerString();
|
||||
int32_t ReadRegexOptions();
|
||||
Local<String> ReadString();
|
||||
Local<String> ReadObjectId();
|
||||
|
||||
unsigned char ReadByte() { return *reinterpret_cast<unsigned char*>(p++); }
|
||||
#if USE_MISALIGNED_MEMORY_ACCESS
|
||||
int32_t ReadInt32() { int32_t returnValue = *reinterpret_cast<int32_t*>(p); p += 4; return returnValue; }
|
||||
uint32_t ReadUInt32() { uint32_t returnValue = *reinterpret_cast<uint32_t*>(p); p += 4; return returnValue; }
|
||||
int64_t ReadInt64() { int64_t returnValue = *reinterpret_cast<int64_t*>(p); p += 8; return returnValue; }
|
||||
double ReadDouble() { double returnValue = *reinterpret_cast<double*>(p); p += 8; return returnValue; }
|
||||
#else
|
||||
int32_t ReadInt32() { int32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; }
|
||||
uint32_t ReadUInt32() { uint32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; }
|
||||
int64_t ReadInt64() { int64_t returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; }
|
||||
double ReadDouble() { double returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; }
|
||||
#endif
|
||||
|
||||
size_t GetSerializeSize() const { return p - pStart; }
|
||||
|
||||
private:
|
||||
Handle<Value> DeserializeArray();
|
||||
Handle<Value> DeserializeValue(BsonType type);
|
||||
Handle<Value> DeserializeDocumentInternal();
|
||||
Handle<Value> DeserializeArrayInternal();
|
||||
|
||||
BSON* bson;
|
||||
char* const pStart;
|
||||
char* p;
|
||||
char* const pEnd;
|
||||
};
|
||||
|
||||
//===========================================================================
|
||||
|
||||
#endif // BSON_H_
|
||||
|
||||
//===========================================================================
|
||||
30
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/index.js
generated
vendored
Normal file
30
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/index.js
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
var bson = null;
|
||||
|
||||
// Load the precompiled win32 binary
|
||||
if(process.platform == "win32" && process.arch == "x64") {
|
||||
bson = require('./win32/x64/bson');
|
||||
} else if(process.platform == "win32" && process.arch == "ia32") {
|
||||
bson = require('./win32/ia32/bson');
|
||||
} else {
|
||||
bson = require('../build/Release/bson');
|
||||
}
|
||||
|
||||
exports.BSON = bson.BSON;
|
||||
exports.Long = require('../lib/bson/long').Long;
|
||||
exports.ObjectID = require('../lib/bson/objectid').ObjectID;
|
||||
exports.DBRef = require('../lib/bson/db_ref').DBRef;
|
||||
exports.Code = require('../lib/bson/code').Code;
|
||||
exports.Timestamp = require('../lib/bson/timestamp').Timestamp;
|
||||
exports.Binary = require('../lib/bson/binary').Binary;
|
||||
exports.Double = require('../lib/bson/double').Double;
|
||||
exports.MaxKey = require('../lib/bson/max_key').MaxKey;
|
||||
exports.MinKey = require('../lib/bson/min_key').MinKey;
|
||||
exports.Symbol = require('../lib/bson/symbol').Symbol;
|
||||
|
||||
// Just add constants tot he Native BSON parser
|
||||
exports.BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
exports.BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
exports.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
exports.BSON.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
exports.BSON.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
exports.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node
generated
vendored
Normal file
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node
generated
vendored
Normal file
Binary file not shown.
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node
generated
vendored
Normal file
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node
generated
vendored
Normal file
Binary file not shown.
39
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/wscript
generated
vendored
Normal file
39
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/ext/wscript
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
import Options
|
||||
from os import unlink, symlink, popen
|
||||
from os.path import exists
|
||||
|
||||
srcdir = "."
|
||||
blddir = "build"
|
||||
VERSION = "0.1.0"
|
||||
|
||||
def set_options(opt):
|
||||
opt.tool_options("compiler_cxx")
|
||||
opt.add_option( '--debug'
|
||||
, action='store_true'
|
||||
, default=False
|
||||
, help='Build debug variant [Default: False]'
|
||||
, dest='debug'
|
||||
)
|
||||
|
||||
def configure(conf):
|
||||
conf.check_tool("compiler_cxx")
|
||||
conf.check_tool("node_addon")
|
||||
conf.env.append_value('CXXFLAGS', ['-O3', '-funroll-loops'])
|
||||
|
||||
# conf.env.append_value('CXXFLAGS', ['-DDEBUG', '-g', '-O0', '-Wall', '-Wextra'])
|
||||
# conf.check(lib='node', libpath=['/usr/lib', '/usr/local/lib'], uselib_store='NODE')
|
||||
|
||||
def build(bld):
|
||||
obj = bld.new_task_gen("cxx", "shlib", "node_addon")
|
||||
obj.target = "bson"
|
||||
obj.source = ["bson.cc"]
|
||||
# obj.uselib = "NODE"
|
||||
|
||||
def shutdown():
|
||||
# HACK to get compress.node out of build directory.
|
||||
# better way to do this?
|
||||
if Options.commands['clean']:
|
||||
if exists('bson.node'): unlink('bson.node')
|
||||
else:
|
||||
if exists('build/default/bson.node') and not exists('bson.node'):
|
||||
symlink('build/default/bson.node', 'bson.node')
|
||||
339
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/binary.js
generated
vendored
Normal file
339
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/binary.js
generated
vendored
Normal file
@@ -0,0 +1,339 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
if(typeof window === 'undefined') {
|
||||
var Buffer = require('buffer').Buffer; // TODO just use global Buffer
|
||||
}
|
||||
|
||||
// Binary default subtype
|
||||
var BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var writeStringToArray = function(data) {
|
||||
// Create a buffer
|
||||
var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length);
|
||||
// Write the content to the buffer
|
||||
for(var i = 0; i < data.length; i++) {
|
||||
buffer[i] = data.charCodeAt(i);
|
||||
}
|
||||
// Write the string to the buffer
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert Array ot Uint8Array to Binary String
|
||||
*
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) {
|
||||
var result = "";
|
||||
for(var i = startIndex; i < endIndex; i++) {
|
||||
result = result + String.fromCharCode(byteArray[i]);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* A class representation of the BSON Binary type.
|
||||
*
|
||||
* Sub types
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type.
|
||||
* - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type.
|
||||
*
|
||||
* @class Represents the Binary BSON type.
|
||||
* @param {Buffer} buffer a buffer object containing the binary data.
|
||||
* @param {Number} [subType] the option binary type.
|
||||
* @return {Grid}
|
||||
*/
|
||||
function Binary(buffer, subType) {
|
||||
if(!(this instanceof Binary)) return new Binary(buffer, subType);
|
||||
|
||||
this._bsontype = 'Binary';
|
||||
|
||||
if(buffer instanceof Number) {
|
||||
this.sub_type = buffer;
|
||||
this.position = 0;
|
||||
} else {
|
||||
this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType;
|
||||
this.position = 0;
|
||||
}
|
||||
|
||||
if(buffer != null && !(buffer instanceof Number)) {
|
||||
// Only accept Buffer, Uint8Array or Arrays
|
||||
if(typeof buffer == 'string') {
|
||||
// Different ways of writing the length of the string for the different types
|
||||
if(typeof Buffer != 'undefined') {
|
||||
this.buffer = new Buffer(buffer);
|
||||
} else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) {
|
||||
this.buffer = writeStringToArray(buffer);
|
||||
} else {
|
||||
throw new Error("only String, Buffer, Uint8Array or Array accepted");
|
||||
}
|
||||
} else {
|
||||
this.buffer = buffer;
|
||||
}
|
||||
this.position = buffer.length;
|
||||
} else {
|
||||
if(typeof Buffer != 'undefined') {
|
||||
this.buffer = new Buffer(Binary.BUFFER_SIZE);
|
||||
} else if(typeof Uint8Array != 'undefined'){
|
||||
this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE));
|
||||
} else {
|
||||
this.buffer = new Array(Binary.BUFFER_SIZE);
|
||||
}
|
||||
// Set position to start of buffer
|
||||
this.position = 0;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates this binary with byte_value.
|
||||
*
|
||||
* @param {Character} byte_value a single byte we wish to write.
|
||||
* @api public
|
||||
*/
|
||||
Binary.prototype.put = function put(byte_value) {
|
||||
// If it's a string and a has more than one character throw an error
|
||||
if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array");
|
||||
if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255");
|
||||
|
||||
// Decode the byte value once
|
||||
var decoded_byte = null;
|
||||
if(typeof byte_value == 'string') {
|
||||
decoded_byte = byte_value.charCodeAt(0);
|
||||
} else if(byte_value['length'] != null) {
|
||||
decoded_byte = byte_value[0];
|
||||
} else {
|
||||
decoded_byte = byte_value;
|
||||
}
|
||||
|
||||
if(this.buffer.length > this.position) {
|
||||
this.buffer[this.position++] = decoded_byte;
|
||||
} else {
|
||||
if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) {
|
||||
// Create additional overflow buffer
|
||||
var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length);
|
||||
// Combine the two buffers together
|
||||
this.buffer.copy(buffer, 0, 0, this.buffer.length);
|
||||
this.buffer = buffer;
|
||||
this.buffer[this.position++] = decoded_byte;
|
||||
} else {
|
||||
var buffer = null;
|
||||
// Create a new buffer (typed or normal array)
|
||||
if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') {
|
||||
buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length));
|
||||
} else {
|
||||
buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length);
|
||||
}
|
||||
|
||||
// We need to copy all the content to the new array
|
||||
for(var i = 0; i < this.buffer.length; i++) {
|
||||
buffer[i] = this.buffer[i];
|
||||
}
|
||||
|
||||
// Reassign the buffer
|
||||
this.buffer = buffer;
|
||||
// Write the byte
|
||||
this.buffer[this.position++] = decoded_byte;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes a buffer or string to the binary.
|
||||
*
|
||||
* @param {Buffer|String} string a string or buffer to be written to the Binary BSON object.
|
||||
* @param {Number} offset specify the binary of where to write the content.
|
||||
* @api public
|
||||
*/
|
||||
Binary.prototype.write = function write(string, offset) {
|
||||
offset = typeof offset == 'number' ? offset : this.position;
|
||||
|
||||
// If the buffer is to small let's extend the buffer
|
||||
if(this.buffer.length < offset + string.length) {
|
||||
var buffer = null;
|
||||
// If we are in node.js
|
||||
if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) {
|
||||
buffer = new Buffer(this.buffer.length + string.length);
|
||||
this.buffer.copy(buffer, 0, 0, this.buffer.length);
|
||||
} else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') {
|
||||
// Create a new buffer
|
||||
buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length))
|
||||
// Copy the content
|
||||
for(var i = 0; i < this.position; i++) {
|
||||
buffer[i] = this.buffer[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Assign the new buffer
|
||||
this.buffer = buffer;
|
||||
}
|
||||
|
||||
if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) {
|
||||
string.copy(this.buffer, offset, 0, string.length);
|
||||
this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position;
|
||||
// offset = string.length
|
||||
} else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) {
|
||||
this.buffer.write(string, 'binary', offset);
|
||||
this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position;
|
||||
// offset = string.length;
|
||||
} else if(Object.prototype.toString.call(string) == '[object Uint8Array]'
|
||||
|| Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') {
|
||||
for(var i = 0; i < string.length; i++) {
|
||||
this.buffer[offset++] = string[i];
|
||||
}
|
||||
|
||||
this.position = offset > this.position ? offset : this.position;
|
||||
} else if(typeof string == 'string') {
|
||||
for(var i = 0; i < string.length; i++) {
|
||||
this.buffer[offset++] = string.charCodeAt(i);
|
||||
}
|
||||
|
||||
this.position = offset > this.position ? offset : this.position;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads **length** bytes starting at **position**.
|
||||
*
|
||||
* @param {Number} position read from the given position in the Binary.
|
||||
* @param {Number} length the number of bytes to read.
|
||||
* @return {Buffer}
|
||||
* @api public
|
||||
*/
|
||||
Binary.prototype.read = function read(position, length) {
|
||||
length = length && length > 0
|
||||
? length
|
||||
: this.position;
|
||||
|
||||
// Let's return the data based on the type we have
|
||||
if(this.buffer['slice']) {
|
||||
return this.buffer.slice(position, position + length);
|
||||
} else {
|
||||
// Create a buffer to keep the result
|
||||
var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length);
|
||||
for(var i = 0; i < length; i++) {
|
||||
buffer[i] = this.buffer[position++];
|
||||
}
|
||||
}
|
||||
// Return the buffer
|
||||
return buffer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the value of this binary as a string.
|
||||
*
|
||||
* @return {String}
|
||||
* @api public
|
||||
*/
|
||||
Binary.prototype.value = function value(asRaw) {
|
||||
asRaw = asRaw == null ? false : asRaw;
|
||||
|
||||
// If it's a node.js buffer object
|
||||
if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) {
|
||||
return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position);
|
||||
} else {
|
||||
if(asRaw) {
|
||||
// we support the slice command use it
|
||||
if(this.buffer['slice'] != null) {
|
||||
return this.buffer.slice(0, this.position);
|
||||
} else {
|
||||
// Create a new buffer to copy content to
|
||||
var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position);
|
||||
// Copy content
|
||||
for(var i = 0; i < this.position; i++) {
|
||||
newBuffer[i] = this.buffer[i];
|
||||
}
|
||||
// Return the buffer
|
||||
return newBuffer;
|
||||
}
|
||||
} else {
|
||||
return convertArraytoUtf8BinaryString(this.buffer, 0, this.position);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Length.
|
||||
*
|
||||
* @return {Number} the length of the binary.
|
||||
* @api public
|
||||
*/
|
||||
Binary.prototype.length = function length() {
|
||||
return this.position;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Binary.prototype.toJSON = function() {
|
||||
return this.buffer != null ? this.buffer.toString('base64') : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Binary.prototype.toString = function(format) {
|
||||
return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : '';
|
||||
}
|
||||
|
||||
Binary.BUFFER_SIZE = 256;
|
||||
|
||||
/**
|
||||
* Default BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_DEFAULT = 0;
|
||||
/**
|
||||
* Function BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_FUNCTION = 1;
|
||||
/**
|
||||
* Byte Array BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_BYTE_ARRAY = 2;
|
||||
/**
|
||||
* OLD UUID BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_UUID_OLD = 3;
|
||||
/**
|
||||
* UUID BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_UUID = 4;
|
||||
/**
|
||||
* MD5 BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_MD5 = 5;
|
||||
/**
|
||||
* User BSON type
|
||||
*
|
||||
* @classconstant SUBTYPE_DEFAULT
|
||||
**/
|
||||
Binary.SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
exports.Binary = Binary;
|
||||
|
||||
385
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js
generated
vendored
Normal file
385
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js
generated
vendored
Normal file
@@ -0,0 +1,385 @@
|
||||
/**
|
||||
* Binary Parser.
|
||||
* Jonas Raoni Soares Silva
|
||||
* http://jsfromhell.com/classes/binary-parser [v1.0]
|
||||
*/
|
||||
var chr = String.fromCharCode;
|
||||
|
||||
var maxBits = [];
|
||||
for (var i = 0; i < 64; i++) {
|
||||
maxBits[i] = Math.pow(2, i);
|
||||
}
|
||||
|
||||
function BinaryParser (bigEndian, allowExceptions) {
|
||||
if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions);
|
||||
|
||||
this.bigEndian = bigEndian;
|
||||
this.allowExceptions = allowExceptions;
|
||||
};
|
||||
|
||||
BinaryParser.warn = function warn (msg) {
|
||||
if (this.allowExceptions) {
|
||||
throw new Error(msg);
|
||||
}
|
||||
|
||||
return 1;
|
||||
};
|
||||
|
||||
BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) {
|
||||
var b = new this.Buffer(this.bigEndian, data);
|
||||
|
||||
b.checkBuffer(precisionBits + exponentBits + 1);
|
||||
|
||||
var bias = maxBits[exponentBits - 1] - 1
|
||||
, signal = b.readBits(precisionBits + exponentBits, 1)
|
||||
, exponent = b.readBits(precisionBits, exponentBits)
|
||||
, significand = 0
|
||||
, divisor = 2
|
||||
, curByte = b.buffer.length + (-precisionBits >> 3) - 1;
|
||||
|
||||
do {
|
||||
for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 );
|
||||
} while (precisionBits -= startBit);
|
||||
|
||||
return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 );
|
||||
};
|
||||
|
||||
BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) {
|
||||
var b = new this.Buffer(this.bigEndian || forceBigEndian, data)
|
||||
, x = b.readBits(0, bits)
|
||||
, max = maxBits[bits]; //max = Math.pow( 2, bits );
|
||||
|
||||
return signed && x >= max / 2
|
||||
? x - max
|
||||
: x;
|
||||
};
|
||||
|
||||
BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) {
|
||||
var bias = maxBits[exponentBits - 1] - 1
|
||||
, minExp = -bias + 1
|
||||
, maxExp = bias
|
||||
, minUnnormExp = minExp - precisionBits
|
||||
, n = parseFloat(data)
|
||||
, status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0
|
||||
, exp = 0
|
||||
, len = 2 * bias + 1 + precisionBits + 3
|
||||
, bin = new Array(len)
|
||||
, signal = (n = status !== 0 ? 0 : n) < 0
|
||||
, intPart = Math.floor(n = Math.abs(n))
|
||||
, floatPart = n - intPart
|
||||
, lastBit
|
||||
, rounded
|
||||
, result
|
||||
, i
|
||||
, j;
|
||||
|
||||
for (i = len; i; bin[--i] = 0);
|
||||
|
||||
for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2));
|
||||
|
||||
for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart);
|
||||
|
||||
for (i = -1; ++i < len && !bin[i];);
|
||||
|
||||
if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) {
|
||||
if (!(rounded = bin[lastBit])) {
|
||||
for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]);
|
||||
}
|
||||
|
||||
for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0));
|
||||
}
|
||||
|
||||
for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];);
|
||||
|
||||
if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) {
|
||||
++i;
|
||||
} else if (exp < minExp) {
|
||||
exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow");
|
||||
i = bias + 1 - (exp = minExp - 1);
|
||||
}
|
||||
|
||||
if (intPart || status !== 0) {
|
||||
this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status);
|
||||
exp = maxExp + 1;
|
||||
i = bias + 2;
|
||||
|
||||
if (status == -Infinity) {
|
||||
signal = 1;
|
||||
} else if (isNaN(status)) {
|
||||
bin[i] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1);
|
||||
|
||||
for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) {
|
||||
n += (1 << j) * result.charAt(--i);
|
||||
if (j == 7) {
|
||||
r[r.length] = String.fromCharCode(n);
|
||||
n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
r[r.length] = n
|
||||
? String.fromCharCode(n)
|
||||
: "";
|
||||
|
||||
return (this.bigEndian ? r.reverse() : r).join("");
|
||||
};
|
||||
|
||||
BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) {
|
||||
var max = maxBits[bits];
|
||||
|
||||
if (data >= max || data < -(max / 2)) {
|
||||
this.warn("encodeInt::overflow");
|
||||
data = 0;
|
||||
}
|
||||
|
||||
if (data < 0) {
|
||||
data += max;
|
||||
}
|
||||
|
||||
for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256));
|
||||
|
||||
for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0");
|
||||
|
||||
return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join("");
|
||||
};
|
||||
|
||||
BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); };
|
||||
BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); };
|
||||
BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); };
|
||||
BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); };
|
||||
BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); };
|
||||
BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); };
|
||||
BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); };
|
||||
BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); };
|
||||
BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); };
|
||||
BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); };
|
||||
BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); };
|
||||
BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); };
|
||||
BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); };
|
||||
BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); };
|
||||
BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); };
|
||||
BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); };
|
||||
BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); };
|
||||
BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); };
|
||||
BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); };
|
||||
BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); };
|
||||
|
||||
// Factor out the encode so it can be shared by add_header and push_int32
|
||||
BinaryParser.encode_int32 = function encode_int32 (number, asArray) {
|
||||
var a, b, c, d, unsigned;
|
||||
unsigned = (number < 0) ? (number + 0x100000000) : number;
|
||||
a = Math.floor(unsigned / 0xffffff);
|
||||
unsigned &= 0xffffff;
|
||||
b = Math.floor(unsigned / 0xffff);
|
||||
unsigned &= 0xffff;
|
||||
c = Math.floor(unsigned / 0xff);
|
||||
unsigned &= 0xff;
|
||||
d = Math.floor(unsigned);
|
||||
return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d);
|
||||
};
|
||||
|
||||
BinaryParser.encode_int64 = function encode_int64 (number) {
|
||||
var a, b, c, d, e, f, g, h, unsigned;
|
||||
unsigned = (number < 0) ? (number + 0x10000000000000000) : number;
|
||||
a = Math.floor(unsigned / 0xffffffffffffff);
|
||||
unsigned &= 0xffffffffffffff;
|
||||
b = Math.floor(unsigned / 0xffffffffffff);
|
||||
unsigned &= 0xffffffffffff;
|
||||
c = Math.floor(unsigned / 0xffffffffff);
|
||||
unsigned &= 0xffffffffff;
|
||||
d = Math.floor(unsigned / 0xffffffff);
|
||||
unsigned &= 0xffffffff;
|
||||
e = Math.floor(unsigned / 0xffffff);
|
||||
unsigned &= 0xffffff;
|
||||
f = Math.floor(unsigned / 0xffff);
|
||||
unsigned &= 0xffff;
|
||||
g = Math.floor(unsigned / 0xff);
|
||||
unsigned &= 0xff;
|
||||
h = Math.floor(unsigned);
|
||||
return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h);
|
||||
};
|
||||
|
||||
/**
|
||||
* UTF8 methods
|
||||
*/
|
||||
|
||||
// Take a raw binary string and return a utf8 string
|
||||
BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) {
|
||||
var len = binaryStr.length
|
||||
, decoded = ''
|
||||
, i = 0
|
||||
, c = 0
|
||||
, c1 = 0
|
||||
, c2 = 0
|
||||
, c3;
|
||||
|
||||
while (i < len) {
|
||||
c = binaryStr.charCodeAt(i);
|
||||
if (c < 128) {
|
||||
decoded += String.fromCharCode(c);
|
||||
i++;
|
||||
} else if ((c > 191) && (c < 224)) {
|
||||
c2 = binaryStr.charCodeAt(i+1);
|
||||
decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
|
||||
i += 2;
|
||||
} else {
|
||||
c2 = binaryStr.charCodeAt(i+1);
|
||||
c3 = binaryStr.charCodeAt(i+2);
|
||||
decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
|
||||
i += 3;
|
||||
}
|
||||
}
|
||||
|
||||
return decoded;
|
||||
};
|
||||
|
||||
// Encode a cstring
|
||||
BinaryParser.encode_cstring = function encode_cstring (s) {
|
||||
return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0);
|
||||
};
|
||||
|
||||
// Take a utf8 string and return a binary string
|
||||
BinaryParser.encode_utf8 = function encode_utf8 (s) {
|
||||
var a = ""
|
||||
, c;
|
||||
|
||||
for (var n = 0, len = s.length; n < len; n++) {
|
||||
c = s.charCodeAt(n);
|
||||
|
||||
if (c < 128) {
|
||||
a += String.fromCharCode(c);
|
||||
} else if ((c > 127) && (c < 2048)) {
|
||||
a += String.fromCharCode((c>>6) | 192) ;
|
||||
a += String.fromCharCode((c&63) | 128);
|
||||
} else {
|
||||
a += String.fromCharCode((c>>12) | 224);
|
||||
a += String.fromCharCode(((c>>6) & 63) | 128);
|
||||
a += String.fromCharCode((c&63) | 128);
|
||||
}
|
||||
}
|
||||
|
||||
return a;
|
||||
};
|
||||
|
||||
BinaryParser.hprint = function hprint (s) {
|
||||
var number;
|
||||
|
||||
for (var i = 0, len = s.length; i < len; i++) {
|
||||
if (s.charCodeAt(i) < 32) {
|
||||
number = s.charCodeAt(i) <= 15
|
||||
? "0" + s.charCodeAt(i).toString(16)
|
||||
: s.charCodeAt(i).toString(16);
|
||||
process.stdout.write(number + " ")
|
||||
} else {
|
||||
number = s.charCodeAt(i) <= 15
|
||||
? "0" + s.charCodeAt(i).toString(16)
|
||||
: s.charCodeAt(i).toString(16);
|
||||
process.stdout.write(number + " ")
|
||||
}
|
||||
}
|
||||
|
||||
process.stdout.write("\n\n");
|
||||
};
|
||||
|
||||
BinaryParser.ilprint = function hprint (s) {
|
||||
var number;
|
||||
|
||||
for (var i = 0, len = s.length; i < len; i++) {
|
||||
if (s.charCodeAt(i) < 32) {
|
||||
number = s.charCodeAt(i) <= 15
|
||||
? "0" + s.charCodeAt(i).toString(10)
|
||||
: s.charCodeAt(i).toString(10);
|
||||
|
||||
require('util').debug(number+' : ');
|
||||
} else {
|
||||
number = s.charCodeAt(i) <= 15
|
||||
? "0" + s.charCodeAt(i).toString(10)
|
||||
: s.charCodeAt(i).toString(10);
|
||||
require('util').debug(number+' : '+ s.charAt(i));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
BinaryParser.hlprint = function hprint (s) {
|
||||
var number;
|
||||
|
||||
for (var i = 0, len = s.length; i < len; i++) {
|
||||
if (s.charCodeAt(i) < 32) {
|
||||
number = s.charCodeAt(i) <= 15
|
||||
? "0" + s.charCodeAt(i).toString(16)
|
||||
: s.charCodeAt(i).toString(16);
|
||||
require('util').debug(number+' : ');
|
||||
} else {
|
||||
number = s.charCodeAt(i) <= 15
|
||||
? "0" + s.charCodeAt(i).toString(16)
|
||||
: s.charCodeAt(i).toString(16);
|
||||
require('util').debug(number+' : '+ s.charAt(i));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* BinaryParser buffer constructor.
|
||||
*/
|
||||
function BinaryParserBuffer (bigEndian, buffer) {
|
||||
this.bigEndian = bigEndian || 0;
|
||||
this.buffer = [];
|
||||
this.setBuffer(buffer);
|
||||
};
|
||||
|
||||
BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) {
|
||||
var l, i, b;
|
||||
|
||||
if (data) {
|
||||
i = l = data.length;
|
||||
b = this.buffer = new Array(l);
|
||||
for (; i; b[l - i] = data.charCodeAt(--i));
|
||||
this.bigEndian && b.reverse();
|
||||
}
|
||||
};
|
||||
|
||||
BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) {
|
||||
return this.buffer.length >= -(-neededBits >> 3);
|
||||
};
|
||||
|
||||
BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) {
|
||||
if (!this.hasNeededBits(neededBits)) {
|
||||
throw new Error("checkBuffer::missing bytes");
|
||||
}
|
||||
};
|
||||
|
||||
BinaryParserBuffer.prototype.readBits = function readBits (start, length) {
|
||||
//shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
|
||||
|
||||
function shl (a, b) {
|
||||
for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
|
||||
return a;
|
||||
}
|
||||
|
||||
if (start < 0 || length <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.checkBuffer(start + length);
|
||||
|
||||
var offsetLeft
|
||||
, offsetRight = start % 8
|
||||
, curByte = this.buffer.length - ( start >> 3 ) - 1
|
||||
, lastByte = this.buffer.length + ( -( start + length ) >> 3 )
|
||||
, diff = curByte - lastByte
|
||||
, sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0);
|
||||
|
||||
for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight));
|
||||
|
||||
return sum;
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
BinaryParser.Buffer = BinaryParserBuffer;
|
||||
|
||||
exports.BinaryParser = BinaryParser;
|
||||
1519
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/bson.js
generated
vendored
Normal file
1519
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/bson.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
25
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/code.js
generated
vendored
Normal file
25
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/code.js
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* A class representation of the BSON Code type.
|
||||
*
|
||||
* @class Represents the BSON Code type.
|
||||
* @param {String|Function} code a string or function.
|
||||
* @param {Object} [scope] an optional scope for the function.
|
||||
* @return {Code}
|
||||
*/
|
||||
function Code(code, scope) {
|
||||
if(!(this instanceof Code)) return new Code(code, scope);
|
||||
|
||||
this._bsontype = 'Code';
|
||||
this.code = code;
|
||||
this.scope = scope == null ? {} : scope;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Code.prototype.toJSON = function() {
|
||||
return {scope:this.scope, code:this.code};
|
||||
}
|
||||
|
||||
exports.Code = Code;
|
||||
31
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js
generated
vendored
Normal file
31
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* A class representation of the BSON DBRef type.
|
||||
*
|
||||
* @class Represents the BSON DBRef type.
|
||||
* @param {String} namespace the collection name.
|
||||
* @param {ObjectID} oid the reference ObjectID.
|
||||
* @param {String} [db] optional db name, if omitted the reference is local to the current db.
|
||||
* @return {DBRef}
|
||||
*/
|
||||
function DBRef(namespace, oid, db) {
|
||||
if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db);
|
||||
|
||||
this._bsontype = 'DBRef';
|
||||
this.namespace = namespace;
|
||||
this.oid = oid;
|
||||
this.db = db;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
DBRef.prototype.toJSON = function() {
|
||||
return {
|
||||
'$ref':this.namespace,
|
||||
'$id':this.oid,
|
||||
'$db':this.db == null ? '' : this.db
|
||||
};
|
||||
}
|
||||
|
||||
exports.DBRef = DBRef;
|
||||
33
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/double.js
generated
vendored
Normal file
33
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/double.js
generated
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* A class representation of the BSON Double type.
|
||||
*
|
||||
* @class Represents the BSON Double type.
|
||||
* @param {Number} value the number we want to represent as a double.
|
||||
* @return {Double}
|
||||
*/
|
||||
function Double(value) {
|
||||
if(!(this instanceof Double)) return new Double(value);
|
||||
|
||||
this._bsontype = 'Double';
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access the number value.
|
||||
*
|
||||
* @return {Number} returns the wrapped double number.
|
||||
* @api public
|
||||
*/
|
||||
Double.prototype.valueOf = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Double.prototype.toJSON = function() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
exports.Double = Double;
|
||||
121
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js
generated
vendored
Normal file
121
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js
generated
vendored
Normal file
@@ -0,0 +1,121 @@
|
||||
// Copyright (c) 2008, Fair Oaks Labs, Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// * Redistributions in binary form must reproduce the above copyright notice,
|
||||
// this list of conditions and the following disclaimer in the documentation
|
||||
// and/or other materials provided with the distribution.
|
||||
//
|
||||
// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
|
||||
// may be used to endorse or promote products derived from this software
|
||||
// without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
// POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
//
|
||||
// Modifications to writeIEEE754 to support negative zeroes made by Brian White
|
||||
|
||||
var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) {
|
||||
var e, m,
|
||||
bBE = (endian === 'big'),
|
||||
eLen = nBytes * 8 - mLen - 1,
|
||||
eMax = (1 << eLen) - 1,
|
||||
eBias = eMax >> 1,
|
||||
nBits = -7,
|
||||
i = bBE ? 0 : (nBytes - 1),
|
||||
d = bBE ? 1 : -1,
|
||||
s = buffer[offset + i];
|
||||
|
||||
i += d;
|
||||
|
||||
e = s & ((1 << (-nBits)) - 1);
|
||||
s >>= (-nBits);
|
||||
nBits += eLen;
|
||||
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
|
||||
|
||||
m = e & ((1 << (-nBits)) - 1);
|
||||
e >>= (-nBits);
|
||||
nBits += mLen;
|
||||
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
|
||||
|
||||
if (e === 0) {
|
||||
e = 1 - eBias;
|
||||
} else if (e === eMax) {
|
||||
return m ? NaN : ((s ? -1 : 1) * Infinity);
|
||||
} else {
|
||||
m = m + Math.pow(2, mLen);
|
||||
e = e - eBias;
|
||||
}
|
||||
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
|
||||
};
|
||||
|
||||
var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) {
|
||||
var e, m, c,
|
||||
bBE = (endian === 'big'),
|
||||
eLen = nBytes * 8 - mLen - 1,
|
||||
eMax = (1 << eLen) - 1,
|
||||
eBias = eMax >> 1,
|
||||
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
|
||||
i = bBE ? (nBytes-1) : 0,
|
||||
d = bBE ? -1 : 1,
|
||||
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
|
||||
|
||||
value = Math.abs(value);
|
||||
|
||||
if (isNaN(value) || value === Infinity) {
|
||||
m = isNaN(value) ? 1 : 0;
|
||||
e = eMax;
|
||||
} else {
|
||||
e = Math.floor(Math.log(value) / Math.LN2);
|
||||
if (value * (c = Math.pow(2, -e)) < 1) {
|
||||
e--;
|
||||
c *= 2;
|
||||
}
|
||||
if (e+eBias >= 1) {
|
||||
value += rt / c;
|
||||
} else {
|
||||
value += rt * Math.pow(2, 1 - eBias);
|
||||
}
|
||||
if (value * c >= 2) {
|
||||
e++;
|
||||
c /= 2;
|
||||
}
|
||||
|
||||
if (e + eBias >= eMax) {
|
||||
m = 0;
|
||||
e = eMax;
|
||||
} else if (e + eBias >= 1) {
|
||||
m = (value * c - 1) * Math.pow(2, mLen);
|
||||
e = e + eBias;
|
||||
} else {
|
||||
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
|
||||
e = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
|
||||
|
||||
e = (e << mLen) | m;
|
||||
eLen += mLen;
|
||||
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
|
||||
|
||||
buffer[offset + i - d] |= s * 128;
|
||||
};
|
||||
|
||||
exports.readIEEE754 = readIEEE754;
|
||||
exports.writeIEEE754 = writeIEEE754;
|
||||
74
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/index.js
generated
vendored
Normal file
74
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/index.js
generated
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
try {
|
||||
exports.BSONPure = require('./bson');
|
||||
exports.BSONNative = require('../../ext');
|
||||
} catch(err) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
[ './binary_parser'
|
||||
, './binary'
|
||||
, './code'
|
||||
, './db_ref'
|
||||
, './double'
|
||||
, './max_key'
|
||||
, './min_key'
|
||||
, './objectid'
|
||||
, './symbol'
|
||||
, './timestamp'
|
||||
, './long'].forEach(function (path) {
|
||||
var module = require('./' + path);
|
||||
for (var i in module) {
|
||||
exports[i] = module[i];
|
||||
}
|
||||
});
|
||||
|
||||
// Exports all the classes for the NATIVE JS BSON Parser
|
||||
exports.native = function() {
|
||||
var classes = {};
|
||||
// Map all the classes
|
||||
[ './binary_parser'
|
||||
, './binary'
|
||||
, './code'
|
||||
, './db_ref'
|
||||
, './double'
|
||||
, './max_key'
|
||||
, './min_key'
|
||||
, './objectid'
|
||||
, './symbol'
|
||||
, './timestamp'
|
||||
, './long'
|
||||
, '../../ext'
|
||||
].forEach(function (path) {
|
||||
var module = require('./' + path);
|
||||
for (var i in module) {
|
||||
classes[i] = module[i];
|
||||
}
|
||||
});
|
||||
// Return classes list
|
||||
return classes;
|
||||
}
|
||||
|
||||
// Exports all the classes for the PURE JS BSON Parser
|
||||
exports.pure = function() {
|
||||
var classes = {};
|
||||
// Map all the classes
|
||||
[ './binary_parser'
|
||||
, './binary'
|
||||
, './code'
|
||||
, './db_ref'
|
||||
, './double'
|
||||
, './max_key'
|
||||
, './min_key'
|
||||
, './objectid'
|
||||
, './symbol'
|
||||
, './timestamp'
|
||||
, './long'
|
||||
, '././bson'].forEach(function (path) {
|
||||
var module = require('./' + path);
|
||||
for (var i in module) {
|
||||
classes[i] = module[i];
|
||||
}
|
||||
});
|
||||
// Return classes list
|
||||
return classes;
|
||||
}
|
||||
854
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/long.js
generated
vendored
Normal file
854
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/long.js
generated
vendored
Normal file
@@ -0,0 +1,854 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Copyright 2009 Google Inc. All Rights Reserved
|
||||
|
||||
/**
|
||||
* Defines a Long class for representing a 64-bit two's-complement
|
||||
* integer value, which faithfully simulates the behavior of a Java "Long". This
|
||||
* implementation is derived from LongLib in GWT.
|
||||
*
|
||||
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
|
||||
* values as *signed* integers. See the from* functions below for more
|
||||
* convenient ways of constructing Longs.
|
||||
*
|
||||
* The internal representation of a Long is the two given signed, 32-bit values.
|
||||
* We use 32-bit pieces because these are the size of integers on which
|
||||
* Javascript performs bit-operations. For operations like addition and
|
||||
* multiplication, we split each number into 16-bit pieces, which can easily be
|
||||
* multiplied within Javascript's floating-point representation without overflow
|
||||
* or change in sign.
|
||||
*
|
||||
* In the algorithms below, we frequently reduce the negative case to the
|
||||
* positive case by negating the input(s) and then post-processing the result.
|
||||
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
|
||||
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
|
||||
* a positive number, it overflows back into a negative). Not handling this
|
||||
* case would often result in infinite recursion.
|
||||
*
|
||||
* @class Represents the BSON Long type.
|
||||
* @param {Number} low the low (signed) 32 bits of the Long.
|
||||
* @param {Number} high the high (signed) 32 bits of the Long.
|
||||
*/
|
||||
function Long(low, high) {
|
||||
if(!(this instanceof Long)) return new Long(low, high);
|
||||
|
||||
this._bsontype = 'Long';
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
this.low_ = low | 0; // force into 32 signed bits.
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
this.high_ = high | 0; // force into 32 signed bits.
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the int value.
|
||||
*
|
||||
* @return {Number} the value, assuming it is a 32-bit integer.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.toInt = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the Number value.
|
||||
*
|
||||
* @return {Number} the closest floating-point representation to this value.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.toNumber = function() {
|
||||
return this.high_ * Long.TWO_PWR_32_DBL_ +
|
||||
this.getLowBitsUnsigned();
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the JSON value.
|
||||
*
|
||||
* @return {String} the JSON representation.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.toJSON = function() {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the String value.
|
||||
*
|
||||
* @param {Number} [opt_radix] the radix in which the text should be written.
|
||||
* @return {String} the textual representation of this value.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.toString = function(opt_radix) {
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (this.isZero()) {
|
||||
return '0';
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
// We need to change the Long value before it can be negated, so we remove
|
||||
// the bottom-most digit in this base and then recurse to do the rest.
|
||||
var radixLong = Long.fromNumber(radix);
|
||||
var div = this.div(radixLong);
|
||||
var rem = div.multiply(radixLong).subtract(this);
|
||||
return div.toString(radix) + rem.toInt().toString(radix);
|
||||
} else {
|
||||
return '-' + this.negate().toString(radix);
|
||||
}
|
||||
}
|
||||
|
||||
// Do several (6) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = Long.fromNumber(Math.pow(radix, 6));
|
||||
|
||||
var rem = this;
|
||||
var result = '';
|
||||
while (true) {
|
||||
var remDiv = rem.div(radixToPower);
|
||||
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
|
||||
var digits = intval.toString(radix);
|
||||
|
||||
rem = remDiv;
|
||||
if (rem.isZero()) {
|
||||
return digits + result;
|
||||
} else {
|
||||
while (digits.length < 6) {
|
||||
digits = '0' + digits;
|
||||
}
|
||||
result = '' + digits + result;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the high 32-bits value.
|
||||
*
|
||||
* @return {Number} the high 32-bits as a signed value.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.getHighBits = function() {
|
||||
return this.high_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the low 32-bits value.
|
||||
*
|
||||
* @return {Number} the low 32-bits as a signed value.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.getLowBits = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the low unsigned 32-bits value.
|
||||
*
|
||||
* @return {Number} the low 32-bits as an unsigned value.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.getLowBitsUnsigned = function() {
|
||||
return (this.low_ >= 0) ?
|
||||
this.low_ : Long.TWO_PWR_32_DBL_ + this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the number of bits needed to represent the absolute value of this Long.
|
||||
*
|
||||
* @return {Number} Returns the number of bits needed to represent the absolute value of this Long.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.getNumBitsAbs = function() {
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
return 64;
|
||||
} else {
|
||||
return this.negate().getNumBitsAbs();
|
||||
}
|
||||
} else {
|
||||
var val = this.high_ != 0 ? this.high_ : this.low_;
|
||||
for (var bit = 31; bit > 0; bit--) {
|
||||
if ((val & (1 << bit)) != 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return this.high_ != 0 ? bit + 33 : bit + 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is zero.
|
||||
*
|
||||
* @return {Boolean} whether this value is zero.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.isZero = function() {
|
||||
return this.high_ == 0 && this.low_ == 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is negative.
|
||||
*
|
||||
* @return {Boolean} whether this value is negative.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.isNegative = function() {
|
||||
return this.high_ < 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is odd.
|
||||
*
|
||||
* @return {Boolean} whether this value is odd.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.isOdd = function() {
|
||||
return (this.low_ & 1) == 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long equals the other
|
||||
*
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {Boolean} whether this Long equals the other
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.equals = function(other) {
|
||||
return (this.high_ == other.high_) && (this.low_ == other.low_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long does not equal the other.
|
||||
*
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {Boolean} whether this Long does not equal the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.notEquals = function(other) {
|
||||
return (this.high_ != other.high_) || (this.low_ != other.low_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long is less than the other.
|
||||
*
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {Boolean} whether this Long is less than the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.lessThan = function(other) {
|
||||
return this.compare(other) < 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long is less than or equal to the other.
|
||||
*
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {Boolean} whether this Long is less than or equal to the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.lessThanOrEqual = function(other) {
|
||||
return this.compare(other) <= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long is greater than the other.
|
||||
*
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {Boolean} whether this Long is greater than the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.greaterThan = function(other) {
|
||||
return this.compare(other) > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Long is greater than or equal to the other.
|
||||
*
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {Boolean} whether this Long is greater than or equal to the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.greaterThanOrEqual = function(other) {
|
||||
return this.compare(other) >= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compares this Long with the given one.
|
||||
*
|
||||
* @param {Long} other Long to compare against.
|
||||
* @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.compare = function(other) {
|
||||
if (this.equals(other)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var thisNeg = this.isNegative();
|
||||
var otherNeg = other.isNegative();
|
||||
if (thisNeg && !otherNeg) {
|
||||
return -1;
|
||||
}
|
||||
if (!thisNeg && otherNeg) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// at this point, the signs are the same, so subtraction will not overflow
|
||||
if (this.subtract(other).isNegative()) {
|
||||
return -1;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The negation of this value.
|
||||
*
|
||||
* @return {Long} the negation of this value.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.negate = function() {
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
return Long.MIN_VALUE;
|
||||
} else {
|
||||
return this.not().add(Long.ONE);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the sum of this and the given Long.
|
||||
*
|
||||
* @param {Long} other Long to add to this one.
|
||||
* @return {Long} the sum of this and the given Long.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.add = function(other) {
|
||||
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xFFFF;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xFFFF;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xFFFF;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xFFFF;
|
||||
|
||||
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
|
||||
c00 += a00 + b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xFFFF;
|
||||
c16 += a16 + b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c32 += a32 + b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c48 += a48 + b48;
|
||||
c48 &= 0xFFFF;
|
||||
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the difference of this and the given Long.
|
||||
*
|
||||
* @param {Long} other Long to subtract from this.
|
||||
* @return {Long} the difference of this and the given Long.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.subtract = function(other) {
|
||||
return this.add(other.negate());
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the product of this and the given Long.
|
||||
*
|
||||
* @param {Long} other Long to multiply with this.
|
||||
* @return {Long} the product of this and the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.multiply = function(other) {
|
||||
if (this.isZero()) {
|
||||
return Long.ZERO;
|
||||
} else if (other.isZero()) {
|
||||
return Long.ZERO;
|
||||
}
|
||||
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
return other.isOdd() ? Long.MIN_VALUE : Long.ZERO;
|
||||
} else if (other.equals(Long.MIN_VALUE)) {
|
||||
return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().multiply(other.negate());
|
||||
} else {
|
||||
return this.negate().multiply(other).negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.multiply(other.negate()).negate();
|
||||
}
|
||||
|
||||
// If both Longs are small, use float multiplication
|
||||
if (this.lessThan(Long.TWO_PWR_24_) &&
|
||||
other.lessThan(Long.TWO_PWR_24_)) {
|
||||
return Long.fromNumber(this.toNumber() * other.toNumber());
|
||||
}
|
||||
|
||||
// Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products.
|
||||
// We can skip products that would overflow.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xFFFF;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xFFFF;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xFFFF;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xFFFF;
|
||||
|
||||
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
|
||||
c00 += a00 * b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xFFFF;
|
||||
c16 += a16 * b00;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c16 += a00 * b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c32 += a32 * b00;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c32 += a16 * b16;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c32 += a00 * b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
|
||||
c48 &= 0xFFFF;
|
||||
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long divided by the given one.
|
||||
*
|
||||
* @param {Long} other Long by which to divide.
|
||||
* @return {Long} this Long divided by the given one.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.div = function(other) {
|
||||
if (other.isZero()) {
|
||||
throw Error('division by zero');
|
||||
} else if (this.isZero()) {
|
||||
return Long.ZERO;
|
||||
}
|
||||
|
||||
if (this.equals(Long.MIN_VALUE)) {
|
||||
if (other.equals(Long.ONE) ||
|
||||
other.equals(Long.NEG_ONE)) {
|
||||
return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
|
||||
} else if (other.equals(Long.MIN_VALUE)) {
|
||||
return Long.ONE;
|
||||
} else {
|
||||
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
|
||||
var halfThis = this.shiftRight(1);
|
||||
var approx = halfThis.div(other).shiftLeft(1);
|
||||
if (approx.equals(Long.ZERO)) {
|
||||
return other.isNegative() ? Long.ONE : Long.NEG_ONE;
|
||||
} else {
|
||||
var rem = this.subtract(other.multiply(approx));
|
||||
var result = approx.add(rem.div(other));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else if (other.equals(Long.MIN_VALUE)) {
|
||||
return Long.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().div(other.negate());
|
||||
} else {
|
||||
return this.negate().div(other).negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.div(other.negate()).negate();
|
||||
}
|
||||
|
||||
// Repeat the following until the remainder is less than other: find a
|
||||
// floating-point that approximates remainder / other *from below*, add this
|
||||
// into the result, and subtract it from the remainder. It is critical that
|
||||
// the approximate value is less than or equal to the real value so that the
|
||||
// remainder never becomes negative.
|
||||
var res = Long.ZERO;
|
||||
var rem = this;
|
||||
while (rem.greaterThanOrEqual(other)) {
|
||||
// Approximate the result of division. This may be a little greater or
|
||||
// smaller than the actual value.
|
||||
var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
|
||||
|
||||
// We will tweak the approximate result by changing it in the 48-th digit or
|
||||
// the smallest non-fractional digit, whichever is larger.
|
||||
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
|
||||
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
|
||||
|
||||
// Decrease the approximation until it is smaller than the remainder. Note
|
||||
// that if it is too large, the product overflows and is negative.
|
||||
var approxRes = Long.fromNumber(approx);
|
||||
var approxRem = approxRes.multiply(other);
|
||||
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
|
||||
approx -= delta;
|
||||
approxRes = Long.fromNumber(approx);
|
||||
approxRem = approxRes.multiply(other);
|
||||
}
|
||||
|
||||
// We know the answer can't be zero... and actually, zero would cause
|
||||
// infinite recursion since we would make no progress.
|
||||
if (approxRes.isZero()) {
|
||||
approxRes = Long.ONE;
|
||||
}
|
||||
|
||||
res = res.add(approxRes);
|
||||
rem = rem.subtract(approxRem);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long modulo the given one.
|
||||
*
|
||||
* @param {Long} other Long by which to mod.
|
||||
* @return {Long} this Long modulo the given one.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.modulo = function(other) {
|
||||
return this.subtract(this.div(other).multiply(other));
|
||||
};
|
||||
|
||||
/**
|
||||
* The bitwise-NOT of this value.
|
||||
*
|
||||
* @return {Long} the bitwise-NOT of this value.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.not = function() {
|
||||
return Long.fromBits(~this.low_, ~this.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-AND of this Long and the given one.
|
||||
*
|
||||
* @param {Long} other the Long with which to AND.
|
||||
* @return {Long} the bitwise-AND of this and the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.and = function(other) {
|
||||
return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-OR of this Long and the given one.
|
||||
*
|
||||
* @param {Long} other the Long with which to OR.
|
||||
* @return {Long} the bitwise-OR of this and the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.or = function(other) {
|
||||
return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-XOR of this Long and the given one.
|
||||
*
|
||||
* @param {Long} other the Long with which to XOR.
|
||||
* @return {Long} the bitwise-XOR of this and the other.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.xor = function(other) {
|
||||
return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the left by the given amount.
|
||||
*
|
||||
* @param {Number} numBits the number of bits by which to shift.
|
||||
* @return {Long} this shifted to the left by the given amount.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.shiftLeft = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var low = this.low_;
|
||||
if (numBits < 32) {
|
||||
var high = this.high_;
|
||||
return Long.fromBits(
|
||||
low << numBits,
|
||||
(high << numBits) | (low >>> (32 - numBits)));
|
||||
} else {
|
||||
return Long.fromBits(0, low << (numBits - 32));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the right by the given amount.
|
||||
*
|
||||
* @param {Number} numBits the number of bits by which to shift.
|
||||
* @return {Long} this shifted to the right by the given amount.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.shiftRight = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return Long.fromBits(
|
||||
(low >>> numBits) | (high << (32 - numBits)),
|
||||
high >> numBits);
|
||||
} else {
|
||||
return Long.fromBits(
|
||||
high >> (numBits - 32),
|
||||
high >= 0 ? 0 : -1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
|
||||
*
|
||||
* @param {Number} numBits the number of bits by which to shift.
|
||||
* @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits.
|
||||
* @api public
|
||||
*/
|
||||
Long.prototype.shiftRightUnsigned = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return Long.fromBits(
|
||||
(low >>> numBits) | (high << (32 - numBits)),
|
||||
high >>> numBits);
|
||||
} else if (numBits == 32) {
|
||||
return Long.fromBits(high, 0);
|
||||
} else {
|
||||
return Long.fromBits(high >>> (numBits - 32), 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Long representing the given (32-bit) integer value.
|
||||
*
|
||||
* @param {Number} value the 32-bit integer in question.
|
||||
* @return {Long} the corresponding Long value.
|
||||
* @api public
|
||||
*/
|
||||
Long.fromInt = function(value) {
|
||||
if (-128 <= value && value < 128) {
|
||||
var cachedObj = Long.INT_CACHE_[value];
|
||||
if (cachedObj) {
|
||||
return cachedObj;
|
||||
}
|
||||
}
|
||||
|
||||
var obj = new Long(value | 0, value < 0 ? -1 : 0);
|
||||
if (-128 <= value && value < 128) {
|
||||
Long.INT_CACHE_[value] = obj;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
|
||||
*
|
||||
* @param {Number} value the number in question.
|
||||
* @return {Long} the corresponding Long value.
|
||||
* @api public
|
||||
*/
|
||||
Long.fromNumber = function(value) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return Long.ZERO;
|
||||
} else if (value <= -Long.TWO_PWR_63_DBL_) {
|
||||
return Long.MIN_VALUE;
|
||||
} else if (value + 1 >= Long.TWO_PWR_63_DBL_) {
|
||||
return Long.MAX_VALUE;
|
||||
} else if (value < 0) {
|
||||
return Long.fromNumber(-value).negate();
|
||||
} else {
|
||||
return new Long(
|
||||
(value % Long.TWO_PWR_32_DBL_) | 0,
|
||||
(value / Long.TWO_PWR_32_DBL_) | 0);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
|
||||
*
|
||||
* @param {Number} lowBits the low 32-bits.
|
||||
* @param {Number} highBits the high 32-bits.
|
||||
* @return {Long} the corresponding Long value.
|
||||
* @api public
|
||||
*/
|
||||
Long.fromBits = function(lowBits, highBits) {
|
||||
return new Long(lowBits, highBits);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Long representation of the given string, written using the given radix.
|
||||
*
|
||||
* @param {String} str the textual representation of the Long.
|
||||
* @param {Number} opt_radix the radix in which the text is written.
|
||||
* @return {Long} the corresponding Long value.
|
||||
* @api public
|
||||
*/
|
||||
Long.fromString = function(str, opt_radix) {
|
||||
if (str.length == 0) {
|
||||
throw Error('number format error: empty string');
|
||||
}
|
||||
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (str.charAt(0) == '-') {
|
||||
return Long.fromString(str.substring(1), radix).negate();
|
||||
} else if (str.indexOf('-') >= 0) {
|
||||
throw Error('number format error: interior "-" character: ' + str);
|
||||
}
|
||||
|
||||
// Do several (8) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = Long.fromNumber(Math.pow(radix, 8));
|
||||
|
||||
var result = Long.ZERO;
|
||||
for (var i = 0; i < str.length; i += 8) {
|
||||
var size = Math.min(8, str.length - i);
|
||||
var value = parseInt(str.substring(i, i + size), radix);
|
||||
if (size < 8) {
|
||||
var power = Long.fromNumber(Math.pow(radix, size));
|
||||
result = result.multiply(power).add(Long.fromNumber(value));
|
||||
} else {
|
||||
result = result.multiply(radixToPower);
|
||||
result = result.add(Long.fromNumber(value));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
|
||||
// from* methods on which they depend.
|
||||
|
||||
|
||||
/**
|
||||
* A cache of the Long representations of small integer values.
|
||||
* @type {Object}
|
||||
* @api private
|
||||
*/
|
||||
Long.INT_CACHE_ = {};
|
||||
|
||||
// NOTE: the compiler should inline these constant values below and then remove
|
||||
// these variables, so there should be no runtime penalty for these.
|
||||
|
||||
/**
|
||||
* Number used repeated below in calculations. This must appear before the
|
||||
* first call to any from* function below.
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Long.TWO_PWR_16_DBL_ = 1 << 16;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Long.TWO_PWR_24_DBL_ = 1 << 24;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2;
|
||||
|
||||
/** @type {Long} */
|
||||
Long.ZERO = Long.fromInt(0);
|
||||
|
||||
/** @type {Long} */
|
||||
Long.ONE = Long.fromInt(1);
|
||||
|
||||
/** @type {Long} */
|
||||
Long.NEG_ONE = Long.fromInt(-1);
|
||||
|
||||
/** @type {Long} */
|
||||
Long.MAX_VALUE =
|
||||
Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
|
||||
|
||||
/** @type {Long} */
|
||||
Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0);
|
||||
|
||||
/**
|
||||
* @type {Long}
|
||||
* @api private
|
||||
*/
|
||||
Long.TWO_PWR_24_ = Long.fromInt(1 << 24);
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
exports.Long = Long;
|
||||
13
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js
generated
vendored
Normal file
13
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* A class representation of the BSON MaxKey type.
|
||||
*
|
||||
* @class Represents the BSON MaxKey type.
|
||||
* @return {MaxKey}
|
||||
*/
|
||||
function MaxKey() {
|
||||
if(!(this instanceof MaxKey)) return new MaxKey();
|
||||
|
||||
this._bsontype = 'MaxKey';
|
||||
}
|
||||
|
||||
exports.MaxKey = MaxKey;
|
||||
13
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js
generated
vendored
Normal file
13
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* A class representation of the BSON MinKey type.
|
||||
*
|
||||
* @class Represents the BSON MinKey type.
|
||||
* @return {MinKey}
|
||||
*/
|
||||
function MinKey() {
|
||||
if(!(this instanceof MinKey)) return new MinKey();
|
||||
|
||||
this._bsontype = 'MinKey';
|
||||
}
|
||||
|
||||
exports.MinKey = MinKey;
|
||||
253
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js
generated
vendored
Normal file
253
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js
generated
vendored
Normal file
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
var BinaryParser = require('./binary_parser').BinaryParser;
|
||||
|
||||
/**
|
||||
* Machine id.
|
||||
*
|
||||
* Create a random 3-byte value (i.e. unique for this
|
||||
* process). Other drivers use a md5 of the machine id here, but
|
||||
* that would mean an asyc call to gethostname, so we don't bother.
|
||||
*/
|
||||
var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10);
|
||||
|
||||
// Regular expression that checks for hex value
|
||||
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
|
||||
|
||||
/**
|
||||
* Create a new ObjectID instance
|
||||
*
|
||||
* @class Represents the BSON ObjectID type
|
||||
* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number.
|
||||
* @return {Object} instance of ObjectID.
|
||||
*/
|
||||
var ObjectID = function ObjectID(id, _hex) {
|
||||
if(!(this instanceof ObjectID)) return new ObjectID(id, _hex);
|
||||
|
||||
this._bsontype = 'ObjectID';
|
||||
var __id = null;
|
||||
|
||||
// Throw an error if it's not a valid setup
|
||||
if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24))
|
||||
throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
|
||||
|
||||
// Generate id based on the input
|
||||
if(id == null || typeof id == 'number') {
|
||||
// convert to 12 byte binary string
|
||||
this.id = this.generate(id);
|
||||
} else if(id != null && id.length === 12) {
|
||||
// assume 12 byte string
|
||||
this.id = id;
|
||||
} else if(checkForHexRegExp.test(id)) {
|
||||
return ObjectID.createFromHexString(id);
|
||||
} else if(!checkForHexRegExp.test(id)) {
|
||||
throw new Error("Value passed in is not a valid 24 character hex string");
|
||||
}
|
||||
|
||||
if(ObjectID.cacheHexString) this.__id = this.toHexString();
|
||||
};
|
||||
|
||||
// Allow usage of ObjectId aswell as ObjectID
|
||||
var ObjectId = ObjectID;
|
||||
|
||||
/**
|
||||
* Return the ObjectID id as a 24 byte hex string representation
|
||||
*
|
||||
* @return {String} return the 24 byte hex string representation.
|
||||
* @api public
|
||||
*/
|
||||
ObjectID.prototype.toHexString = function() {
|
||||
if(ObjectID.cacheHexString && this.__id) return this.__id;
|
||||
|
||||
var hexString = ''
|
||||
, number
|
||||
, value;
|
||||
|
||||
for (var index = 0, len = this.id.length; index < len; index++) {
|
||||
value = BinaryParser.toByte(this.id[index]);
|
||||
number = value <= 15
|
||||
? '0' + value.toString(16)
|
||||
: value.toString(16);
|
||||
hexString = hexString + number;
|
||||
}
|
||||
|
||||
if(ObjectID.cacheHexString) this.__id = hexString;
|
||||
return hexString;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update the ObjectID index used in generating new ObjectID's on the driver
|
||||
*
|
||||
* @return {Number} returns next index value.
|
||||
* @api private
|
||||
*/
|
||||
ObjectID.prototype.get_inc = function() {
|
||||
return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update the ObjectID index used in generating new ObjectID's on the driver
|
||||
*
|
||||
* @return {Number} returns next index value.
|
||||
* @api private
|
||||
*/
|
||||
ObjectID.prototype.getInc = function() {
|
||||
return this.get_inc();
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate a 12 byte id string used in ObjectID's
|
||||
*
|
||||
* @param {Number} [time] optional parameter allowing to pass in a second based timestamp.
|
||||
* @return {String} return the 12 byte id binary string.
|
||||
* @api private
|
||||
*/
|
||||
ObjectID.prototype.generate = function(time) {
|
||||
if ('number' == typeof time) {
|
||||
var time4Bytes = BinaryParser.encodeInt(time, 32, true, true);
|
||||
/* for time-based ObjectID the bytes following the time will be zeroed */
|
||||
var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false);
|
||||
var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid);
|
||||
var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true);
|
||||
} else {
|
||||
var unixTime = parseInt(Date.now()/1000,10);
|
||||
var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true);
|
||||
var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false);
|
||||
var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid);
|
||||
var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true);
|
||||
}
|
||||
|
||||
return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes;
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts the id into a 24 byte hex string for printing
|
||||
*
|
||||
* @return {String} return the 24 byte hex string representation.
|
||||
* @api private
|
||||
*/
|
||||
ObjectID.prototype.toString = function() {
|
||||
return this.toHexString();
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts to a string representation of this Id.
|
||||
*
|
||||
* @return {String} return the 24 byte hex string representation.
|
||||
* @api private
|
||||
*/
|
||||
ObjectID.prototype.inspect = ObjectID.prototype.toString;
|
||||
|
||||
/**
|
||||
* Converts to its JSON representation.
|
||||
*
|
||||
* @return {String} return the 24 byte hex string representation.
|
||||
* @api private
|
||||
*/
|
||||
ObjectID.prototype.toJSON = function() {
|
||||
return this.toHexString();
|
||||
};
|
||||
|
||||
/**
|
||||
* Compares the equality of this ObjectID with `otherID`.
|
||||
*
|
||||
* @param {Object} otherID ObjectID instance to compare against.
|
||||
* @return {Bool} the result of comparing two ObjectID's
|
||||
* @api public
|
||||
*/
|
||||
ObjectID.prototype.equals = function equals (otherID) {
|
||||
var id = (otherID instanceof ObjectID || otherID.toHexString)
|
||||
? otherID.id
|
||||
: ObjectID.createFromHexString(otherID).id;
|
||||
|
||||
return this.id === id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the generation time in seconds that this ID was generated.
|
||||
*
|
||||
* @return {Number} return number of seconds in the timestamp part of the 12 byte id.
|
||||
* @api public
|
||||
*/
|
||||
ObjectID.prototype.getTimestamp = function() {
|
||||
var timestamp = new Date();
|
||||
timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000);
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
ObjectID.index = 0;
|
||||
|
||||
ObjectID.createPk = function createPk () {
|
||||
return new ObjectID();
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
|
||||
*
|
||||
* @param {Number} time an integer number representing a number of seconds.
|
||||
* @return {ObjectID} return the created ObjectID
|
||||
* @api public
|
||||
*/
|
||||
ObjectID.createFromTime = function createFromTime (time) {
|
||||
var id = BinaryParser.encodeInt(time, 32, true, true) +
|
||||
BinaryParser.encodeInt(0, 64, true, true);
|
||||
return new ObjectID(id);
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates an ObjectID from a hex string representation of an ObjectID.
|
||||
*
|
||||
* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring.
|
||||
* @return {ObjectID} return the created ObjectID
|
||||
* @api public
|
||||
*/
|
||||
ObjectID.createFromHexString = function createFromHexString (hexString) {
|
||||
// Throw an error if it's not a valid setup
|
||||
if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24)
|
||||
throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
|
||||
|
||||
var len = hexString.length;
|
||||
|
||||
if(len > 12*2) {
|
||||
throw new Error('Id cannot be longer than 12 bytes');
|
||||
}
|
||||
|
||||
var result = ''
|
||||
, string
|
||||
, number;
|
||||
|
||||
for (var index = 0; index < len; index += 2) {
|
||||
string = hexString.substr(index, 2);
|
||||
number = parseInt(string, 16);
|
||||
result += BinaryParser.fromByte(number);
|
||||
}
|
||||
|
||||
return new ObjectID(result, hexString);
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Object.defineProperty(ObjectID.prototype, "generationTime", {
|
||||
enumerable: true
|
||||
, get: function () {
|
||||
return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true));
|
||||
}
|
||||
, set: function (value) {
|
||||
var value = BinaryParser.encodeInt(value, 32, true, true);
|
||||
this.id = value + this.id.substr(4);
|
||||
// delete this.__id;
|
||||
this.toHexString();
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
exports.ObjectID = ObjectID;
|
||||
exports.ObjectId = ObjectID;
|
||||
48
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js
generated
vendored
Normal file
48
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* A class representation of the BSON Symbol type.
|
||||
*
|
||||
* @class Represents the BSON Symbol type.
|
||||
* @param {String} value the string representing the symbol.
|
||||
* @return {Symbol}
|
||||
*/
|
||||
function Symbol(value) {
|
||||
if(!(this instanceof Symbol)) return new Symbol(value);
|
||||
this._bsontype = 'Symbol';
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access the wrapped string value.
|
||||
*
|
||||
* @return {String} returns the wrapped string.
|
||||
* @api public
|
||||
*/
|
||||
Symbol.prototype.valueOf = function() {
|
||||
return this.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Symbol.prototype.toString = function() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Symbol.prototype.inspect = function() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
* @api private
|
||||
*/
|
||||
Symbol.prototype.toJSON = function() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
exports.Symbol = Symbol;
|
||||
853
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js
generated
vendored
Normal file
853
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js
generated
vendored
Normal file
@@ -0,0 +1,853 @@
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
// Copyright 2009 Google Inc. All Rights Reserved
|
||||
|
||||
/**
|
||||
* Defines a Timestamp class for representing a 64-bit two's-complement
|
||||
* integer value, which faithfully simulates the behavior of a Java "Timestamp". This
|
||||
* implementation is derived from TimestampLib in GWT.
|
||||
*
|
||||
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit
|
||||
* values as *signed* integers. See the from* functions below for more
|
||||
* convenient ways of constructing Timestamps.
|
||||
*
|
||||
* The internal representation of a Timestamp is the two given signed, 32-bit values.
|
||||
* We use 32-bit pieces because these are the size of integers on which
|
||||
* Javascript performs bit-operations. For operations like addition and
|
||||
* multiplication, we split each number into 16-bit pieces, which can easily be
|
||||
* multiplied within Javascript's floating-point representation without overflow
|
||||
* or change in sign.
|
||||
*
|
||||
* In the algorithms below, we frequently reduce the negative case to the
|
||||
* positive case by negating the input(s) and then post-processing the result.
|
||||
* Note that we must ALWAYS check specially whether those values are MIN_VALUE
|
||||
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
|
||||
* a positive number, it overflows back into a negative). Not handling this
|
||||
* case would often result in infinite recursion.
|
||||
*
|
||||
* @class Represents the BSON Timestamp type.
|
||||
* @param {Number} low the low (signed) 32 bits of the Timestamp.
|
||||
* @param {Number} high the high (signed) 32 bits of the Timestamp.
|
||||
*/
|
||||
function Timestamp(low, high) {
|
||||
if(!(this instanceof Timestamp)) return new Timestamp(low, high);
|
||||
this._bsontype = 'Timestamp';
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
this.low_ = low | 0; // force into 32 signed bits.
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
this.high_ = high | 0; // force into 32 signed bits.
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the int value.
|
||||
*
|
||||
* @return {Number} the value, assuming it is a 32-bit integer.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.toInt = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the Number value.
|
||||
*
|
||||
* @return {Number} the closest floating-point representation to this value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.toNumber = function() {
|
||||
return this.high_ * Timestamp.TWO_PWR_32_DBL_ +
|
||||
this.getLowBitsUnsigned();
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the JSON value.
|
||||
*
|
||||
* @return {String} the JSON representation.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.toJSON = function() {
|
||||
return this.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the String value.
|
||||
*
|
||||
* @param {Number} [opt_radix] the radix in which the text should be written.
|
||||
* @return {String} the textual representation of this value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.toString = function(opt_radix) {
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (this.isZero()) {
|
||||
return '0';
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
// We need to change the Timestamp value before it can be negated, so we remove
|
||||
// the bottom-most digit in this base and then recurse to do the rest.
|
||||
var radixTimestamp = Timestamp.fromNumber(radix);
|
||||
var div = this.div(radixTimestamp);
|
||||
var rem = div.multiply(radixTimestamp).subtract(this);
|
||||
return div.toString(radix) + rem.toInt().toString(radix);
|
||||
} else {
|
||||
return '-' + this.negate().toString(radix);
|
||||
}
|
||||
}
|
||||
|
||||
// Do several (6) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6));
|
||||
|
||||
var rem = this;
|
||||
var result = '';
|
||||
while (true) {
|
||||
var remDiv = rem.div(radixToPower);
|
||||
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt();
|
||||
var digits = intval.toString(radix);
|
||||
|
||||
rem = remDiv;
|
||||
if (rem.isZero()) {
|
||||
return digits + result;
|
||||
} else {
|
||||
while (digits.length < 6) {
|
||||
digits = '0' + digits;
|
||||
}
|
||||
result = '' + digits + result;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the high 32-bits value.
|
||||
*
|
||||
* @return {Number} the high 32-bits as a signed value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.getHighBits = function() {
|
||||
return this.high_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the low 32-bits value.
|
||||
*
|
||||
* @return {Number} the low 32-bits as a signed value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.getLowBits = function() {
|
||||
return this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return the low unsigned 32-bits value.
|
||||
*
|
||||
* @return {Number} the low 32-bits as an unsigned value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.getLowBitsUnsigned = function() {
|
||||
return (this.low_ >= 0) ?
|
||||
this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the number of bits needed to represent the absolute value of this Timestamp.
|
||||
*
|
||||
* @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.getNumBitsAbs = function() {
|
||||
if (this.isNegative()) {
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
return 64;
|
||||
} else {
|
||||
return this.negate().getNumBitsAbs();
|
||||
}
|
||||
} else {
|
||||
var val = this.high_ != 0 ? this.high_ : this.low_;
|
||||
for (var bit = 31; bit > 0; bit--) {
|
||||
if ((val & (1 << bit)) != 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return this.high_ != 0 ? bit + 33 : bit + 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is zero.
|
||||
*
|
||||
* @return {Boolean} whether this value is zero.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.isZero = function() {
|
||||
return this.high_ == 0 && this.low_ == 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is negative.
|
||||
*
|
||||
* @return {Boolean} whether this value is negative.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.isNegative = function() {
|
||||
return this.high_ < 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this value is odd.
|
||||
*
|
||||
* @return {Boolean} whether this value is odd.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.isOdd = function() {
|
||||
return (this.low_ & 1) == 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp equals the other
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {Boolean} whether this Timestamp equals the other
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.equals = function(other) {
|
||||
return (this.high_ == other.high_) && (this.low_ == other.low_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp does not equal the other.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {Boolean} whether this Timestamp does not equal the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.notEquals = function(other) {
|
||||
return (this.high_ != other.high_) || (this.low_ != other.low_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp is less than the other.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {Boolean} whether this Timestamp is less than the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.lessThan = function(other) {
|
||||
return this.compare(other) < 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp is less than or equal to the other.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {Boolean} whether this Timestamp is less than or equal to the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.lessThanOrEqual = function(other) {
|
||||
return this.compare(other) <= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp is greater than the other.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {Boolean} whether this Timestamp is greater than the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.greaterThan = function(other) {
|
||||
return this.compare(other) > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Return whether this Timestamp is greater than or equal to the other.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {Boolean} whether this Timestamp is greater than or equal to the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.greaterThanOrEqual = function(other) {
|
||||
return this.compare(other) >= 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Compares this Timestamp with the given one.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to compare against.
|
||||
* @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.compare = function(other) {
|
||||
if (this.equals(other)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var thisNeg = this.isNegative();
|
||||
var otherNeg = other.isNegative();
|
||||
if (thisNeg && !otherNeg) {
|
||||
return -1;
|
||||
}
|
||||
if (!thisNeg && otherNeg) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// at this point, the signs are the same, so subtraction will not overflow
|
||||
if (this.subtract(other).isNegative()) {
|
||||
return -1;
|
||||
} else {
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The negation of this value.
|
||||
*
|
||||
* @return {Timestamp} the negation of this value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.negate = function() {
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
return Timestamp.MIN_VALUE;
|
||||
} else {
|
||||
return this.not().add(Timestamp.ONE);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the sum of this and the given Timestamp.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to add to this one.
|
||||
* @return {Timestamp} the sum of this and the given Timestamp.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.add = function(other) {
|
||||
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xFFFF;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xFFFF;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xFFFF;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xFFFF;
|
||||
|
||||
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
|
||||
c00 += a00 + b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xFFFF;
|
||||
c16 += a16 + b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c32 += a32 + b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c48 += a48 + b48;
|
||||
c48 &= 0xFFFF;
|
||||
return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the difference of this and the given Timestamp.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to subtract from this.
|
||||
* @return {Timestamp} the difference of this and the given Timestamp.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.subtract = function(other) {
|
||||
return this.add(other.negate());
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the product of this and the given Timestamp.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp to multiply with this.
|
||||
* @return {Timestamp} the product of this and the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.multiply = function(other) {
|
||||
if (this.isZero()) {
|
||||
return Timestamp.ZERO;
|
||||
} else if (other.isZero()) {
|
||||
return Timestamp.ZERO;
|
||||
}
|
||||
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;
|
||||
} else if (other.equals(Timestamp.MIN_VALUE)) {
|
||||
return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().multiply(other.negate());
|
||||
} else {
|
||||
return this.negate().multiply(other).negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.multiply(other.negate()).negate();
|
||||
}
|
||||
|
||||
// If both Timestamps are small, use float multiplication
|
||||
if (this.lessThan(Timestamp.TWO_PWR_24_) &&
|
||||
other.lessThan(Timestamp.TWO_PWR_24_)) {
|
||||
return Timestamp.fromNumber(this.toNumber() * other.toNumber());
|
||||
}
|
||||
|
||||
// Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products.
|
||||
// We can skip products that would overflow.
|
||||
|
||||
var a48 = this.high_ >>> 16;
|
||||
var a32 = this.high_ & 0xFFFF;
|
||||
var a16 = this.low_ >>> 16;
|
||||
var a00 = this.low_ & 0xFFFF;
|
||||
|
||||
var b48 = other.high_ >>> 16;
|
||||
var b32 = other.high_ & 0xFFFF;
|
||||
var b16 = other.low_ >>> 16;
|
||||
var b00 = other.low_ & 0xFFFF;
|
||||
|
||||
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
|
||||
c00 += a00 * b00;
|
||||
c16 += c00 >>> 16;
|
||||
c00 &= 0xFFFF;
|
||||
c16 += a16 * b00;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c16 += a00 * b16;
|
||||
c32 += c16 >>> 16;
|
||||
c16 &= 0xFFFF;
|
||||
c32 += a32 * b00;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c32 += a16 * b16;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c32 += a00 * b32;
|
||||
c48 += c32 >>> 16;
|
||||
c32 &= 0xFFFF;
|
||||
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
|
||||
c48 &= 0xFFFF;
|
||||
return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp divided by the given one.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp by which to divide.
|
||||
* @return {Timestamp} this Timestamp divided by the given one.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.div = function(other) {
|
||||
if (other.isZero()) {
|
||||
throw Error('division by zero');
|
||||
} else if (this.isZero()) {
|
||||
return Timestamp.ZERO;
|
||||
}
|
||||
|
||||
if (this.equals(Timestamp.MIN_VALUE)) {
|
||||
if (other.equals(Timestamp.ONE) ||
|
||||
other.equals(Timestamp.NEG_ONE)) {
|
||||
return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
|
||||
} else if (other.equals(Timestamp.MIN_VALUE)) {
|
||||
return Timestamp.ONE;
|
||||
} else {
|
||||
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
|
||||
var halfThis = this.shiftRight(1);
|
||||
var approx = halfThis.div(other).shiftLeft(1);
|
||||
if (approx.equals(Timestamp.ZERO)) {
|
||||
return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE;
|
||||
} else {
|
||||
var rem = this.subtract(other.multiply(approx));
|
||||
var result = approx.add(rem.div(other));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else if (other.equals(Timestamp.MIN_VALUE)) {
|
||||
return Timestamp.ZERO;
|
||||
}
|
||||
|
||||
if (this.isNegative()) {
|
||||
if (other.isNegative()) {
|
||||
return this.negate().div(other.negate());
|
||||
} else {
|
||||
return this.negate().div(other).negate();
|
||||
}
|
||||
} else if (other.isNegative()) {
|
||||
return this.div(other.negate()).negate();
|
||||
}
|
||||
|
||||
// Repeat the following until the remainder is less than other: find a
|
||||
// floating-point that approximates remainder / other *from below*, add this
|
||||
// into the result, and subtract it from the remainder. It is critical that
|
||||
// the approximate value is less than or equal to the real value so that the
|
||||
// remainder never becomes negative.
|
||||
var res = Timestamp.ZERO;
|
||||
var rem = this;
|
||||
while (rem.greaterThanOrEqual(other)) {
|
||||
// Approximate the result of division. This may be a little greater or
|
||||
// smaller than the actual value.
|
||||
var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber()));
|
||||
|
||||
// We will tweak the approximate result by changing it in the 48-th digit or
|
||||
// the smallest non-fractional digit, whichever is larger.
|
||||
var log2 = Math.ceil(Math.log(approx) / Math.LN2);
|
||||
var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48);
|
||||
|
||||
// Decrease the approximation until it is smaller than the remainder. Note
|
||||
// that if it is too large, the product overflows and is negative.
|
||||
var approxRes = Timestamp.fromNumber(approx);
|
||||
var approxRem = approxRes.multiply(other);
|
||||
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
|
||||
approx -= delta;
|
||||
approxRes = Timestamp.fromNumber(approx);
|
||||
approxRem = approxRes.multiply(other);
|
||||
}
|
||||
|
||||
// We know the answer can't be zero... and actually, zero would cause
|
||||
// infinite recursion since we would make no progress.
|
||||
if (approxRes.isZero()) {
|
||||
approxRes = Timestamp.ONE;
|
||||
}
|
||||
|
||||
res = res.add(approxRes);
|
||||
rem = rem.subtract(approxRem);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp modulo the given one.
|
||||
*
|
||||
* @param {Timestamp} other Timestamp by which to mod.
|
||||
* @return {Timestamp} this Timestamp modulo the given one.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.modulo = function(other) {
|
||||
return this.subtract(this.div(other).multiply(other));
|
||||
};
|
||||
|
||||
/**
|
||||
* The bitwise-NOT of this value.
|
||||
*
|
||||
* @return {Timestamp} the bitwise-NOT of this value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.not = function() {
|
||||
return Timestamp.fromBits(~this.low_, ~this.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-AND of this Timestamp and the given one.
|
||||
*
|
||||
* @param {Timestamp} other the Timestamp with which to AND.
|
||||
* @return {Timestamp} the bitwise-AND of this and the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.and = function(other) {
|
||||
return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-OR of this Timestamp and the given one.
|
||||
*
|
||||
* @param {Timestamp} other the Timestamp with which to OR.
|
||||
* @return {Timestamp} the bitwise-OR of this and the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.or = function(other) {
|
||||
return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the bitwise-XOR of this Timestamp and the given one.
|
||||
*
|
||||
* @param {Timestamp} other the Timestamp with which to XOR.
|
||||
* @return {Timestamp} the bitwise-XOR of this and the other.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.xor = function(other) {
|
||||
return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp with bits shifted to the left by the given amount.
|
||||
*
|
||||
* @param {Number} numBits the number of bits by which to shift.
|
||||
* @return {Timestamp} this shifted to the left by the given amount.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.shiftLeft = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var low = this.low_;
|
||||
if (numBits < 32) {
|
||||
var high = this.high_;
|
||||
return Timestamp.fromBits(
|
||||
low << numBits,
|
||||
(high << numBits) | (low >>> (32 - numBits)));
|
||||
} else {
|
||||
return Timestamp.fromBits(0, low << (numBits - 32));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp with bits shifted to the right by the given amount.
|
||||
*
|
||||
* @param {Number} numBits the number of bits by which to shift.
|
||||
* @return {Timestamp} this shifted to the right by the given amount.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.shiftRight = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return Timestamp.fromBits(
|
||||
(low >>> numBits) | (high << (32 - numBits)),
|
||||
high >> numBits);
|
||||
} else {
|
||||
return Timestamp.fromBits(
|
||||
high >> (numBits - 32),
|
||||
high >= 0 ? 0 : -1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit.
|
||||
*
|
||||
* @param {Number} numBits the number of bits by which to shift.
|
||||
* @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.prototype.shiftRightUnsigned = function(numBits) {
|
||||
numBits &= 63;
|
||||
if (numBits == 0) {
|
||||
return this;
|
||||
} else {
|
||||
var high = this.high_;
|
||||
if (numBits < 32) {
|
||||
var low = this.low_;
|
||||
return Timestamp.fromBits(
|
||||
(low >>> numBits) | (high << (32 - numBits)),
|
||||
high >>> numBits);
|
||||
} else if (numBits == 32) {
|
||||
return Timestamp.fromBits(high, 0);
|
||||
} else {
|
||||
return Timestamp.fromBits(high >>> (numBits - 32), 0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Timestamp representing the given (32-bit) integer value.
|
||||
*
|
||||
* @param {Number} value the 32-bit integer in question.
|
||||
* @return {Timestamp} the corresponding Timestamp value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.fromInt = function(value) {
|
||||
if (-128 <= value && value < 128) {
|
||||
var cachedObj = Timestamp.INT_CACHE_[value];
|
||||
if (cachedObj) {
|
||||
return cachedObj;
|
||||
}
|
||||
}
|
||||
|
||||
var obj = new Timestamp(value | 0, value < 0 ? -1 : 0);
|
||||
if (-128 <= value && value < 128) {
|
||||
Timestamp.INT_CACHE_[value] = obj;
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned.
|
||||
*
|
||||
* @param {Number} value the number in question.
|
||||
* @return {Timestamp} the corresponding Timestamp value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.fromNumber = function(value) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return Timestamp.ZERO;
|
||||
} else if (value <= -Timestamp.TWO_PWR_63_DBL_) {
|
||||
return Timestamp.MIN_VALUE;
|
||||
} else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) {
|
||||
return Timestamp.MAX_VALUE;
|
||||
} else if (value < 0) {
|
||||
return Timestamp.fromNumber(-value).negate();
|
||||
} else {
|
||||
return new Timestamp(
|
||||
(value % Timestamp.TWO_PWR_32_DBL_) | 0,
|
||||
(value / Timestamp.TWO_PWR_32_DBL_) | 0);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits.
|
||||
*
|
||||
* @param {Number} lowBits the low 32-bits.
|
||||
* @param {Number} highBits the high 32-bits.
|
||||
* @return {Timestamp} the corresponding Timestamp value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.fromBits = function(lowBits, highBits) {
|
||||
return new Timestamp(lowBits, highBits);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Timestamp representation of the given string, written using the given radix.
|
||||
*
|
||||
* @param {String} str the textual representation of the Timestamp.
|
||||
* @param {Number} opt_radix the radix in which the text is written.
|
||||
* @return {Timestamp} the corresponding Timestamp value.
|
||||
* @api public
|
||||
*/
|
||||
Timestamp.fromString = function(str, opt_radix) {
|
||||
if (str.length == 0) {
|
||||
throw Error('number format error: empty string');
|
||||
}
|
||||
|
||||
var radix = opt_radix || 10;
|
||||
if (radix < 2 || 36 < radix) {
|
||||
throw Error('radix out of range: ' + radix);
|
||||
}
|
||||
|
||||
if (str.charAt(0) == '-') {
|
||||
return Timestamp.fromString(str.substring(1), radix).negate();
|
||||
} else if (str.indexOf('-') >= 0) {
|
||||
throw Error('number format error: interior "-" character: ' + str);
|
||||
}
|
||||
|
||||
// Do several (8) digits each time through the loop, so as to
|
||||
// minimize the calls to the very expensive emulated div.
|
||||
var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8));
|
||||
|
||||
var result = Timestamp.ZERO;
|
||||
for (var i = 0; i < str.length; i += 8) {
|
||||
var size = Math.min(8, str.length - i);
|
||||
var value = parseInt(str.substring(i, i + size), radix);
|
||||
if (size < 8) {
|
||||
var power = Timestamp.fromNumber(Math.pow(radix, size));
|
||||
result = result.multiply(power).add(Timestamp.fromNumber(value));
|
||||
} else {
|
||||
result = result.multiply(radixToPower);
|
||||
result = result.add(Timestamp.fromNumber(value));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
|
||||
// from* methods on which they depend.
|
||||
|
||||
|
||||
/**
|
||||
* A cache of the Timestamp representations of small integer values.
|
||||
* @type {Object}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.INT_CACHE_ = {};
|
||||
|
||||
// NOTE: the compiler should inline these constant values below and then remove
|
||||
// these variables, so there should be no runtime penalty for these.
|
||||
|
||||
/**
|
||||
* Number used repeated below in calculations. This must appear before the
|
||||
* first call to any from* function below.
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.TWO_PWR_16_DBL_ = 1 << 16;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.TWO_PWR_24_DBL_ = 1 << 24;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2;
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.ZERO = Timestamp.fromInt(0);
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.ONE = Timestamp.fromInt(1);
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.NEG_ONE = Timestamp.fromInt(-1);
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.MAX_VALUE =
|
||||
Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0);
|
||||
|
||||
/** @type {Timestamp} */
|
||||
Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0);
|
||||
|
||||
/**
|
||||
* @type {Timestamp}
|
||||
* @api private
|
||||
*/
|
||||
Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24);
|
||||
|
||||
/**
|
||||
* Expose.
|
||||
*/
|
||||
exports.Timestamp = Timestamp;
|
||||
51
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/package.json
generated
vendored
Normal file
51
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/package.json
generated
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "bson",
|
||||
"description": "A bson parser for node.js and the browser",
|
||||
"keywords": [
|
||||
"mongodb",
|
||||
"bson",
|
||||
"parser"
|
||||
],
|
||||
"version": "0.1.8",
|
||||
"author": {
|
||||
"name": "Christian Amor Kvalheim",
|
||||
"email": "christkv@gmail.com"
|
||||
},
|
||||
"contributors": [],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/mongodb/js-bson.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/mongodb/js-bson/issues"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodeunit": "0.7.3",
|
||||
"gleak": "0.2.3",
|
||||
"one": "latest"
|
||||
},
|
||||
"config": {
|
||||
"native": false
|
||||
},
|
||||
"main": "./lib/bson/index",
|
||||
"directories": {
|
||||
"lib": "./lib/bson"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6.19"
|
||||
},
|
||||
"scripts": {
|
||||
"install": "(node-gyp rebuild 2> builderror.log) || (exit 0)",
|
||||
"test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node"
|
||||
},
|
||||
"licenses": [
|
||||
{
|
||||
"type": "Apache License, Version 2.0",
|
||||
"url": "http://www.apache.org/licenses/LICENSE-2.0"
|
||||
}
|
||||
],
|
||||
"readme": "A JS/C++ Bson parser for node, used in the MongoDB Native driver",
|
||||
"readmeFilename": "README.md",
|
||||
"_id": "bson@0.1.8",
|
||||
"_from": "bson@0.1.8"
|
||||
}
|
||||
19
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/browser_example.htm
generated
vendored
Normal file
19
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/browser_example.htm
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
<head>
|
||||
<script src="https://raw.github.com/mongodb/js-bson/master/browser_build/bson.js">
|
||||
</script>
|
||||
</head>
|
||||
<body onload="start();">
|
||||
<script>
|
||||
function start() {
|
||||
var BSON = bson().BSON;
|
||||
var Long = bson().Long;
|
||||
|
||||
var doc = {long: Long.fromNumber(100)}
|
||||
|
||||
// Serialize a document
|
||||
var data = BSON.serialize(doc, false, true, false);
|
||||
// De serialize it again
|
||||
var doc_2 = BSON.deserialize(data);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
260
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/bson_test.js
generated
vendored
Normal file
260
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/bson_test.js
generated
vendored
Normal file
@@ -0,0 +1,260 @@
|
||||
this.bson_test = {
|
||||
'Full document serialization and deserialization': function (test) {
|
||||
var motherOfAllDocuments = {
|
||||
'string': "客家话",
|
||||
'array': [1,2,3],
|
||||
'hash': {'a':1, 'b':2},
|
||||
'date': new Date(),
|
||||
'oid': new ObjectID(),
|
||||
'binary': new Binary('hello world'),
|
||||
'int': 42,
|
||||
'float': 33.3333,
|
||||
'regexp': /regexp/,
|
||||
'boolean': true,
|
||||
'long': Long.fromNumber(100),
|
||||
'where': new Code('this.a > i', {i:1}),
|
||||
'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
|
||||
'minkey': new MinKey(),
|
||||
'maxkey': new MaxKey()
|
||||
}
|
||||
|
||||
// Let's serialize it
|
||||
var data = BSON.serialize(motherOfAllDocuments, true, true, false);
|
||||
// Deserialize the object
|
||||
var object = BSON.deserialize(data);
|
||||
|
||||
// Asserts
|
||||
test.equal(Utf8.decode(motherOfAllDocuments.string), object.string);
|
||||
test.deepEqual(motherOfAllDocuments.array, object.array);
|
||||
test.deepEqual(motherOfAllDocuments.date, object.date);
|
||||
test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
|
||||
test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
|
||||
test.ok(assertArrayEqual(motherOfAllDocuments.binary.value(true), object.binary.value(true)));
|
||||
test.deepEqual(motherOfAllDocuments.int, object.int);
|
||||
test.deepEqual(motherOfAllDocuments.float, object.float);
|
||||
test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
|
||||
test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
|
||||
test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long);
|
||||
test.deepEqual(motherOfAllDocuments.where, object.where);
|
||||
test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
|
||||
test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
|
||||
test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
|
||||
test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
|
||||
test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
|
||||
test.done();
|
||||
},
|
||||
|
||||
'exercise all the binary object constructor methods': function (test) {
|
||||
// Construct using array
|
||||
var string = 'hello world';
|
||||
// String to array
|
||||
var array = stringToArrayBuffer(string);
|
||||
|
||||
// Binary from array buffer
|
||||
var binary = new Binary(stringToArrayBuffer(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
test.ok(assertArrayEqual(array, binary.buffer));
|
||||
|
||||
// Construct using number of chars
|
||||
binary = new Binary(5);
|
||||
test.ok(5, binary.buffer.length);
|
||||
|
||||
// Construct using an Array
|
||||
var binary = new Binary(stringToArray(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
test.ok(assertArrayEqual(array, binary.buffer));
|
||||
|
||||
// Construct using a string
|
||||
var binary = new Binary(string);
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
test.ok(assertArrayEqual(array, binary.buffer));
|
||||
test.done();
|
||||
},
|
||||
|
||||
'exercise the put binary object method for an instance when using Uint8Array': function (test) {
|
||||
// Construct using array
|
||||
var string = 'hello world';
|
||||
// String to array
|
||||
var array = stringToArrayBuffer(string + 'a');
|
||||
|
||||
// Binary from array buffer
|
||||
var binary = new Binary(stringToArrayBuffer(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
|
||||
// Write a byte to the array
|
||||
binary.put('a')
|
||||
|
||||
// Verify that the data was writtencorrectly
|
||||
test.equal(string.length + 1, binary.position);
|
||||
test.ok(assertArrayEqual(array, binary.value(true)));
|
||||
test.equal('hello worlda', binary.value());
|
||||
|
||||
// Exercise a binary with lots of space in the buffer
|
||||
var binary = new Binary();
|
||||
test.ok(Binary.BUFFER_SIZE, binary.buffer.length);
|
||||
|
||||
// Write a byte to the array
|
||||
binary.put('a')
|
||||
|
||||
// Verify that the data was writtencorrectly
|
||||
test.equal(1, binary.position);
|
||||
test.ok(assertArrayEqual(['a'.charCodeAt(0)], binary.value(true)));
|
||||
test.equal('a', binary.value());
|
||||
test.done();
|
||||
},
|
||||
|
||||
'exercise the write binary object method for an instance when using Uint8Array': function (test) {
|
||||
// Construct using array
|
||||
var string = 'hello world';
|
||||
// Array
|
||||
var writeArrayBuffer = new Uint8Array(new ArrayBuffer(1));
|
||||
writeArrayBuffer[0] = 'a'.charCodeAt(0);
|
||||
var arrayBuffer = ['a'.charCodeAt(0)];
|
||||
|
||||
// Binary from array buffer
|
||||
var binary = new Binary(stringToArrayBuffer(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
|
||||
// Write a string starting at end of buffer
|
||||
binary.write('a');
|
||||
test.equal('hello worlda', binary.value());
|
||||
// Write a string starting at index 0
|
||||
binary.write('a', 0);
|
||||
test.equal('aello worlda', binary.value());
|
||||
// Write a arraybuffer starting at end of buffer
|
||||
binary.write(writeArrayBuffer);
|
||||
test.equal('aello worldaa', binary.value());
|
||||
// Write a arraybuffer starting at position 5
|
||||
binary.write(writeArrayBuffer, 5);
|
||||
test.equal('aelloaworldaa', binary.value());
|
||||
// Write a array starting at end of buffer
|
||||
binary.write(arrayBuffer);
|
||||
test.equal('aelloaworldaaa', binary.value());
|
||||
// Write a array starting at position 6
|
||||
binary.write(arrayBuffer, 6);
|
||||
test.equal('aelloaaorldaaa', binary.value());
|
||||
test.done();
|
||||
},
|
||||
|
||||
'exercise the read binary object method for an instance when using Uint8Array': function (test) {
|
||||
// Construct using array
|
||||
var string = 'hello world';
|
||||
var array = stringToArrayBuffer(string);
|
||||
|
||||
// Binary from array buffer
|
||||
var binary = new Binary(stringToArrayBuffer(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
|
||||
// Read the first 2 bytes
|
||||
var data = binary.read(0, 2);
|
||||
test.ok(assertArrayEqual(stringToArrayBuffer('he'), data));
|
||||
|
||||
// Read the entire field
|
||||
var data = binary.read(0);
|
||||
test.ok(assertArrayEqual(stringToArrayBuffer(string), data));
|
||||
|
||||
// Read 3 bytes
|
||||
var data = binary.read(6, 5);
|
||||
test.ok(assertArrayEqual(stringToArrayBuffer('world'), data));
|
||||
test.done();
|
||||
},
|
||||
|
||||
'Should correctly handle toBson function for an object': function(test) {
|
||||
// Test object
|
||||
var doc = {
|
||||
hello: new ObjectID(),
|
||||
a:1
|
||||
};
|
||||
// Add a toBson method to the object
|
||||
doc.toBSON = function() {
|
||||
return {b:1};
|
||||
}
|
||||
|
||||
// Serialize the data
|
||||
var serialized_data = BSON.serialize(doc, false, true);
|
||||
var deserialized_doc = BSON.deserialize(serialized_data);
|
||||
test.equal(1, deserialized_doc.b);
|
||||
test.done();
|
||||
}
|
||||
};
|
||||
|
||||
var assertArrayEqual = function(array1, array2) {
|
||||
if(array1.length != array2.length) return false;
|
||||
for(var i = 0; i < array1.length; i++) {
|
||||
if(array1[i] != array2[i]) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// String to arraybuffer
|
||||
var stringToArrayBuffer = function(string) {
|
||||
var dataBuffer = new Uint8Array(new ArrayBuffer(string.length));
|
||||
// Return the strings
|
||||
for(var i = 0; i < string.length; i++) {
|
||||
dataBuffer[i] = string.charCodeAt(i);
|
||||
}
|
||||
// Return the data buffer
|
||||
return dataBuffer;
|
||||
}
|
||||
|
||||
// String to arraybuffer
|
||||
var stringToArray = function(string) {
|
||||
var dataBuffer = new Array(string.length);
|
||||
// Return the strings
|
||||
for(var i = 0; i < string.length; i++) {
|
||||
dataBuffer[i] = string.charCodeAt(i);
|
||||
}
|
||||
// Return the data buffer
|
||||
return dataBuffer;
|
||||
}
|
||||
|
||||
var Utf8 = {
|
||||
// public method for url encoding
|
||||
encode : function (string) {
|
||||
string = string.replace(/\r\n/g,"\n");
|
||||
var utftext = "";
|
||||
|
||||
for (var n = 0; n < string.length; n++) {
|
||||
var c = string.charCodeAt(n);
|
||||
if (c < 128) {
|
||||
utftext += String.fromCharCode(c);
|
||||
} else if((c > 127) && (c < 2048)) {
|
||||
utftext += String.fromCharCode((c >> 6) | 192);
|
||||
utftext += String.fromCharCode((c & 63) | 128);
|
||||
} else {
|
||||
utftext += String.fromCharCode((c >> 12) | 224);
|
||||
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
|
||||
utftext += String.fromCharCode((c & 63) | 128);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return utftext;
|
||||
},
|
||||
|
||||
// public method for url decoding
|
||||
decode : function (utftext) {
|
||||
var string = "";
|
||||
var i = 0;
|
||||
var c = c1 = c2 = 0;
|
||||
|
||||
while ( i < utftext.length ) {
|
||||
c = utftext.charCodeAt(i);
|
||||
if(c < 128) {
|
||||
string += String.fromCharCode(c);
|
||||
i++;
|
||||
} else if((c > 191) && (c < 224)) {
|
||||
c2 = utftext.charCodeAt(i+1);
|
||||
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
|
||||
i += 2;
|
||||
} else {
|
||||
c2 = utftext.charCodeAt(i+1);
|
||||
c3 = utftext.charCodeAt(i+2);
|
||||
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
|
||||
i += 3;
|
||||
}
|
||||
}
|
||||
return string;
|
||||
}
|
||||
}
|
||||
2034
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/nodeunit.js
generated
vendored
Normal file
2034
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/nodeunit.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
13
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/suite2.js
generated
vendored
Normal file
13
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/suite2.js
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
this.suite2 = {
|
||||
'another test': function (test) {
|
||||
setTimeout(function () {
|
||||
// lots of assertions
|
||||
test.ok(true, 'everythings ok');
|
||||
test.ok(true, 'everythings ok');
|
||||
test.ok(true, 'everythings ok');
|
||||
test.ok(true, 'everythings ok');
|
||||
test.ok(true, 'everythings ok');
|
||||
test.done();
|
||||
}, 10);
|
||||
}
|
||||
};
|
||||
7
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/suite3.js
generated
vendored
Normal file
7
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/suite3.js
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
this.suite3 = {
|
||||
'test for ie6,7,8': function (test) {
|
||||
test.deepEqual(["test"], ["test"]);
|
||||
test.notDeepEqual(["a"], ["b"]);
|
||||
test.done();
|
||||
}
|
||||
};
|
||||
30
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/test.html
generated
vendored
Normal file
30
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/browser/test.html
generated
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>Example tests</title>
|
||||
<!-- Actual BSON Code -->
|
||||
<script src="../../lib/bson/binary_parser.js"></script>
|
||||
<script src="../../lib/bson/code.js"></script>
|
||||
<script src="../../lib/bson/db_ref.js"></script>
|
||||
<script src="../../lib/bson/double.js"></script>
|
||||
<script src="../../lib/bson/float_parser.js"></script>
|
||||
<script src="../../lib/bson/long.js"></script>
|
||||
<script src="../../lib/bson/max_key.js"></script>
|
||||
<script src="../../lib/bson/min_key.js"></script>
|
||||
<script src="../../lib/bson/objectid.js"></script>
|
||||
<script src="../../lib/bson/symbol.js"></script>
|
||||
<script src="../../lib/bson/timestamp.js"></script>
|
||||
<script src="../../lib/bson/bson.js"></script>
|
||||
<script src="../../lib/bson/binary.js"></script>
|
||||
|
||||
<!-- Unit tests -->
|
||||
<script src="nodeunit.js"></script>
|
||||
<script src="bson_test.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
nodeunit.run({
|
||||
'bson_test': bson_test,
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
240
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/bson_array_test.js
generated
vendored
Normal file
240
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/bson_array_test.js
generated
vendored
Normal file
@@ -0,0 +1,240 @@
|
||||
var mongodb = require('../../lib/bson').pure();
|
||||
|
||||
var testCase = require('nodeunit').testCase,
|
||||
mongoO = require('../../lib/bson').pure(),
|
||||
debug = require('util').debug,
|
||||
inspect = require('util').inspect,
|
||||
Buffer = require('buffer').Buffer,
|
||||
gleak = require('../../tools/gleak'),
|
||||
fs = require('fs'),
|
||||
BSON = mongoO.BSON,
|
||||
Code = mongoO.Code,
|
||||
Binary = mongoO.Binary,
|
||||
Timestamp = mongoO.Timestamp,
|
||||
Long = mongoO.Long,
|
||||
MongoReply = mongoO.MongoReply,
|
||||
ObjectID = mongoO.ObjectID,
|
||||
Symbol = mongoO.Symbol,
|
||||
DBRef = mongoO.DBRef,
|
||||
Double = mongoO.Double,
|
||||
MinKey = mongoO.MinKey,
|
||||
MaxKey = mongoO.MaxKey,
|
||||
BinaryParser = mongoO.BinaryParser,
|
||||
utils = require('./tools/utils');
|
||||
|
||||
var BSONSE = mongodb,
|
||||
BSONDE = mongodb;
|
||||
|
||||
// for tests
|
||||
BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
var hexStringToBinary = function(string) {
|
||||
var numberofValues = string.length / 2;
|
||||
var array = "";
|
||||
|
||||
for(var i = 0; i < numberofValues; i++) {
|
||||
array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16));
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
var assertBuffersEqual = function(test, buffer1, buffer2) {
|
||||
if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2);
|
||||
|
||||
for(var i = 0; i < buffer1.length; i++) {
|
||||
test.equal(buffer1[i], buffer2[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Module for parsing an ISO 8601 formatted string into a Date object.
|
||||
*/
|
||||
var ISODate = function (string) {
|
||||
var match;
|
||||
|
||||
if (typeof string.getTime === "function")
|
||||
return string;
|
||||
else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) {
|
||||
var date = new Date();
|
||||
date.setUTCFullYear(Number(match[1]));
|
||||
date.setUTCMonth(Number(match[3]) - 1 || 0);
|
||||
date.setUTCDate(Number(match[5]) || 0);
|
||||
date.setUTCHours(Number(match[7]) || 0);
|
||||
date.setUTCMinutes(Number(match[8]) || 0);
|
||||
date.setUTCSeconds(Number(match[10]) || 0);
|
||||
date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0);
|
||||
|
||||
if (match[13] && match[13] !== "Z") {
|
||||
var h = Number(match[16]) || 0,
|
||||
m = Number(match[17]) || 0;
|
||||
|
||||
h *= 3600000;
|
||||
m *= 60000;
|
||||
|
||||
var offset = h + m;
|
||||
if (match[15] == "+")
|
||||
offset = -offset;
|
||||
|
||||
date = new Date(date.valueOf() + offset);
|
||||
}
|
||||
|
||||
return date;
|
||||
} else
|
||||
throw new Error("Invalid ISO 8601 date given.", __filename);
|
||||
};
|
||||
|
||||
var _Uint8Array = null;
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.setUp = function(callback) {
|
||||
_Uint8Array = global.Uint8Array;
|
||||
delete global['Uint8Array'];
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.tearDown = function(callback) {
|
||||
global['Uint8Array'] = _Uint8Array;
|
||||
callback();
|
||||
}
|
||||
|
||||
// /**
|
||||
// * @ignore
|
||||
// */
|
||||
// exports.shouldCorrectlyDeserializeUsingTypedArray = function(test) {
|
||||
// var motherOfAllDocuments = {
|
||||
// 'string': '客家话',
|
||||
// 'array': [1,2,3],
|
||||
// 'hash': {'a':1, 'b':2},
|
||||
// 'date': new Date(),
|
||||
// 'oid': new ObjectID(),
|
||||
// 'binary': new Binary(new Buffer("hello")),
|
||||
// 'int': 42,
|
||||
// 'float': 33.3333,
|
||||
// 'regexp': /regexp/,
|
||||
// 'boolean': true,
|
||||
// 'long': Long.fromNumber(100),
|
||||
// 'where': new Code('this.a > i', {i:1}),
|
||||
// 'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
|
||||
// 'minkey': new MinKey(),
|
||||
// 'maxkey': new MaxKey()
|
||||
// }
|
||||
//
|
||||
// // Let's serialize it
|
||||
// var data = BSONSE.BSON.serialize(motherOfAllDocuments, true, true, false);
|
||||
// // Build a typed array
|
||||
// var arr = new Uint8Array(new ArrayBuffer(data.length));
|
||||
// // Iterate over all the fields and copy
|
||||
// for(var i = 0; i < data.length; i++) {
|
||||
// arr[i] = data[i]
|
||||
// }
|
||||
//
|
||||
// // Deserialize the object
|
||||
// var object = BSONDE.BSON.deserialize(arr);
|
||||
// // Asserts
|
||||
// test.equal(motherOfAllDocuments.string, object.string);
|
||||
// test.deepEqual(motherOfAllDocuments.array, object.array);
|
||||
// test.deepEqual(motherOfAllDocuments.date, object.date);
|
||||
// test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
|
||||
// test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
|
||||
// // Assert the values of the binary
|
||||
// for(var i = 0; i < motherOfAllDocuments.binary.length(); i++) {
|
||||
// test.equal(motherOfAllDocuments.binary.value[i], object.binary[i]);
|
||||
// }
|
||||
// test.deepEqual(motherOfAllDocuments.int, object.int);
|
||||
// test.deepEqual(motherOfAllDocuments.float, object.float);
|
||||
// test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
|
||||
// test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
|
||||
// test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long);
|
||||
// test.deepEqual(motherOfAllDocuments.where, object.where);
|
||||
// test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
|
||||
// test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
|
||||
// test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
|
||||
// test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
|
||||
// test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
|
||||
// test.done();
|
||||
// }
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports.shouldCorrectlySerializeUsingTypedArray = function(test) {
|
||||
var motherOfAllDocuments = {
|
||||
'string': 'hello',
|
||||
'array': [1,2,3],
|
||||
'hash': {'a':1, 'b':2},
|
||||
'date': new Date(),
|
||||
'oid': new ObjectID(),
|
||||
'binary': new Binary(new Buffer("hello")),
|
||||
'int': 42,
|
||||
'float': 33.3333,
|
||||
'regexp': /regexp/,
|
||||
'boolean': true,
|
||||
'long': Long.fromNumber(100),
|
||||
'where': new Code('this.a > i', {i:1}),
|
||||
'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
|
||||
'minkey': new MinKey(),
|
||||
'maxkey': new MaxKey()
|
||||
}
|
||||
|
||||
// Let's serialize it
|
||||
var data = BSONSE.BSON.serialize(motherOfAllDocuments, true, false, false);
|
||||
// And deserialize it again
|
||||
var object = BSONSE.BSON.deserialize(data);
|
||||
// Asserts
|
||||
test.equal(motherOfAllDocuments.string, object.string);
|
||||
test.deepEqual(motherOfAllDocuments.array, object.array);
|
||||
test.deepEqual(motherOfAllDocuments.date, object.date);
|
||||
test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
|
||||
test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
|
||||
// Assert the values of the binary
|
||||
for(var i = 0; i < motherOfAllDocuments.binary.length(); i++) {
|
||||
test.equal(motherOfAllDocuments.binary.value[i], object.binary[i]);
|
||||
}
|
||||
test.deepEqual(motherOfAllDocuments.int, object.int);
|
||||
test.deepEqual(motherOfAllDocuments.float, object.float);
|
||||
test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
|
||||
test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
|
||||
test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long);
|
||||
test.deepEqual(motherOfAllDocuments.where, object.where);
|
||||
test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
|
||||
test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
|
||||
test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
|
||||
test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
|
||||
test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.noGlobalsLeaked = function(test) {
|
||||
var leaks = gleak.detectNew();
|
||||
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
|
||||
test.done();
|
||||
}
|
||||
493
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/bson_parser_comparision_test.js
generated
vendored
Normal file
493
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/bson_parser_comparision_test.js
generated
vendored
Normal file
@@ -0,0 +1,493 @@
|
||||
var sys = require('util'),
|
||||
debug = require('util').debug,
|
||||
inspect = require('util').inspect,
|
||||
Buffer = require('buffer').Buffer,
|
||||
BSON = require('../../ext').BSON,
|
||||
Buffer = require('buffer').Buffer,
|
||||
BSONJS = require('../../lib/bson/bson').BSON,
|
||||
BinaryParser = require('../../lib/bson/binary_parser').BinaryParser,
|
||||
Long = require('../../lib/bson/long').Long,
|
||||
ObjectID = require('../../lib/bson/bson').ObjectID,
|
||||
Binary = require('../../lib/bson/bson').Binary,
|
||||
Code = require('../../lib/bson/bson').Code,
|
||||
DBRef = require('../../lib/bson/bson').DBRef,
|
||||
Symbol = require('../../lib/bson/bson').Symbol,
|
||||
Double = require('../../lib/bson/bson').Double,
|
||||
MaxKey = require('../../lib/bson/bson').MaxKey,
|
||||
MinKey = require('../../lib/bson/bson').MinKey,
|
||||
Timestamp = require('../../lib/bson/bson').Timestamp,
|
||||
gleak = require('../../tools/gleak'),
|
||||
assert = require('assert');
|
||||
|
||||
// Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey
|
||||
var bsonC = new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
|
||||
var bsonJS = new BSONJS([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.setUp = function(callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.tearDown = function(callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize simple edge value'] = function(test) {
|
||||
// Simple serialization and deserialization of edge value
|
||||
var doc = {doc:0x1ffffffffffffe};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
|
||||
var doc = {doc:-0x1ffffffffffffe};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly execute toJSON'] = function(test) {
|
||||
var a = Long.fromNumber(10);
|
||||
assert.equal(10, a);
|
||||
|
||||
var a = Long.fromNumber(9223372036854775807);
|
||||
assert.equal(9223372036854775807, a);
|
||||
|
||||
// Simple serialization and deserialization test for a Single String value
|
||||
var doc = {doc:'Serialize'};
|
||||
var simple_string_serialized = bsonC.serialize(doc, true, false);
|
||||
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Serialize and Deserialize nested document'] = function(test) {
|
||||
// Nested doc
|
||||
var doc = {a:{b:{c:1}}};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple integer serialization/deserialization test, including testing boundary conditions'] = function(test) {
|
||||
var doc = {doc:-1};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
|
||||
var doc = {doc:2147483648};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
|
||||
var doc = {doc:-2147483648};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization test for a Long value'] = function(test) {
|
||||
var doc = {doc:Long.fromNumber(9223372036854775807)};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize({doc:Long.fromNumber(9223372036854775807)}, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
|
||||
var doc = {doc:Long.fromNumber(-9223372036854775807)};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize({doc:Long.fromNumber(-9223372036854775807)}, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a Float value'] = function(test) {
|
||||
var doc = {doc:2222.3333};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
|
||||
var doc = {doc:-2222.3333};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a null value'] = function(test) {
|
||||
var doc = {doc:null};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a boolean value'] = function(test) {
|
||||
var doc = {doc:true};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a date value'] = function(test) {
|
||||
var date = new Date();
|
||||
var doc = {doc:date};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')), bsonC.deserialize(simple_string_serialized));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a boolean value'] = function(test) {
|
||||
var doc = {doc:/abcd/mi};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.equal(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString(), bsonC.deserialize(simple_string_serialized).doc.toString());
|
||||
|
||||
var doc = {doc:/abcd/};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc, false, true));
|
||||
assert.equal(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString(), bsonC.deserialize(simple_string_serialized).doc.toString());
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a objectId value'] = function(test) {
|
||||
var doc = {doc:new ObjectID()};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
var doc2 = {doc:ObjectID.createFromHexString(doc.doc.toHexString())};
|
||||
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize(doc2, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString(), bsonC.deserialize(simple_string_serialized).doc.toString());
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a Binary value'] = function(test) {
|
||||
var binary = new Binary();
|
||||
var string = 'binstring'
|
||||
for(var index = 0; index < string.length; index++) { binary.put(string.charAt(index)); }
|
||||
|
||||
var simple_string_serialized = bsonC.serialize({doc:binary}, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize({doc:binary}, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.value(), bsonC.deserialize(simple_string_serialized).doc.value());
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a Binary value of type 2'] = function(test) {
|
||||
var binary = new Binary(new Buffer('binstring'), Binary.SUBTYPE_BYTE_ARRAY);
|
||||
var simple_string_serialized = bsonC.serialize({doc:binary}, false, true);
|
||||
assert.deepEqual(simple_string_serialized, bsonJS.serialize({doc:binary}, false, true));
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.value(), bsonC.deserialize(simple_string_serialized).doc.value());
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a Code value'] = function(test) {
|
||||
var code = new Code('this.a > i', {'i': 1});
|
||||
var simple_string_serialized_2 = bsonJS.serialize({doc:code}, false, true);
|
||||
var simple_string_serialized = bsonC.serialize({doc:code}, false, true);
|
||||
|
||||
assert.deepEqual(simple_string_serialized, simple_string_serialized_2);
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary')).doc.scope, bsonC.deserialize(simple_string_serialized).doc.scope);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for an Object'] = function(test) {
|
||||
var simple_string_serialized = bsonC.serialize({doc:{a:1, b:{c:2}}}, false, true);
|
||||
var simple_string_serialized_2 = bsonJS.serialize({doc:{a:1, b:{c:2}}}, false, true);
|
||||
assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary')).doc, bsonC.deserialize(simple_string_serialized).doc);
|
||||
|
||||
// Simple serialization and deserialization for an Array
|
||||
var simple_string_serialized = bsonC.serialize({doc:[9, 9, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1]}, false, true);
|
||||
var simple_string_serialized_2 = bsonJS.serialize({doc:[9, 9, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1]}, false, true);
|
||||
|
||||
assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
|
||||
assert.deepEqual(bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary')).doc, bsonC.deserialize(simple_string_serialized).doc);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Simple serialization and deserialization for a DBRef'] = function(test) {
|
||||
var oid = new ObjectID()
|
||||
var oid2 = new ObjectID.createFromHexString(oid.toHexString())
|
||||
var simple_string_serialized = bsonJS.serialize({doc:new DBRef('namespace', oid2, 'integration_tests_')}, false, true);
|
||||
var simple_string_serialized_2 = bsonC.serialize({doc:new DBRef('namespace', oid, 'integration_tests_')}, false, true);
|
||||
|
||||
assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
|
||||
// Ensure we have the same values for the dbref
|
||||
var object_js = bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary'));
|
||||
var object_c = bsonC.deserialize(simple_string_serialized);
|
||||
|
||||
assert.equal(object_js.doc.namespace, object_c.doc.namespace);
|
||||
assert.equal(object_js.doc.oid.toHexString(), object_c.doc.oid.toHexString());
|
||||
assert.equal(object_js.doc.db, object_c.doc.db);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should correctly deserialize bytes array'] = function(test) {
|
||||
// Serialized document
|
||||
var bytes = [47,0,0,0,2,110,97,109,101,0,6,0,0,0,80,97,116,116,121,0,16,97,103,101,0,34,0,0,0,7,95,105,100,0,76,100,12,23,11,30,39,8,89,0,0,1,0];
|
||||
var serialized_data = '';
|
||||
// Convert to chars
|
||||
for(var i = 0; i < bytes.length; i++) {
|
||||
serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
|
||||
}
|
||||
var object = bsonC.deserialize(new Buffer(serialized_data, 'binary'));
|
||||
assert.equal('Patty', object.name)
|
||||
assert.equal(34, object.age)
|
||||
assert.equal('4c640c170b1e270859000001', object._id.toHexString())
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Serialize utf8'] = function(test) {
|
||||
var doc = { "name" : "本荘由利地域に洪水警報", "name1" : "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "name2" : "abcdedede"};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
var simple_string_serialized2 = bsonJS.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, simple_string_serialized2)
|
||||
|
||||
var object = bsonC.deserialize(simple_string_serialized);
|
||||
assert.equal(doc.name, object.name)
|
||||
assert.equal(doc.name1, object.name1)
|
||||
assert.equal(doc.name2, object.name2)
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Serialize object with array'] = function(test) {
|
||||
var doc = {b:[1, 2, 3]};
|
||||
var simple_string_serialized = bsonC.serialize(doc, false, true);
|
||||
var simple_string_serialized_2 = bsonJS.serialize(doc, false, true);
|
||||
assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
|
||||
|
||||
var object = bsonC.deserialize(simple_string_serialized);
|
||||
assert.deepEqual(doc, object)
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Test equality of an object ID'] = function(test) {
|
||||
var object_id = new ObjectID();
|
||||
var object_id_2 = new ObjectID();
|
||||
assert.ok(object_id.equals(object_id));
|
||||
assert.ok(!(object_id.equals(object_id_2)))
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Test same serialization for Object ID'] = function(test) {
|
||||
var object_id = new ObjectID();
|
||||
var object_id2 = ObjectID.createFromHexString(object_id.toString())
|
||||
var simple_string_serialized = bsonJS.serialize({doc:object_id}, false, true);
|
||||
var simple_string_serialized_2 = bsonC.serialize({doc:object_id2}, false, true);
|
||||
|
||||
assert.equal(simple_string_serialized_2.length, simple_string_serialized.length);
|
||||
assert.deepEqual(simple_string_serialized, simple_string_serialized_2)
|
||||
var object = bsonJS.deserialize(new Buffer(simple_string_serialized_2, 'binary'));
|
||||
var object2 = bsonC.deserialize(simple_string_serialized);
|
||||
assert.equal(object.doc.id, object2.doc.id)
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Complex object serialization'] = function(test) {
|
||||
// JS Object
|
||||
var c1 = { _id: new ObjectID, comments: [], title: 'number 1' };
|
||||
var c2 = { _id: new ObjectID, comments: [], title: 'number 2' };
|
||||
var doc = {
|
||||
numbers: []
|
||||
, owners: []
|
||||
, comments: [c1, c2]
|
||||
, _id: new ObjectID
|
||||
};
|
||||
|
||||
var simple_string_serialized = bsonJS.serialize(doc, false, true);
|
||||
|
||||
// C++ Object
|
||||
var c1 = { _id: ObjectID.createFromHexString(c1._id.toHexString()), comments: [], title: 'number 1' };
|
||||
var c2 = { _id: ObjectID.createFromHexString(c2._id.toHexString()), comments: [], title: 'number 2' };
|
||||
var doc = {
|
||||
numbers: []
|
||||
, owners: []
|
||||
, comments: [c1, c2]
|
||||
, _id: ObjectID.createFromHexString(doc._id.toHexString())
|
||||
};
|
||||
|
||||
var simple_string_serialized_2 = bsonC.serialize(doc, false, true);
|
||||
|
||||
for(var i = 0; i < simple_string_serialized_2.length; i++) {
|
||||
// debug(i + "[" + simple_string_serialized_2[i] + "] = [" + simple_string_serialized[i] + "]")
|
||||
assert.equal(simple_string_serialized_2[i], simple_string_serialized[i]);
|
||||
}
|
||||
|
||||
var doc1 = bsonJS.deserialize(new Buffer(simple_string_serialized_2));
|
||||
var doc2 = bsonC.deserialize(new Buffer(simple_string_serialized_2));
|
||||
assert.equal(doc._id.id, doc1._id.id)
|
||||
assert.equal(doc._id.id, doc2._id.id)
|
||||
assert.equal(doc1._id.id, doc2._id.id)
|
||||
|
||||
var doc = {
|
||||
_id: 'testid',
|
||||
key1: { code: 'test1', time: {start:1309323402727,end:1309323402727}, x:10, y:5 },
|
||||
key2: { code: 'test1', time: {start:1309323402727,end:1309323402727}, x:10, y:5 }
|
||||
};
|
||||
|
||||
var simple_string_serialized = bsonJS.serialize(doc, false, true);
|
||||
var simple_string_serialized_2 = bsonC.serialize(doc, false, true);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Serialize function'] = function(test) {
|
||||
var doc = {
|
||||
_id: 'testid',
|
||||
key1: function() {}
|
||||
}
|
||||
|
||||
var simple_string_serialized = bsonJS.serialize(doc, false, true, true);
|
||||
var simple_string_serialized_2 = bsonC.serialize(doc, false, true, true);
|
||||
|
||||
// Deserialize the string
|
||||
var doc1 = bsonJS.deserialize(new Buffer(simple_string_serialized_2));
|
||||
var doc2 = bsonC.deserialize(new Buffer(simple_string_serialized_2));
|
||||
assert.equal(doc1.key1.code.toString(), doc2.key1.code.toString())
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Serialize document with special operators'] = function(test) {
|
||||
var doc = {"user_id":"4e9fc8d55883d90100000003","lc_status":{"$ne":"deleted"},"owner_rating":{"$exists":false}};
|
||||
var simple_string_serialized = bsonJS.serialize(doc, false, true, true);
|
||||
var simple_string_serialized_2 = bsonC.serialize(doc, false, true, true);
|
||||
|
||||
// Should serialize to the same value
|
||||
assert.equal(simple_string_serialized_2.toString('base64'), simple_string_serialized.toString('base64'))
|
||||
var doc1 = bsonJS.deserialize(simple_string_serialized_2);
|
||||
var doc2 = bsonC.deserialize(simple_string_serialized);
|
||||
assert.deepEqual(doc1, doc2)
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Create ObjectID from hex string'] = function(test) {
|
||||
// Hex Id
|
||||
var hexId = new ObjectID().toString();
|
||||
var docJS = {_id: ObjectID.createFromHexString(hexId), 'funds.remaining': {$gte: 1.222}, 'transactions.id': {$ne: ObjectID.createFromHexString(hexId)}};
|
||||
var docC = {_id: ObjectID.createFromHexString(hexId), 'funds.remaining': {$gte: 1.222}, 'transactions.id': {$ne: ObjectID.createFromHexString(hexId)}};
|
||||
var docJSBin = bsonJS.serialize(docJS, false, true, true);
|
||||
var docCBin = bsonC.serialize(docC, false, true, true);
|
||||
assert.equal(docCBin.toString('base64'), docJSBin.toString('base64'));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Serialize big complex document'] = function(test) {
|
||||
// Complex document serialization
|
||||
var doc = {"DateTime": "Tue Nov 40 2011 17:27:55 GMT+0000 (WEST)","isActive": true,"Media": {"URL": "http://videos.sapo.pt/Tc85NsjaKjj8o5aV7Ubb"},"Title": "Lisboa fecha a ganhar 0.19%","SetPosition": 60,"Type": "videos","Thumbnail": [{"URL": "http://rd3.videos.sapo.pt/Tc85NsjaKjj8o5aV7Ubb/pic/320x240","Dimensions": {"Height": 240,"Width": 320}}],"Source": {"URL": "http://videos.sapo.pt","SetID": "1288","SourceID": "http://videos.sapo.pt/tvnet/rss2","SetURL": "http://noticias.sapo.pt/videos/tv-net_1288/","ItemID": "Tc85NsjaKjj8o5aV7Ubb","Name": "SAPO VÃdeos"},"Category": "Tec_ciencia","Description": "Lisboa fecha a ganhar 0.19%","GalleryID": new ObjectID("4eea2a634ce8573200000000"),"InternalRefs": {"RegisterDate": "Thu Dec 15 2011 17:12:51 GMT+0000 (WEST)","ChangeDate": "Thu Dec 15 2011 17:12:51 GMT+0000 (WEST)","Hash": 332279244514},"_id": new ObjectID("4eea2a96e52778160000003a")}
|
||||
var docJSBin = bsonJS.serialize(doc, false, true, true);
|
||||
var docCBin = bsonC.serialize(doc, false, true, true);
|
||||
assert.equal(docCBin.toString('base64'), docJSBin.toString('base64'));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should error out due to 24 characters but not valid hexstring for ObjectID'] = function(test) {
|
||||
try {
|
||||
var oid = new ObjectID("tttttttttttttttttttttttt");
|
||||
test.ok(false);
|
||||
} catch(err) {}
|
||||
|
||||
test.done();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports.noGlobalsLeaked = function(test) {
|
||||
var leaks = gleak.detectNew();
|
||||
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
|
||||
test.done();
|
||||
}
|
||||
1694
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/bson_test.js
generated
vendored
Normal file
1694
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/bson_test.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
392
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/bson_typed_array_test.js
generated
vendored
Normal file
392
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/bson_typed_array_test.js
generated
vendored
Normal file
@@ -0,0 +1,392 @@
|
||||
var mongodb = require('../../lib/bson').pure();
|
||||
|
||||
var testCase = require('nodeunit').testCase,
|
||||
mongoO = require('../../lib/bson').pure(),
|
||||
debug = require('util').debug,
|
||||
inspect = require('util').inspect,
|
||||
Buffer = require('buffer').Buffer,
|
||||
gleak = require('../../tools/gleak'),
|
||||
fs = require('fs'),
|
||||
BSON = mongoO.BSON,
|
||||
Code = mongoO.Code,
|
||||
Binary = mongoO.Binary,
|
||||
Timestamp = mongoO.Timestamp,
|
||||
Long = mongoO.Long,
|
||||
MongoReply = mongoO.MongoReply,
|
||||
ObjectID = mongoO.ObjectID,
|
||||
Symbol = mongoO.Symbol,
|
||||
DBRef = mongoO.DBRef,
|
||||
Double = mongoO.Double,
|
||||
MinKey = mongoO.MinKey,
|
||||
MaxKey = mongoO.MaxKey,
|
||||
BinaryParser = mongoO.BinaryParser,
|
||||
utils = require('./tools/utils');
|
||||
|
||||
var BSONSE = mongodb,
|
||||
BSONDE = mongodb;
|
||||
|
||||
// for tests
|
||||
BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
var hexStringToBinary = function(string) {
|
||||
var numberofValues = string.length / 2;
|
||||
var array = "";
|
||||
|
||||
for(var i = 0; i < numberofValues; i++) {
|
||||
array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16));
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
var assertBuffersEqual = function(test, buffer1, buffer2) {
|
||||
if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2);
|
||||
|
||||
for(var i = 0; i < buffer1.length; i++) {
|
||||
test.equal(buffer1[i], buffer2[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Module for parsing an ISO 8601 formatted string into a Date object.
|
||||
*/
|
||||
var ISODate = function (string) {
|
||||
var match;
|
||||
|
||||
if (typeof string.getTime === "function")
|
||||
return string;
|
||||
else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) {
|
||||
var date = new Date();
|
||||
date.setUTCFullYear(Number(match[1]));
|
||||
date.setUTCMonth(Number(match[3]) - 1 || 0);
|
||||
date.setUTCDate(Number(match[5]) || 0);
|
||||
date.setUTCHours(Number(match[7]) || 0);
|
||||
date.setUTCMinutes(Number(match[8]) || 0);
|
||||
date.setUTCSeconds(Number(match[10]) || 0);
|
||||
date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0);
|
||||
|
||||
if (match[13] && match[13] !== "Z") {
|
||||
var h = Number(match[16]) || 0,
|
||||
m = Number(match[17]) || 0;
|
||||
|
||||
h *= 3600000;
|
||||
m *= 60000;
|
||||
|
||||
var offset = h + m;
|
||||
if (match[15] == "+")
|
||||
offset = -offset;
|
||||
|
||||
date = new Date(date.valueOf() + offset);
|
||||
}
|
||||
|
||||
return date;
|
||||
} else
|
||||
throw new Error("Invalid ISO 8601 date given.", __filename);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.setUp = function(callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.tearDown = function(callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports.shouldCorrectlyDeserializeUsingTypedArray = function(test) {
|
||||
if(typeof ArrayBuffer == 'undefined') {
|
||||
test.done();
|
||||
return;
|
||||
}
|
||||
|
||||
var motherOfAllDocuments = {
|
||||
'string': '客家话',
|
||||
'array': [1,2,3],
|
||||
'hash': {'a':1, 'b':2},
|
||||
'date': new Date(),
|
||||
'oid': new ObjectID(),
|
||||
'binary': new Binary(new Buffer("hello")),
|
||||
'int': 42,
|
||||
'float': 33.3333,
|
||||
'regexp': /regexp/,
|
||||
'boolean': true,
|
||||
'long': Long.fromNumber(100),
|
||||
'where': new Code('this.a > i', {i:1}),
|
||||
'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
|
||||
'minkey': new MinKey(),
|
||||
'maxkey': new MaxKey()
|
||||
}
|
||||
|
||||
// Let's serialize it
|
||||
var data = BSONSE.BSON.serialize(motherOfAllDocuments, true, true, false);
|
||||
// Build a typed array
|
||||
var arr = new Uint8Array(new ArrayBuffer(data.length));
|
||||
// Iterate over all the fields and copy
|
||||
for(var i = 0; i < data.length; i++) {
|
||||
arr[i] = data[i]
|
||||
}
|
||||
|
||||
// Deserialize the object
|
||||
var object = BSONDE.BSON.deserialize(arr);
|
||||
// Asserts
|
||||
test.equal(motherOfAllDocuments.string, object.string);
|
||||
test.deepEqual(motherOfAllDocuments.array, object.array);
|
||||
test.deepEqual(motherOfAllDocuments.date, object.date);
|
||||
test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
|
||||
test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
|
||||
// Assert the values of the binary
|
||||
for(var i = 0; i < motherOfAllDocuments.binary.length(); i++) {
|
||||
test.equal(motherOfAllDocuments.binary.value[i], object.binary[i]);
|
||||
}
|
||||
test.deepEqual(motherOfAllDocuments.int, object.int);
|
||||
test.deepEqual(motherOfAllDocuments.float, object.float);
|
||||
test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
|
||||
test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
|
||||
test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long);
|
||||
test.deepEqual(motherOfAllDocuments.where, object.where);
|
||||
test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
|
||||
test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
|
||||
test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
|
||||
test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
|
||||
test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports.shouldCorrectlySerializeUsingTypedArray = function(test) {
|
||||
if(typeof ArrayBuffer == 'undefined') {
|
||||
test.done();
|
||||
return;
|
||||
}
|
||||
|
||||
var motherOfAllDocuments = {
|
||||
'string': 'hello',
|
||||
'array': [1,2,3],
|
||||
'hash': {'a':1, 'b':2},
|
||||
'date': new Date(),
|
||||
'oid': new ObjectID(),
|
||||
'binary': new Binary(new Buffer("hello")),
|
||||
'int': 42,
|
||||
'float': 33.3333,
|
||||
'regexp': /regexp/,
|
||||
'boolean': true,
|
||||
'long': Long.fromNumber(100),
|
||||
'where': new Code('this.a > i', {i:1}),
|
||||
'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
|
||||
'minkey': new MinKey(),
|
||||
'maxkey': new MaxKey()
|
||||
}
|
||||
|
||||
// Let's serialize it
|
||||
var data = BSONSE.BSON.serialize(motherOfAllDocuments, true, false, false);
|
||||
// And deserialize it again
|
||||
var object = BSONSE.BSON.deserialize(data);
|
||||
// Asserts
|
||||
test.equal(motherOfAllDocuments.string, object.string);
|
||||
test.deepEqual(motherOfAllDocuments.array, object.array);
|
||||
test.deepEqual(motherOfAllDocuments.date, object.date);
|
||||
test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
|
||||
test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
|
||||
// Assert the values of the binary
|
||||
for(var i = 0; i < motherOfAllDocuments.binary.length(); i++) {
|
||||
test.equal(motherOfAllDocuments.binary.value[i], object.binary[i]);
|
||||
}
|
||||
test.deepEqual(motherOfAllDocuments.int, object.int);
|
||||
test.deepEqual(motherOfAllDocuments.float, object.float);
|
||||
test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
|
||||
test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
|
||||
test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long);
|
||||
test.deepEqual(motherOfAllDocuments.where, object.where);
|
||||
test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
|
||||
test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
|
||||
test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
|
||||
test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
|
||||
test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['exercise all the binary object constructor methods'] = function (test) {
|
||||
if(typeof ArrayBuffer == 'undefined') {
|
||||
test.done();
|
||||
return;
|
||||
}
|
||||
|
||||
// Construct using array
|
||||
var string = 'hello world';
|
||||
// String to array
|
||||
var array = utils.stringToArrayBuffer(string);
|
||||
|
||||
// Binary from array buffer
|
||||
var binary = new Binary(utils.stringToArrayBuffer(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
test.ok(utils.assertArrayEqual(array, binary.buffer));
|
||||
|
||||
// Construct using number of chars
|
||||
binary = new Binary(5);
|
||||
test.ok(5, binary.buffer.length);
|
||||
|
||||
// Construct using an Array
|
||||
var binary = new Binary(utils.stringToArray(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
test.ok(utils.assertArrayEqual(array, binary.buffer));
|
||||
|
||||
// Construct using a string
|
||||
var binary = new Binary(string);
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
test.ok(utils.assertArrayEqual(array, binary.buffer));
|
||||
test.done();
|
||||
};
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['exercise the put binary object method for an instance when using Uint8Array'] = function (test) {
|
||||
if(typeof ArrayBuffer == 'undefined') {
|
||||
test.done();
|
||||
return;
|
||||
}
|
||||
|
||||
// Construct using array
|
||||
var string = 'hello world';
|
||||
// String to array
|
||||
var array = utils.stringToArrayBuffer(string + 'a');
|
||||
|
||||
// Binary from array buffer
|
||||
var binary = new Binary(utils.stringToArrayBuffer(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
|
||||
// Write a byte to the array
|
||||
binary.put('a')
|
||||
|
||||
// Verify that the data was writtencorrectly
|
||||
test.equal(string.length + 1, binary.position);
|
||||
test.ok(utils.assertArrayEqual(array, binary.value(true)));
|
||||
test.equal('hello worlda', binary.value());
|
||||
|
||||
// Exercise a binary with lots of space in the buffer
|
||||
var binary = new Binary();
|
||||
test.ok(Binary.BUFFER_SIZE, binary.buffer.length);
|
||||
|
||||
// Write a byte to the array
|
||||
binary.put('a')
|
||||
|
||||
// Verify that the data was writtencorrectly
|
||||
test.equal(1, binary.position);
|
||||
test.ok(utils.assertArrayEqual(['a'.charCodeAt(0)], binary.value(true)));
|
||||
test.equal('a', binary.value());
|
||||
test.done();
|
||||
},
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['exercise the write binary object method for an instance when using Uint8Array'] = function (test) {
|
||||
if(typeof ArrayBuffer == 'undefined') {
|
||||
test.done();
|
||||
return;
|
||||
}
|
||||
|
||||
// Construct using array
|
||||
var string = 'hello world';
|
||||
// Array
|
||||
var writeArrayBuffer = new Uint8Array(new ArrayBuffer(1));
|
||||
writeArrayBuffer[0] = 'a'.charCodeAt(0);
|
||||
var arrayBuffer = ['a'.charCodeAt(0)];
|
||||
|
||||
// Binary from array buffer
|
||||
var binary = new Binary(utils.stringToArrayBuffer(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
|
||||
// Write a string starting at end of buffer
|
||||
binary.write('a');
|
||||
test.equal('hello worlda', binary.value());
|
||||
// Write a string starting at index 0
|
||||
binary.write('a', 0);
|
||||
test.equal('aello worlda', binary.value());
|
||||
// Write a arraybuffer starting at end of buffer
|
||||
binary.write(writeArrayBuffer);
|
||||
test.equal('aello worldaa', binary.value());
|
||||
// Write a arraybuffer starting at position 5
|
||||
binary.write(writeArrayBuffer, 5);
|
||||
test.equal('aelloaworldaa', binary.value());
|
||||
// Write a array starting at end of buffer
|
||||
binary.write(arrayBuffer);
|
||||
test.equal('aelloaworldaaa', binary.value());
|
||||
// Write a array starting at position 6
|
||||
binary.write(arrayBuffer, 6);
|
||||
test.equal('aelloaaorldaaa', binary.value());
|
||||
test.done();
|
||||
},
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['exercise the read binary object method for an instance when using Uint8Array'] = function (test) {
|
||||
if(typeof ArrayBuffer == 'undefined') {
|
||||
test.done();
|
||||
return;
|
||||
}
|
||||
|
||||
// Construct using array
|
||||
var string = 'hello world';
|
||||
var array = utils.stringToArrayBuffer(string);
|
||||
|
||||
// Binary from array buffer
|
||||
var binary = new Binary(utils.stringToArrayBuffer(string));
|
||||
test.ok(string.length, binary.buffer.length);
|
||||
|
||||
// Read the first 2 bytes
|
||||
var data = binary.read(0, 2);
|
||||
test.ok(utils.assertArrayEqual(utils.stringToArrayBuffer('he'), data));
|
||||
|
||||
// Read the entire field
|
||||
var data = binary.read(0);
|
||||
test.ok(utils.assertArrayEqual(utils.stringToArrayBuffer(string), data));
|
||||
|
||||
// Read 3 bytes
|
||||
var data = binary.read(6, 5);
|
||||
test.ok(utils.assertArrayEqual(utils.stringToArrayBuffer('world'), data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.noGlobalsLeaked = function(test) {
|
||||
var leaks = gleak.detectNew();
|
||||
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
|
||||
test.done();
|
||||
}
|
||||
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/data/test_gs_weird_bug.png
generated
vendored
Normal file
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/data/test_gs_weird_bug.png
generated
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 51 KiB |
315
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/test_full_bson.js
generated
vendored
Normal file
315
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/test_full_bson.js
generated
vendored
Normal file
@@ -0,0 +1,315 @@
|
||||
var sys = require('util'),
|
||||
fs = require('fs'),
|
||||
BSON = require('../../ext').BSON,
|
||||
Buffer = require('buffer').Buffer,
|
||||
BSONJS = require('../../lib/bson/bson').BSON,
|
||||
BinaryParser = require('../../lib/bson/binary_parser').BinaryParser,
|
||||
Long = require('../../lib/bson/long').Long,
|
||||
ObjectID = require('../../lib/bson/bson').ObjectID,
|
||||
Binary = require('../../lib/bson/bson').Binary,
|
||||
Code = require('../../lib/bson/bson').Code,
|
||||
DBRef = require('../../lib/bson/bson').DBRef,
|
||||
Symbol = require('../../lib/bson/bson').Symbol,
|
||||
Double = require('../../lib/bson/bson').Double,
|
||||
MaxKey = require('../../lib/bson/bson').MaxKey,
|
||||
MinKey = require('../../lib/bson/bson').MinKey,
|
||||
Timestamp = require('../../lib/bson/bson').Timestamp,
|
||||
gleak = require('../../tools/gleak'),
|
||||
assert = require('assert');
|
||||
|
||||
// Parsers
|
||||
var bsonC = new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
|
||||
var bsonJS = new BSONJS([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.setUp = function(callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.tearDown = function(callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Deserialize object'] = function(test) {
|
||||
var bytes = [95,0,0,0,2,110,115,0,42,0,0,0,105,110,116,101,103,114,97,116,105,111,110,95,116,101,115,116,115,95,46,116,101,115,116,95,105,110,100,101,120,95,105,110,102,111,114,109,97,116,105,111,110,0,8,117,110,105,113,117,101,0,0,3,107,101,121,0,12,0,0,0,16,97,0,1,0,0,0,0,2,110,97,109,101,0,4,0,0,0,97,95,49,0,0];
|
||||
var serialized_data = '';
|
||||
// Convert to chars
|
||||
for(var i = 0; i < bytes.length; i++) {
|
||||
serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
|
||||
}
|
||||
|
||||
var object = bsonC.deserialize(serialized_data);
|
||||
assert.equal("a_1", object.name);
|
||||
assert.equal(false, object.unique);
|
||||
assert.equal(1, object.key.a);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Deserialize object with all types'] = function(test) {
|
||||
var bytes = [26,1,0,0,7,95,105,100,0,161,190,98,75,118,169,3,0,0,3,0,0,4,97,114,114,97,121,0,26,0,0,0,16,48,0,1,0,0,0,16,49,0,2,0,0,0,16,50,0,3,0,0,0,0,2,115,116,114,105,110,103,0,6,0,0,0,104,101,108,108,111,0,3,104,97,115,104,0,19,0,0,0,16,97,0,1,0,0,0,16,98,0,2,0,0,0,0,9,100,97,116,101,0,161,190,98,75,0,0,0,0,7,111,105,100,0,161,190,98,75,90,217,18,0,0,1,0,0,5,98,105,110,97,114,121,0,7,0,0,0,2,3,0,0,0,49,50,51,16,105,110,116,0,42,0,0,0,1,102,108,111,97,116,0,223,224,11,147,169,170,64,64,11,114,101,103,101,120,112,0,102,111,111,98,97,114,0,105,0,8,98,111,111,108,101,97,110,0,1,15,119,104,101,114,101,0,25,0,0,0,12,0,0,0,116,104,105,115,46,120,32,61,61,32,51,0,5,0,0,0,0,3,100,98,114,101,102,0,37,0,0,0,2,36,114,101,102,0,5,0,0,0,116,101,115,116,0,7,36,105,100,0,161,190,98,75,2,180,1,0,0,2,0,0,0,10,110,117,108,108,0,0];
|
||||
var serialized_data = '';
|
||||
// Convert to chars
|
||||
for(var i = 0; i < bytes.length; i++) {
|
||||
serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
|
||||
}
|
||||
|
||||
var object = bsonJS.deserialize(new Buffer(serialized_data, 'binary'));
|
||||
assert.equal("hello", object.string);
|
||||
assert.deepEqual([1, 2, 3], object.array);
|
||||
assert.equal(1, object.hash.a);
|
||||
assert.equal(2, object.hash.b);
|
||||
assert.ok(object.date != null);
|
||||
assert.ok(object.oid != null);
|
||||
assert.ok(object.binary != null);
|
||||
assert.equal(42, object.int);
|
||||
assert.equal(33.3333, object.float);
|
||||
assert.ok(object.regexp != null);
|
||||
assert.equal(true, object.boolean);
|
||||
assert.ok(object.where != null);
|
||||
assert.ok(object.dbref != null);
|
||||
assert.ok(object['null'] == null);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Serialize and Deserialize String'] = function(test) {
|
||||
var test_string = {hello: 'world'}
|
||||
var serialized_data = bsonC.serialize(test_string)
|
||||
assert.deepEqual(test_string, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Integer'] = function(test) {
|
||||
var test_number = {doc: 5}
|
||||
var serialized_data = bsonC.serialize(test_number)
|
||||
assert.deepEqual(test_number, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize null value'] = function(test) {
|
||||
var test_null = {doc:null}
|
||||
var serialized_data = bsonC.serialize(test_null)
|
||||
var object = bsonC.deserialize(serialized_data);
|
||||
assert.deepEqual(test_null, object);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize undefined value'] = function(test) {
|
||||
var test_undefined = {doc:undefined}
|
||||
var serialized_data = bsonC.serialize(test_undefined)
|
||||
var object = bsonJS.deserialize(new Buffer(serialized_data, 'binary'));
|
||||
assert.equal(null, object.doc)
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Number'] = function(test) {
|
||||
var test_number = {doc: 5.5}
|
||||
var serialized_data = bsonC.serialize(test_number)
|
||||
assert.deepEqual(test_number, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Integer'] = function(test) {
|
||||
var test_int = {doc: 42}
|
||||
var serialized_data = bsonC.serialize(test_int)
|
||||
assert.deepEqual(test_int, bsonC.deserialize(serialized_data));
|
||||
|
||||
test_int = {doc: -5600}
|
||||
serialized_data = bsonC.serialize(test_int)
|
||||
assert.deepEqual(test_int, bsonC.deserialize(serialized_data));
|
||||
|
||||
test_int = {doc: 2147483647}
|
||||
serialized_data = bsonC.serialize(test_int)
|
||||
assert.deepEqual(test_int, bsonC.deserialize(serialized_data));
|
||||
|
||||
test_int = {doc: -2147483648}
|
||||
serialized_data = bsonC.serialize(test_int)
|
||||
assert.deepEqual(test_int, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Object'] = function(test) {
|
||||
var doc = {doc: {age: 42, name: 'Spongebob', shoe_size: 9.5}}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
assert.deepEqual(doc, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Array'] = function(test) {
|
||||
var doc = {doc: [1, 2, 'a', 'b']}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
assert.deepEqual(doc, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Array with added on functions'] = function(test) {
|
||||
var doc = {doc: [1, 2, 'a', 'b']}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
assert.deepEqual(doc, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize A Boolean'] = function(test) {
|
||||
var doc = {doc: true}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
assert.deepEqual(doc, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize a Date'] = function(test) {
|
||||
var date = new Date()
|
||||
//(2009, 11, 12, 12, 00, 30)
|
||||
date.setUTCDate(12)
|
||||
date.setUTCFullYear(2009)
|
||||
date.setUTCMonth(11 - 1)
|
||||
date.setUTCHours(12)
|
||||
date.setUTCMinutes(0)
|
||||
date.setUTCSeconds(30)
|
||||
var doc = {doc: date}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
assert.deepEqual(doc, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Oid'] = function(test) {
|
||||
var doc = {doc: new ObjectID()}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
assert.deepEqual(doc.doc.toHexString(), bsonC.deserialize(serialized_data).doc.toHexString())
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Buffer'] = function(test) {
|
||||
var doc = {doc: new Buffer("123451234512345")}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
|
||||
assert.equal("123451234512345", bsonC.deserialize(serialized_data).doc.buffer.toString('ascii'));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly encode Empty Hash'] = function(test) {
|
||||
var test_code = {}
|
||||
var serialized_data = bsonC.serialize(test_code)
|
||||
assert.deepEqual(test_code, bsonC.deserialize(serialized_data));
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Ordered Hash'] = function(test) {
|
||||
var doc = {doc: {b:1, a:2, c:3, d:4}}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
var decoded_hash = bsonC.deserialize(serialized_data).doc
|
||||
var keys = []
|
||||
for(var name in decoded_hash) keys.push(name)
|
||||
assert.deepEqual(['b', 'a', 'c', 'd'], keys)
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize Regular Expression'] = function(test) {
|
||||
var doc = {doc: /foobar/mi}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
var doc2 = bsonC.deserialize(serialized_data);
|
||||
assert.equal(doc.doc.toString(), doc2.doc.toString())
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize a Binary object'] = function(test) {
|
||||
var bin = new Binary()
|
||||
var string = 'binstring'
|
||||
for(var index = 0; index < string.length; index++) {
|
||||
bin.put(string.charAt(index))
|
||||
}
|
||||
var doc = {doc: bin}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
var deserialized_data = bsonC.deserialize(serialized_data);
|
||||
assert.equal(doc.doc.value(), deserialized_data.doc.value())
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should Correctly Serialize and Deserialize a big Binary object'] = function(test) {
|
||||
var data = fs.readFileSync("test/node/data/test_gs_weird_bug.png", 'binary');
|
||||
var bin = new Binary()
|
||||
bin.write(data)
|
||||
var doc = {doc: bin}
|
||||
var serialized_data = bsonC.serialize(doc)
|
||||
var deserialized_data = bsonC.deserialize(serialized_data);
|
||||
assert.equal(doc.doc.value(), deserialized_data.doc.value())
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports.noGlobalsLeaked = function(test) {
|
||||
var leaks = gleak.detectNew();
|
||||
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
|
||||
test.done();
|
||||
}
|
||||
109
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/to_bson_test.js
generated
vendored
Normal file
109
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/to_bson_test.js
generated
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/bson').native() : require('../../lib/bson').pure();
|
||||
|
||||
var testCase = require('nodeunit').testCase,
|
||||
mongoO = require('../../lib/bson').pure(),
|
||||
Buffer = require('buffer').Buffer,
|
||||
gleak = require('../../tools/gleak'),
|
||||
fs = require('fs'),
|
||||
BSON = mongoO.BSON,
|
||||
Code = mongoO.Code,
|
||||
Binary = mongoO.Binary,
|
||||
Timestamp = mongoO.Timestamp,
|
||||
Long = mongoO.Long,
|
||||
MongoReply = mongoO.MongoReply,
|
||||
ObjectID = mongoO.ObjectID,
|
||||
Symbol = mongoO.Symbol,
|
||||
DBRef = mongoO.DBRef,
|
||||
Double = mongoO.Double,
|
||||
MinKey = mongoO.MinKey,
|
||||
MaxKey = mongoO.MaxKey,
|
||||
BinaryParser = mongoO.BinaryParser;
|
||||
|
||||
var BSONSE = mongodb,
|
||||
BSONDE = mongodb;
|
||||
|
||||
// for tests
|
||||
BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_UUID = 3;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4;
|
||||
BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
|
||||
|
||||
var hexStringToBinary = function(string) {
|
||||
var numberofValues = string.length / 2;
|
||||
var array = "";
|
||||
|
||||
for(var i = 0; i < numberofValues; i++) {
|
||||
array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16));
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
var assertBuffersEqual = function(test, buffer1, buffer2) {
|
||||
if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2);
|
||||
|
||||
for(var i = 0; i < buffer1.length; i++) {
|
||||
test.equal(buffer1[i], buffer2[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.setUp = function(callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.tearDown = function(callback) {
|
||||
callback();
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
exports['Should correctly handle toBson function for an object'] = function(test) {
|
||||
// Test object
|
||||
var doc = {
|
||||
hello: new ObjectID(),
|
||||
a:1
|
||||
};
|
||||
// Add a toBson method to the object
|
||||
doc.toBSON = function() {
|
||||
return {b:1};
|
||||
}
|
||||
|
||||
// Serialize the data
|
||||
var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true);
|
||||
var deserialized_doc = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data);
|
||||
test.deepEqual({b:1}, deserialized_doc);
|
||||
test.done();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the server information for the current
|
||||
* instance of the db client
|
||||
*
|
||||
* @ignore
|
||||
*/
|
||||
exports.noGlobalsLeaked = function(test) {
|
||||
var leaks = gleak.detectNew();
|
||||
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
|
||||
test.done();
|
||||
}
|
||||
80
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/tools/utils.js
generated
vendored
Normal file
80
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/test/node/tools/utils.js
generated
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
exports.assertArrayEqual = function(array1, array2) {
|
||||
if(array1.length != array2.length) return false;
|
||||
for(var i = 0; i < array1.length; i++) {
|
||||
if(array1[i] != array2[i]) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// String to arraybuffer
|
||||
exports.stringToArrayBuffer = function(string) {
|
||||
var dataBuffer = new Uint8Array(new ArrayBuffer(string.length));
|
||||
// Return the strings
|
||||
for(var i = 0; i < string.length; i++) {
|
||||
dataBuffer[i] = string.charCodeAt(i);
|
||||
}
|
||||
// Return the data buffer
|
||||
return dataBuffer;
|
||||
}
|
||||
|
||||
// String to arraybuffer
|
||||
exports.stringToArray = function(string) {
|
||||
var dataBuffer = new Array(string.length);
|
||||
// Return the strings
|
||||
for(var i = 0; i < string.length; i++) {
|
||||
dataBuffer[i] = string.charCodeAt(i);
|
||||
}
|
||||
// Return the data buffer
|
||||
return dataBuffer;
|
||||
}
|
||||
|
||||
exports.Utf8 = {
|
||||
// public method for url encoding
|
||||
encode : function (string) {
|
||||
string = string.replace(/\r\n/g,"\n");
|
||||
var utftext = "";
|
||||
|
||||
for (var n = 0; n < string.length; n++) {
|
||||
var c = string.charCodeAt(n);
|
||||
if (c < 128) {
|
||||
utftext += String.fromCharCode(c);
|
||||
} else if((c > 127) && (c < 2048)) {
|
||||
utftext += String.fromCharCode((c >> 6) | 192);
|
||||
utftext += String.fromCharCode((c & 63) | 128);
|
||||
} else {
|
||||
utftext += String.fromCharCode((c >> 12) | 224);
|
||||
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
|
||||
utftext += String.fromCharCode((c & 63) | 128);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return utftext;
|
||||
},
|
||||
|
||||
// public method for url decoding
|
||||
decode : function (utftext) {
|
||||
var string = "";
|
||||
var i = 0;
|
||||
var c = c1 = c2 = 0;
|
||||
|
||||
while ( i < utftext.length ) {
|
||||
c = utftext.charCodeAt(i);
|
||||
if(c < 128) {
|
||||
string += String.fromCharCode(c);
|
||||
i++;
|
||||
} else if((c > 191) && (c < 224)) {
|
||||
c2 = utftext.charCodeAt(i+1);
|
||||
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
|
||||
i += 2;
|
||||
} else {
|
||||
c2 = utftext.charCodeAt(i+1);
|
||||
c3 = utftext.charCodeAt(i+2);
|
||||
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
|
||||
i += 3;
|
||||
}
|
||||
}
|
||||
return string;
|
||||
}
|
||||
}
|
||||
21
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/gleak.js
generated
vendored
Normal file
21
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/gleak.js
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
|
||||
var gleak = require('gleak')();
|
||||
gleak.ignore('AssertionError');
|
||||
gleak.ignore('testFullSpec_param_found');
|
||||
gleak.ignore('events');
|
||||
gleak.ignore('Uint8Array');
|
||||
gleak.ignore('Uint8ClampedArray');
|
||||
gleak.ignore('TAP_Global_Harness');
|
||||
gleak.ignore('setImmediate');
|
||||
gleak.ignore('clearImmediate');
|
||||
|
||||
gleak.ignore('DTRACE_NET_SERVER_CONNECTION');
|
||||
gleak.ignore('DTRACE_NET_STREAM_END');
|
||||
gleak.ignore('DTRACE_NET_SOCKET_READ');
|
||||
gleak.ignore('DTRACE_NET_SOCKET_WRITE');
|
||||
gleak.ignore('DTRACE_HTTP_SERVER_REQUEST');
|
||||
gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE');
|
||||
gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST');
|
||||
gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE');
|
||||
|
||||
module.exports = gleak;
|
||||
20
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE
generated
vendored
Normal file
20
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2008-2011 Pivotal Labs
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
190
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js
generated
vendored
Normal file
190
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js
generated
vendored
Normal file
@@ -0,0 +1,190 @@
|
||||
jasmine.TrivialReporter = function(doc) {
|
||||
this.document = doc || document;
|
||||
this.suiteDivs = {};
|
||||
this.logRunningSpecs = false;
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) {
|
||||
var el = document.createElement(type);
|
||||
|
||||
for (var i = 2; i < arguments.length; i++) {
|
||||
var child = arguments[i];
|
||||
|
||||
if (typeof child === 'string') {
|
||||
el.appendChild(document.createTextNode(child));
|
||||
} else {
|
||||
if (child) { el.appendChild(child); }
|
||||
}
|
||||
}
|
||||
|
||||
for (var attr in attrs) {
|
||||
if (attr == "className") {
|
||||
el[attr] = attrs[attr];
|
||||
} else {
|
||||
el.setAttribute(attr, attrs[attr]);
|
||||
}
|
||||
}
|
||||
|
||||
return el;
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) {
|
||||
var showPassed, showSkipped;
|
||||
|
||||
this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' },
|
||||
this.createDom('div', { className: 'banner' },
|
||||
this.createDom('div', { className: 'logo' },
|
||||
this.createDom('span', { className: 'title' }, "Jasmine"),
|
||||
this.createDom('span', { className: 'version' }, runner.env.versionString())),
|
||||
this.createDom('div', { className: 'options' },
|
||||
"Show ",
|
||||
showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
|
||||
this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
|
||||
showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
|
||||
this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
|
||||
)
|
||||
),
|
||||
|
||||
this.runnerDiv = this.createDom('div', { className: 'runner running' },
|
||||
this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
|
||||
this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
|
||||
this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
|
||||
);
|
||||
|
||||
this.document.body.appendChild(this.outerDiv);
|
||||
|
||||
var suites = runner.suites();
|
||||
for (var i = 0; i < suites.length; i++) {
|
||||
var suite = suites[i];
|
||||
var suiteDiv = this.createDom('div', { className: 'suite' },
|
||||
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
|
||||
this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description));
|
||||
this.suiteDivs[suite.id] = suiteDiv;
|
||||
var parentDiv = this.outerDiv;
|
||||
if (suite.parentSuite) {
|
||||
parentDiv = this.suiteDivs[suite.parentSuite.id];
|
||||
}
|
||||
parentDiv.appendChild(suiteDiv);
|
||||
}
|
||||
|
||||
this.startedAt = new Date();
|
||||
|
||||
var self = this;
|
||||
showPassed.onclick = function(evt) {
|
||||
if (showPassed.checked) {
|
||||
self.outerDiv.className += ' show-passed';
|
||||
} else {
|
||||
self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
|
||||
}
|
||||
};
|
||||
|
||||
showSkipped.onclick = function(evt) {
|
||||
if (showSkipped.checked) {
|
||||
self.outerDiv.className += ' show-skipped';
|
||||
} else {
|
||||
self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
|
||||
var results = runner.results();
|
||||
var className = (results.failedCount > 0) ? "runner failed" : "runner passed";
|
||||
this.runnerDiv.setAttribute("class", className);
|
||||
//do it twice for IE
|
||||
this.runnerDiv.setAttribute("className", className);
|
||||
var specs = runner.specs();
|
||||
var specCount = 0;
|
||||
for (var i = 0; i < specs.length; i++) {
|
||||
if (this.specFilter(specs[i])) {
|
||||
specCount++;
|
||||
}
|
||||
}
|
||||
var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s");
|
||||
message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s";
|
||||
this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild);
|
||||
|
||||
this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString()));
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
|
||||
var results = suite.results();
|
||||
var status = results.passed() ? 'passed' : 'failed';
|
||||
if (results.totalCount === 0) { // todo: change this to check results.skipped
|
||||
status = 'skipped';
|
||||
}
|
||||
this.suiteDivs[suite.id].className += " " + status;
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) {
|
||||
if (this.logRunningSpecs) {
|
||||
this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
|
||||
}
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
|
||||
var results = spec.results();
|
||||
var status = results.passed() ? 'passed' : 'failed';
|
||||
if (results.skipped) {
|
||||
status = 'skipped';
|
||||
}
|
||||
var specDiv = this.createDom('div', { className: 'spec ' + status },
|
||||
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"),
|
||||
this.createDom('a', {
|
||||
className: 'description',
|
||||
href: '?spec=' + encodeURIComponent(spec.getFullName()),
|
||||
title: spec.getFullName()
|
||||
}, spec.description));
|
||||
|
||||
|
||||
var resultItems = results.getItems();
|
||||
var messagesDiv = this.createDom('div', { className: 'messages' });
|
||||
for (var i = 0; i < resultItems.length; i++) {
|
||||
var result = resultItems[i];
|
||||
|
||||
if (result.type == 'log') {
|
||||
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
|
||||
} else if (result.type == 'expect' && result.passed && !result.passed()) {
|
||||
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
|
||||
|
||||
if (result.trace.stack) {
|
||||
messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (messagesDiv.childNodes.length > 0) {
|
||||
specDiv.appendChild(messagesDiv);
|
||||
}
|
||||
|
||||
this.suiteDivs[spec.suite.id].appendChild(specDiv);
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.log = function() {
|
||||
var console = jasmine.getGlobal().console;
|
||||
if (console && console.log) {
|
||||
if (console.log.apply) {
|
||||
console.log.apply(console, arguments);
|
||||
} else {
|
||||
console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.getLocation = function() {
|
||||
return this.document.location;
|
||||
};
|
||||
|
||||
jasmine.TrivialReporter.prototype.specFilter = function(spec) {
|
||||
var paramMap = {};
|
||||
var params = this.getLocation().search.substring(1).split('&');
|
||||
for (var i = 0; i < params.length; i++) {
|
||||
var p = params[i].split('=');
|
||||
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
|
||||
}
|
||||
|
||||
if (!paramMap.spec) {
|
||||
return true;
|
||||
}
|
||||
return spec.getFullName().indexOf(paramMap.spec) === 0;
|
||||
};
|
||||
166
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css
generated
vendored
Normal file
166
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css
generated
vendored
Normal file
@@ -0,0 +1,166 @@
|
||||
body {
|
||||
font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;
|
||||
}
|
||||
|
||||
|
||||
.jasmine_reporter a:visited, .jasmine_reporter a {
|
||||
color: #303;
|
||||
}
|
||||
|
||||
.jasmine_reporter a:hover, .jasmine_reporter a:active {
|
||||
color: blue;
|
||||
}
|
||||
|
||||
.run_spec {
|
||||
float:right;
|
||||
padding-right: 5px;
|
||||
font-size: .8em;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.jasmine_reporter {
|
||||
margin: 0 5px;
|
||||
}
|
||||
|
||||
.banner {
|
||||
color: #303;
|
||||
background-color: #fef;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
float: left;
|
||||
font-size: 1.1em;
|
||||
padding-left: 5px;
|
||||
}
|
||||
|
||||
.logo .version {
|
||||
font-size: .6em;
|
||||
padding-left: 1em;
|
||||
}
|
||||
|
||||
.runner.running {
|
||||
background-color: yellow;
|
||||
}
|
||||
|
||||
|
||||
.options {
|
||||
text-align: right;
|
||||
font-size: .8em;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
.suite {
|
||||
border: 1px outset gray;
|
||||
margin: 5px 0;
|
||||
padding-left: 1em;
|
||||
}
|
||||
|
||||
.suite .suite {
|
||||
margin: 5px;
|
||||
}
|
||||
|
||||
.suite.passed {
|
||||
background-color: #dfd;
|
||||
}
|
||||
|
||||
.suite.failed {
|
||||
background-color: #fdd;
|
||||
}
|
||||
|
||||
.spec {
|
||||
margin: 5px;
|
||||
padding-left: 1em;
|
||||
clear: both;
|
||||
}
|
||||
|
||||
.spec.failed, .spec.passed, .spec.skipped {
|
||||
padding-bottom: 5px;
|
||||
border: 1px solid gray;
|
||||
}
|
||||
|
||||
.spec.failed {
|
||||
background-color: #fbb;
|
||||
border-color: red;
|
||||
}
|
||||
|
||||
.spec.passed {
|
||||
background-color: #bfb;
|
||||
border-color: green;
|
||||
}
|
||||
|
||||
.spec.skipped {
|
||||
background-color: #bbb;
|
||||
}
|
||||
|
||||
.messages {
|
||||
border-left: 1px dashed gray;
|
||||
padding-left: 1em;
|
||||
padding-right: 1em;
|
||||
}
|
||||
|
||||
.passed {
|
||||
background-color: #cfc;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.failed {
|
||||
background-color: #fbb;
|
||||
}
|
||||
|
||||
.skipped {
|
||||
color: #777;
|
||||
background-color: #eee;
|
||||
display: none;
|
||||
}
|
||||
|
||||
|
||||
/*.resultMessage {*/
|
||||
/*white-space: pre;*/
|
||||
/*}*/
|
||||
|
||||
.resultMessage span.result {
|
||||
display: block;
|
||||
line-height: 2em;
|
||||
color: black;
|
||||
}
|
||||
|
||||
.resultMessage .mismatch {
|
||||
color: black;
|
||||
}
|
||||
|
||||
.stackTrace {
|
||||
white-space: pre;
|
||||
font-size: .8em;
|
||||
margin-left: 10px;
|
||||
max-height: 5em;
|
||||
overflow: auto;
|
||||
border: 1px inset red;
|
||||
padding: 1em;
|
||||
background: #eef;
|
||||
}
|
||||
|
||||
.finished-at {
|
||||
padding-left: 1em;
|
||||
font-size: .6em;
|
||||
}
|
||||
|
||||
.show-passed .passed,
|
||||
.show-skipped .skipped {
|
||||
display: block;
|
||||
}
|
||||
|
||||
|
||||
#jasmine_content {
|
||||
position:fixed;
|
||||
right: 100%;
|
||||
}
|
||||
|
||||
.runner {
|
||||
border: 1px solid gray;
|
||||
display: block;
|
||||
margin: 5px 0;
|
||||
padding: 2px 0 2px 10px;
|
||||
}
|
||||
2476
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js
generated
vendored
Normal file
2476
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png
generated
vendored
Normal file
BIN
mongoui/mongoui-master/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png
generated
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 905 B |
220
mongoui/mongoui-master/node_modules/mongodb/package.json
generated
vendored
Executable file
220
mongoui/mongoui-master/node_modules/mongodb/package.json
generated
vendored
Executable file
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user